sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function options() { $args = func_get_args(); return $this->mapRoute($args)->via(\Slim\Http\Request::METHOD_OPTIONS); }
Add OPTIONS route @return \Slim\Route @api
entailment
public function group() { $args = func_get_args(); $pattern = array_shift($args); $callable = array_pop($args); $this['router']->pushGroup($pattern, $args); if (is_callable($callable)) { call_user_func($callable); } $this['router']->popGroup(); ...
Route Groups This method accepts a route pattern and a callback. All route declarations in the callback will be prepended by the group(s) that it is in. Accepts the same parameters as a standard route so: (pattern, middleware1, middleware2, ..., $callback) @api
entailment
public function notFound ($callable = null) { if (is_callable($callable)) { $this['notFound'] = function () use ($callable) { return $callable; }; } else { ob_start(); if (isset($this['notFound']) && is_callable($this['notFound'])) { ...
Not Found Handler This method defines or invokes the application-wide Not Found handler. There are two contexts in which this method may be invoked: 1. When declaring the handler: If the $callable parameter is not null and is callable, this method will register the callable to be invoked when no routes match the cur...
entailment
public function error($argument = null) { if (is_callable($argument)) { //Register error handler $this['error'] = function () use ($argument) { return $argument; }; } else { //Invoke error handler $this['response']->write($t...
Error Handler This method defines or invokes the application-wide Error handler. There are two contexts in which this method may be invoked: 1. When declaring the handler: If the $argument parameter is callable, this method will register the callable to be invoked when an uncaught Exception is detected, or when othe...
entailment
protected function callErrorHandler($argument = null) { $this['response']->setStatus(500); ob_start(); if (isset($this['error']) && is_callable($this['error'])) { call_user_func_array($this['error'], array($argument)); } else { call_user_func_array(array($thi...
Call error handler This will invoke the custom or default error handler and RETURN its output. @param \Exception|null $argument @return string
entailment
public function render($template, $data = array(), $status = null) { if (!is_null($status)) { $this['response']->setStatus($status); } $this['view']->display($template, $data); }
Render a template Call this method within a GET, POST, PUT, PATCH, DELETE, NOT FOUND, or ERROR callable to render a template whose output is appended to the current HTTP response body. How the template is rendered is delegated to the current View. @param string $template The name of the template passed into the view...
entailment
public function lastModified($time) { if (is_integer($time)) { $this['response']->setHeader('Last-Modified', gmdate('D, d M Y H:i:s T', $time)); if ($time === strtotime($this['request']->getHeader('IF_MODIFIED_SINCE'))) { $this->halt(304); } } else...
Set Last-Modified HTTP Response Header Set the HTTP 'Last-Modified' header and stop if a conditional GET request's `If-Modified-Since` header matches the last modified time of the resource. The `time` argument is a UNIX timestamp integer value. When the current request includes an 'If-Modified-Since' header that match...
entailment
public function etag($value, $type = 'strong') { // Ensure type is correct if (!in_array($type, array('strong', 'weak'))) { throw new \InvalidArgumentException('Invalid Slim::etag type. Expected "strong" or "weak".'); } // Set etag value $value = '"' . $value . '...
Set ETag HTTP Response Header Set the etag header and stop if the conditional GET request matches. The `value` argument is a unique identifier for the current resource. The `type` argument indicates whether the etag should be used as a strong or weak cache validator. When the current request includes an 'If-None-Matc...
entailment
public function expires($time) { if (is_string($time)) { $time = strtotime($time); } $this['response']->setHeader('Expires', gmdate('D, d M Y H:i:s T', $time)); }
Set Expires HTTP response header The `Expires` header tells the HTTP client the time at which the current resource should be considered stale. At that time the HTTP client will send a conditional GET request to the server; the server may return a 200 OK if the resource has changed, else a 304 Not Modified if the resou...
entailment
public function setCookie($name, $value, $time = null, $path = null, $domain = null, $secure = null, $httponly = null) { $settings = array( 'value' => $value, 'expires' => is_null($time) ? $this->config('cookies.lifetime') : $time, 'path' => is_null($path) ? $this->config...
Set HTTP cookie to be sent with the HTTP response @param string $name The cookie name @param string $value The cookie value @param int|string $time The duration of the cookie; If integer, should be UNIX timestamp; If string, converted to UNIX timestamp with `strtotime`; @param string $path ...
entailment
public function deleteCookie($name, $path = null, $domain = null, $secure = null, $httponly = null) { $settings = array( 'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain, 'path' => is_null($path) ? $this->config('cookies.path') : $path, 'secure' =>...
Delete HTTP cookie (encrypted or unencrypted) Remove a Cookie from the client. This method will overwrite an existing Cookie with a new, empty, auto-expiring Cookie. This method's arguments must match the original Cookie's respective arguments for the original Cookie to be removed. If any of this method's arguments ar...
entailment
public function halt($status, $message = '') { $this->cleanBuffer(); $this['response']->setStatus($status); $this['response']->write($message, true); $this->stop(); }
Halt Stop the application and immediately send the response with a specific status and body to the HTTP client. This may send any type of response: info, success, redirect, client error, or server error. If you need to render a template AND customize the response status, use the application's `render()` method instead...
entailment
public function hook($name, $callable, $priority = 10) { if (!isset($this->hooks[$name])) { $this->hooks[$name] = array(array()); } if (is_callable($callable)) { $this->hooks[$name][(int) $priority][] = $callable; } }
Assign hook @param string $name The hook name @param mixed $callable A callable object @param int $priority The hook priority; 0 = high, 10 = low @api
entailment
public function applyHook($name, $hookArg = null) { if (!isset($this->hooks[$name])) { $this->hooks[$name] = array(array()); } if (!empty($this->hooks[$name])) { // Sort by priority, low to high, if there's more than one priority if (count($this->hooks[$na...
Invoke hook @param string $name The hook name @param mixed $hookArg (Optional) Argument for hooked functions @api
entailment
public function getHooks($name = null) { if (!is_null($name)) { return isset($this->hooks[(string) $name]) ? $this->hooks[(string) $name] : null; } else { return $this->hooks; } }
Get hook listeners Return an array of registered hooks. If `$name` is a valid hook name, only the listeners attached to that hook are returned. Else, all listeners are returned as an associative array whose keys are hook names and whose values are arrays of listeners. @param string $name A hook name (Optional) @...
entailment
public function clearHooks($name = null) { if (!is_null($name) && isset($this->hooks[(string) $name])) { $this->hooks[(string) $name] = array(array()); } else { foreach ($this->hooks as $key => $value) { $this->hooks[$key] = array(array()); } ...
Clear hook listeners Clear all listeners for all hooks. If `$name` is a valid hook name, only the listeners attached to that hook will be cleared. @param string $name A hook name (Optional) @api
entailment
public function sendFile($file, $contentType = false) { $fp = fopen($file, "r"); $this['response']->setBody(new \Guzzle\Stream\Stream($fp)); if ($contentType) { $this['response']->setHeader("Content-Type", $contentType); } else { if (file_exists($file)) { ...
Send a File This method streams a local or remote file to the client @param string $file The URI of the file, can be local or remote @param string $contentType Optional content type of the stream, if not specified Slim will attempt to get this @api
entailment
public function sendProcess($command, $contentType = "text/plain") { $this['response']->setBody(new \Guzzle\Stream\Stream(popen($command, 'r'))); $this['response']->setHeader("Content-Type", $contentType); }
Send a Process This method streams a process to a client @param string $command The command to run @param string $contentType Optional content type of the stream @api
entailment
public function setDownload($filename = false) { $h = "attachment;"; if ($filename) { $h .= "filename='" . $filename . "'"; } $this['response']->setHeader("Content-Disposition", $h); }
Set Download This method triggers a download in the browser @param string $filename Optional filename for the download @api
entailment
public function add(\Slim\Middleware $newMiddleware) { $middleware = $this['middleware']; if(in_array($newMiddleware, $middleware)) { $middleware_class = get_class($newMiddleware); throw new \RuntimeException("Circular Middleware setup detected. Tried to queue the same Middle...
Add middleware This method prepends new middleware to the application middleware stack. The argument must be an instance that subclasses Slim_Middleware. @param \Slim\Middleware @api
entailment
public function run() { set_error_handler(array('\Slim\App', 'handleErrors')); // Invoke middleware and application stack try { $this['middleware'][0]->call(); } catch (\Exception $e) { $this['response']->write($this->callErrorHandler($e), true); } ...
Run This method invokes the middleware stack, including the core Slim application; the result is an array of HTTP status, header, and body. These three items are returned to the HTTP client. @api
entailment
protected function dispatchRequest(\Slim\Http\Request $request, \Slim\Http\Response $response) { try { $this->applyHook('slim.before'); ob_start(); $this->applyHook('slim.before.router'); $dispatched = false; $matchedRoutes = $this['router']->getMa...
Dispatch request and build response This method will route the provided Request object against all available application routes. The provided response will reflect the status, header, and body set by the invoked matching route. The provided Request and Response objects are updated by reference. There is no value retu...
entailment
public function subRequest($url, $method = 'GET', array $headers = array(), array $cookies = array(), $body = '', array $serverVariables = array()) { // Build sub-request and sub-response $environment = new \Slim\Environment(array_merge(array( 'REQUEST_METHOD' => $method, 'RE...
Perform a sub-request from within an application route This method allows you to prepare and initiate a sub-request, run within the context of the current request. This WILL NOT issue a remote HTTP request. Instead, it will route the provided URL, method, headers, cookies, body, and server variables against the set of...
entailment
public function finalize() { if (!$this->responded) { $this->responded = true; // Finalise session if it has been used if (isset($_SESSION)) { // Save flash messages to session $this['flash']->save(); // Encrypt, save, close s...
Finalize send response This method sends the response object
entailment
protected function defaultError($e) { $this->contentType('text/html'); if ($this['mode'] === 'development') { $title = 'Slim Application Error'; $html = ''; if ($e instanceof \Exception) { $code = $e->getCode(); $message = $e->get...
Default Error handler
entailment
public function up() { if (! Schema::hasColumn('users', 'remember_token')) { Schema::table('users', function (Blueprint $table) { $table->rememberToken()->after('status'); }); } }
Run the migrations. @return void
entailment
public function make(string $name = null, ?Provider $memory = null): AuthorizationContract { $name = $name ?? 'default'; if (! isset($this->drivers[$name])) { $this->drivers[$name] = (new Authorization($name, $memory))->setAuthenticator($this->auth); } return $this->dri...
Initiate a new ACL Container instance. @param string|null $name @param \Orchestra\Contracts\Memory\Provider|null $memory @return \Orchestra\Contracts\Authorization\Authorization
entailment
public function register($name, ?callable $callback = null): AuthorizationContract { if (\is_callable($name)) { $callback = $name; $name = null; } $instance = $this->make($name); $callback($instance); return $instance; }
Register an ACL Container instance with Closure. @param string $name @param callable|null $callback @return \Orchestra\Contracts\Authorization\Authorization
entailment
public function finish() { // Re-sync before shutting down. foreach ($this->drivers as $acl) { $acl->sync(); } $this->drivers = []; return $this; }
Shutdown/finish all ACL. @return $this
entailment
public function up() { Schema::create('users', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('email')->unique(); $table->string('password'); Event::dispatch('orchestra.install.schema: users', [$table]); $table->string...
Run the migrations. @return void
entailment
public function parse(array $environment) { foreach ($environment as $key => $value) { $this->set($key, $value); } }
Parse environment array This method will parse an environment array and add the data to this collection @param array $environment @return void
entailment
public function mock(array $settings = array()) { $this->mocked['REQUEST_TIME'] = time(); $settings = array_merge($this->mocked, $settings); $this->parse($settings); }
Mock environment This method will parse a mock environment array and add the data to this collection @param array $environment @return void
entailment
public function up() { Schema::create('user_role', function (Blueprint $table) { $table->bigIncrements('id'); $table->bigInteger('user_id')->unsigned(); $table->bigInteger('role_id')->unsigned(); $table->nullableTimestamps(); $table->index(['use...
Run the migrations. @return void
entailment
public function parseHeaders(EnvironmentInterface $environment) { foreach ($environment as $key => $value) { $key = strtoupper($key); if (strpos($key, 'HTTP_') === 0 || in_array($key, $this->special)) { if ($key === 'HTTP_CONTENT_TYPE' || $key === 'HTTP_CONTENT_LENGT...
Parse provided headers into this collection @param \Slim\Interfaces\EnvironmentInterface $environment @return void @api
entailment
public function get($key, $asArray = false) { if ($asArray) { return parent::get($this->normalizeKey($key), array()); } else { return implode(', ', parent::get($this->normalizeKey($key), array())); } }
Get data value with key @param string $key The data key @param mixed $default The value to return if data key does not exist @return mixed The data value, or the default value @api
entailment
public function add($key, $value) { $header = $this->get($key, true); if (is_array($value)) { $header = array_merge($header, $value); } else { $header[] = $value; } parent::set($this->normalizeKey($key), $header); }
Add data to key @param string $key The data key @param mixed $value The data value @api
entailment
public function normalizeKey($key) { $key = strtolower($key); $key = str_replace(array('-', '_'), ' ', $key); $key = preg_replace('#^http #', '', $key); $key = ucwords($key); $key = str_replace(' ', '-', $key); return $key; }
Transform header name into canonical form @param string $key @return string
entailment
protected function normalizeValue($value, $original = false) { if (is_array($value)) { return $value; } if ($value instanceof Arrayable) { return $value->toArray(); } return [ $value => [] ]; }
Normalizes a value to make sure it can be processed uniformly. @param mixed $value @param bool $original @return mixed
entailment
protected function decorateFieldData(array $data) { // Get the key-reference pairs to allow the form to display values for the // currently selected keys for the model. $keys = $data['value'] ?: []; if ($keys instanceof Arrayable) { $keys = $keys->toArray(); } ...
Enriches field data before passing it on to the view. @param array $data @return array
entailment
public function observe($class) { $className = is_string($class) ? $class : get_class($class); if (!class_exists($className)) { return; } foreach ($this->getObservableAbilities() as $ability) { if (method_exists($class, $ability)) { $this->re...
Register an observer with the Component. @param $class
entailment
public function registerAbility($ability, $callback) { $this->abilities->put($ability, $this->makeAbilityCallback($callback)); }
register ability to access. @param string $ability @param string|\Closure $callback
entailment
protected function makeAbilityCallback($callback) { return function ($component) use ($callback) { if (is_callable($callback)) { return $callback($component); } if (is_string($callback)) { list($class, $method) = Str::parseCallback($callbac...
@param string|\Closure $callback @return \Closure
entailment
final public function can($ability) { if (! $this->abilities->has($ability)) { return false; } $value = $this->abilities->get($ability); return $value($this) ? true : false; }
Determine if the entity has a given ability. @param string $ability @return bool
entailment
public function getAccesses() { return $this->abilities->mapWithKeys(function ($item, $key) { return [$key => $this->can($key)]; }); }
Get all ability. @return Collection
entailment
public function render(Model $model, $source) { $source = $this->resolveModelSource($model, $source); if ( ! ($source instanceof AttachmentInterface)) { throw new UnexpectedValueException("Paperclip strategy expects Attachment as source"); } $resize = $this->getVariantt...
Renders a display value to print to the list view. @param Model $model @param mixed|AttachmentInterface $source source column, method name or value @return string|View
entailment
protected function getSmallestVariant(AttachmentInterface $attachment) { $smallestKey = null; $smallest = null; foreach (array_get($attachment->getNormalizedConfig(), 'variants', []) as $variantKey => $variantSteps) { if ( ! $variantSteps) { continue; ...
Returns smallest available resize for the attachment. @param AttachmentInterface $attachment @return null|string
entailment
public function field() { $field = $this->getAttribute('field'); if ($field || false === $field) { return $field; } return $this->getAttribute('relation'); }
Returns the field key. @return mixed
entailment
public function columns(): array { $columns = $this->columns ?: []; if ( ! count($columns)) { $columns = $this->getGroupContentColumns(); } // If columns are set, fill them out if they don't fit the grid if ($remainder = $this->getRemainderForColumns($columns)) ...
Returns grid column layout as list of twelfths. @return int[]
entailment
public function matchesFieldKeys(array $keys): bool { if ( ! count($keys)) return false; return count(array_intersect($keys, $this->descendantFieldKeys())) > 0; }
Returns whether any of the children have field keys that appear in a given list of keys. @param string[] $keys @return bool
entailment
protected function getGroupContentColumns(): array { $contents = $this->getGroupContents(); $contentCount = count($contents); $denominator = floor(static::GRID_SIZE_WITHOUT_LABEL / $contentCount); $labelWidth = $denominator > 1 ? 2 : 1; // If there is enough space, make l...
Returns default column widths based on content types. @return int[]
entailment
protected function getGroupContents(): array { $contents = []; foreach ($this->children() as $key => $child) { if (is_string($child)) { $contents[] = [ 'key' => $child, 'type' => 'field' ]; continue; } $contents[] = [ 'key' => $k...
Returns the groups contents with type information. @return array list of arrays with key, type child data
entailment
protected function getRemainderForColumns(array $columns): int { $total = array_reduce($columns, function ($total, $column) { return $total + $column; }); return max(static::GRID_SIZE_WITHOUT_LABEL - $total, 0); }
Returns remainder for column widths, if total is smaller than full grid (minus label). @param int[] $columns @return int
entailment
protected function modifyRelationQueryForContext(Model $model, $query) { /** @var Relation $relation */ $information = $this->getInformationRepository()->getByModel($model); if ( ! $information) { return $query; } // Deal with global scopes, if any $disa...
Modifies the relation query according to the model's CMS information. @param Model $model @param Builder|Relation $query @return Builder
entailment
public function renderField($value, $originalValue, array $errors = [], $locale = null) { $value = $this->normalizeValue($value); $originalValue = $this->normalizeValue($originalValue, true); $type = $this->field->type ?: array_get($this->field->options(), 'type', $this->getDefaultF...
Renders a form field. @param mixed $value @param mixed $originalValue @param array $errors @param null|string $locale @return string
entailment
protected function getFormFieldName($locale = null) { if ( ! $locale) { return $this->field->key(); } return $this->field->key() . '[' . $locale . ']'; }
Returns name for the form field input tag. @param null|string $locale @return string
entailment
public function read($path) { try { $contents = file_get_contents($path); } catch (Exception $e) { throw (new ModelConfigurationFileException( "Could not find or open configuraion file at '{$path}'" ))->setPath($path); } // Deter...
Attempts to retrieve CMS model information array data from a file. @param string $path @return array @throws ModelConfigurationFileException
entailment
public function label() { if ($this->label_translated) { return cms_trans($this->label_translated); } if ($this->label) { return $this->label; } return ucfirst(str_replace('_', ' ', snake_case($this->strategy))); }
Returns display label for the export link/button. @return string
entailment
public function permissions() { if (is_array($this->permissions)) { return $this->permissions; } if ($this->permissions) { return [ $this->permissions ]; } return false; }
Returns permissions required to use the export strategy. @return false|string[]
entailment
public function handle() { /** @var \Illuminate\Database\Connection|CouchbaseConnection $connection */ $connection = $this->databaseManager->connection($this->option('database')); if ($connection instanceof CouchbaseConnection) { $bucket = $connection->openBucket($this->argument(...
Execute the console command
entailment
protected function renderInlineAssignment($name, $value) { if ($value instanceof RawText) { $value = $value->getText(); } else { $value = $this->escape($value); } return $this->escape($name).'='.$value; }
Renders an inline assignment (without indent or end return line). It will handle escaping, according to the value. @param string $name A name @param string $value A value @return string
entailment
protected function modelHasTrait($names) { if ( ! is_array($names)) { $names = (array) $names; } return (bool) count(array_intersect($names, $this->getTraitNames())); }
Returns whether the model class uses a trait by a name or list of names. @param string|string[] $names @return bool
entailment
public function initialize(ModelActionReferenceDataInterface $data, $modelClass) { $this->actionData = $data; $this->modelClass = $modelClass; $this->performInit(); return $this; }
Initializes the strategy instances for further calls. @param ModelActionReferenceDataInterface $data @param string $modelClass FQN of current model @return $this
entailment
public function render(Model $model, $source) { $source = $this->resolveModelSource($model, $source); if ($this->interpretAsBoolean($source)) { return '<i class="fa fa-check text-success" title="' . e(cms_trans('common.boolean.true')) . '"></i>'; } return '<i class="fa ...
Renders a display value to print to the list view. @param Model $model @param mixed $source source column, method name or value @return string
entailment
protected function interpretAsBoolean($value) { if (is_bool($value)) { return $value; } if (is_numeric($value)) { return $value != 0; } if (is_string($value)) { $value = trim($value); if ('' === $value || preg_match('#^n|no|...
Parses a source value as a boolean value. @param mixed $value @return bool
entailment
public function getForModelClassByType($modelClass, $type, $key, $targetModel = null) { $info = $this->getModelInformation($modelClass); if ( ! $info) return false; return $this->getForInformationByType($info, $type, $key, $targetModel); }
Returns reference data for a model class, type and key. @param string $modelClass @param string $type @param string $key @param string|null $targetModel for multiple/nested models, the target to use @return ModelMetaReferenceInterface|false
entailment
public function getForInformationByType(ModelInformationInterface $info, $type, $key, $targetModel = null) { // Find the reference information for type and key specified switch ($type) { case 'form.field': return $this->getInformationReferenceDataForFormField($info, $key...
Returns reference data for model information, type and key. @param ModelInformationInterface $info @param string $type @param string $key @param string|null $targetModel for multiple/nested models, the target to use @return ModelMetaReferenceInterface|false
entailment
public function getNestedModelClassesByType(ModelInformationInterface $info, $type, $key) { // Find the reference information for type and key specified switch ($type) { case 'form.field': return $this->getInformationReferenceModelClassesForFormField($info, $key); ...
Returns nested model classes for model information, type and key. This can be used to check whether reference data is for multiple models, and if so, which. @param ModelInformationInterface $info @param string $type @param string $key @return false|string[] Returns false if the...
entailment
protected function getNestedReferenceFieldOptionData(array $options, $modelClass) { $data = array_get($options, 'models.' . $modelClass, false); if (false === $data || ! is_array($data)) { // If we could not retrieve the model data by key, // it was either omitted are set as...
Returns nested reference data for a given model class, if possible. @param array $options @param string $modelClass @return array
entailment
protected function determineTargetModelFromSource($modelClass, $source) { if ( ! is_a($modelClass, Model::class, true)) { // @codeCoverageIgnoreStart throw new UnexpectedValueException("{$modelClass} is not an Eloquent model"); // @codeCoverageIgnoreEnd } ...
Resolves and returns model instance for a given source on a (CMS) model. @param string $modelClass @param string $source @return Model
entailment
protected function enrichReferenceData(ModelMetaReferenceInterface $data) { // If the source/strategy are not set, check if we can use the model's reference data if (null === $data->source() || null === $data->strategy()) { // todo: take into account that this might be a morph relation....
Enriches refernce data object as required. @param ModelMetaReferenceInterface|ModelMetaReference $data @return ModelMetaReferenceInterface
entailment
protected function decorateFieldData(array $data) { // Get the key-reference pairs required to fill the drop-down $referenceData = $this->getReferenceDataProvider()->getForModelClassByType( get_class($this->model), 'form.field', $this->field->key() ); ...
Enriches field data before passing it on to the view. @param array $data @return array
entailment
protected function applyParameter($parameterName, $parameterValue, $query) { if ( ! array_key_exists($parameterName, $this->filterInformation)) { parent::applyParameter($parameterName, $parameterValue, $query); // @codeCoverageIgnoreStart return; // @codeCover...
{@inheritdoc}
entailment
public function boot() { $this->package('atrakeur/forum'); if (\Config::get('forum::routes.enable')) { $routebase = \Config::get('forum::routes.base'); $viewController = \Config::get('forum::integration.viewcontroller'); $postController = \Config::get('forum::integration.postcontroller'); includ...
Bootstrap the application events. @return void
entailment
public function registerCommands() { $this->app['foruminstallcommand'] = $this->app->share(function($app) { return new InstallCommand; }); $this->commands('foruminstallcommand'); }
Register package artisan commands. @return void
entailment
protected function getListColumnStrategyInstances() { $instances = []; $info = $this->getModelInformation(); foreach ($info->list->columns as $key => $data) { $instance = $this->getListDisplayFactory()->make($data->strategy); // Feed any extra information we can g...
Collects and returns strategy instances for list columns. @return ListDisplayInterface[]
entailment
public function collect() { $this->information = new Collection; $this->cmsModelFiles = $this->getCmsModelFiles(); $this->modelClasses = $this->getModelsToCollect(); $this->collectRawModels() ->collectCmsModels() ->enrichModelInformation(); retur...
Collects and returns information about models. @return Collection|ModelInformationInterface[]
entailment
protected function collectRawModels() { foreach ($this->modelClasses as $class) { $key = $this->moduleHelper->modelInformationKeyForModel($class); try { $this->information->put($key, $this->modelAnalyzer->analyze($class)); } catch (\Exception $e) { ...
Collects information about config-defined app model classes. @return $this @throws ModelInformationCollectionException
entailment
protected function collectCmsModels() { foreach ($this->cmsModelFiles as $file) { try { $this->collectSingleCmsModelFromFile($file); } catch (\Exception $e) { $message = $e->getMessage(); if ($e instanceof ModelConfigurationDataExce...
Collects information from dedicated CMS model information classes. @return $this @throws ModelInformationCollectionException
entailment
protected function collectSingleCmsModelFromFile(SplFileInfo $file) { $info = $this->informationReader->read($file->getRealPath()); if ( ! is_array($info)) { $path = basename($file->getRelativePath() ?: $file->getRealPath()); throw new UnexpectedValueException( ...
Collects CMS configuration information from a given Spl file. @param SplFileInfo $file
entailment
protected function makeModelFqnFromCmsModelPath($path) { $extension = pathinfo($path, PATHINFO_EXTENSION); if ($extension) { $path = substr($path, 0, -1 * strlen($extension) - 1); } return rtrim(config('cms-models.collector.source.models-namespace'), '\\') ...
Returns the FQN for the model that is related to a given cms model information file path. @param string $path relative path @return string
entailment
public function apply(Builder $query) { $name = $this->getName(); if (strpos($name, '.') !== false) { list($relation, $name) = explode('.', $name, 2); $query->whereHas($relation, function ($q) use ($name) { $this->buildQuery($q, $name); }); ...
{@inheritdoc}
entailment
protected function buildQuery(Builder $query, $name) { $op = $this->getOperator(); $value = $this->getValue(); switch ($op) { case 'in': $query->whereIn($name, (array) $value); break; case 'between': $query->whereBetwee...
Build the filter query. @param \Illuminate\Database\Eloquent\Builder $query @param string $name
entailment
protected function getMorphableModelsForFieldData(ModelFormFieldDataInterface $data) { $modelsOption = array_get($data->options(), 'models', []); // Users may have set the string value with the model class, instead of a class => array value pair $modelClasses = array_map( functi...
Returns the model class names that the model may be related to. @param ModelFormFieldDataInterface|ModelFormFieldData $data @return string[]
entailment
public function apply(Builder $query) { $this->each(function ($scope) use ($query) { $method = array_shift($scope); $parameters = $scope; call_user_func_array([$query, $method], $parameters); }); }
{@inheritdoc}
entailment
protected function performStep() { $relations = []; foreach ($this->reflection()->getMethods() as $method) { if ( ! $this->isPotentialRelationMethod($method) || ! $this->isReflectionMethodEloquentRelation($method) ) { continue; ...
Performs the analyzer step on the stored model information instance.
entailment
protected function isPotentialRelationMethod(ReflectionMethod $method) { if ( ! $method->isPublic() // Check if we should ignore the method always || in_array($method->name, $this->getIgnoredRelationNames()) // If the method has required parameters, we ca...
Returns whether a reflected method may be an Eloquent relation. @param ReflectionMethod $method @return bool
entailment
protected function isNullableKey($key) { if ( ! array_key_exists($key, $this->info->attributes)) { throw new RuntimeException( "Foreign key '{$key}' defined for relation does not exist on model " . get_class($this->model()) ); } return (bool) $this->i...
Returns whether attribute with key is known to be nullable. @param string $key @return bool
entailment
protected function isReflectionMethodEloquentRelation(ReflectionMethod $method) { // Check if there is a docblock cms tag // this may either 'ignore' the method, or confirm it as a 'relation' $cmsTags = $this->getCmsDocBlockTags($method); if (array_get($cmsTags, 'relation')) { ...
Determines whether a given method is a typical relation method @param ReflectionMethod $method @return bool
entailment
protected function findRelationMethodCall($methodBody) { $methodBody = trim(preg_replace('#\\n\\s*#', '', $methodBody)); // find the last potential relation method opener and position $foundOpener = null; $lastPosition = -1; foreach ($this->relationMethodCallOpeners() as $...
Attempts to find the relation method call in a string method body. This looks for $this->belongsTo(...) and the like. @param string $methodBody @return string|false
entailment
public function render(Model $model, $source) { $source = $this->resolveModelSource($model, $source); return '#' . $model->getKey() . ': ' . $source; }
Returns model reference string @param Model $model @param string $source @return string
entailment
public function analyze(Model $model, $strategy = 'translatable') { $this->model = $model; $this->info = new ModelInformation([]); switch ($strategy) { case 'translatable': $this->analyzeForTranslatable(); break; // @codeCoverageIgn...
Analyzes a model for its translations and returns relevant information. @param Model $model @param string $strategy @return ModelInformation
entailment
protected function analyzeForTranslatable() { /** @var Model|Translatable $model */ $model = $this->model; $translationModel = $model->getTranslationModelName(); $this->info = $this->analyzer->analyze($translationModel); $attributes = $this->info['attributes']; fo...
Analyzes a model using the translatable trait strategy.
entailment
protected function decorateFieldData(array $data) { // Prevent causing errors in the view if the value is not castable to string. try { $data['value'] = (string) $data['value']; } catch (\Exception $e) { throw new FormFieldDisplayException( "Failed t...
Enriches field data before passing it on to the view. @param array $data @return array @throws FormFieldDisplayException
entailment
protected function decorateFieldData(array $data) { $data['hasTextField'] = (bool) array_get($this->field->options(), 'text'); // Default location to use, if any if ( array_get($this->field->options(), 'default_latitude') && array_get($this->field->options(), 'default_longit...
Enriches field data before passing it on to the view. @param array $data @return array
entailment
public function handle() { /** @var \Illuminate\Database\Connection|CouchbaseConnection $connection */ $connection = $this->databaseManager->connection($this->option('database')); if ($connection instanceof CouchbaseConnection) { /** @var \Couchbase\Bucket $bucket */ ...
Execute the console command
entailment
public function compileInsert(Builder $query, array $values) { // keyspace-ref: $table = $this->wrapTable($query->from); // use-keys-clause: $keyClause = $this->wrapKey($query->key); // returning-clause $returning = implode(', ', $query->returning); if (!is_a...
{@inheritdoc}
entailment
public function compileDelete(Builder $query) { // keyspace-ref: $table = $this->wrapTable($query->from); // use-keys-clause: $keyClause = null; if ($query->key) { $key = $this->wrapKey($query->key); $keyClause = "USE KEYS {$key}"; } //...
{@inheritdoc} @see http://developer.couchbase.com/documentation/server/4.1/n1ql/n1ql-language-reference/delete.html
entailment
public function compileUpsert(QueryBuilder $query, array $values): string { // keyspace-ref: $table = $this->wrapTable($query->from); // use-keys-clause: $keyClause = $this->wrapKey($query->key); // returning-clause $returning = implode(', ', $query->returning); ...
@param QueryBuilder $query @param array $values @return string
entailment
public function errors() { $errors = parent::errors(); if ( ! empty($errors)) { $errors[ $this->generalErrorsKey() ] = $this->collectGeneralErrors($errors); } return $errors; }
Get all of the validation error messages. @return array
entailment
public function header() { if ($this->header_translated) { return cms_trans($this->header_translated); } if ($this->header) { return $this->header; } return ucfirst(str_replace('_', ' ', snake_case($this->source))); }
Returns display header label for the column. @return string
entailment