sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function parseMiddleware($middleware) { list($name, $parameters) = array_pad(explode(':', $middleware, 2), 2, array()); if (is_string($parameters)) { $parameters = explode(',', $parameters); } return array($name, $parameters); }
Parse a middleware string to get the name and parameters. @param string $middleware @return array
entailment
public function pushMiddleware($middleware) { if (array_search($middleware, $this->middleware) === false) { array_push($this->middleware, $middleware); } return $this; }
Add a new middleware to end of the stack if it does not already exist. @param string|\Closure $middleware @return \Nova\Foundation\Application
entailment
public function setRequestForConsoleEnvironment() { $url = $this['config']->get('app.url', 'http://localhost'); $parameters = array($url, 'GET', array(), array(), array(), $_SERVER); $this->refreshRequest(static::onRequest('create', $parameters)); }
Set the application request for the console environment. @return void
entailment
public function registerCoreContainerAliases() { $aliases = array( 'app' => 'Nova\Foundation\Application', 'forge' => 'Nova\Console\Application', 'auth' => 'Nova\Auth\AuthManager', 'cache' => 'Nova\Cache\CacheManager', 'cache.store' => 'Nova\Cache\Repository', 'config' => 'Nova\Config\Repository', 'cookie' => 'Nova\Cookie\CookieJar', 'encrypter' => 'Nova\Encryption\Encrypter', 'db' => 'Nova\Database\DatabaseManager', 'events' => 'Nova\Events\Dispatcher', 'files' => 'Nova\Filesystem\Filesystem', 'hash' => 'Nova\Hashing\HasherInterface', 'language' => 'Nova\Language\LanguageManager', 'log' => array('Nova\Log\Writer', 'Psr\Log\LoggerInterface'), 'mailer' => 'Nova\Mail\Mailer', 'redirect' => 'Nova\Routing\Redirector', 'request' => 'Nova\Http\Request', 'router' => 'Nova\Routing\Router', 'session' => 'Nova\Session\SessionManager', 'session.store' => 'Nova\Session\Store', 'url' => 'Nova\Routing\UrlGenerator', 'validator' => 'Nova\Validation\Factory', 'view' => 'Nova\View\Factory', 'assets' => 'Nova\Assets\AssetManager', 'assets.dispatcher' => 'Nova\Assets\AssetDispatcher', ); foreach ($aliases as $key => $value) { foreach ((array) $value as $alias) { $this->alias($key, $alias); } } }
Register the core class aliases in the container. @return void
entailment
protected function setKeysForSaveQuery(Builder $query) { $query->where($this->foreignKey, $this->getAttribute($this->foreignKey)); return $query->where($this->otherKey, $this->getAttribute($this->otherKey)); }
Set the keys for a save update query. @param \Nova\Database\ORM\Builder @return \Nova\Database\ORM\Builder
entailment
protected function getDeleteQuery() { $foreign = $this->getAttribute($this->foreignKey); $query = $this->newQuery()->where($this->foreignKey, $foreign); return $query->where($this->otherKey, $this->getAttribute($this->otherKey)); }
Get the query builder for a delete operation on the pivot. @return \Nova\Database\ORM\Builder
entailment
public function getParams(): array { $params = [ 'chat_id' => $this->chatId, 'video' => $this->video, ]; $params = array_merge($params, $this->buildJsonAttributes([ 'duration' => $this->duration, 'width' => $this->width, 'height' => $this->height, 'disable_notification' => $this->disableNotification, 'reply_to_message_id' => $this->replyToMessageId ])); return $params; }
Get parameters for HTTP query. @return mixed
entailment
public function abuseReport($start = 0, $limit = 2000, $string = null) { $payload = array( 'id' => $this->listId, 'start' => $start, 'limit' => $limit, 'string' => $string ); $apiCall = 'lists/abuse-reports'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Get all email addresses that complained about a campaign sent to a list @link http://apidocs.mailchimp.com/api/2.0/lists/abuse-reports.php @param int $start @param int $limit @param string $string @return array @throws MailchimpAPIException
entailment
public function batchSubscribe($batch, $double_optin = true, $update_existing = true, $replace_interests = true) { $payload = array( 'id' => $this->listId, 'batch' => $batch, 'double_optin' => $double_optin, 'update_existing' => $update_existing, 'replace_interests' => $replace_interests, ); $apiCall = 'lists/batch-subscribe'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Subscribe a batch of email addresses to a list at once, These calls are also long, so be sure you increase your timeout values @link http://apidocs.mailchimp.com/api/2.0/lists/batch-subscribe.php @param string $batch - array of arrays with ['email','email_type','merge_vars'] @param boolean $double_optin optional @param boolean $update_existing optional @param boolean $replace_interests optional @return array @throws MailchimpAPIException
entailment
public function batchUnsubscribe($batch, $delete_member = false, $send_goodbye = false, $send_notify = false) { $payload = array( 'id' => $this->listId, 'batch' => $batch, 'delete_member' => $delete_member, 'send_goodbye' => $send_goodbye, 'send_notify' => $send_notify ); $apiCall = 'lists/batch-unsubscribe'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Unsubscribe a batch of email addresses to a list at once, These calls are also long, so be sure you increase your timeout values @link http://apidocs.mailchimp.com/api/2.0/lists/batch-unsubscribe.php @param string $batch - array of arrays with ['email','email_type','merge_vars'] @param boolean $delete_member optionnal @param boolean $send_goodbye optionnal @param boolean $send_notify optionnal @return array @throws MailchimpAPIException
entailment
public function subscribe($email_id, $email_type = 'html', $double_optin = true, $update_existing = true, $replace_interests = true, $send_welcome = false, $email_identifier = 'email') { if (!in_array($email_identifier, array("email", "euid", "leid"))) throw new InvalidArgumentException('email identifier should be one of ("email","euid","leid")'); $payload = array( 'id' => $this->listId, 'email' => array( $email_identifier => $email_id ), 'merge_vars' => $this->merge_vars, 'email_type' => $email_type, 'double_optin' => $double_optin, 'update_existing' => $update_existing, 'replace_interests' => $replace_interests, 'send_welcome' => $send_welcome ); $apiCall = 'lists/subscribe'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Subscribe an email addresses to a list, These calls are also long, so be sure you increase your timeout values @link http://apidocs.mailchimp.com/api/2.0/lists/subscribe.php @param string $email @param string $email_type @param boolean $double_optin optional @param boolean $update_existing optional @param boolean $replace_interests optional @param boolean $send_welcome optional @param string $email_identifier optional can be (email,euid, leid) @return array @throws MailchimpAPIException
entailment
public function unsubscribe($email_id, $delete_member = false, $send_goodbye = true, $send_notify = true, $email_identifier = 'email') { if (!in_array($email_identifier, array("email", "euid", "leid"))) throw new InvalidArgumentException('email identifier should be one of ("email","euid","leid")'); $payload = array( 'id' => $this->listId, 'email' => array( $email_identifier => $email_id ), 'delete_member' => $delete_member, 'send_goodbye' => $send_goodbye, 'send_notify' => $send_notify ); $apiCall = 'lists/unsubscribe'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return true; }
Unsubscribe the given email address from the list @link http://apidocs.mailchimp.com/api/2.0/lists/unsubscribe.php @param string $email_id @param boolean $delete_member @param boolean $send_goodbye @param boolean $send_notify @param string $email_identifier optional can be (email,euid, leid) @return boolean true on success @throws InvalidArgumentException @throws MailchimpAPIException
entailment
public function memberInfo($email_id, $email_identifier = 'email') { if (!in_array($email_identifier, array("email", "euid", "leid"))) throw new InvalidArgumentException('email identifier should be one of ("email","euid","leid")'); $email_ids = array(); if (is_array($email_id)) { foreach ($email_id as $email) { $email_ids[] = array($email_identifier => $email); } } else { $email_ids[] = array($email_identifier => $email_id); } $payload = array( 'id' => $this->listId, 'emails' => $email_ids ); $apiCall = 'lists/member-info'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Get all the information for particular members of a list @link http://apidocs.mailchimp.com/api/2.0/lists/member-info.php @param mix $email_id email id or ids array of emails or string @param string $email_identifier optional can be (email,euid, leid) @return array @throws InvalidArgumentException
entailment
public function members($status = 'subscribed', $opts = null) { $payload = array( 'id' => $this->listId, 'status' => $status ); if (!is_null($opts)) { $payload['opts'] = $opts; } $apiCall = 'lists/members'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Get a list of members for a list @link http://apidocs.mailchimp.com/api/2.0/lists/members.php @param string $status optional 'subscribed', 'unsubscribed', 'cleaned' @param array $opts optional @return array @throws InvalidArgumentException
entailment
public function lists($filters = array(), $start=0, $end=100, $sort_field="created", $sort_dir="DESC") { $payload = array( 'id' => $this->listId, 'filters' => $filters, 'start' => $start, 'end' => $end, 'sort_field' => $sort_field, 'sort_dir' => $sort_dir ); $apiCall = 'lists/list'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Retrieve all of the lists defined for your user account @link http://apidocs.mailchimp.com/api/2.0/lists/list.php @param array $filters optional - filters to apply to this query @param integer $start optional - optional - control paging of lists, start results at this list #, defaults to 1st page of data (page 0) @param integer $end optional - optional - control paging of lists, number of lists to return with each call, defaults to 25 (max=100) @param string $sort_field optional - optional - "created" (the created date, default) or "web" (the display order in the web app). Invalid values will fall back on "created" - case insensitive. @param string $sort_dir optional - optional - "DESC" for descending (default), "ASC" for Ascending. Invalid values will fall back on "created" - case insensitive. Note: to get the exact display order as the web app you'd use "web" and "ASC" @return array lists @throws MailchimpAPIException
entailment
public function updateMember($email_id, $email_type = 'html', $replace_interests = true, $email_identifier = 'email') { if (!in_array($email_identifier, array("email", "euid", "leid"))) throw new InvalidArgumentException('email identifier should be one of ("email","euid","leid")'); $payload = array( 'id' => $this->listId, 'email' => array( $email_identifier => $email_id ), 'merge_vars' => $this->merge_vars, 'email_type' => $email_type, 'replace_interests' => $replace_interests ); $apiCall = 'lists/update-member'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Edit the email address, merge fields, and interest groups for a list member. If you are doing a batch update on lots of users, consider using listBatchSubscribe() with the update_existing and possible replace_interests parameter. @link http://apidocs.mailchimp.com/api/2.0/lists/update-member.php @param string $email_id optinal @param string $email_type optional can be "html" or "text", defaults "html" @param boolean $replace_interests optional @param string $email_identifier optional can be (email,euid, leid) @return array email information (email,euid, leid) @throws InvalidArgumentException @throws MailchimpAPIException
entailment
public function interestGroupings($count = null) { $payload = array( 'id' => $this->listId, 'count' => $count ); $apiCall = 'lists/interest-groupings'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Get the list of interest groupings for a given list, including the label, form information, and included groups for each @link http://apidocs.mailchimp.com/api/2.0/lists/interest-groupings.php @param bool $count optional wether to get subscriber count or not @return array all groups information for specific list @throws MailchimpAPIException
entailment
public function addInterestGroupings($name, $type, array $groups) { $payload = array( 'id' => $this->listId, 'name' => $name, 'type' => $type, 'groups' => $groups ); $apiCall = 'lists/interest-grouping-add'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Add a new Interest Grouping - if interest groups for the List are not yet enabled, adding the first grouping will automatically turn them on. @link http://apidocs.mailchimp.com/api/2.0/lists/interest-grouping-add.php @param string $name the interest grouping to add - grouping names must be unique @param string $type The type of the grouping to add - one of "checkboxes", "hidden", "dropdown", "radio" @param array $groups The lists of initial group names to be added - at least 1 is required and the names must be unique within a grouping. If the number takes you over the 60 group limit @return array contains id of the new group @throws MailchimpAPIException
entailment
public function delInterestGrouping($group_id = false) { $payload = array( 'grouping_id' => (FALSE === $group_id) ? $this->grouping_id : $group_id ); $apiCall = 'lists/interest-grouping-del'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return true; }
Delete an existing Interest Grouping - this will permanently delete all contained interest groups and will remove those selections from all list members @link http://apidocs.mailchimp.com/api/2.0/lists/interest-grouping-del.php @param int $group_id optional the interest grouping id @return boolean true on success @throws MailchimpAPIException
entailment
public function updateInterestGrouping($name, $value, $group_id = false) { $payload = array( 'grouping_id' => (FALSE === $group_id) ? $this->grouping_id : $group_id, 'name' => $name, 'value' => $value ); $apiCall = 'lists/interest-grouping-update'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return true; }
Update an existing Interest Grouping @link http://apidocs.mailchimp.com/api/2.0/lists/interest-grouping-update.php @param string $name The name of the field to update - either "name" or "type". Groups within the grouping should be manipulated using the standard listInterestGroup* methods @param string $value The new value of the field. Grouping names must be unique - only "hidden" and "checkboxes" grouping types can be converted between each other. @param int $group_id optional unless not has been set before @return boolean true on success @throws MailchimpAPIException
entailment
public function addInterestGroup($name, $group_id = NULL) { $payload = array( 'id' => $this->listId, 'group_name' => $name, 'grouping_id' => (NULL === $group_id) ? $this->grouping_id : $group_id, ); $apiCall = 'lists/interest-group-add'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return true; }
Add a single Interest Group - if interest groups for the List are not yet enabled, adding the first group will automatically turn them on. @link http://apidocs.mailchimp.com/api/2.0/lists/interest-group-add.php @param string $name the interest group to add - group names must be unique within a grouping @param int $group_id optional The grouping to add the new group to - get using listInterestGrouping() . If not supplied, the first grouping on the list is used. @return boolean true on success @throws MailchimpAPIException
entailment
public function updateInterestGroup($old_name, $new_name, $grouping_id = NULL) { $payload = array( 'id' => $this->listId, 'old_name' => $old_name, 'new_name' => $new_name, 'grouping_id' => (NULL === $grouping_id) ? $this->grouping_id : $grouping_id ); $apiCall = 'lists/interest-group-update'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return true; }
Change the name of an Interest Group @link http://apidocs.mailchimp.com/api/2.0/lists/interest-group-update.php @param string $old_name the interest group name to be changed @param string $new_name the new interest group name to be set @param int $grouping_id optional The grouping to delete the group from If not supplied, the first grouping on the list is used. @return boolean true on success @throws MailchimpAPIException
entailment
public function addStaticSegment($name) { $payload = array( 'id' => $this->listId, 'name' => $name, ); $apiCall = 'lists/static-segment-add'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data['id']) ? $data['id'] : false; }
Save a segment against a list for later use. - no limit After creating the segment, add members with addMembersStaticSegment @link http://apidocs.mailchimp.com/api/2.0/lists/static-segment-members-add.php @param $name - Name of segment @return bool/int - ID of new segment @throws MailchimpAPIException
entailment
public function addMembersStaticSegment($seg_id, $batch) { $payload = array( 'id' => $this->listId, 'seg_id' => $seg_id, 'batch' => $batch ); $apiCall = 'lists/static-segment-members-add'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Save members to a static segment @link http://apidocs.mailchimp.com/api/2.0/lists/static-segment-members-add.php @param $seg_id @param $batch - array of emails and uuid @return bool @throws MailchimpAPIException
entailment
public function listStaticSegments() { $payload = array( 'id' => $this->listId, ); $apiCall = 'lists/static-segments'; $data = $this->requestMonkey($apiCall, $payload); $data = json_decode($data, true); if (isset($data['error'])) throw new MailchimpAPIException($data); else return isset($data) ? $data : false; }
Retrieve all of the Static Segments for a list. @link http://apidocs.mailchimp.com/api/2.0/lists/static-segments.php @return bool|mixed @throws \Hype\MailchimpBundle\Mailchimp\MailchimpAPIException
entailment
public function getParams(): array { $params = []; if ($this->chatId !== null) { $params['chat_id'] = $this->chatId; } if ($this->messageId) { $params['message_id'] = $this->messageId; } if ($this->inlineMessageId !== null) { $params['inline_message_id'] = $this->inlineMessageId; } return $params; }
Get parameters for HTTP query. @return mixed
entailment
protected function compileCreateEncoding($sql, Connection $connection) { if (! is_null($charset = $connection->getConfig('charset'))) { $sql .= ' default character set '.$charset; } if (! is_null($collation = $connection->getConfig('collation'))) { $sql .= ' collate '.$collation; } return $sql; }
Append the character set specifications to a command. @param string $sql @param \Nova\Database\Connection $connection @return string
entailment
public function register() { $this->app->bindShared('packages', function ($app) { $repository = new Repository($app['config'], $app['files']); return new PackageManager($app, $repository); }); }
Register the Service Provider.
entailment
public function handle($request, Closure $next) { if (!app()->bound(Tenant::class)) { app()->bind(Tenant::class, config('artify.tenant')); } optional($this->resolveTenant(session('tenant') ?? $request->tenant), function ($tenant) use ($request) { if (!auth()->user()->{str_plural(app(Tenant::class)->getTable())}->contains('id', $tenant->id)) { throw new AuthenticationException( 'Unauthenticated.', [], $this->redirectTo($request) ); } event(new TenantIdentified($tenant)); }); return $next($request); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
public function build(ContainerBuilder $container) { parent::build($container); // Add all resource paths to keep them handy. $container->setParameter('cca.legacy_dic', $this->getResourcePaths($container)); }
{@inheritDoc}
entailment
private function getResourcePaths(ContainerBuilder $container) { $paths = []; $rootDir = dirname($container->getParameter('kernel.root_dir')); foreach ($container->getParameter('kernel.bundles') as $name => $class) { if (null !== ($path = $this->getResourcePathFromBundle($rootDir, $name, $class))) { $paths[] = $path; } } if (is_readable($rootDir . '/app/Resources/contao/config/services.php')) { $paths[] = $rootDir . '/app/Resources/contao/config/services.php'; } if (is_readable($rootDir . '/system/config/services.php')) { $paths[] = $rootDir . '/system/config/services.php'; } return $paths; }
Returns the Contao resources paths as array. @param ContainerBuilder $container The container builder. @return array
entailment
private function getResourcePathFromClassName($class) { $reflection = new \ReflectionClass($class); if (is_dir($dir = dirname($reflection->getFileName()).'/Resources/contao')) { return $dir; } return null; }
Returns the resources path from the class name. @param string $class The class name of the bundle. @return string|null
entailment
protected function startSession(Request $request) { $session = $this->manager->driver(); $session->setId( $this->getSessionId($request, $session) ); $session->setRequestOnHandler($request); $session->start(); return $session; }
Start the session for the given request. @param \Nova\Http\Request $request @return \Nova\Session\SessionInterface
entailment
protected function getSessionId(Request $request, SessionInterface $session) { $name = $session->getName(); return $request->cookies->get($name); }
Get the session ID from the request. @param \Nova\Http\Request $request @param \Nova\Session\SessionInterface $session @return string|null
entailment
protected function collectGarbage(SessionInterface $session) { $config = $this->getSessionConfig(); if ($this->configHitsLottery($config)) { $lifetime = Arr::get($config, 'lifetime', 180); $session->getHandler()->gc($lifetime * 60); } }
Remove the garbage from the session if necessary. @param \Nova\Session\SessionInterface $session @return void
entailment
protected function configHitsLottery(array $config) { list ($trigger, $max) = $config['lottery']; $value = mt_rand(1, $max); return ($value <= $trigger); }
Determine if the configuration odds hit the lottery. @param array $config @return bool
entailment
protected function addCookieToResponse(Response $response, SessionInterface $session) { if ($this->usingCookieSessions()) { $this->manager->driver()->save(); } $config = $this->getSessionConfig(); if ($this->sessionIsPersistent($config)) { $cookie = $this->createCookie($config, $session); $response->headers->setCookie($cookie); } }
Add the session cookie to the application response. @param \Symfony\Component\HttpFoundation\Response $response @param \Nova\Session\SessionInterface $session @return void
entailment
protected function createCookie(array $config, SessionInterface $session) { $expireOnClose = Arr::get($config, 'expireOnClose', false); if ($expireOnClose !== false) { $lifetime = Arr::get($config, 'lifetime', 180); $expire = Carbon::now()->addMinutes($lifetime); } else { $expire = 0; } $secure = Arr::get($config, 'secure', false); return new Cookie( $session->getName(), $session->getId(), $expire, $config['path'], $config['domain'], $secure ); }
Create a Cookie instance for the specified Session and configuration. @param array $config @param \Nova\Session\SessionInterface $session @return \Symfony\Component\HttpFoundation\Cookie
entailment
protected function sessionIsPersistent(array $config = null) { if (is_null($config)) { $config = $this->getSessionConfig(); } return ! in_array($config['driver'], array(null, 'array')); }
Determine if the configured session driver is persistent. @param array|null $config @return bool
entailment
protected function usingCookieSessions() { if (! $this->sessionConfigured()) { return false; } $session = $this->manager->driver(); // $handler = $session->getHandler(); return ($handler instanceof CookieSessionHandler); }
Determine if the session is using cookie sessions. @return bool
entailment
public function send(Swift_Mime_Message $message, &$failedRecipients = null) { $this->logger->debug($this->getMimeEntityString($message)); }
{@inheritdoc}
entailment
public function dispatch(SymfonyRequest $request) { if (! is_null($route = $this->findRoute($request))) { list($callback, $parameters) = $route; array_unshift($parameters, $request); return call_user_func_array($callback, $parameters); } }
Dispatch a Assets File Response. For proper Assets serving, the file URI should be either of the following: /assets/css/style.css /plugins/blog/assets/css/style.css @return \Symfony\Component\HttpFoundation\Response|null
entailment
protected function findRoute(Request $request) { if (! in_array($request->method(), array('GET', 'HEAD', 'OPTIONS'))) { return; } $uri = $request->path(); foreach ($this->routes as $pattern => $callback) { if (preg_match('#^' .$pattern .'$#s', $uri, $matches)) { return array($callback, array_slice($matches, 1)); } } }
Dispatch an URI and return the associated file path. @param string $uri @return string|null
entailment
public function serve($path, SymfonyRequest $request, $disposition = 'inline', $fileName = null, $prepared = true) { if (! file_exists($path)) { return new Response('File Not Found', 404); } else if (! is_readable($path)) { return new Response('Unauthorized Access', 403); } // Create a Binary File Response instance. $headers = array( 'Access-Control-Allow-Origin' => '*', ); $mimeType = $this->guessMimeType($path); if ($request->getMethod() == 'OPTIONS') { $headers = array_merge($headers, array( 'Access-Control-Allow-Methods' => 'GET, HEAD, OPTIONS', 'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin', )); return new Response('OK', 200, $headers); } // Not an OPTIONS request. else { $headers['Content-Type'] = $mimeType; } if ($mimeType !== 'application/json') { $response = new BinaryFileResponse($path, 200, $headers, true, $disposition, true, false); // Set the Content Disposition. $response->setContentDisposition($disposition, $fileName ?: basename($path)); // Setup the (browser) Cache Control. $this->setupCacheControl($response); // Setup the Not Modified since... $response->isNotModified($request); } else { // We will do a special processing for the JSON files. $response = new JsonResponse( json_decode(file_get_contents($path), true), 200, $headers ); } // Prepare the Response against the Request instance, if is requested. if ($prepared) { return $response->prepare($request); } return $response; }
Serve a File. @param string $path @param \Symfony\Component\HttpFoundation\Request $request @param string $disposition @param string|null $fileName @param bool $prepared @return \Symfony\Component\HttpFoundation\Response
entailment
protected function getPackagePath($env, $package, $group) { $file = str_replace('/', DS, "Packages/{$package}/{$env}/{$group}.php"); return $this->defaultPath .DS .$file; }
Get the Package path for an environment and group. @param string $env @param string $package @param string $group @return string
entailment
public function group(string $prefix, \Closure $callback, array $opts = []) { $previousGroupPrefix = $this->currentGroupPrefix; $this->currentGroupPrefix = $previousGroupPrefix . '/' . \trim($prefix, '/'); $previousGroupOption = $this->currentGroupOption; $this->currentGroupOption = $opts; $callback($this); $this->currentGroupPrefix = $previousGroupPrefix; $this->currentGroupOption = $previousGroupOption; }
Create a route group with a common prefix. All routes created in the passed callback will have the given group prefix prepended. @ref package 'nikic/fast-route' @param string $prefix @param \Closure $callback @param array $opts
entailment
public function validateArguments($methods, $handler): array { if (!$methods || !$handler) { throw new \InvalidArgumentException('The method and route handler is not allow empty.'); } $allow = self::ALLOWED_METHODS_STR . ','; $hasAny = false; $methods = \array_map(function ($m) use ($allow, &$hasAny) { $m = \strtoupper(trim($m)); if (!$m || false === \strpos($allow, $m . ',')) { throw new \InvalidArgumentException("The method [$m] is not supported, Allow: " . trim($allow, ',')); } if (!$hasAny && $m === self::ANY) { $hasAny = true; } return $m; }, (array)$methods); return $hasAny ? self::ALLOWED_METHODS : $methods; }
validate and format arguments @param string|array $methods @param mixed $handler @return array @throws \InvalidArgumentException
entailment
public function parseParamRoute(string $route, array $params, array $conf): array { $bak = $route; $noOptional = null; // 解析可选参数位 if (false !== ($pos = \strpos($route, '['))) { // $hasOptional = true; $noOptional = \substr($route, 0, $pos); $withoutClosingOptionals = rtrim($route, ']'); $optionalNum = \strlen($route) - \strlen($withoutClosingOptionals); if ($optionalNum !== \substr_count($withoutClosingOptionals, '[')) { throw new \LogicException('Optional segments can only occur at the end of a route'); } // '/hello[/{name}]' -> '/hello(?:/{name})?' $route = \str_replace(['[', ']'], ['(?:', ')?'], $route); } // quote '.','/' to '\.','\/' if (false !== \strpos($route, '.')) { // $route = preg_quote($route, '/'); $route = \str_replace('.', '\.', $route); } // 解析参数,替换为对应的 正则 if (\preg_match_all('#\{([a-zA-Z_][a-zA-Z0-9_-]*)\}#', $route, $m)) { /** @var array[] $m */ $replacePairs = []; foreach ($m[1] as $name) { $key = '{' . $name . '}'; $regex = $params[$name] ?? self::DEFAULT_REGEX; // 将匹配结果命名 (?P<arg1>[^/]+) $replacePairs[$key] = '(?P<' . $name . '>' . $regex . ')'; // $replacePairs[$key] = '(' . $regex . ')'; } $route = \strtr($route, $replacePairs); } // 分析路由字符串是否是有规律的 $first = null; $conf['regex'] = '#^' . $route . '$#'; // first node is a normal string // e.g '/user/{id}' first: 'user', '/a/{post}' first: 'a' if (\preg_match('#^/([\w-]+)/[\w-]*/?#', $bak, $m)) { $first = $m[1]; $conf['start'] = $m[0]; return [$first, $conf]; } // first node contain regex param '/hello[/{name}]' '/{some}/{some2}/xyz' $include = null; if ($noOptional) { if (\strpos($noOptional, '{') === false) { $include = $noOptional; } else { $bak = $noOptional; } } if (!$include && \preg_match('#/([\w-]+)/?[\w-]*#', $bak, $m)) { $include = $m[0]; } $conf['include'] = $include; return [$first, $conf]; }
parse param route @param string $route @param array $params @param array $conf @return array @throws \LogicException
entailment
public static function convertNodeStr($str): string { $str = \trim($str, '-'); // convert 'first-second' to 'firstSecond' if (\strpos($str, '-')) { $str = (string)\preg_replace_callback('/-+([a-z])/', function ($c) { return \strtoupper($c[1]); }, \trim($str, '- ')); } return $str; }
convert 'first-second' to 'firstSecond' @param string $str @return string
entailment
public function handle() { if (file_exists($publicPath = public_path('assets'))) { return $this->error('The "webroot/assets" directory already exists.'); } $assetsPath = $this->container['config']->get('routing.assets.path', base_path('assets')); $this->container->make('files')->link( $assetsPath, $publicPath ); $this->info('The [webroot/assets] directory has been linked.'); }
Execute the console command. @return void
entailment
public function addConstraints() { if (static::$constraints) { $table = $this->related->getTable(); $this->query->where($table.'.'.$this->otherKey, '=', $this->parent->{$this->foreignKey}); } }
Set the base constraints on the relation query. @return void
entailment
public function getRelationCountQuery(Builder $query, Builder $parent) { $query->select(new Expression('count(*)')); $otherKey = $this->wrap($query->getModel()->getTable().'.'.$this->otherKey); return $query->where($this->getQualifiedForeignKey(), '=', new Expression($otherKey)); }
Add the constraints for a relationship count query. @param \Nova\Database\ORM\Builder $query @param \Nova\Database\ORM\Builder $parent @return \Nova\Database\ORM\Builder
entailment
protected function getEagerModelKeys(array $models) { $keys = array(); foreach ($models as $model) { if (! is_null($value = $model->{$this->foreignKey})) { $keys[] = $value; } } if (count($keys) == 0) { return array(0); } return array_values(array_unique($keys)); }
Gather the keys from an array of related models. @param array $models @return array
entailment
public function match(array $models, Collection $results, $relation) { $foreign = $this->foreignKey; $other = $this->otherKey; $dictionary = array(); foreach ($results as $result) { $dictionary[$result->getAttribute($other)] = $result; } foreach ($models as $model) { if (isset($dictionary[$model->$foreign])) { $model->setRelation($relation, $dictionary[$model->$foreign]); } } return $models; }
Match the eagerly loaded results to their parents. @param array $models @param \Nova\Database\ORM\Collection $results @param string $relation @return array
entailment
public function associate(Model $model) { $this->parent->setAttribute($this->foreignKey, $model->getAttribute($this->otherKey)); return $this->parent->setRelation($this->relation, $model); }
Associate the model instance to the given parent. @param \Nova\Database\ORM\Model $model @return \Nova\Database\ORM\Model
entailment
public function dissociate() { $this->parent->setAttribute($this->foreignKey, null); return $this->parent->setRelation($this->relation, null); }
Dissociate previously associated model from the given parent. @return \Nova\Database\ORM\Model
entailment
protected function getContainer() { if (!isset($GLOBALS['container'])) { $GLOBALS['container'] = new PimpleGate([], $this->getSymfonyContainer()); } $container = $GLOBALS['container']; if (!$container instanceof PimpleGate) { throw new \RuntimeException( 'Dependency container is incompatible class. Expected PimpleGate but found ' . get_class($container), 1 ); } return $container; }
Get the currently defined global container or create it if no container is present so far. @return PimpleGate @throws \RuntimeException When an incompatible DIC is encountered. @SuppressWarnings(PHPMD.Superglobals) @SuppressWarnings(PHPMD.CamelCaseVariableName)
entailment
private function getSymfonyContainer() { // 1. Preferred way in contao 4.0+ if (method_exists('Contao\System', 'getContainer') && ($container = System::getContainer()) instanceof ContainerInterface ) { return $container; } // 2. Fallback to fetch from kernel. if (isset($GLOBALS['kernel']) && $GLOBALS['kernel'] instanceof KernelInterface && ($container = $GLOBALS['kernel']->getContainer()) instanceof ContainerInterface ) { return $container; } // 3. Nothing worked out, throw Exception as this may never happen. throw new \RuntimeException('Could not obtain symfony container.'); }
Determine the symfony container. @return ContainerInterface|null @throws \RuntimeException When the container can not be obtained. @SuppressWarnings(PHPMD.Superglobals) @SuppressWarnings(PHPMD.CamelCaseVariableName)
entailment
protected function callHooks(PimpleGate $container) { if (isset($GLOBALS['TL_HOOKS']['initializeDependencyContainer']) && is_array($GLOBALS['TL_HOOKS']['initializeDependencyContainer']) ) { foreach ($GLOBALS['TL_HOOKS']['initializeDependencyContainer'] as $callback) { if (is_array($callback)) { $class = new \ReflectionClass($callback[0]); if (!$class->hasMethod($callback[1])) { if ($class->hasMethod('__call')) { $method = $class->getMethod('__call'); $args = [$callback[1], $container]; } else { throw new \InvalidArgumentException( sprintf('No such Method %s::%s', $callback[0], $callback[1]) ); } } else { $method = $class->getMethod($callback[1]); $args = [$container]; } $object = null; if (!$method->isStatic()) { $object = $this->getInstanceOf($callback[0]); } $method->invokeArgs($object, $args); } else { call_user_func($callback, $container); } } } }
Call the initialization hooks. @param PimpleGate $container The container that got initialized. @return void @throws \InvalidArgumentException When the hook method is invalid. @SuppressWarnings(PHPMD.Superglobals) @SuppressWarnings(PHPMD.CamelCaseVariableName)
entailment
private function loadServiceConfigurations(PimpleGate $container) { $paths = $container->getSymfonyParameter('cca.legacy_dic'); // include the module services configurations foreach ($paths as $file) { require_once $file; } }
Load all services files. @param PimpleGate $container The DIC to populate. @return void @SuppressWarnings(PHPMD.UnusedFormalParameter)
entailment
public function init() { // Retrieve the default service container. $container = $this->getContainer(); // Now load the additional service configurations. $this->loadServiceConfigurations($container); // Finally call the HOOKs to allow additional handling. $this->callHooks($container); }
Init the global dependency container. @return void
entailment
public function dispatch(Route $route, $controller, $method) { $parameters = $this->resolveClassMethodDependencies( $route->parametersWithoutNulls(), $controller, $method ); if (method_exists($controller, 'callAction')) { return $controller->callAction($method, $parameters); } return call_user_func_array(array($controller, $method), $parameters); }
Dispatch a request to a given controller and method. @param \Nova\Routing\Route $route @param mixed $controller @param string $method @return mixed
entailment
public static function getMiddleware($controller, $method) { if (! method_exists($controller, 'getMiddleware')) { return array(); } $results = array(); foreach ($controller->getMiddleware() as $middleware => $options) { if (static::methodExcludedByOptions($method, $options)) { continue; } $results[] = $middleware; } return $results; }
Get the middleware for the controller instance. @param \Nova\Routing\Controller $controller @param string $method @return array
entailment
protected function getValidatorInstance() { $factory = $this->container->make(ValidationFactory::class); if (method_exists($this, 'validator')) { return $this->container->call(array($this, 'validator'), compact('factory')); } $rules = $this->container->call(array($this, 'rules')); return $factory->make($this->all(), $rules, $this->messages(), $this->attributes()); }
Get the validator instance for the request. @return \Nova\Validation\Validator
entailment
public function response(array $errors) { if ($this->ajax() || $this->wantsJson()) { return new JsonResponse($errors, 422); } return $this->redirector->to($this->getRedirectUrl()) ->withInput($this->except($this->dontFlash)) ->withErrors($errors, $this->errorBag); }
Get the proper failed validation response for the request. @param array $errors @return \Symfony\Component\HttpFoundation\Response
entailment
public function read($sessionId) { $session = (object) $this->getQuery()->find($sessionId); if (isset($session->payload)) { $this->exists = true; return base64_decode($session->payload); } }
{@inheritDoc}
entailment
protected function getSerializedPropertyValue($value) { return ($value instanceof QueueableEntityInterface) ? new ModelIdentifier(get_class($value), $value->getQueueableId()) : $value; }
Get the property value prepared for serialization. @param mixed $value @return mixed
entailment
protected function getRestoredPropertyValue($value) { return ($value instanceof ModelIdentifier) ? (new $value->class)->newQuery()->findOrFail($value->id) : $value; }
Get the restored property value after deserialization. @param mixed $value @return mixed
entailment
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { // Fix Chrome ico request bug if ($request->getUri()->getPath() === '/favicon.ico') { throw new NotAcceptableException('access favicon.ico'); } // Parser /* @var \Swoft\Http\Server\Parser\RequestParserInterface $requestParser */ $requestParser = App::getBean('requestParser'); $request = $requestParser->parse($request); // Router $request = $this->handleRouter($request); // Delegate to next handler $response = $handler->handle($request); // Power by $response = $response->withAddedHeader('X-Powered-By', 'Swoft'); // Response handler, according to Accept $response = $this->handleAccept($request, $response); return $response; }
Process an incoming server request and return a response, optionally delegating response creation to a handler. @param \Psr\Http\Message\ServerRequestInterface $request @param \Psr\Http\Server\RequestHandlerInterface $handler @return \Psr\Http\Message\ResponseInterface @throws \Swoft\Http\Server\Exception\NotAcceptableException @throws \InvalidArgumentException
entailment
protected function createPayload($job, $data = '', $queue = null) { if ($job instanceof Closure) { $payload = $this->createClosurePayload($job, $data); } else if (is_object($job)) { $payload = $this->createObjectPayload($job, $data); } else { $payload = array( 'job' => $job, 'data' => $this->prepareQueueableEntities($data), ); } return json_encode($payload); }
Create a payload string from the given job and data. @param string $job @param mixed $data @param string $queue @return string
entailment
protected function prepareQueueableEntities($data) { if ($data instanceof QueueableEntityInterface) { return $this->prepareQueueableEntity($data); } if (! is_array($data)) { return $data; } return array_map(function ($d) { if (is_array($d)) { return $this->prepareQueueableEntities($d); } return $this->prepareQueueableEntity($d); }, $data); }
Prepare any queueable entities for storage in the queue. @param mixed $data @return mixed
entailment
protected function createObjectPayload($job, $data) { $commandName = get_class($job); $command = serialize(clone $job); return array( 'job' => 'Nova\Queue\CallQueuedHandler@call', 'data' => compact('commandName', 'command'), ); }
Create a payload string for the given Closure job. @param object $job @param mixed $data @return string
entailment
protected function setMeta($payload, $key, $value) { $payload = json_decode($payload, true); return json_encode(array_set($payload, $key, $value)); }
Set additional meta on a payload string. @param string $payload @param string $key @param string $value @return string
entailment
protected function getSeconds($delay) { if ($delay instanceof DateTime) { return max(0, $delay->getTimestamp() - $this->getTime()); } return (int) $delay; }
Calculate the number of seconds with the given delay. @param \DateTime|int $delay @return int
entailment
protected function doExecute(Profile $profile, InputInterface $input, OutputInterface $output) { foreach ($profile->getDestinations() as $destination) { $this->listBackups($destination, $output); } }
{@inheritdoc}
entailment
public function getParams(): array { $params = [ 'chat_id' => $this->chatId, 'latitude' => $this->latitude, 'longitude' => $this->longitude ]; if ($this->disableNotification !== null) { $params['disable_notification'] = (int)$this->disableNotification; } if ($this->replyToMessageId) { $params['reply_to_message_id'] = $this->replyToMessageId; } return $params; }
Get parameters for HTTP query. @return mixed
entailment
public function handle() { $package = $this->input->getArgument('package'); // Direct specification of the package and Views path. if (! is_null($path = $this->getPath())) { $this->publisher->publish($package, $path); } // For the packages which are registered as plugins. else if ($this->plugins->exists($package)) { if (Str::length($package) > 3) { $slug = Str::snake($package); } else { $slug = Str::lower($package); } $properties = $this->plugins->where('slug', $slug); // $package = $properties['name']; if ($properties['type'] == 'package') { $path = $properties['path'] .str_replace('/', DS, '/src/Views'); } else { $path = $properties['path'] .DS . 'Views'; } $this->publisher->publish($package, $path); } // For other packages located in vendor. else { $this->publisher->publishPackage($package); } $this->output->writeln('<info>Views published for package:</info> '.$package); }
Execute the console command. @return void
entailment
protected function getPath() { $path = $this->input->getOption('path'); if (! is_null($path)) { return $this->container['path.base'] .DS .$path; } }
Get the specified path to the files. @return string
entailment
protected function publishAssets($package) { if (! $this->dispatcher->hasNamespace($package)) { return $this->error('Package does not exist.'); } if ( ! is_null($path = $this->getPath())) { $this->publisher->publish($package, $path); } else { $path = $this->dispatcher->getPackagePath($package); $this->publisher->publishPackage($package, $path); } $this->output->writeln('<info>Assets published for package:</info> ' .$package); }
Publish the assets for a given package name. @param string $package @return void
entailment
protected function getPackages() { if (! is_null($package = $this->input->getArgument('package'))) { if (Str::length($package) > 3) { $package = Str::snake($package, '-'); } else { $package = Str::lower($package); } return array($package); } return $this->findAllAssetPackages(); }
Get the name of the package being published. @return array
entailment
protected function findAllAssetPackages() { $packages = array(); // $namespaces = $this->dispatcher->getHints(); foreach ($namespaces as $name => $hint) { $packages[] = $name; } return $packages; }
Find all the asset hosting packages in the system. @return array
entailment
function jsonSerialize() { $result = [ 'remove_keyboard' => $this->removeKeyboard ]; if ($this->selective !== null) { $result['selective'] = $this->selective; } return $result; }
Specify data which should be serialized to JSON
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder('sonata_timeline'); // Keep compatibility with symfony/config < 4.2 if (!method_exists($treeBuilder, 'getRootNode')) { $rootNode = $treeBuilder->root('sonata_timeline'); } else { $rootNode = $treeBuilder->getRootNode(); } $supportedManagerTypes = ['orm', 'mongodb']; $rootNode ->children() ->scalarNode('manager_type') ->defaultValue('orm') ->validate() ->ifNotInArray($supportedManagerTypes) ->thenInvalid('The manager type %s is not supported. Please choose one of '.json_encode($supportedManagerTypes)) ->end() ->end() ->arrayNode('class') ->beforeNormalization() ->ifTrue(static function ($v) { return isset($v['actionComponent']); }) ->then(static function ($v) { $v['action_component'] = $v['actionComponent']; unset($v['actionComponent']); return $v; }) ->end() ->children() ->scalarNode('component')->defaultValue('%spy_timeline.class.component%')->cannotBeEmpty()->end() // NEXT_MAJOR: Remove this key ->scalarNode('actionComponent')->end() ->scalarNode('action_component')->defaultValue('%spy_timeline.class.action_component%')->cannotBeEmpty()->end() // fix the actionComponent deprecated parameter ... ->scalarNode('action')->defaultValue('%spy_timeline.class.action%')->cannotBeEmpty()->end() ->scalarNode('timeline')->defaultValue('%spy_timeline.class.timeline%')->cannotBeEmpty()->end() // NEXT_MAJOR: Change this to App\Entity\User ->scalarNode('user')->defaultValue('%sonata.user.admin.user.entity%')->cannotBeEmpty()->end() ->end() ->end() ->end(); return $treeBuilder; }
{@inheritdoc}
entailment
public function render($size, array $parts) { ArgumentChecker::check($size, 'integer'); $this->calculateTotal($parts); $this->size = $size; $this->parts = $parts; $r = ''; foreach ($parts as $color => $x) { $bars = $this->valueToBars($x); $r .= $this->colorSpaces($bars, $color); } $r = $this->fillToSize($r); return $r; }
Render the progress bar. @param integer $size The width (in column/characters of the progress bar). @param array $parts The individual [color => value] that make up the progress bar. @return string
entailment
public function user() { // If we've already retrieved the user for the current request we can just // return it back immediately. We do not want to fetch the user data on // every call to this method because that would be tremendously slow. if (! is_null($this->user)) { return $this->user; } return $this->user = call_user_func($this->callback, $this->request); }
Get the currently authenticated user. @return \Nova\Auth\UserInterface|null
entailment
public function user() { // If we've already retrieved the user for the current request we can just // return it back immediately. We do not want to fetch the user data on // every call to this method because that would be tremendously slow. if (! is_null($this->user)) { return $this->user; } $user = null; $token = $this->getTokenForRequest(); if (! empty($token)) { $user = $this->provider->retrieveByCredentials( array($this->storageKey => $token) ); } return $this->user = $user; }
Get the currently authenticated user. @return \Nova\Auth\UserInterface|null
entailment
public function createUserService() { $config = $this->container->get('cca.legacy_dic.contao_config'); // Work around the fact that \Contao\Database::getInstance() always creates an instance, // even when no driver is configured (Database and Config are being imported into the user class and there- // fore causing an fatal error). if (!$config->get('dbDatabase')) { throw new \RuntimeException('Contao Database is not properly configured.'); } $matcher = $this->container->get('contao.routing.scope_matcher'); $request = $this->container->get('request_stack')->getCurrentRequest(); // NULL request => CLI mode. if ((null === $request) || $matcher->isBackendRequest($request)) { return $this->container->get('contao.framework')->createInstance(BackendUser::class); } if ($matcher->isFrontendRequest($request)) { return $this->container->get('contao.framework')->createInstance(FrontendUser::class); } throw new \RuntimeException('Unknown TL_MODE encountered', 1); }
Create the user service for contao user. @return BackendUser|FrontendUser @throws \RuntimeException Throw an exception if contao mode not defined.
entailment
public function createPageProviderService() { $pageProvider = new PageProvider(); if (isset($GLOBALS['TL_HOOKS']['getPageLayout']) && is_array($GLOBALS['TL_HOOKS']['getPageLayout'])) { array_unshift( $GLOBALS['TL_HOOKS']['getPageLayout'], [PageProvider::class, 'setPage'] ); } else { $GLOBALS['TL_HOOKS']['getPageLayout'] = [[PageProvider::class, 'setPage']]; } return $pageProvider; }
Create the page provider service for provide the current active page model. @return PageProvider @SuppressWarnings(PHPMD.Superglobals)
entailment
public function register() { $this->app->bindShared('command.session.database', function($app) { return new Console\SessionTableCommand($app['files']); }); $this->commands('command.session.database'); }
Register the service provider. @return void
entailment
public function doHandler(ServerRequestInterface $request, array $routeInfo) { /** * @var int $status * @var string $path * @var array $info */ list($status, $path, $info) = $routeInfo; // not founded route if ($status === HandlerMapping::NOT_FOUND) { throw new RouteNotFoundException('Route not found for ' . $path); } // method not allowed if ($status === HandlerMapping::METHOD_NOT_ALLOWED) { throw new MethodNotAllowedException(sprintf( "Method '%s' not allowed for access %s, Allow: %s", $request->getMethod(), $path, \implode(',', $routeInfo[2]) )); } // handler info list($handler, $matches) = $this->createHandler($path, $info); if (\is_array($handler)) { $handler = $this->defaultHandler($handler); } // execute handler $params = $this->bindParams($request, $handler, $matches); $response = PhpHelper::call($handler, $params); // response if (!$response instanceof Response) { /* @var Response $newResponse*/ $newResponse = RequestContext::getResponse(); // if is Payload if ($response instanceof Payload) { $response = $newResponse ->withStatus($response->getStatus()) ->withAttribute(AttributeEnum::RESPONSE_ATTRIBUTE , $response->data); } else { $response = $newResponse->withAttribute(AttributeEnum::RESPONSE_ATTRIBUTE , $response); } } return $response; }
Execute handler with controller and action @param ServerRequestInterface $request request object @param array $routeInfo handler info @return Response @throws \Swoft\Exception\InvalidArgumentException @throws \InvalidArgumentException @throws \Swoft\Http\Server\Exception\MethodNotAllowedException @throws \Swoft\Http\Server\Exception\RouteNotFoundException @throws \ReflectionException
entailment
public function createHandler(string $path, array $info): array { $handler = $info['handler']; $matches = $info['matches'] ?? []; // is a \Closure or a callable object if (\is_object($handler)) { return [$handler, $matches]; } // is array ['controller', 'action'] if (\is_array($handler)) { $segments = $handler; } elseif (\is_string($handler)) { // e.g `Controllers\Home@index` Or only `Controllers\Home` $segments = explode('@', trim($handler)); } else { App::error('Invalid route handler for URI: ' . $path); throw new \InvalidArgumentException('Invalid route handler for URI: ' . $path); } $action = ''; $className = $segments[0]; if (isset($segments[1])) { // Already assign action $action = $segments[1]; } elseif (isset($matches[0])) { // use dynamic action $action = array_shift($matches); } $action = HandlerMapping::convertNodeStr($action); $controller = App::getBean($className); $handler = [$controller, $action]; // Set Controller and Action info to Request Context RequestContext::setContextData([ 'controllerClass' => $className, 'controllerAction' => $action ?: 'index', ]); return [$handler, $matches]; }
Create handler @param string $path url path @param array $info path info @return array @throws \InvalidArgumentException
entailment
private function bindParams(ServerRequestInterface $request, $handler, array $matches): array { if (\is_array($handler)) { list($controller, $method) = $handler; $reflectMethod = new \ReflectionMethod($controller, $method); $reflectParams = $reflectMethod->getParameters(); } else { $reflectMethod = new \ReflectionFunction($handler); $reflectParams = $reflectMethod->getParameters(); } $bindParams = []; // Binding params foreach ($reflectParams as $key => $reflectParam) { $reflectType = $reflectParam->getType(); $name = $reflectParam->getName(); // undefined type of the param if ($reflectType === null) { if (isset($matches[$name])) { $bindParams[$key] = $matches[$name]; } else { $bindParams[$key] = null; } continue; } /** * Defined type of the param * @notice \ReflectType::getName() is not supported in PHP 7.0, that is why use __toString() */ $type = $reflectType->__toString(); if ($type === Request::class) { // Current Request Object $bindParams[$key] = $request; } elseif ($type === Response::class) { // Current Response Object $bindParams[$key] = RequestContext::getResponse(); } elseif (isset($matches[$name])) { // Request parameters $bindParams[$key] = $this->parserParamType($type, $matches[$name]); } elseif (App::hasBean($type)) { // Bean $bindParams[$key] = App::getBean($type); } elseif (\class_exists($type)) { // Class $bindParams[$key] = $this->bindRequestParamsToClass($request, new \ReflectionClass($type)); } else { $bindParams[$key] = $this->getDefaultValue($type); } } return $bindParams; }
Binding params of action method @param ServerRequestInterface $request request object @param mixed $handler handler @param array $matches route params info @return array @throws \ReflectionException
entailment
private function bindRequestParamsToClass(ServerRequestInterface $request, \ReflectionClass $reflectClass) { try { $object = $reflectClass->newInstance(); $queryParams = $request->getQueryParams(); // Get request body, auto decode when content type is json format if (StringHelper::startsWith($request->getHeaderLine('Content-Type'), 'application/json')) { $requestBody = JsonHelper::decode($request->getBody()->getContents(), true); } else { $requestBody = $request->getParsedBody(); } // Merge query params and request body $requestParams = array_merge($queryParams, $requestBody); // Binding request params to target object $properties = $reflectClass->getProperties(); foreach ($properties as $property) { $name = $property->getName(); if (!isset($requestParams[$name])) { continue; } if (!$property->isPublic()) { $property->setAccessible(true); } $property->setValue($object, $requestParams[$name]); } } catch (\Exception $e) { $object = null; } return $object; }
Bind request parameters to instance of ReflectClass @param ServerRequestInterface $request @param \ReflectionClass $reflectClass @return Object
entailment
private function parserParamType(string $type, $value) { switch ($type) { case 'int': $value = (int)$value; break; case 'string': $value = (string)$value; break; case 'bool': $value = (bool)$value; break; case 'float': $value = (float)$value; break; case 'double': $value = (double)$value; break; } return $value; }
parser the type of binding param @param string $type the type of param @param mixed $value the value of param @return bool|float|int|string
entailment
private function getDefaultValue(string $type) { $value = null; switch ($type) { case 'int': $value = 0; break; case 'string': $value = ''; break; case 'bool': $value = false; break; case 'float': $value = 0; break; case 'double': $value = 0; break; } return $value; }
the default value of param @param string $type the type of param @return bool|float|int|string
entailment
public function setContainerClass(string $containerClass) { if (!\class_exists($containerClass) || ( $containerClass !== DIContainer::class && !\is_subclass_of($containerClass, DIContainer::class) ) ) { throw new \InvalidArgumentException( \sprintf('class "%s" must extend %s', $containerClass, DIContainer::class) ); } $this->containerClass = $containerClass; return $this; }
Set container class. @param string $containerClass @throws \InvalidArgumentException @return static
entailment
public function setProxiesPath(string $proxiesPath) { if (!\file_exists($proxiesPath) || !\is_dir($proxiesPath) || !\is_writable($proxiesPath)) { throw new \RuntimeException(\sprintf('%s directory does not exist or is write protected', $proxiesPath)); } $this->proxiesPath = $proxiesPath; return $this; }
Set proxies path. @param string $proxiesPath @throws \RuntimeException @return static
entailment
public function setCompilationPath(string $compilationPath) { if (!\file_exists($compilationPath) || !\is_dir($compilationPath) || !\is_writable($compilationPath)) { throw new \RuntimeException(\sprintf( '%s directory does not exist or is write protected', $compilationPath )); } $this->compilationPath = $compilationPath; return $this; }
Set compilation path. @param string $compilationPath @throws \RuntimeException @return static
entailment
public function setCompiledContainerClass(string $compiledContainerClass) { if (!\class_exists($compiledContainerClass) || ( $compiledContainerClass !== DICompiledContainer::class && !\is_subclass_of($compiledContainerClass, DICompiledContainer::class) ) ) { throw new \InvalidArgumentException( \sprintf('class "%s" must extend %s', $compiledContainerClass, DICompiledContainer::class) ); } $this->compiledContainerClass = $compiledContainerClass; return $this; }
Set compiled container class. @param string $compiledContainerClass @throws \InvalidArgumentException @return static
entailment
public function setDefinitions($definitions) { if (\is_string($definitions)) { $definitions = [$definitions]; } if ($definitions instanceof \Traversable) { $definitions = \iterator_to_array($definitions); } if (!\is_array($definitions)) { throw new \InvalidArgumentException( \sprintf('Definitions must be a string or traversable. %s given', \gettype($definitions)) ); } \array_walk( $definitions, function ($definition) { if (!\is_array($definition) && !\is_string($definition)) { throw new \InvalidArgumentException( \sprintf( 'A definition must be an array or a file or directory path. %s given', \gettype($definition) ) ); } } ); $this->definitions = $definitions; return $this; }
Set definitions. @param string|array|\Traversable $definitions @throws \InvalidArgumentException @return static
entailment