sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function boot(Application $app) { $app->on(KernelEvents::EXCEPTION, function (GetResponseForExceptionEvent $event) { $e = $event->getException(); if ($e instanceof MethodNotAllowedHttpException && $e->getHeaders()["Allow"] === "OPTIONS") { $event->setException(new NotFoundHttpException("No route found for \"{$event->getRequest()->getMethod()} {$event->getRequest()->getPathInfo()}\"")); } }); }
Add OPTIONS method support for all routes @param Application $app
entailment
public function register(Container $app) { $app["cors.allowOrigin"] = "*"; // Defaults to all $app["cors.allowMethods"] = null; // Defaults to all $app["cors.allowHeaders"] = null; // Defaults to all $app["cors.maxAge"] = null; $app["cors.allowCredentials"] = null; $app["cors.exposeHeaders"] = null; $app["allow"] = $app->protect(new Allow()); $app["options"] = $app->protect(function ($subject) use ($app) { $optionsController = function () { return Response::create("", 204); }; if ($subject instanceof Controller) { $optionsRoute = $app->options($subject->getRoute()->getPath(), $optionsController) ->after($app["allow"]); } else { $optionsRoute = $subject->options("{path}", $optionsController) ->after($app["allow"]) ->assert("path", ".*"); } return $optionsRoute; }); $app["cors-enabled"] = $app->protect(function ($subject, $config = []) use ($app) { $optionsController = $app["options"]($subject); $cors = new Cors($config); if ($subject instanceof Controller) { $optionsController->after($cors); } $subject->after($cors); return $subject; }); $app["cors"] = function () use ($app) { $app["options"]($app); return new Cors(); }; }
Register the cors function and set defaults @param Container $app
entailment
public function boot(Router $router) { $this->publishes([ __DIR__ . '/Config/version.php' => config_path('version.php'), ], 'version'); $this->app->singleton('version', function ($app) { return new Version($app); }); }
Bootstrap the application services. @param Router $router @return void
entailment
protected function initiate() { $name = $this->name; $data = ['acl' => [], 'actions' => [], 'roles' => []]; $data = \array_merge($data, $this->memory->get("acl_{$name}", [])); // Loop through all the roles and actions in memory and add it to // this ACL instance. $this->roles->attach($data['roles']); $this->actions->attach($data['actions']); // Loop through all the ACL in memory and add it to this ACL // instance. foreach ($data['acl'] as $id => $allow) { list($role, $action) = \explode(':', $id); $this->assign($role, $action, $allow); } return $this->sync(); }
Initiate ACL data from memory. @return $this
entailment
public function allow($roles, $actions, bool $allow = true) { $this->setAuthorization($roles, $actions, $allow); return $this->sync(); }
Assign single or multiple $roles + $actions to have access. @param string|array $roles A string or an array of roles @param string|array $actions A string or an array of action name @param bool $allow @return $this
entailment
public function canIf(string $action): bool { $roles = $this->getUserRoles(); $action = Keyword::make($action); if (\is_null($this->actions->search($action))) { return false; } return $this->checkAuthorization($roles, $action); }
Verify whether current user has sufficient roles to access the actions based on available type of access if the action exist. @param string $action A string of action name @return bool
entailment
public function canAs(Authorizable $user, string $action): bool { $this->setUser($user); $permission = $this->can($action); $this->revokeUser(); return $permission; }
Verify whether current user has sufficient roles to access the actions based on available type of access. @param \Orchestra\Contracts\Authorization\Authorizable $user @param string $action A string of action name @throws \InvalidArgumentException @return bool
entailment
public function canIfAs(Authorizable $user, string $action): bool { $this->setUser($user); $permission = $this->canIf($action); $this->revokeUser(); return $permission; }
Verify whether current user has sufficient roles to access the actions based on available type of access if the action exist. @param \Orchestra\Contracts\Authorization\Authorizable $user @param string $action A string of action name @return bool
entailment
public function sync() { if ($this->attached()) { $name = $this->name; $this->memory->put("acl_{$name}", [ 'acl' => $this->acl, 'actions' => $this->actions->get(), 'roles' => $this->roles->get(), ]); } return $this; }
Sync memory with ACL instance, make sure anything that added before ->with($memory) got called is appended to memory as well. @return $this
entailment
public function execute(string $type, string $operation, array $parameters = []) { return $this->{$type}->{$operation}(...$parameters); }
Forward call to roles or actions. @param string $type 'roles' or 'actions' @param string $operation @param array $parameters @return \Orchestra\Authorization\Fluent
entailment
protected function resolveDynamicExecution(string $method): array { // Preserve legacy CRUD structure for actions and roles. $method = Str::snake($method, '_'); $matcher = '/^(add|rename|has|get|remove|fill|attach|detach)_(role|action)(s?)$/'; if (! \preg_match($matcher, $method, $matches)) { throw new InvalidArgumentException("Invalid keyword [$method]"); } $type = $matches[2].'s'; $multiple = (isset($matches[3]) && $matches[3] === 's'); $operation = $this->resolveOperationName($matches[1], $multiple); return [$type, $operation]; }
Dynamically resolve operation name especially to resolve attach and detach multiple actions or roles. @param string $method @throws \InvalidArgumentException @return array
entailment
protected function resolveOperationName(string $operation, bool $multiple = true): string { if (! $multiple) { return $operation; } elseif (\in_array($operation, ['fill', 'add'])) { return 'attach'; } return 'detach'; }
Dynamically resolve operation name especially when multiple operation was used. @param string $operation @param bool $multiple @return string
entailment
public function setAuthorization(FactoryContract $factory) { $this->acl = $factory->make($this->getAuthorizationName()); return $this; }
Set authorization driver. @param \Orchestra\Contracts\Authorization\Factory $factory @return $this
entailment
protected function can(string $action, ?Authorizable $user = null): bool { return ! \is_null($user) ? $this->acl->canAs($user, $action) : $this->acl->can($action); }
Resolve if authorization can. @param string $action @param \Orchestra\Contracts\Authorization\Authorizable|null $user @return bool
entailment
protected function canIf(string $action, ?Authorizable $user = null): bool { return ! \is_null($user) ? $this->acl->canIfAs($user, $action) : $this->acl->canIf($action); }
Resolve if authorization can if action exists. @param string $action @param \Orchestra\Contracts\Authorization\Authorizable|null $user @return bool
entailment
public function set($key, $value) { if (is_array($value)) { $settings = array_replace($this->defaults, $value); } else { $settings = array_replace($this->defaults, array('value' => $value)); } parent::set($key, $settings); }
Set cookie The second argument may be a single scalar value, in which case it will be merged with the default settings and considered the `value` of the merged result. The second argument may also be an array containing any or all of the keys shown in the default settings above. This array will be merged with the defaults shown above. @param string $key Cookie name @param mixed $value Cookie settings @api
entailment
public function remove($key, $settings = array()) { $settings['value'] = ''; $settings['expires'] = time() - 86400; $this->set($key, array_replace($this->defaults, $settings)); }
Remove cookie Unlike \Slim\Collection, this will actually *set* a cookie with an expiration date in the past. This expiration date will force the client-side cache to remove its cookie with the given name and settings. @param string $key Cookie name @param array $settings Optional cookie settings @api
entailment
public function encrypt(CryptInterface $crypt) { foreach ($this as $name => $settings) { $settings['value'] = $crypt->encrypt($settings['value']); $this->set($name, $settings); } }
Encrypt cookies This method iterates and encrypts data values. @param \Slim\Interfaces\CryptInterface $crypt @api
entailment
public function setHeaders(HeadersInterface &$headers) { foreach ($this->data as $name => $settings) { $this->setHeader($headers, $name, $settings); } }
Serialize this collection of cookies into a raw HTTP header @param \Slim\Interfaces\Http\HeadersInterface $headers @api
entailment
public function setHeader(HeadersInterface &$headers, $name, $value) { $values = array(); if (is_array($value)) { if (isset($value['domain']) && $value['domain']) { $values[] = '; domain=' . $value['domain']; } if (isset($value['path']) && $value['path']) { $values[] = '; path=' . $value['path']; } if (isset($value['expires'])) { if (is_string($value['expires'])) { $timestamp = strtotime($value['expires']); } else { $timestamp = (int) $value['expires']; } if ($timestamp !== 0) { $values[] = '; expires=' . gmdate('D, d-M-Y H:i:s e', $timestamp); } } if (isset($value['secure']) && $value['secure']) { $values[] = '; secure'; } if (isset($value['httponly']) && $value['httponly']) { $values[] = '; HttpOnly'; } $value = (string)$value['value']; } $cookie = sprintf( '%s=%s', urlencode($name), urlencode((string) $value) . implode('', $values) ); if (!$headers->has('Set-Cookie') || $headers->get('Set-Cookie') === '') { $headers->set('Set-Cookie', $cookie); } else { $headers->set('Set-Cookie', implode("\n", array($headers->get('Set-Cookie'), $cookie))); } }
Set HTTP cookie header This method will construct and set the HTTP `Set-Cookie` header. Slim uses this method instead of PHP's native `setcookie` method. This allows more control of the HTTP header irrespective of the native implementation's dependency on PHP versions. This method accepts the \Slim\Http\Headers object by reference as its first argument; this method directly modifies this object instead of returning a value. @param \Slim\Interfaces\Http\HeadersInterface $header @param string $name @param string $value @api
entailment
public function deleteHeader(HeadersInterface &$headers, $name, $value = array()) { $crumbs = ($headers->has('Set-Cookie') ? explode("\n", $headers->get('Set-Cookie')) : array()); $cookies = array(); foreach ($crumbs as $crumb) { if (isset($value['domain']) && $value['domain']) { $regex = sprintf('@%s=.*domain=%s@', urlencode($name), preg_quote($value['domain'])); } else { $regex = sprintf('@%s=@', urlencode($name)); } if (preg_match($regex, $crumb) === 0) { $cookies[] = $crumb; } } if (!empty($cookies)) { $headers->set('Set-Cookie', implode("\n", $cookies)); } else { $headers->remove('Set-Cookie'); } $this->setHeader($headers, $name, array_merge(array('value' => '', 'path' => null, 'domain' => null, 'expires' => time() - 100), $value)); }
Delete HTTP cookie header This method will construct and set the HTTP `Set-Cookie` header to invalidate a client-side HTTP cookie. If a cookie with the same name (and, optionally, domain) is already set in the HTTP response, it will also be removed. Slim uses this method instead of PHP's native `setcookie` method. This allows more control of the HTTP header irrespective of PHP's native implementation's dependency on PHP versions. This method accepts the \Slim\Http\Headers object by reference as its first argument; this method directly modifies this object instead of returning a value. @param \Slim\Interfaces\Http\HeadersInterface $headers @param string $name @param array $value @api
entailment
public function parseHeader($header) { $header = rtrim($header, "\r\n"); $pieces = preg_split('@\s*[;,]\s*@', $header); $cookies = array(); foreach ($pieces as $cookie) { $cookie = explode('=', $cookie, 2); if (count($cookie) === 2) { $key = urldecode($cookie[0]); $value = urldecode($cookie[1]); if (!isset($cookies[$key])) { $cookies[$key] = $value; } } } return $cookies; }
Parse cookie header This method will parse the HTTP request's `Cookie` header and extract an associative array of cookie names and values. @param string $header @return array @api
entailment
public function getReasonPhrase() { if (isset(static::$messages[$this->status]) === true) { return static::$messages[$this->status]; } return null; }
Get response reason phrase @return string @api
entailment
public function addHeaders(array $headers) { foreach ($headers as $name => $value) { $this->headers->add($name, $value); } }
Add multiple header values @param array $headers @api
entailment
public function write($body, $overwrite = false) { if ($overwrite === true) { $this->body->close(); $this->body = new \Guzzle\Stream\Stream(fopen('php://temp', 'r+')); } $this->body->write($body); }
Append response body @param string $body Content to append to the current HTTP response body @param bool $overwrite Clear the existing body before writing new content? @api
entailment
public function finalize(\Slim\Interfaces\Http\RequestInterface $request) { $sendBody = true; if (in_array($this->status, array(204, 304)) === true) { $this->headers->remove('Content-Type'); $this->headers->remove('Content-Length'); $sendBody = false; } else { $size = @$this->getSize(); if ($size) { $this->headers->set('Content-Length', $size); } } // Serialize cookies into HTTP header $this->cookies->setHeaders($this->headers); // Remove body if HEAD request if ($request->isHead() === true) { $sendBody = false; } // Truncate body if it should not be sent with response if ($sendBody === false) { $this->body->close(); $this->body = new \Guzzle\Stream\Stream(fopen('php://temp', 'r+')); } return $this; }
Finalize response for delivery to client Apply final preparations to the resposne object so that it is suitable for delivery to the client. @param \Slim\Interfaces\Http\RequestInterface $request @return \Slim\Interfaces\Http\Response Self @api
entailment
public function send() { // Send headers if (headers_sent() === false) { if (strpos(PHP_SAPI, 'cgi') === 0) { header(sprintf('Status: %s', $this->getReasonPhrase())); } else { header(sprintf('%s %s', $this->getProtocolVersion(), $this->getReasonPhrase())); } foreach ($this->headers as $name => $value) { foreach ($value as $hVal) { header("$name: $hVal", false); } } } // Send body $this->body->seek(0); while ($this->body->feof() === false) { echo $this->body->read(1024); } return $this; }
Send HTTP response headers and body @return \Slim\Interfaces\Http\Response Self @api
entailment
public function redirect($url, $status = 302) { $this->setStatus($status); $this->headers->set('Location', $url); }
Redirect This method prepares the response object to return an HTTP Redirect response to the client. @param string $url The redirect destination @param int $status The redirect HTTP status code @api
entailment
public function getLoginUrl() { // required params $params = array( 'client_id' => $this->getClientId(), 'redirect_uri' => $this->getRedirectUri(), ); // optional params if ($this->getScope()) { $params['scope'] = implode(',', $this->getScope()); } if ($this->getResponceType()) { $params['response_type'] = $this->getResponceType(); } if ($this->apiVersion) { $params['v'] = $this->apiVersion; } if ($this->state) { $params['state'] = $this->state; } return 'https://oauth.vk.com/authorize?' . http_build_query($params); }
Get the login URL for Vkontakte sign in @return string
entailment
public function authenticate($code = null) { if (null === $code) { if (isset($_GET['code'])) { $code = $_GET['code']; } } $url = 'https://oauth.vk.com/access_token?' . http_build_query(array( 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'code' => $code, 'redirect_uri' => $this->getRedirectUri(), )); $token = $this->curl($url); $decodedToken = json_decode($token, true); $decodedToken['created'] = time(); // add access token created unix timestamp to array $this->setAccessToken($decodedToken); return $this; }
Authenticate user and get access token from server @param string $code @return $this
entailment
public function api($method, array $query = array()) { /* Generate query string from array */ foreach ($query as $param => $value) { if (is_array($value)) { // implode values of each nested array with comma $query[$param] = implode(',', $value); } } $query['access_token'] = isset($this->accessToken['access_token']) ? $this->accessToken['access_token'] : ''; if (empty($query['v'])) { $query['v'] = $this->getApiVersion(); } $url = 'https://api.vk.com/method/' . $method . '?' . http_build_query($query); $result = json_decode($this->curl($url), true); if (isset($result['response'])) { return $result['response']; } return $result; }
Make an API call to https://api.vk.com/method/ @param string $method API method name @param array $query API method params @return mixed The response @throws \Exception
entailment
public function setAccessToken($token) { if (is_string($token)) { $this->accessToken = json_decode($token, true); } else { $this->accessToken = (array)$token; } return $this; }
Set the access token @param string|array $token The access token in json|array format @return $this
entailment
protected function curl($url) { // create curl resource if ($this->persistentConnect) { if (!is_resource(static::$connection)) { static::$connection = curl_init(); } $ch = static::$connection; } else { $ch = curl_init(); } // set url curl_setopt($ch, CURLOPT_URL, $url); // return the transfer as a string curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE); // disable SSL verifying curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); if ($this->IPv6Disabled) { curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); } // $output contains the output string $result = curl_exec($ch); if (!$result) { $errno = curl_errno($ch); $error = curl_error($ch); } if (!$this->persistentConnect) { // close curl resource to free up system resources curl_close($ch); } if (isset($errno) && isset($error)) { throw new \Exception($error, $errno); } return $result; }
Make the curl request to specified url @param string $url The url for curl() function @return mixed The result of curl_exec() function @throws \Exception
entailment
public function keep() { foreach ($this->messages['prev'] as $key => $val) { $this->next($key, $val); } }
Persist flash messages from previous request to the next request @api
entailment
public function offsetGet($offset) { $messages = $this->getMessages(); return isset($messages[$offset]) ? $messages[$offset] : null; }
Offset get @param mixed $offset @return mixed|null The value at specified offset, or null
entailment
public function up() { $datetime = now(); Collection::make([ ['name' => 'Administrator', 'created_at' => $datetime, 'updated_at' => $datetime], ['name' => 'Member', 'created_at' => $datetime, 'updated_at' => $datetime], ])->each(function ($role) { DB::table('roles')->insert($role); }); }
Run the migrations. @return void
entailment
public function sendResetLink(array $credentials): string { // First we will check to see if we found a user at the given credentials and // if we did not we will redirect back to this current URI with a piece of // "flash" data in the session to indicate to the developers the errors. if (\is_null($user = $this->getUser($credentials))) { return static::INVALID_USER; } // Once we have the reminder token, we are ready to send a message out to the // user with a link to reset their password. We will then redirect back to // the current URI having nothing set in the session to indicate errors. $user->sendPasswordResetNotification( $this->tokens->create($user), $this->provider ); return static::RESET_LINK_SENT; }
Send a password reminder to a user. @param array $credentials @return string
entailment
public function offsetUnset($key) { $keys = $this->parseKey($key); $array = &$this->values; while (count($keys) > 1) { $key = array_shift($keys); if (!isset($array[$key]) || !is_array($array[$key])) { return; } $array =& $array[$key]; } unset($array[array_shift($keys)]); }
Remove nested array value based on a separated key @param string $key
entailment
protected function parseKey($key) { if (!isset($this->keys[$key])) { $this->keys[$key] = explode($this->separator, $key); } return $this->keys[$key]; }
Parse a separated key and cache the result @param string $key @return array
entailment
protected function getValue($key, array $array = array()) { $keys = $this->parseKey($key); while (count($keys) > 0 and !is_null($array)) { $key = array_shift($keys); $array = isset($array[$key]) ? $array[$key] : null; } return $array; }
Get a value from a nested array based on a separated key @param string $key @param array $array @return mixed
entailment
protected function setValue($key, $value, array &$array = array()) { $keys = $this->parseKey($key, $this->separator); $pointer = &$array; while (count($keys) > 0) { $key = array_shift($keys); $pointer[$key] = (isset($pointer[$key]) ? $pointer[$key] : array()); $pointer = &$pointer[$key]; } $pointer = $value; return $array; }
Set nested array values based on a separated key @param string $key @param mixed $value @param array $array @return array
entailment
protected function mergeArrays() { $arrays = func_get_args(); $merged = array(); foreach ($arrays as $array) { foreach ($array as $key => $value) { $merged = $this->setValue($key, $value, $merged); } } return $merged; }
Merge arrays with nested keys into the values store Usage: $this->mergeArrays(array $array [, array $...]) @return array
entailment
protected function flattenArray(array $array, $separator = null) { $flattened = array(); if (is_null($separator)) { $separator = $this->separator; } foreach ($array as $key => $value) { if (is_array($value)) { $flattened = array_merge($flattened, $this->flattenArray($value, $key.$separator)); } else { $flattened[trim($separator.$key, $this->separator)] = $value; } } return $flattened; }
Flatten a nested array to a separated key @param array $array @param string $separator @return array
entailment
public function setup($event): void { $this->userRoles = null; $this->events->forget('orchestra.auth: roles'); $this->events->listen('orchestra.auth: roles', $event); }
Setup roles event listener. @param \Closure|string $event @return void
entailment
public function roles(): Collection { $user = $this->user(); $userId = 0; // This is a simple check to detect if the user is actually logged-in, // otherwise it's just as the same as setting userId as 0. \is_null($user) || $userId = $user->getAuthIdentifier(); $roles = ($this->userRoles ?: [])["{$userId}"] ?? new Collection(); // This operation might be called more than once in a request, by // cached the event result we can avoid duplicate events being fired. if ($roles->isEmpty()) { $roles = $this->getUserRolesFromEventDispatcher($user, $roles); } $roles = new Collection($roles); $this->userRoles["{$userId}"] = $roles; return $roles; }
Get the current user's roles of the application. If the user is a guest, empty array should be returned. @return \Illuminate\Support\Collection
entailment
public function is($roles): bool { $userRoles = $this->roles()->all(); // For a pre-caution, we should return false in events where user // roles not an array. if (! \is_array($userRoles)) { return false; } // We should ensure that all given roles match the current user, // consider it as a AND condition instead of OR. foreach ((array) $roles as $role) { if (! \in_array($role, $userRoles)) { return false; } } return true; }
Determine if current user has the given role. @param string|array $roles @return bool
entailment
protected function getUserRolesFromEventDispatcher(Authenticatable $user = null, $roles = []): Collection { $roles = $this->events->until('orchestra.auth: roles', [$user, $roles]); // It possible that after event are all propagated we don't have a // roles for the user, in this case we should properly append "Guest" // user role to the current user. if (\is_null($roles)) { $roles = ['Guest']; } return new Collection($roles); }
Ger user roles from event dispatcher. @param \Illuminate\Contracts\Auth\Authenticatable $user @param \Illuminate\Support\Collection|array $roles @return \Illuminate\Support\Collection
entailment
protected function resolve($name): PasswordBroker { if (\is_null($config = $this->getConfig($name))) { throw new InvalidArgumentException("Password resetter [{$name}] is not defined."); } // The password broker uses a token repository to validate tokens and send user // password e-mails, as well as validating that password reset process as an // aggregate service of sorts providing a convenient interface for resets. return new PasswordBroker( $this->createTokenRepository($config), $this->app->make('auth')->createUserProvider($config['provider']), $name ); }
Resolve the given broker. @param string $name @return \Illuminate\Contracts\Auth\PasswordBroker
entailment
public function checkAuthorization($roles, $action): bool { $name = $action; $action = $this->actions->search($name); if (\is_null($action)) { throw new InvalidArgumentException("Unable to verify unknown action {$name}."); } $authorized = false; $roles = new Collection($roles); foreach ($roles->all() as $role) { $role = $this->roles->search($role); $permission = $this->acl[$role.':'.$action] ?? false; // array_search() will return false when no key is found based // on given haystack, therefore we should just ignore and // continue to the next role. if (! \is_null($role) && $permission === true) { $authorized = true; } } return $authorized; }
Verify whether given roles has sufficient roles to access the actions based on available type of access. @param string|array $roles A string or an array of roles @param string $action A string of action name @throws \InvalidArgumentException @return bool
entailment
public function setAuthorization($roles, $actions, bool $allow = true): void { $roles = $this->roles->filter($roles); $actions = $this->actions->filter($actions); foreach ($roles as $role) { if (! $this->roles->has($role)) { throw new InvalidArgumentException("Role {$role} does not exist."); } $this->groupedAssignAction($role, $actions, $allow); } }
Assign single or multiple $roles + $actions to have access. @param string|array $roles A string or an array of roles @param string|array $actions A string or an array of action name @param bool $allow @throws \InvalidArgumentException @return void
entailment
protected function assign(?string $role = null, ?string $action = null, bool $allow = true): void { $role = $this->roles->findKey($role); $action = $this->actions->findKey($action); if (! \is_null($role) && ! \is_null($action)) { $this->acl["{$role}:{$action}"] = $allow; } }
Assign a key combination of $roles + $actions to have access. @param string $role A key or string representation of roles @param string $action A key or string representation of action name @param bool $allow @return void
entailment
public function setUser(Authorizable $user) { $userRoles = $user->getRoles(); $this->userRoles = $userRoles; return $this; }
Assign user instance. @param \Orchestra\Contracts\Authorization\Authorizable $user @return $this
entailment
protected function getUserRoles(): Collection { if (! \is_null($this->userRoles)) { return $this->userRoles; } elseif (! $this->auth->guest()) { return $this->auth->roles(); } return new Collection($this->roles->has('guest') ? ['guest'] : []); }
Get all possible user roles. @return \Illuminate\Support\Collection
entailment
public function getCurrentRoute() { if ($this->currentRoute !== null) { return $this->currentRoute; } if (is_array($this->matchedRoutes) && count($this->matchedRoutes) > 0) { return $this->matchedRoutes[0]; } return null; }
Get current route This method will return the current \Slim\Route object. If a route has not been dispatched, but route matching has been completed, the first matching \Slim\Route object will be returned. If route matching has not completed, null will be returned. @return \Slim\Interfaces\RouteInterface|null @api
entailment
public function getMatchedRoutes($httpMethod, $resourceUri, $save = true) { $matchedRoutes = array(); foreach ($this->routes as $route) { if (!$route->supportsHttpMethod($httpMethod) && !$route->supportsHttpMethod("ANY")) { continue; } if ($route->matches($resourceUri)) { $matchedRoutes[] = $route; } } if ($save === true) { $this->matchedRoutes = $matchedRoutes; } return $matchedRoutes; }
Get route objects that match a given HTTP method and URI This method is responsible for finding and returning all \Slim\Interfaces\RouteInterface objects that match a given HTTP method and URI. Slim uses this method to determine which \Slim\Interfaces\RouteInterface objects are candidates to be dispatched for the current HTTP request. @param string $httpMethod The HTTP request method @param string $resourceUri The resource URI @param bool $reload Should matching routes be re-parsed? @return array[\Slim\Interfaces\RouteInterface] @api
entailment
protected function processGroups() { $pattern = ""; $middleware = array(); foreach ($this->routeGroups as $group) { $k = key($group); $pattern .= $k; if (is_array($group[$k])) { $middleware = array_merge($middleware, $group[$k]); } } return array($pattern, $middleware); }
Process route groups A helper method for processing the group's pattern and middleware. @return array An array with the elements: pattern, middlewareArr
entailment
public function urlFor($name, $params = array()) { if (!$this->hasNamedRoute($name)) { throw new \RuntimeException('Named route not found for name: ' . $name); } $search = array(); foreach ($params as $key => $value) { $search[] = '#:' . preg_quote($key, '#') . '\+?(?!\w)#'; } $pattern = preg_replace($search, $params, $this->getNamedRoute($name)->getPattern()); //Remove remnants of unpopulated, trailing optional pattern segments, escaped special characters return preg_replace('#\(/?:.+\)|\(|\)|\\\\#', '', $pattern); }
Get URL for named route @param string $name The name of the route @param array $params Associative array of URL parameter names and replacement values @return string The URL for the given route populated with provided replacement values @throws \RuntimeException If named route not found @api
entailment
public function addNamedRoute($name, RouteInterface $route) { if ($this->hasNamedRoute($name)) { throw new \RuntimeException('Named route already exists with name: ' . $name); } $this->namedRoutes[(string) $name] = $route; }
Add named route @param string $name The route name @param \Slim\Interfaces\RouteInterface $route The route object @throws \RuntimeException If a named route already exists with the same name @api
entailment
public function getNamedRoutes() { if (is_null($this->namedRoutes)) { $this->namedRoutes = array(); foreach ($this->routes as $route) { if ($route->getName() !== null) { $this->addNamedRoute($route->getName(), $route); } } } return new \ArrayIterator($this->namedRoutes); }
Get external iterator for named routes @return \ArrayIterator @api
entailment
protected function render($template, array $data = array()) { // Resolve and verify template file $templatePathname = $this->templateDirectory . DIRECTORY_SEPARATOR . ltrim($template, DIRECTORY_SEPARATOR); if (!is_file($templatePathname)) { throw new \RuntimeException("Cannot render template `$templatePathname` because the template does not exist. Make sure your view's template directory is correct."); } // Render template with view variables into a temporary output buffer $this->replace($data); extract($this->all()); ob_start(); require $templatePathname; // Return temporary output buffer content, destroy output buffer return ob_get_clean(); }
Render template This method will render the specified template file using the current application view. Although this method will work perfectly fine, it is recommended that you create your own custom view class that implements \Slim\ViewInterface instead of using this default view class. This default implementation is largely intended as an example. @var string $template Pathname of template file relative to templates directory @return string The rendered template @throws \RuntimeException If resolved template pathname is not a valid file
entailment
public function setCallable($callable) { $matches = array(); if (is_string($callable) && preg_match('!^([^\:]+)\:([a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*)$!', $callable, $matches)) { $class = $matches[1]; $method = $matches[2]; $callable = function() use ($class, $method) { static $obj = null; if ($obj === null) { $obj = new $class; } return call_user_func_array(array($obj, $method), func_get_args()); }; } if (!is_callable($callable)) { throw new \InvalidArgumentException('Route callable must be callable'); } $this->callable = $callable; }
Set route callable @param mixed $callable @throws \InvalidArgumentException If argument is not callable @api
entailment
public function getParam($index) { if (!isset($this->params[$index])) { throw new \InvalidArgumentException('Route parameter does not exist at specified index'); } return $this->params[$index]; }
Get route parameter value @param string $index Name of URL parameter @return string @throws \InvalidArgumentException If route parameter does not exist at index @api
entailment
public function setParam($index, $value) { if (!isset($this->params[$index])) { throw new \InvalidArgumentException('Route parameter does not exist at specified index'); } $this->params[$index] = $value; }
Set route parameter value @param string $index Name of URL parameter @param mixed $value The new parameter value @return void @throws \InvalidArgumentException If route parameter does not exist at index @api
entailment
public function appendHttpMethods() { $args = func_get_args(); if(count($args) && is_array($args[0])){ $args = $args[0]; } $this->methods = array_merge($this->methods, $args); }
Append supported HTTP methods (this method accepts an unlimited number of string arguments) @api
entailment
public function via() { $args = func_get_args(); if(count($args) && is_array($args[0])){ $args = $args[0]; } $this->methods = array_merge($this->methods, $args); return $this; }
Append supported HTTP methods (alias for Route::appendHttpMethods) @return \Slim\Route @api
entailment
public function setMiddleware($middleware) { if (is_callable($middleware)) { $this->middleware[] = $middleware; } elseif (is_array($middleware)) { foreach ($middleware as $callable) { if (!is_callable($callable)) { throw new \InvalidArgumentException('All Route middleware must be callable'); } } $this->middleware = array_merge($this->middleware, $middleware); } else { throw new \InvalidArgumentException('Route middleware must be callable or an array of callables'); } return $this; }
Set middleware This method allows middleware to be assigned to a specific Route. If the method argument `is_callable` (including callable arrays!), we directly append the argument to `$this->middleware`. Else, we assume the argument is an array of callables and merge the array with `$this->middleware`. Each middleware is checked for is_callable() and an InvalidArgumentException is thrown immediately if it isn't. @param Callable|array[Callable] @return \Slim\Route @throws \InvalidArgumentException If argument is not callable or not an array of callables. @api
entailment
public function matches($resourceUri) { //Convert URL params into regex patterns, construct a regex for this route, init params $patternAsRegex = preg_replace_callback( '#:([\w]+)\+?#', array($this, 'matchesCallback'), str_replace(')', ')?', (string)$this->pattern) ); if (substr($this->pattern, -1) === '/') { $patternAsRegex .= '?'; } $regex = '#^' . $patternAsRegex . '$#'; if ($this->caseSensitive === false) { $regex .= 'i'; } //Cache URL params' names and values if this route matches the current HTTP request if (!preg_match($regex, $resourceUri, $paramValues)) { return false; } foreach ($this->paramNames as $name) { if (isset($paramValues[$name])) { if (isset($this->paramNamesPath[$name])) { $this->params[$name] = explode('/', urldecode($paramValues[$name])); } else { $this->params[$name] = urldecode($paramValues[$name]); } } } return true; }
Matches URI? Parse this route's pattern, and then compare it to an HTTP resource URI This method was modeled after the techniques demonstrated by Dan Sosedoff at: http://blog.sosedoff.com/2009/09/20/rails-like-php-url-router/ @param string $resourceUri A Request URI @return bool @api
entailment
protected function matchesCallback($m) { $this->paramNames[] = $m[1]; if (isset($this->conditions[$m[1]])) { return '(?P<' . $m[1] . '>' . $this->conditions[$m[1]] . ')'; } if (substr($m[0], -1) === '+') { $this->paramNamesPath[$m[1]] = 1; return '(?P<' . $m[1] . '>.+)'; } return '(?P<' . $m[1] . '>[^/]+)'; }
Convert a URL parameter (e.g. ":id", ":id+") into a regular expression @param array $m URL parameters @return string Regular expression for URL parameter
entailment
public function dispatch() { foreach ($this->middleware as $mw) { call_user_func_array($mw, array($this)); } $return = call_user_func_array($this->getCallable(), array_values($this->getParams())); return ($return === false) ? false : true; }
Dispatch route This method invokes the route object's callable. If middleware is registered for the route, each callable middleware is invoked in the order specified. @return bool @api
entailment
public function encrypt($data) { // Get module $module = mcrypt_module_open($this->cipher, '', $this->mode, ''); // Create initialization vector $vector = mcrypt_create_iv(mcrypt_enc_get_iv_size($module), MCRYPT_DEV_URANDOM); // Validate key length $this->validateKeyLength($this->key, $module); // Initialize encryption $initResult = mcrypt_generic_init($module, $this->key, $vector); if (!is_null($initResult)) { $this->throwInitError($initResult, 'encrypt'); } // Encrypt $encryptedData = mcrypt_generic($module, $data); // Deinitialize encryption mcrypt_generic_deinit($module); // Ensure integrity of encrypted data with HMAC hash $hmac = $this->getHmac($encryptedData); return implode('|', array(base64_encode($vector), base64_encode($encryptedData), $hmac)); }
Encrypt data @param string $data Unencrypted data @return string Encrypted data @throws \RuntimeException If mcrypt extension not loaded @throws \RuntimeException If encryption module initialization failed @api
entailment
public function decrypt($data) { // Extract components of encrypted data string $parts = explode('|', $data); if (count($parts) !== 3) { return $data; // throw new \RuntimeException('Trying to decrypt invalid data in \Slim\Crypt::decrypt'); } $vector = base64_decode($parts[0]); $encryptedData = base64_decode($parts[1]); $hmac = $parts[2]; // Verify integrity of encrypted data if ($this->getHmac($encryptedData) !== $hmac) { throw new \RuntimeException('Integrity of encrypted data has been compromised in \Slim\Crypt::decrypt'); } // Get module $module = mcrypt_module_open($this->cipher, '', $this->mode, ''); // Validate key $this->validateKeyLength($this->key, $module); // Initialize decryption $initResult = mcrypt_generic_init($module, $this->key, $vector); if (!is_null($initResult)) { $this->throwInitError($initResult, 'decrypt'); } // Decrypt $decryptedData = mdecrypt_generic($module, $encryptedData); $decryptedData = str_replace("\x0", '', $decryptedData); // Deinitialize decryption mcrypt_generic_deinit($module); return $decryptedData; }
Decrypt data @param string $data Encrypted string @return string Decrypted data @throws \RuntimeException If mcrypt extension not loaded @throws \RuntimeException If decryption module initialization failed @throws \RuntimeException If HMAC integrity verification fails @api
entailment
protected function validateKeyLength($key, $module) { $keySize = strlen($key); $keySizeMin = 1; $keySizeMax = mcrypt_enc_get_key_size($module); $validKeySizes = mcrypt_enc_get_supported_key_sizes($module); if ($validKeySizes) { if (!in_array($keySize, $validKeySizes)) { throw new \InvalidArgumentException('Encryption key length must be one of: ' . implode(', ', $validKeySizes)); } } else { if ($keySize < $keySizeMin || $keySize > $keySizeMax) { throw new \InvalidArgumentException(sprintf( 'Encryption key length must be between %s and %s, inclusive', $keySizeMin, $keySizeMax )); } } }
Validate encryption key based on valid key sizes for selected cipher and cipher mode @param string $key Encryption key @param resource $module Encryption module @return void @throws \InvalidArgumentException If key size is invalid for selected cipher
entailment
protected function throwInitError($code, $function) { switch ($code) { case -4: throw new \RuntimeException(sprintf( 'There was a memory allocation problem while calling %s::%s', __CLASS__, $function )); break; case -3: throw new \RuntimeException(sprintf( 'An incorrect encryption key length was used while calling %s::%s', __CLASS__, $function )); break; default: if (is_integer($code) && $code < 0) { throw new \RuntimeException(sprintf( 'An unknown error was caught while calling %s::%s', __CLASS__, $function )); } break; } }
Throw an exception based on a provided exit code @param mixed $code @param string $function @throws \RuntimeException If there was a memory allocation problem @throws \RuntimeException If there was an incorrect key length specified @throws \RuntimeException If an unknown error occured
entailment
protected function runPaginationCountQuery($columns = ['*']) { if ($this->havings) { $query = $this->cloneWithout(['orders', 'limit', 'offset']) ->cloneWithoutBindings(['order']); // We don't need simple columns, only specials // like subselects which is why we're using // havings after all. foreach ($query->columns as $key => $value) { if (is_string($value)) { unset($query->columns[$key]); } } $countQuery = DB::table(DB::raw('('.$query->toSql().') as x'))->mergeBindings($query); // Using a aggregate here won't work when // groups are present because the // getCountForPagination() is // checking for it. if (!$this->groups) { $countQuery->setAggregate('count', $this->withoutSelectAliases($columns)); } return $countQuery->get()->all(); } return $this->cloneWithout(['columns', 'orders', 'limit', 'offset']) ->cloneWithoutBindings(['select', 'order']) ->setAggregate('count', $this->withoutSelectAliases($columns)) ->get()->all(); }
Run a pagination count query. @param array $columns @return array
entailment
public function encrypt(CryptInterface $crypt) { foreach ($this->data as $key => $value) { $this->set($key, $crypt->encrypt($value)); } }
Encrypt set @param \Slim\Interfaces\CryptInterface $crypt @return void @api
entailment
public function getMethod() { // Get actual request method $method = $this->env->get('REQUEST_METHOD'); $methodOverride = $this->headers->get('HTTP_X_HTTP_METHOD_OVERRIDE'); // Detect method override (by HTTP header or POST parameter) if (!empty($methodOverride)) { $method = strtoupper($methodOverride); } else if ($method === static::METHOD_POST) { $customMethod = $this->post(static::METHOD_OVERRIDE, false); if ($customMethod !== false) { $method = strtoupper($customMethod); } } return $method; }
Get HTTP method @return string @api
entailment
public function getUrl() { $url = $this->getScheme() . '://' . $this->getHost(); if (($this->getScheme() === 'https' && $this->getPort() !== 443) || ($this->getScheme() === 'http' && $this->getPort() !== 80)) { $url .= sprintf(':%s', $this->getPort()); } return $url; }
Get URL (scheme + host [ + port if non-standard ]) @return string @api
entailment
public function get($key = null, $default = null) { // Parse and cache query parameters if (is_null($this->queryParameters) === true) { $qs = $this->env->get('QUERY_STRING'); if (function_exists('mb_parse_str') === true) { mb_parse_str($qs, $this->queryParameters); // <-- Url decodes too } else { parse_str($qs, $this->queryParameters); // <-- Url decodes too } } // Fetch requested query parameter(s) if ($key) { if (array_key_exists($key, $this->queryParameters) === true) { $returnVal = $this->queryParameters[$key]; } else { $returnVal = $default; } } else { $returnVal = $this->queryParameters; } return $returnVal; }
Fetch GET query parameter(s) Use this method to fetch a GET request query parameter. If the requested GET query parameter identified by the argument does not exist, NULL is returned. If the argument is omitted, all GET query parameters are returned as an array. @param string $key @param mixed $default Default return value when key does not exist @return array|mixed|null @api
entailment
public function post($key = null, $default = null) { // Parse and cache request body if (is_null($this->body) === true) { $this->body = $_POST; // Parse raw body if form-urlencoded if ($this->isFormData() === true) { $rawBody = (string)$this->getBody(); if (function_exists('mb_parse_str') === true) { mb_parse_str($rawBody, $this->body); } else { parse_str($rawBody, $this->body); } } } // Fetch POST parameter(s) if ($key) { if (array_key_exists($key, $this->body) === true) { $returnVal = $this->body[$key]; } else { $returnVal = $default; } } else { $returnVal = $this->body; } return $returnVal; }
Fetch POST parameter(s) Use this method to fetch a POST body parameter. If the requested POST body parameter identified by the argument does not exist, NULL is returned. If the argument is omitted, all POST body parameters are returned as an array. @param string $key @param mixed $default Default return value when key does not exist @return array|mixed|null @throws \RuntimeException If environment input is not available @api
entailment
public function isFormData() { return ($this->getContentType() == '' && $this->getOriginalMethod() === static::METHOD_POST) || in_array($this->getMediaType(), self::$formDataMediaTypes); }
Does the Request body contain parsed form data? @return bool @api
entailment
public function getHost() { $host = $this->headers->get('HTTP_HOST'); if ($host) { if (strpos($host, ':') !== false) { $hostParts = explode(':', $host); return $hostParts[0]; } return $host; } return $this->env->get('SERVER_NAME'); }
Get Host @return string @api
entailment
public function getScheme() { $isHttps = false; if ($this->headers->has('X_FORWARDED_PROTO') === true) { $headerValue = $this->headers->get('X_FORWARDED_PROTO'); $isHttps = (strtolower($headerValue) === 'https'); } else { $headerValue = $this->env->get('HTTPS'); $isHttps = (empty($headerValue) === false && $headerValue !== 'off'); } return $isHttps ? 'https' : 'http'; }
Get Scheme (https or http) @return string @api
entailment
public function getClientIp() { $keys = array('HTTP_X_FORWARDED_FOR', 'CLIENT_IP', 'REMOTE_ADDR'); foreach ($keys as $key) { if ($this->env->has($key) === true) { return $this->env->get($key); } } return null; }
Get client IP address @return string @api
entailment
protected function parsePaths() { if (is_null($this->paths) === true) { // Server params $scriptName = $this->env->get('SCRIPT_NAME'); // <-- "/foo/index.php" $requestUri = $this->env->get('REQUEST_URI'); // <-- "/foo/bar?test=abc" or "/foo/index.php/bar?test=abc" $queryString = $this->getQueryString(); // <-- "test=abc" or "" // Physical path if (strpos($requestUri, $scriptName) !== false) { $physicalPath = $scriptName; // <-- Without rewriting } else { $physicalPath = str_replace('\\', '', dirname($scriptName)); // <-- With rewriting } $scriptName = rtrim($physicalPath, '/'); // <-- Remove trailing slashes // Virtual path $pathInfo = substr_replace($requestUri, '', 0, strlen($physicalPath)); // <-- Remove physical path $pathInfo = str_replace('?' . $queryString, '', $pathInfo); // <-- Remove query string $pathInfo = '/' . ltrim($pathInfo, '/'); // <-- Ensure leading slash $this->paths = array(); $this->paths['physical'] = $scriptName; $this->paths['virtual'] = $pathInfo; } return $this->paths; }
Parse the physical and virtual paths from the request URI @return array
entailment
public function add($key): bool { if (\is_null($key)) { throw new InvalidArgumentException("Can't add NULL to {$this->name}."); } // Type-hint the attribute value of an Eloquent result, if it was // given instead of a string. if ($key instanceof Eloquent) { $key = $key->getAttribute('name'); } $keyword = $this->getKeyword($key); if ($this->has($keyword)) { return false; } \array_push($this->items, $keyword->getSlug()); return true; }
Add a key to collection. @param \Illuminate\Database\Eloquent\Model|string $key @throws \InvalidArgumentException @return bool
entailment
public function attach($keys): bool { if ($keys instanceof Arrayable) { $keys = $keys->toArray(); } foreach ($keys as $key) { $this->add($key); } return true; }
Add multiple key to collection. @param \Illuminate\Contracts\Support\Arrayable|array $keys @return bool
entailment
public function detach($keys): bool { if ($keys instanceof Arrayable) { $keys = $keys->toArray(); } foreach ($keys as $key) { $this->remove($key); } return true; }
Remove multiple key to collection. @param \Illuminate\Contracts\Support\Arrayable|array $keys @return bool
entailment
public function filter($request): array { if (\is_array($request)) { return $request; } elseif ($request === '*') { return $this->get(); } elseif ($request[0] === '!') { return \array_diff($this->get(), [\substr($request, 1)]); } return [$request]; }
Filter request. @param string|array $request @return array
entailment
public function findKey($name): ?int { $keyword = $this->getKeyword($name); if (! (\is_numeric($name) && $keyword->hasIn($this->items))) { return (string) $keyword->searchIn($this->items); } return $name; }
Find collection key from a name. @param \Orchestra\Support\Keyword|string $name @return int|null
entailment
public function has($key): bool { $key = $this->getKeyword($key)->getSlug(); return ! empty($key) && \in_array($key, $this->items); }
Determine whether a key exists in collection. @param \Orchestra\Support\Keyword|string $key @return bool
entailment
public function rename($from, $to): bool { $key = $this->search($from); if (\is_null($key)) { return false; } $this->items[$key] = $this->getKeyword($to)->getSlug(); return true; }
Rename a key from collection. @param \Orchestra\Support\Keyword|string $from @param \Orchestra\Support\Keyword|string $to @return bool
entailment
public function search($key): ?int { $id = $this->getKeyword($key)->searchIn($this->items); if (false === $id) { return null; } return $id; }
Get the ID from a key. @param \Orchestra\Support\Keyword|string $key @return int|null
entailment
protected function getKeyword($key): Keyword { if ($key instanceof Keyword) { return $key; } if (! isset($this->cachedKeyword[$key])) { $this->cachedKeyword[$key] = Keyword::make($key); } return $this->cachedKeyword[$key]; }
Get keyword instance. @param \Orchestra\Support\Keyword|string $key @return \Orchestra\Support\Keyword
entailment
public function start() { // Initialize new session if a session is not already started if ($this->isStarted() === false) { $this->initialize(); } // Set data source from which session data is loaded, to which session data is saved if (isset($this->dataSource) === false) { $this->dataSource = &$_SESSION; } // Load existing session data if available if (isset($this->dataSource['slim.session']) === true) { $this->replace($this->dataSource['slim.session']); } }
Start the session @api
entailment
public function isStarted() { $started = false; if (version_compare(phpversion(), '5.4.0', '>=')) { $started = session_status() === PHP_SESSION_ACTIVE ? true : false; } else { $started = session_id() === '' ? false : true; } return $started; }
Is session started? @return bool @see http://us2.php.net/manual/en/function.session-status.php#113468 Sourced from this comment from on php.net
entailment
public function config($name, $value = null) { if (func_num_args() === 1) { if (is_array($name)) { foreach ($name as $key => $value) { $this['settings'][$key] = $value; } } else { return isset($this['settings'][$name]) ? $this['settings'][$name] : null; } } else { $this['settings'][$name] = $value; } }
Configure Slim Settings This method defines application settings and acts as a setter and a getter. If only one argument is specified and that argument is a string, the value of the setting identified by the first argument will be returned, or NULL if that setting does not exist. If only one argument is specified and that argument is an associative array, the array will be merged into the existing application settings. If two arguments are provided, the first argument is the name of the setting to be created or updated, and the second argument is the setting value. @param string|array $name If a string, the name of the setting to set or retrieve. Else an associated array of setting names and values @param mixed $value If name is a string, the value of the setting identified by $name @return mixed The value of a setting if only one argument is a string @api
entailment
protected function mapRoute($args) { $pattern = array_shift($args); $callable = array_pop($args); $route = new \Slim\Route($pattern, $callable, $this['settings']['routes.case_sensitive']); $this['router']->map($route); if (count($args) > 0) { $route->setMiddleware($args); } return $route; }
Add GET|POST|PUT|PATCH|DELETE route Adds a new route to the router with associated callable. This route will only be invoked when the HTTP request's method matches this route's method. ARGUMENTS: First: string The URL pattern (REQUIRED) In-Between: mixed Anything that returns TRUE for `is_callable` (OPTIONAL) Last: mixed Anything that returns TRUE for `is_callable` (REQUIRED) The first argument is required and must always be the route pattern (ie. '/books/:id'). The last argument is required and must always be the callable object to be invoked when the route matches an HTTP request. You may also provide an unlimited number of in-between arguments; each interior argument must be callable and will be invoked in the order specified before the route's callable is invoked. USAGE: Slim::get('/foo'[, middleware, middleware, ...], callable); @param array @return \Slim\Route
entailment
public function get() { $args = func_get_args(); return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_GET, \Slim\Http\Request::METHOD_HEAD); }
Add GET route @return \Slim\Route @api
entailment
public function post() { $args = func_get_args(); return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_POST); }
Add POST route @return \Slim\Route @api
entailment
public function delete() { $args = func_get_args(); return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_DELETE); }
Add DELETE route @return \Slim\Route @api
entailment