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'])) {
call_user_func($this['notFound']);
} else {
call_user_func(array($this, 'defaultNotFound'));
}
$this->halt(404, ob_get_clean());
}
} | 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 current HTTP request. It WILL NOT invoke the callable.
2. When invoking the handler:
If the $callable parameter is null, Slim assumes you want
to invoke an already-registered handler. If the handler has been
registered and is callable, it is invoked and sends a 404 HTTP Response
whose body is the output of the Not Found handler.
@param mixed $callable Anything that returns true for is_callable()
@api | 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($this->callErrorHandler($argument), true);
$this->stop();
}
} | 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 otherwise explicitly invoked.
The handler WILL NOT be invoked in this context.
2. When invoking the handler:
If the $argument parameter is not callable, Slim assumes you want
to invoke an already-registered handler. If the handler has been
registered and is callable, it is invoked and passed the caught Exception
as its one and only argument. The error handler's output is captured
into an output buffer and sent as the body of a 500 HTTP Response.
@param mixed $argument A callable or an exception
@api | 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($this, 'defaultError'), array($argument));
}
return ob_get_clean();
} | 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's render() method
@param array $data Associative array of data made available to the view
@param int $status The HTTP response status code to use (optional)
@api | 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 {
throw new \InvalidArgumentException('Slim::lastModified only accepts an integer UNIX timestamp value.');
}
} | 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
matches the specified last modified time, the application will stop
and send a '304 Not Modified' response to the client.
@param int $time The last modified UNIX timestamp
@throws \InvalidArgumentException If provided timestamp is not an integer
@api | 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 . '"';
if ($type === 'weak') {
$value = 'W/'.$value;
}
$this['response']->setHeader('ETag', $value);
// Check conditional GET
if ($etagsHeader = $this['request']->getHeader('IF_NONE_MATCH')) {
$etags = preg_split('@\s*,\s*@', $etagsHeader);
if (in_array($value, $etags) || in_array('*', $etags)) {
$this->halt(304);
}
}
} | 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-Match' header with
a matching etag, execution is immediately stopped. If the request
method is GET or HEAD, a '304 Not Modified' response is sent.
@param string $value The etag value
@param string $type The type of etag to create; either "strong" or "weak"
@throws \InvalidArgumentException If provided type is invalid
@api | 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 resource has not changed. The `Expires` header should be used in
conjunction with the `etag()` or `lastModified()` methods above.
@param string|int $time If string, a time to be parsed by `strtotime()`;
If int, a UNIX timestamp;
@api | 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('cookies.path') : $path,
'domain' => is_null($domain) ? $this->config('cookies.domain') : $domain,
'secure' => is_null($secure) ? $this->config('cookies.secure') : $secure,
'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
);
$this['response']->setCookie($name, $settings);
} | 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 The path on the server in which the cookie will be available on
@param string $domain The domain that the cookie is available to
@param bool $secure Indicates that the cookie should only be transmitted over a secure
HTTPS connection to/from the client
@param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
@api | 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' => is_null($secure) ? $this->config('cookies.secure') : $secure,
'httponly' => is_null($httponly) ? $this->config('cookies.httponly') : $httponly
);
$this['response']->removeCookie($name, $settings);
} | 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 are omitted or set to NULL, the
default Cookie setting values (set during Slim::init) will be used instead.
@param string $name The cookie name
@param string $path The path on the server in which the cookie will be available on
@param string $domain The domain that the cookie is available to
@param bool $secure Indicates that the cookie should only be transmitted over a secure
HTTPS connection from the client
@param bool $httponly When TRUE the cookie will be made accessible only through the HTTP protocol
@api | 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.
@param int $status The HTTP response status
@param string $message The HTTP response body
@api | 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[$name]) > 1) {
ksort($this->hooks[$name]);
}
foreach ($this->hooks[$name] as $priority) {
if (!empty($priority)) {
foreach ($priority as $callable) {
call_user_func($callable, $hookArg);
}
}
}
}
} | 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)
@return array|null
@api | 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)) {
//Set Content-Type
if (extension_loaded('fileinfo')) {
$finfo = new \finfo(FILEINFO_MIME_TYPE);
$type = $finfo->file($file);
$this['response']->setHeader("Content-Type", $type);
} else {
$this['response']->setHeader("Content-Type", "application/octet-stream");
}
//Set Content-Length
$stat = fstat($fp);
$this['response']->setHeader("Content-Length", $stat['size']);
} else {
//Set Content-Type and Content-Length
$data = stream_get_meta_data($fp);
foreach ($data['wrapper_data'] as $header) {
list($k, $v) = explode(": ", $header, 2);
if ($k === "Content-Type") {
$this['response']->setHeader("Content-Type", $v);
} else if ($k === "Content-Length") {
$this['response']->setHeader("Content-Length", $v);
}
}
}
}
} | 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 Middleware instance ({$middleware_class}) twice.");
}
$newMiddleware->setApplication($this);
$newMiddleware->setNextMiddleware($this['middleware'][0]);
array_unshift($middleware, $newMiddleware);
$this['middleware'] = $middleware;
} | 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);
}
// Finalize and send response
$this->finalize();
restore_error_handler();
} | 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']->getMatchedRoutes($request->getMethod(), $request->getPathInfo(), false);
foreach ($matchedRoutes as $route) {
try {
$this->applyHook('slim.before.dispatch');
$dispatched = $route->dispatch();
$this->applyHook('slim.after.dispatch');
if ($dispatched) {
break;
}
} catch (\Slim\Exception\Pass $e) {
continue;
}
}
if (!$dispatched) {
$this->notFound();
}
$this->applyHook('slim.after.router');
} catch (\Slim\Exception\Stop $e) {}
$response->write(ob_get_clean());
$this->applyHook('slim.after');
} | 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 returned by this method.
@param \Slim\Http\Request The request instance
@param \Slim\Http\Response The response instance | 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,
'REQUEST_URI' => $url,
'SCRIPT_NAME' => '/index.php'
), $serverVariables));
$headers = new \Slim\Http\Headers($environment);
$cookies = new \Slim\Http\Cookies($headers);
$subRequest = new \Slim\Http\Request($environment, $headers, $cookies, $body);
$subResponse = new \Slim\Http\Response(new \Slim\Http\Headers(), new \Slim\Http\Cookies());
// Cache original request and response
$oldRequest = $this['request'];
$oldResponse = $this['response'];
unset($this['request'], $this['response']);
// Set sub-request and sub-response
$this['request'] = $subRequest;
$this['response'] = $subResponse;
// Dispatch sub-request through application router
$this->dispatchRequest($subRequest, $subResponse);
// Restore original request and response
unset($this['request'], $this['response']);
$this['request'] = $oldRequest;
$this['response'] = $oldResponse;
return $subResponse;
} | 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 registered
application routes. The result response object is returned.
@param string $url The request URL
@param string $method The request method
@param array $headers Associative array of request headers
@param array $cookies Associative array of request cookies
@param string $body The request body
@param array $serverVariables Custom $_SERVER variables
@return \Slim\Http\Response | 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 session
if ($this->config('session.encrypt') === true) {
$this['session']->encrypt($this['crypt']);
}
$this['session']->save();
}
// Encrypt cookies
if ($this['settings']['cookies.encrypt']) {
$this['response']->encryptCookies($this['crypt']);
}
// Send response
$this['response']->finalize($this['request'])->send();
}
} | 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->getMessage();
$file = $e->getFile();
$line = $e->getLine();
$trace = str_replace(array('#', '\n'), array('<div>#', '</div>'), $e->getTraceAsString());
$html = '<p>The application could not run because of the following error:</p>';
$html .= '<h2>Details</h2>';
$html .= sprintf('<div><strong>Type:</strong> %s</div>', get_class($e));
if ($code) {
$html .= sprintf('<div><strong>Code:</strong> %s</div>', $code);
}
if ($message) {
$html .= sprintf('<div><strong>Message:</strong> %s</div>', $message);
}
if ($file) {
$html .= sprintf('<div><strong>File:</strong> %s</div>', $file);
}
if ($line) {
$html .= sprintf('<div><strong>Line:</strong> %s</div>', $line);
}
if ($trace) {
$html .= '<h2>Trace</h2>';
$html .= sprintf('<pre>%s</pre>', $trace);
}
} else {
$html = sprintf('<p>%s</p>', $e);
}
echo self::generateTemplateMarkup($title, $html);
} else {
echo self::generateTemplateMarkup(
'Error',
'<p>A website error has occurred. The website administrator has been notified of the issue. Sorry'
. 'for the temporary inconvenience.</p>'
);
}
} | 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->drivers[$name];
} | 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('fullname', 100)->nullable();
$table->integer('status')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->rememberToken();
$table->nullableTimestamps();
$table->softDeletes();
});
} | 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(['user_id', 'role_id']);
});
} | 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_LENGTH') {
continue;
}
parent::set($this->normalizeKey($key), array($value));
}
}
} | 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();
}
$data['references'] = $this->getReferencesForModelKeys(array_keys($keys));
return $data;
} | 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->registerAbility($ability, $className . '@' . $ability);
}
}
} | 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($callback);
return call_user_func([$this->app->make($class), $method], $component);
}
};
} | @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->getVarianttoUse($source);
if ($this->listColumnData) {
$width = array_get($this->listColumnData->options, 'width');
$height = array_get($this->listColumnData->options, 'height');
} else {
$width = null;
$height = null;
}
return view(static::VIEW, [
'exists' => $source->size() > 0,
'filename' => $source->originalFilename(),
'urlThumb' => $source->url($resize),
'urlOriginal' => $source->url(),
'width' => $width ?: $height ?: static::WIDTH,
'height' => $height ?: $width ?: static::HEIGHT,
]);
} | 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;
}
foreach ($variantSteps as $stepKey => $step) {
if ( ! in_array($stepKey, $this->resizeVariantStepKeys)) {
continue;
}
if ( ! preg_match('#(\d+)?x(\d+)?#', array_get($step, 'dimensions', ''), $matches)) {
continue;
}
$smallestForVariant = null;
if ((int) $matches[1] > 0) {
$smallestForVariant = (int) $matches[1];
}
if ((int) $matches[2] > 0 && (int) $matches[2] < $smallestForVariant) {
$smallestForVariant = (int) $matches[2];
}
if ( null !== $smallestForVariant
&& ($smallestForVariant < $smallest || null === $smallest)
) {
$smallestKey = $variantKey;
$smallest = $smallestForVariant;
}
break;
}
}
return $smallestKey;
} | 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)) {
$columns[ count($columns) - 1 ] += $remainder;
}
return $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 labels size 2
// and spread the rest as evenly as possible over the fields
// If there is not enough space, try again with labels at size 1
$labelsTotalWidth = $labelWidth * array_reduce(
$contents,
function ($total, $content) {
return $total + ($content['type'] !== 'field' ? 1 : 0);
}
);
$fieldsCount = array_reduce(
$contents,
function ($total, $content) {
return $total + ($content['type'] === 'field' ? 1 : 0);
}
);
$fieldWidth = (int) floor((static::GRID_SIZE_WITHOUT_LABEL - $labelsTotalWidth) / $fieldsCount);
$columns = [];
foreach ($contents as $content) {
$columns[] = ($content['type'] === 'field') ? $fieldWidth : $labelWidth;
}
return $columns;
} | 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' => $key, 'type' => $child->type() ];
}
return $contents;
} | 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
$disableScopes = $information->meta->disable_global_scopes;
if (true === $disableScopes || is_array($disableScopes)) {
$query->withoutGlobalScopes(
true === $disableScopes ? null : $disableScopes
);
}
// Apply repository context, if any
$strategy = $information->meta->repository_strategy;
if ($strategy) {
$strategy = $this->resolveContextStrategy($strategy);
if ($strategy) {
$query = $strategy->apply($query, $information);
}
}
return $query;
} | 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->getDefaultFieldType());
$data = [
'record' => $this->model,
'key' => $this->field->key() . ($locale ? '-locale:' . $locale : null),
'baseKey' => $this->field->key(),
'name' => $this->getFormFieldName($locale),
'value' => $value,
'original' => $originalValue,
'type' => $type,
'errors' => $errors,
'required' => $this->field->required(),
'options' => $this->field->options(),
'translated' => $this->field->translated(),
];
return view($this->getView(), $this->decorateFieldData($data));
} | 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);
}
// Determine whether to interpret the contents as PHP code or JSON data
if ('<?php' == substr($contents, 0, 5)) {
try {
$contents = eval('?>' . $contents);
} catch (Exception $e) {
throw (new ModelConfigurationFileException(
"Could not interpret CMS model configuration PHP data for '{$path}'"
))->setPath($path);
}
if ( ! is_array($contents)) {
throw (new ModelConfigurationFileException(
"CMS model configuration PHP file did not return an array for '{$path}'"
))->setPath($path);
}
return $contents;
}
// Fall back is to assume the file contains JSON content
$json = json_decode($contents, true);
if (null === $json) {
throw (new ModelConfigurationFileException(
"Could not interpret CMS model configuration as JSON data for '{$path}'"
))->setPath($path);
}
return $json;
} | 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('bucket'));
$primary = self::PRIMARY_KEY;
try {
$bucket->manager()->createN1qlPrimaryIndex(
$primary,
$this->option('ignore'),
$this->option('defer')
);
$this->info("created PRIMARY INDEX [{$primary}] for [{$this->argument('bucket')}] bucket.");
} catch (\Exception $e) {
$this->error($e->getMessage());
}
foreach ($this->secondaryIndexes as $name => $fields) {
try {
$bucket->manager()->createN1qlIndex(
$name,
$fields,
'',
$this->option('ignore'),
$this->option('defer')
);
$field = implode(",", $fields);
$this->info("created SECONDARY INDEX [{$name}] fields [{$field}], for [{$this->argument('bucket')}] bucket.");
} catch (\Exception $e) {
$this->error($e->getMessage());
}
}
}
return;
} | 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 fa-times text-danger" title="' . e(cms_trans('common.boolean.false')) . '"></i>';
} | 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|f|false|nee|off|disabled|inactive&#', trim($value))) {
return false;
}
return true;
}
if (is_array($value) || $value instanceof Collection) {
return count($value) > 0;
}
return (bool) $value;
} | 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, $targetModel);
// Default omitted on purpose
}
return false;
} | 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);
// Default omitted on purpose
}
return false;
} | 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 relation does not have nested model data. | 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 a string value (non-assiative).
// In either case, there is no specified reference data.
return [];
}
return $data;
} | 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
}
$model = new $modelClass;
if ( ! ($relation = $this->getNestedRelation($model, $source))) {
// @codeCoverageIgnoreStart
$relation = $this->resolveModelSource($model, $source);
// @codeCoverageIgnoreEnd
}
if ( ! ($relation instanceof Relation)) {
// @codeCoverageIgnoreStart
throw new UnexpectedValueException(
"Source {$source} on {$modelClass} does not resolve to an Eloquent relation instance"
);
// @codeCoverageIgnoreEnd
}
/** @var Relation $relation */
return $relation->getRelated();
} | 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...
if ($info = $this->getModelInformation($data->model())) {
if (null === $data->source()) {
$data->source = $info->reference->source;
}
if (null === $data->strategy()) {
$data->strategy = $info->reference->strategy;
}
}
}
return $data;
} | 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()
);
if ($referenceData) {
$references = $this->getReferenceRepository()->getReferencesForModelMetaReference($referenceData)->all();
} else {
$references = [];
}
$data['dropdownOptions'] = $references;
return $data;
} | 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;
// @codeCoverageIgnoreEnd
}
// We know about this filter, load up the relevant application strategy and apply it
$information = $this->filterInformation[ $parameterName ];
$filter = $this->getFilterFactory()->make(
$information->strategy(),
$parameterName,
$this->filterInformation[ $parameterName ]
);
$filter->apply($query, $information->target(), $parameterValue);
} | {@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');
include __DIR__.'/../../routes.php';
}
} | 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 gather to the instance
$instance
->setListInformation($data)
->setOptions($data->options());
if ($data->source) {
if (isset($info->attributes[ $data->source ])) {
$instance->setAttributeInformation(
$info->attributes[ $data->source ]
);
}
}
$instance->initialize($info->modelClass());
$instances[ $key ] = $instance;
}
return $instances;
} | 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();
return $this->information;
} | 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) {
// Wrap and decorate exceptions so it is easier to track the problem source
throw (new ModelInformationCollectionException(
"Issue analyzing model {$class}: \n{$e->getMessage()}",
(int) $e->getCode(),
$e
))
->setModelClass($class);
}
}
return $this;
} | 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 ModelConfigurationDataException) {
$message = "{$e->getMessage()} ({$e->getDotKey()})";
}
// Wrap and decorate exceptions so it is easier to track the problem source
throw (new ModelInformationCollectionException(
"Issue reading/interpreting model configuration file {$file->getRealPath()}: \n{$message}",
(int) $e->getCode(),
$e
))
->setConfigurationFile($file->getRealPath());
}
}
return $this;
} | 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(
"Incorrect data from CMS model information file: '{$path}'"
);
}
$info = $this->informationInterpreter->interpret($info);
$modelClass = $this->makeModelFqnFromCmsModelPath(
$file->getRelativePathname()
);
$key = $this->moduleHelper->modelInformationKeyForModel($modelClass);
if ( ! $this->information->has($key)) {
$this->getCore()->log('debug', "CMS model data for unset model information key '{$key}'");
return;
}
/** @var ModelInformationInterface $originalInfo */
$originalInfo = $this->information->get($key);
$originalInfo->merge($info);
$this->information->put($key, $originalInfo);
} | 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'), '\\')
. '\\' . str_replace('/', '\\', $path);
} | 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);
});
} else {
$this->buildQuery($query, $this->getName());
}
} | {@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->whereBetween($name, (array) $value);
break;
case 'like':
$value .= '%';
$query->where($name, $op, $value);
break;
default:
$query->where($name, $op, $value);
}
} | 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(
function ($key, $value) {
if (is_string($value)) {
return $value;
}
return $key;
},
array_keys($modelsOption),
array_values($modelsOption)
);
return array_unique($modelClasses);
} | 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;
}
// It's a relationship method; get information from method
try {
$relation = $this->model()->{$method->name}();
} catch (Exception $e) {
// If an exception occurs, ignore it and ignore the method
continue;
}
if ( ! ($relation instanceof Relation)) {
continue;
}
$type = camel_case(class_basename($relation));
$morphModels = [];
// Determine if the foreign key for this relation is nullable.
// For now, this only concerns belongsTo relations.
$nullableKey = false;
$foreignKeys = [];
if ($type == RelationType::BELONGS_TO || $type == RelationType::BELONGS_TO_THROUGH) {
/** @var $relation Relations\BelongsTo */
$foreignKeys = [ $relation->getForeignKeyName() ];
$nullableKey = $this->isNullableKey($relation->getForeignKeyName());
} elseif ($type == RelationType::MORPH_TO) {
/** @var Relations\MorphTo $relation */
$foreignKeys = [$relation->getForeignKeyName(), $relation->getMorphType()];
$nullableKey = $this->isNullableKey($relation->getForeignKeyName());
$morphModels = $this->getMorphedModelsFromMorphToReflectionMethod($method);
} elseif ($type == RelationType::HAS_ONE || $type == RelationType::HAS_MANY) {
/** @var $relation Relations\HasMany */
$foreignKeys = [ $relation->getQualifiedForeignKeyName() ];
} elseif ($type == RelationType::BELONGS_TO_MANY) {
/** @var Relations\BelongsToMany $relation */
$foreignKeys = [
$relation->getQualifiedForeignPivotKeyName(),
$relation->getQualifiedRelatedPivotKeyName(),
];
} elseif ($type == RelationType::MORPH_TO_MANY) {
/** @var Relations\MorphToMany $relation */
$foreignKeys = [
$relation->getQualifiedForeignPivotKeyName(),
$relation->getMorphType(),
$relation->getQualifiedRelatedPivotKeyName(),
];
// The relation is inverse if the MorphClass is not this model
if (get_class($this->model()) !== $relation->getMorphClass()) {
$type = RelationType::MORPHED_BY_MANY;
}
}
$relations[ $method->name ] = new ModelRelationData([
'name' => $method->name,
'method' => $method->name,
'type' => $type,
'relationClass' => get_class($relation),
'relatedModel' => get_class($relation->getRelated()),
'foreign_keys' => $foreignKeys,
'nullable_key' => $nullableKey,
'morphModels' => $morphModels,
]);
}
$this->info['relations'] = $relations;
} | 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 cannot call or use it
|| $method->getNumberOfRequiredParameters()
) {
return false;
}
// Don't examine methods defined in certain namespaces
foreach ($this->mustNotMatchClass as $regEx) {
if (preg_match($regEx, $method->class)) {
return false;
}
}
// Don't examine methods defined in certain files
$file = $method->getFileName();
foreach ($this->mustNotMatchFile as $regEx) {
if (preg_match($regEx, $file)) {
return false;
}
}
return true;
} | 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->info->attributes[ $key ]->nullable;
} | 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')) {
return true;
}
if (array_get($cmsTags, 'ignore')) {
return false;
}
// analyze the method to see whether it is a relation
$body = $this->getMethodBody($method);
return (bool) $this->findRelationMethodCall($body);
} | 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 $opener) {
if ( false === ($pos = strrpos($methodBody, $opener))
|| $pos <= $lastPosition
) {
continue;
}
$foundOpener = $opener;
$lastPosition = $pos;
}
if ( ! $foundOpener || $lastPosition < 0) {
return false;
}
// todo further checks to prevent false positives
// use https://github.com/nikic/PHP-Parser/
return $foundOpener;
} | 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;
// @codeCoverageIgnoreStart
default:
throw new \UnexpectedValueException("Cannot handle translation strategy '{$strategy}");
}
return $this->info;
} | 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'];
foreach ($attributes as $key => $attribute) {
if ( ! $model->isTranslationAttribute($key)) continue;
// mark the fields as translated for merging by model analyzer
$attributes[$key]['translated'] = true;
}
$this->info['attributes'] = $attributes;
} | 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 to cast value to string for field '{$this->field->key()}' "
. "with source '{$this->field->source()}'",
0,
$e
);
}
return $data;
} | 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_longitude')
) {
$data['defaultLocation'] = array_get($this->field->options(), 'default_location');
$data['defaultLatitude'] = array_get($this->field->options(), 'default_latitude');
$data['defaultLongitude'] = array_get($this->field->options(), 'default_longitude');
} elseif (array_get($this->field->options(), 'default')) {
$data['defaultLocation'] = config('cms-models.custom-strategies.location.default.location');
$data['defaultLatitude'] = config('cms-models.custom-strategies.location.default.latitude');
$data['defaultLongitude'] = config('cms-models.custom-strategies.location.default.longitude');
} else {
$data['defaultLocation'] = null;
$data['defaultLatitude'] = null;
$data['defaultLongitude'] = null;
}
$data['googleMapsApiKey'] = config('cms-models.api-keys.google-maps');
return $data;
} | 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 */
$bucket = $connection->openBucket($this->argument('bucket'));
foreach ($this->config as $name => $document) {
$bucket->manager()->insertDesignDocument($name, $document);
$this->comment("created view name [{$name}]");
}
}
return;
} | 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_array(reset($values))) {
$values = [$values];
}
$parameters = [];
foreach ($values as $record) {
$parameters[] = '(' . $this->parameterize($record) . ')';
}
$parameters = (!$keyClause) ? implode(', ', $parameters) : "({$keyClause}, \$parameters)";
$keyValue = (!$keyClause) ? null : '(KEY, VALUE)';
return "insert into {$table} {$keyValue} values $parameters RETURNING {$returning}";
} | {@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}";
}
// returning-clause
$returning = implode(', ', $query->returning);
$where = is_array($query->wheres) ? $this->compileWheres($query) : '';
return trim("delete from {$table} {$keyClause} {$where} RETURNING {$returning}");
} | {@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);
if (!is_array(reset($values))) {
$values = [$values];
}
$parameters = [];
foreach ($values as $record) {
$parameters[] = '(' . $this->parameterize($record) . ')';
}
$parameters = (!$keyClause) ? implode(', ', $parameters) : "({$keyClause}, \$parameters)";
$keyValue = (!$keyClause) ? null : '(KEY, VALUE)';
return "UPSERT INTO {$table} {$keyValue} VALUES $parameters RETURNING {$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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.