sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
protected function reset($slug)
{
if (! $this->packages->exists($slug)) {
return $this->error('Package does not exist.');
}
$this->requireMigrations($slug);
//
$this->migrator->setconnection($this->input->getOption('database'));
$pretend = $this->input->getOption('pretend');
while (true) {
$count = $this->migrator->rollback($pretend, $slug);
foreach ($this->migrator->getNotes() as $note) {
$this->output->writeln($note);
}
if ($count == 0) break;
}
} | Run the migration reset for the specified Package.
Migrations should be reset in the reverse order that they were
migrated up as. This ensures the database is properly reversed
without conflict.
@param string $slug
@return mixed | entailment |
public function slugs()
{
$slugs = collect();
$this->all()->each(function ($item) use ($slugs)
{
$slugs->push($item['slug']);
});
return $slugs;
} | Get all module slugs.
@return Collection | entailment |
public function exists($slug)
{
if (Str::length($slug) > 3) {
$slug = Str::snake($slug);
} else {
$slug = Str::lower($slug);
}
$slugs = $this->slugs()->toArray();
return in_array($slug, $slugs);
} | Determines if the given module exists.
@param string $slug
@return bool | entailment |
public function getPackagePath($slug)
{
if (Str::length($slug) > 3) {
$package = Str::studly($slug);
} else {
$package = Str::upper($slug);
}
return $this->getPackagesPath() .DS .$package .DS;
} | Get local path for the specified Package.
@param string $slug
@return string | entailment |
public function getModulePath($slug)
{
if (Str::length($slug) > 3) {
$module = Str::studly($slug);
} else {
$module = Str::upper($slug);
}
return $this->getModulesPath() .DS .$module .DS;
} | Get path for the specified Module.
@param string $slug
@return string | entailment |
public function getThemePath($slug)
{
if (Str::length($slug) > 3) {
$theme = Str::studly($slug);
} else {
$theme = Str::upper($slug);
}
return $this->getThemesPath() .DS .$theme .DS;
} | Get path for the specified Theme.
@param string $slug
@return string | entailment |
public function optimize()
{
$path = $this->getCachePath();
$packages = $this->getPackages();
$this->writeCache($path, $packages);
} | Update cached repository of packages information.
@return bool | entailment |
public function getCached()
{
if (isset(static::$packages)) {
return static::$packages;
}
$path = $this->getCachePath();
$configPath = app_path('Config/Packages.php');
$packagesPath = base_path('vendor/nova-packages.php');
if ($this->isCacheExpired($path, $packagesPath) || $this->isCacheExpired($path, $configPath)) {
$packages = $this->getPackages();
$this->writeCache($path, $packages);
}
// The packages cache is valid.
else {
$packages = collect(
$this->files->getRequire($path)
);
}
return static::$packages = $packages;
} | Get the contents of the cache file.
The cache file lists all Packages slugs and their enabled or disabled status.
This can be used to filter out Packages depending on their status.
@return Collection | entailment |
public function writeCache($path, $packages)
{
$data = array();
foreach ($packages->all() as $key => $package) {
$properties = ($package instanceof Collection) ? $package->all() : $package;
// Normalize to *nix paths.
$properties['path'] = str_replace('\\', '/', $properties['path']);
//
ksort($properties);
$data[] = $properties;
}
//
$data = var_export($data, true);
$content = <<<PHP
<?php
return $data;
PHP;
$this->files->put($path, $content);
} | Write the service cache file to disk.
@param string $path
@param array $packages
@return void | entailment |
public function isCacheExpired($cachePath, $path)
{
if (! $this->files->exists($cachePath)) {
return true;
}
$lastModified = $this->files->lastModified($path);
if ($lastModified >= $this->files->lastModified($cachePath)) {
return true;
}
return false;
} | Determine if the cache file is expired.
@param string $cachePath
@param string $path
@return bool | entailment |
protected function getPackageName($package)
{
if (strpos($package, '/') === false) {
return $package;
}
list($vendor, $namespace) = explode('/', $package);
return $namespace;
} | Get the name for a Package.
@param string $package
@param string $namespace
@return string | entailment |
protected function createSingleConnection(array $config)
{
$pdo = $this->createConnector($config)->connect($config);
return $this->createConnection($config['driver'], $pdo, $config['database'], $config['prefix'], $config);
} | Create a single database connection instance.
@param array $config
@return \Nova\Database\Connection | entailment |
protected function createReadPdo(array $config)
{
$readConfig = $this->getReadConfig($config);
return $this->createConnector($readConfig)->connect($readConfig);
} | Create a new PDO instance for reading.
@param array $config
@return \PDO | entailment |
protected function getReadConfig(array $config)
{
$readConfig = $this->getReadWriteConfig($config, 'read');
return $this->mergeReadWriteConfig($config, $readConfig);
} | Get the read configuration for a read / write connection.
@param array $config
@return array | entailment |
protected function getWriteConfig(array $config)
{
$writeConfig = $this->getReadWriteConfig($config, 'write');
return $this->mergeReadWriteConfig($config, $writeConfig);
} | Get the read configuration for a read / write connection.
@param array $config
@return array | entailment |
public function createConnector(array $config)
{
if (! isset($config['driver'])) {
throw new \InvalidArgumentException("A driver must be specified.");
}
if ($this->container->bound($key = "db.connector.{$config['driver']}")) {
return $this->container->make($key);
}
switch ($config['driver'])
{
case 'mysql':
return new MySqlConnector;
case 'pgsql':
return new PostgresConnector;
case 'sqlite':
return new SQLiteConnector;
case 'sqlsrv':
return new SqlServerConnector;
}
throw new \InvalidArgumentException("Unsupported driver [{$config['driver']}]");
} | Create a connector instance based on the configuration.
@param array $config
@return \Nova\Database\Connectors\ConnectorInterface
@throws \InvalidArgumentException | entailment |
protected function createConnection($driver, PDO $connection, $database, $prefix = '', array $config = array())
{
if ($this->container->bound($key = "db.connection.{$driver}")) {
return $this->container->make($key, array($connection, $database, $prefix, $config));
}
switch ($driver)
{
case 'mysql':
return new MySqlConnection($connection, $database, $prefix, $config);
case 'pgsql':
return new PostgresConnection($connection, $database, $prefix, $config);
case 'sqlite':
return new SQLiteConnection($connection, $database, $prefix, $config);
case 'sqlsrv':
return new SqlServerConnection($connection, $database, $prefix, $config);
}
throw new \InvalidArgumentException("Unsupported driver [$driver]");
} | Create a new connection instance.
@param string $driver
@param \PDO $connection
@param string $database
@param string $prefix
@param array $config
@return \Nova\Database\Connection
@throws \InvalidArgumentException | entailment |
public function up() {
Schema::create('tenant_connections', function (Blueprint $table) {
$table->increments('id');
$table->integer('tenant_id')->unsigned()->index();
$table->string('database');
$table->timestamps();
$table->foreign('tenant_id')->references('id')->on(str_plural(app(config('artify.tenant'))->getTable()));
});
} | Run the migrations.
@return void | entailment |
public function add($key, $value, $minutes)
{
if (! is_null($this->get($key))) {
return false;
}
$this->put($key, $value, $minutes);
return true;
} | Store an item in the cache if the key does not exist.
@param string $key
@param mixed $value
@param \DateTime|int $minutes
@return bool | entailment |
public function start()
{
$httpServer = $this->getHttpServer();
// 是否正在运行
if ($httpServer->isRunning()) {
$serverStatus = $httpServer->getServerSetting();
\output()->writeln("<error>The server have been running!(PID: {$serverStatus['masterPid']})</error>", true, true);
} else {
$serverStatus = $httpServer->getServerSetting();
}
// 启动参数
$this->setStartArgs($httpServer);
$httpStatus = $httpServer->getHttpSetting();
$tcpStatus = $httpServer->getTcpSetting();
// Setting
$workerNum = $httpServer->setting['worker_num'];
// HTTP 启动参数
$httpHost = $httpStatus['host'];
$httpPort = $httpStatus['port'];
$httpMode = $httpStatus['mode'];
$httpType = $httpStatus['type'];
// TCP 启动参数
$tcpEnable = $serverStatus['tcpable'];
$tcpHost = $tcpStatus['host'];
$tcpPort = $tcpStatus['port'];
$tcpType = $tcpStatus['type'];
$tcpEnable = $tcpEnable ? '<info>Enabled</info>' : '<warning>Disabled</warning>';
// 信息面板
$lines = [
' Server Information ',
'********************************************************************',
"* HTTP | host: <note>$httpHost</note>, port: <note>$httpPort</note>, type: <note>$httpType</note>, worker: <note>$workerNum</note>, mode: <note>$httpMode</note>",
"* TCP | host: <note>$tcpHost</note>, port: <note>$tcpPort</note>, type: <note>$tcpType</note>, worker: <note>$workerNum</note> ($tcpEnable)",
'********************************************************************',
];
// 启动服务器
\output()->writeln(implode("\n", $lines));
$httpServer->start();
} | Start http server
@Usage {fullCommand} [-d|--daemon]
@Options
-d, --daemon Run server on the background
@Example
{fullCommand}
{fullCommand} -d
@throws \InvalidArgumentException
@throws \Swoft\Exception\RuntimeException
@throws \RuntimeException | entailment |
public function reload()
{
$httpServer = $this->getHttpServer();
// 是否已启动
if (!$httpServer->isRunning()) {
output()->writeln('<error>The server is not running! cannot reload</error>', true, true);
}
output()->writeln(sprintf('<info>Server %s is reloading</info>', input()->getScript()));
// 重载
$reloadTask = input()->hasOpt('t');
$httpServer->reload($reloadTask);
output()->writeln(sprintf('<success>Server %s reload success</success>', input()->getScript()));
} | Reload worker processes
@Usage {fullCommand} [-t]
@Options
-t Only to reload task processes, default to reload worker and task
@Example {fullCommand}
@throws \InvalidArgumentException
@throws \RuntimeException | entailment |
public function stop()
{
$httpServer = $this->getHttpServer();
// 是否已启动
if (!$httpServer->isRunning()) {
\output()->writeln('<error>The server is not running! cannot stop</error>', true, true);
}
// pid文件
$serverStatus = $httpServer->getServerSetting();
$pidFile = $serverStatus['pfile'];
\output()->writeln(sprintf('<info>Swoft %s is stopping ...</info>', input()->getScript()));
$result = $httpServer->stop();
// 停止失败
if (!$result) {
\output()->writeln(sprintf('<error>Swoft %s stop fail</error>', input()->getScript()), true, true);
}
//删除pid文件
@unlink($pidFile);
output()->writeln(sprintf('<success>Swoft %s stop success!</success>', input()->getScript()));
} | Stop the http server
@Usage {fullCommand}
@Example {fullCommand}
@throws \InvalidArgumentException
@throws \RuntimeException | entailment |
public function restart()
{
$httpServer = $this->getHttpServer();
// 是否已启动
if ($httpServer->isRunning()) {
$this->stop();
}
// 重启默认是守护进程
$httpServer->setDaemonize();
$this->start();
} | Restart the http server
@Usage {fullCommand} [-d|--daemon]
@Options
-d, --daemon Run server on the background
@Example
{fullCommand}
{fullCommand} -d
@throws \Swoft\Exception\RuntimeException
@throws \InvalidArgumentException
@throws \RuntimeException | entailment |
private function setStartArgs(HttpServer $httpServer)
{
$daemonize = \input()->getSameOpt(['d', 'daemon'], false);
if ($daemonize) {
$httpServer->setDaemonize();
}
} | 设置启动选项,覆盖 config/server.php 配置选项
@param HttpServer $httpServer | entailment |
public function handle($request, Closure $next, $guard = null)
{
return Auth::guard($guard)->basic() ?: $next($request);
} | Handle an incoming request.
@param \Nova\Http\Request $request
@param \Closure $next
@param string|null $guard
@return mixed | entailment |
public function validate(...$params)
{
/**
* @var Request $request
* @var array $matches
*/
list($validators, $request, $matches) = $params;
if (! \is_array($validators)) {
return $request;
}
foreach ($validators as $type => $validatorAry) {
$request = $this->validateField($request, $matches, $type, $validatorAry);
}
return $request;
} | Validate
@param array ...$params
@return mixed
@throws \Swoft\Exception\ValidatorException | entailment |
private function validateField($request, array $matches, string $type, array $validatorAry)
{
$get = $request->getQueryParams();
$post = $request->getParsedBody();
$contentType = $request->getHeader('content-type');
$isPostJson = false;
if (isset($contentType[0]) && StringHelper::startsWith($contentType[0], 'application/json')) {
$isPostJson = true;
$post = $request->json();
}
foreach ($validatorAry as $name => $info) {
$default = array_pop($info['params']);
if ($type === ValidatorFrom::GET) {
if (!isset($get[$name])) {
$request = $request->addQueryParam($name, $default);
$this->doValidation($name, $default, $info);
continue;
}
$this->doValidation($name, $get[$name], $info);
continue;
}
if ($type === ValidatorFrom::POST && \is_array($post)) {
if (! ArrayHelper::has($post, $name)) {
ArrayHelper::set($post, $name, $default);
if ($isPostJson) {
$request = $request->withBody(new SwooleStream(JsonHelper::encode($post)));
} else {
$request = $request->addParserBody($name, $default);
}
$this->doValidation($name, $default, $info);
continue;
}
$this->doValidation($name, ArrayHelper::get($post, $name), $info);
continue;
}
if ($type === ValidatorFrom::PATH) {
if (!isset($matches[$name])) {
continue;
}
$this->doValidation($name, $matches[$name], $info);
continue;
}
}
return $request;
} | Validate field
@param Request $request
@param array $matches
@param string $type
@param array $validatorAry
@return mixed
@throws \Swoft\Exception\ValidatorException | entailment |
public static function createMultiple(?array $messageEntityArray): ?array
{
if (is_array($messageEntityArray)) {
return array_map(function (array $messageEntityData) {
return new self($messageEntityData);
}, $messageEntityArray);
}
return null;
} | @param array $messageEntityArray
@return self[]|null | entailment |
public function handle(SymfonyRequest $request, $type = HttpKernelInterface::MASTER_REQUEST, $catch = true)
{
$response = $this->app->handle($request, $type, $catch);
$response->headers->set('X-Frame-Options', 'SAMEORIGIN', false);
return $response;
} | Handle the given request and get the response.
@implements HttpKernelInterface::handle
@param \Symfony\Component\HttpFoundation\Request $request
@param int $type
@param bool $catch
@return \Symfony\Component\HttpFoundation\Response | entailment |
public function withMethod($method) : RequestInterface
{
$this->validateMethod($method);
$clone = clone $this;
$clone->method = \strtoupper($method);
return $clone;
} | {@inheritDoc} | entailment |
public function getRequestTarget() : string
{
if (! (null === $this->requestTarget))
{
return $this->requestTarget;
}
if (! ($this->uri instanceof UriInterface))
{
return '/';
}
// https://tools.ietf.org/html/rfc7230#section-5.3.1
// https://tools.ietf.org/html/rfc7230#section-2.7
//
// origin-form = absolute-path [ "?" query ]
// absolute-path = 1*( "/" segment )
if (! (0 === \strncmp($this->uri->getPath(), '/', 1)))
{
return '/';
}
$origin = $this->uri->getPath();
if (! ('' === $this->uri->getQuery()))
{
$origin .= '?' . $this->uri->getQuery();
}
return $origin;
} | {@inheritDoc} | entailment |
public function withUri(UriInterface $uri, $preserveHost = false) : RequestInterface
{
$clone = clone $this;
$clone->uri = $uri;
if ('' === $uri->getHost() || ($preserveHost && $clone->hasHeader('host')))
{
return $clone;
}
$newhost = $uri->getHost();
if (! (null === $uri->getPort()))
{
$newhost .= ':' . $uri->getPort();
}
// Reassigning the "Host" header
return $clone->withHeader('host', $newhost);
} | {@inheritDoc} | entailment |
protected function validateMethod($method) : void
{
if (! \is_string($method))
{
throw new \InvalidArgumentException('HTTP method must be a string');
}
else if (! \preg_match(HeaderInterface::RFC7230_TOKEN, $method))
{
throw new \InvalidArgumentException(\sprintf('The given method "%s" is not valid', $method));
}
} | Validates the given method
@param mixed $method
@return void
@throws \InvalidArgumentException
@link https://tools.ietf.org/html/rfc7230#section-3.1.1 | entailment |
protected function validateRequestTarget($requestTarget) : void
{
if (! \is_string($requestTarget))
{
throw new \InvalidArgumentException('HTTP request-target must be a string');
}
else if (! \preg_match('/^[\x21-\x7E\x80-\xFF]+$/', $requestTarget))
{
throw new \InvalidArgumentException(\sprintf('The given request-target "%s" is not valid', $requestTarget));
}
} | Validates the given request-target
@param mixed $requestTarget
@return void
@throws \InvalidArgumentException
@link https://tools.ietf.org/html/rfc7230#section-5.3 | entailment |
public function map(Router $router)
{
$router->group(array('namespace' => $this->namespace), function ($router)
{
$basePath = $this->guessPackageRoutesPath();
if (is_readable($path = $basePath .DS .'Api.php')) {
$router->group(array('prefix' => 'api', 'middleware' => 'api'), function ($router) use ($path)
{
require $path;
});
}
if (is_readable($path = $basePath .DS .'Web.php')) {
$router->group(array('middleware' => 'web'), function ($router) use ($path)
{
require $path;
});
}
});
} | Define the routes for the module.
@param \Nova\Routing\Router $router
@return void | entailment |
protected function addRouteMiddleware($routeMiddleware)
{
if (is_array($routeMiddleware) && (count($routeMiddleware) > 0)) {
foreach ($routeMiddleware as $key => $middleware) {
$this->middleware($key, $middleware);
}
}
} | Add middleware to the router.
@param array $routeMiddleware | entailment |
protected function addMiddlewareGroups($middlewareGroups)
{
if (is_array($middlewareGroups) && (count($middlewareGroups) > 0)) {
foreach ($middlewareGroups as $key => $groupMiddleware) {
foreach ($groupMiddleware as $middleware) {
$this->pushMiddlewareToGroup($key, $middleware);
}
}
}
} | Add middleware groups to the router.
@param array $middlewareGroups | entailment |
public function collapse()
{
$results = array();
foreach ($this->items as $values) {
$results = array_merge($results, $values);
}
return new static($results);
} | Collapse the collection items into a single array.
@return \Nova\Support\Collection | entailment |
public function where($key, $value, $strict = true)
{
return $this->filter(function ($item) use ($key, $value, $strict)
{
return ($strict ? (data_get($item, $key) === $value) : (data_get($item, $key) == $value));
});
} | Filter items by the given key value pair.
@param string $key
@param mixed $value
@param bool $strict
@return static | entailment |
public function groupBy($groupBy)
{
$results = array();
foreach ($this->items as $key => $value) {
$key = is_callable($groupBy) ? $groupBy($value, $key) : data_get($value, $groupBy);
$results[$key][] = $value;
}
return new static($results);
} | Group an associative array by a field or Closure value.
@param callable|string $groupBy
@return \Nova\Support\Collection | entailment |
public function sortBy($callback, $options = SORT_REGULAR, $descending = false)
{
$results = array();
if (is_string($callback)) {
$callback = $this->valueRetriever($callback);
}
// First we will loop through the items and get the comparator from a callback
// function which we were given. Then, we will sort the returned values and
// and grab the corresponding values for the sorted keys from this array.
foreach ($this->items as $key => $value) {
$results[$key] = $callback($value);
}
$descending ? arsort($results, $options) : asort($results, $options);
// Once we have sorted all of the keys in the array, we will loop through them
// and grab the corresponding model so we can set the underlying items list
// to the sorted version. Then we'll just return the collection instance.
foreach (array_keys($results) as $key) {
$results[$key] = $this->items[$key];
}
$this->items = $results;
return $this;
} | Sort the collection using the given Closure.
@param \Closure|string $callback
@param int $options
@param bool $descending
@return \Nova\Support\Collection | entailment |
public function sum($callback)
{
if (is_string($callback)) {
$callback = $this->valueRetriever($callback);
}
return $this->reduce(function($result, $item) use ($callback) {
return $result += $callback($item);
}, 0);
} | Get the sum of the given values.
@param \Closure $callback
@param string $callback
@return mixed | entailment |
public function transform(Closure $callback)
{
$this->items = array_map($callback, $this->items);
return $this;
} | Transform each item in the collection using a callback.
@param Closure $callback
@return \Nova\Support\Collection | entailment |
public function pluck($value, $key = null)
{
return with(new static(Arr::pluck($this->items, $value, $key)))->first();
} | Get the values of a given key.
@param string|array $value
@param string|null $key
@return static | entailment |
public function toJson($options = 0)
{
$items = array_map(function ($value)
{
if ($value instanceof JsonableInterface) {
return json_decode($value->toJson(), true);
} elseif ($value instanceof ArrayableInterface) {
return $value->toArray();
} else {
return $value;
}
}, $this->items);
return json_encode($items, $options);
} | Get the collection of items as JSON.
@param int $options
@return string | entailment |
public function validAuthenticationResponse(Request $request, $result)
{
$channel = $request->input('channel_name');
$socketId = $request->input('socket_id');
if (Str::startsWith($channel, 'presence-')) {
$user = $request->user();
return $this->presenceAuth(
$channel, $socketId, $user->getAuthIdentifier(), $result
);
}
return $this->socketAuth($channel, $socketId);
} | Return the valid authentication response.
@param \Nova\Http\Request $request
@param mixed $result
@return mixed | entailment |
public function broadcast(array $channels, $event, array $payload = array())
{
$socket = Arr::pull($payload, 'socket');
$this->trigger($this->formatChannels($channels), $event, $payload, $socket);
} | {@inheritdoc} | entailment |
protected function trigger($channels, $event, $data, $socketId = null)
{
$payload = array(
'channels' => json_encode($channels),
'event' => str_replace('\\', '.', $event),
'data' => json_encode($data),
'socketId' => $socketId ?: '',
);
$path = 'apps/' .$this->publicKey .'/events';
//
$hash = hash_hmac('sha256', "POST\n" .$path .':' .json_encode($payload), $this->secretKey, false);
// Compute the server URL.
$host = Arr::get($this->options, 'httpHost', '127.0.0.1');
$port = Arr::get($this->options, 'httpPort', 2121);
$url = $host .':' .$port .'/' .$path;
// Create a Guzzle Http Client instance.
$client = new HttpClient();
try {
$response = $client->post($url, array(
'headers' => array(
'CONNECTION' => 'close',
'AUTHORIZATION' => 'Bearer ' .$hash,
),
'body' => $payload,
));
$status = (int) $response->getStatusCode();
return ($status == 200) && ($response->getBody() == '200 OK');
}
catch (RequestException $e) {
throw new BroadcastException($e->getMessage());
}
} | Trigger an event by providing event name and payload.
Optionally provide a socket ID to exclude a client (most likely the sender).
@param array|string $channels A channel name or an array of channel names to publish the event on.
@param string $event
@param mixed $data Event data
@param string|null $socketId [optional]
@return bool
@throws \Nova\Broadcasting\BroadcastException | entailment |
public function socketAuth($channel, $socketId, $customData = null)
{
if (preg_match('/^[-a-z0-9_=@,.;]+$/i', $channel) !== 1) {
throw new BroadcastException('Invalid channel name ' .$channel);
}
if (preg_match('/^(?:\/[a-z0-9]+#)?[a-z0-9]+$/i', $socketId) !== 1) {
throw new BroadcastException('Invalid socket ID ' .$socketId);
}
if (! is_null($customData)) {
$signature = hash_hmac('sha256', $socketId .':' .$channel .':' .$customData, $this->secretKey, false);
} else {
$signature = hash_hmac('sha256', $socketId .':' .$channel, $this->secretKey, false);
}
$signature = array('auth' => $signature);
// Add the custom data if it has been supplied.
if (! is_null($customData)) {
$signature['payload'] = $customData;
}
return json_encode($signature);
} | Creates a socket signature.
@param string $socketId
@param string $customData
@return string | entailment |
public function presenceAuth($channel, $socketId, $userId, $userInfo = null)
{
$userData = array('userId' => $userId);
if (! is_null($userInfo)) {
$userData['userInfo'] = $userInfo;
}
return $this->socketAuth($channel, $socketId, json_encode($userData));
} | Creates a presence signature (an extension of socket signing).
@param string $socketId
@param string $userId
@param mixed $userInfo
@return string | entailment |
public function hasProperty()
{
if (!array_key_exists($this->data[1], (array)$this->data[0])) {
throw new DidNotMatchException();
}
return $this->data[0]->{$this->data[1]};
} | Assert that an object has a property. Returns the properties value.
@return mixed
@throws DidNotMatchException
@syntax object ?:object has property ?:string | entailment |
public static function objectToArrayLessId($object)
{
// convert object into associative array
$objectAsArray = (array)$object;
$objectsAsArrayLessNamespaces = self::removeNamespacesFromKeys($objectAsArray, $object);
// remove the 'id' element
unset($objectsAsArrayLessNamespaces['id']);
// return this array
return $objectsAsArrayLessNamespaces;
} | convert an Object into an associate array, and remove the first element (the 'id')
e.g. convert from this:
Itb\Message Object
(
[id:Itb\Message:public] => (null or whatever)
[text:Itb\Message:public] => hello there
[user:Itb\Message:public] => matt
[timestamp:Itb\Message:public] => 1456340266
)
to this:
Array
(
[text] => hello there
[user] => matt
[timestamp] => 1456341484
)
this is a convenient way to INSERT objects into autoincrement tables (so we don't want to pass the ID value - we want the DB to choose a new ID for us...)
@param $object
@return array | entailment |
public static function fieldListToValuesString($fields)
{
$formattedFields = [];
foreach ($fields as $field) {
$fieldWithColonPrefix = ':' . $field;
$formattedFields[] = $fieldWithColonPrefix;
}
return ' value (' . implode(', ', $formattedFields) . ')';
} | given array of field names output parenthesied, comma separate list, with colon prefix
e.g.
input:
['one', 'two', 'three']
output
'value (:one, :two, :three)'
@param array $fields
@return string | entailment |
public static function fieldListToUpdateString($fields)
{
$formattedFields = [];
foreach ($fields as $field) {
$fieldWithEqualsColonPrefix = $field . ' = :' . $field;
$formattedFields[] = $fieldWithEqualsColonPrefix;
}
return ' ' . implode(', ', $formattedFields) . ' ';
} | given array of field names output comma separate list, with equals-colon syntax
e.g.
input:
['a', 'b']
output
'a = :a, b = :b'
@param array $fields
@return string | entailment |
protected function addImpliedCommands()
{
if (count($this->columns) > 0 && ! $this->creating()) {
array_unshift($this->commands, $this->createCommand('add'));
}
$this->addFluentIndexes();
} | Add the commands that are implied by the blueprint.
@return void | entailment |
protected function dropIndexCommand($command, $type, $index)
{
$columns = array();
// If the given "index" is actually an array of columns, the developer means
// to drop an index merely by specifying the columns involved without the
// conventional name, so we will build the index name from the columns.
if (is_array($index)) {
$columns = $index;
$index = $this->createIndexName($type, $columns);
}
return $this->indexCommand($command, $columns, $index);
} | Create a new drop index command on the blueprint.
@param string $command
@param string $type
@param string|array $index
@return \Nova\Support\Fluent | entailment |
protected function indexCommand($type, $columns, $index)
{
$columns = (array) $columns;
// If no name was specified for this index, we will create one using a basic
// convention of the table name, followed by the columns, followed by an
// index type, such as primary or index, which makes the index unique.
if (is_null($index)) {
$index = $this->createIndexName($type, $columns);
}
return $this->addCommand($type, compact('index', 'columns'));
} | Add a new index command to the blueprint.
@param string $type
@param string|array $columns
@param string $index
@return \Nova\Support\Fluent | entailment |
protected function createIndexName($type, array $columns)
{
$index = strtolower($this->table.'_'.implode('_', $columns).'_'.$type);
return str_replace(array('-', '.'), '_', $index);
} | Create a default index name for the table.
@param string $type
@param array $columns
@return string | entailment |
protected function addColumn($type, $name, array $parameters = array())
{
$attributes = array_merge(compact('type', 'name'), $parameters);
$this->columns[] = $column = new Fluent($attributes);
return $column;
} | Add a new column to the blueprint.
@param string $type
@param string $name
@param array $parameters
@return \Nova\Support\Fluent | entailment |
public function removeColumn($name)
{
$this->columns = array_values(array_filter($this->columns, function($c) use ($name)
{
return $c['attributes']['name'] != $name;
}));
return $this;
} | Remove a column from the schema blueprint.
@param string $name
@return $this | entailment |
protected function addCommand($name, array $parameters = array())
{
$this->commands[] = $command = $this->createCommand($name, $parameters);
return $command;
} | Add a new command to the blueprint.
@param string $name
@param array $parameters
@return \Nova\Support\Fluent | entailment |
public function can($ability, $arguments = array())
{
$gate = App::make('Nova\Auth\Access\GateInterface')->forUser($this);
return $gate->check($ability, $arguments);
} | Determine if the entity has a given ability.
@param string $ability
@param array|mixed $arguments
@return bool | entailment |
protected function sendRequest()
{
$this->command['limit'] = $this->pageSize;
if ($this->nextToken) {
$this->command['starting_after'] = $this->nextToken;
}
$result = $this->command->execute();
$data = $result['data'];
$lastItem = end($data);
// This avoid to do any additional request
$this->nextToken = $result['has_more'] ? $lastItem['id'] : false;
return $data;
} | {@inheritDoc} | entailment |
public function handle()
{
$this->cache->flush();
$this->files->delete($this->container['config']['app.manifest'] .DS .'services.php');
$this->info('Application cache cleared!');
} | Execute the console command.
@return void | entailment |
protected function throwValidationException(Request $request, $validator)
{
$response = $this->buildFailedValidationResponse(
$request, $this->formatValidationErrors($validator)
);
throw new HttpResponseException($response);
} | Throw the failed validation exception.
@param \Nova\Http\Request $request
@param \Nova\Validation\Validator $validator
@return void
@throws \Nova\Http\Exception\HttpResponseException | entailment |
protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->ajax() || $request->wantsJson()) {
return new JsonResponse($errors, 422);
}
$url = $this->getRedirectUrl();
return Redirect::to($url)
->withInput($request->input())
->withErrors($errors, $this->errorBag());
} | Create the response for when a request fails validation.
@param \Nova\Http\Request $request
@param array $errors
@return \Nova\Http\Response | entailment |
protected function withErrorBag($errorBag, callable $callback)
{
$this->validatesRequestErrorBag = $errorBag;
call_user_func($callback);
$this->validatesRequestErrorBag = null;
} | Execute a Closure within with a given error bag set as the default bag.
@param string $errorBag
@param callable $callback
@return void | entailment |
protected function explodeRules($rules)
{
foreach ($rules as $key => $rule) {
$rules[$key] = is_string($rule) ? explode('|', $rule) : $rule;
}
return $rules;
} | Explode the rules into an array of rules.
@param string|array $rules
@return array | entailment |
public function sometimes($attribute, $rules, callable $callback)
{
$payload = new Fluent(array_merge($this->data, $this->files));
if (call_user_func($callback, $payload)) {
foreach ((array) $attribute as $key) {
$this->mergeRules($key, $rules);
}
}
} | Add conditions to a given field based on a Closure.
@param string $attribute
@param string|array $rules
@param callable $callback
@return void | entailment |
protected function getValue($attribute)
{
if (! is_null($value = Arr::get($this->data, $attribute))) {
return $value;
} else if (! is_null($value = Arr::get($this->files, $attribute))) {
return $value;
}
} | Get the value of a given attribute.
@param string $attribute
@return mixed | entailment |
protected function isValidatable($rule, $attribute, $value)
{
return $this->presentOrRuleIsImplicit($rule, $attribute, $value) &&
$this->passesOptionalCheck($attribute) &&
$this->hasNotFailedPreviousRuleIfPresenceRule($rule, $attribute);
} | Determine if the attribute is validatable.
@param string $rule
@param string $attribute
@param mixed $value
@return bool | entailment |
protected function presentOrRuleIsImplicit($rule, $attribute, $value)
{
return $this->validateRequired($attribute, $value) || $this->isImplicit($rule);
} | Determine if the field is present, or the rule implies required.
@param string $rule
@param string $attribute
@param mixed $value
@return bool | entailment |
protected function passesOptionalCheck($attribute)
{
if (! $this->hasRule($attribute, array('Sometimes'))) {
return true;
}
return array_key_exists($attribute, Arr::dot($this->data))
|| in_array($attribute, array_keys($this->data))
|| array_key_exists($attribute, $this->files);
} | Determine if the attribute passes any optional check.
@param string $attribute
@return bool | entailment |
protected function addError($attribute, $rule, $parameters)
{
$message = $this->getMessage($attribute, $rule);
$message = $this->doReplacements($message, $attribute, $rule, $parameters);
$this->messages->add($attribute, $message);
} | Add an error message to the validator's collection of messages.
@param string $attribute
@param string $rule
@param array $parameters
@return void | entailment |
protected function validateFilled($attribute, $value)
{
if (array_key_exists($attribute, $this->data) || array_key_exists($attribute, $this->files)) {
return $this->validateRequired($attribute, $value);
}
return true;
} | Validate the given attribute is filled if it is present.
@param string $attribute
@param mixed $value
@return bool | entailment |
protected function validateRequiredWith($attribute, $value, $parameters)
{
if (! $this->allFailingRequired($parameters)) {
return $this->validateRequired($attribute, $value);
}
return true;
} | Validate that an attribute exists when any other attribute exists.
@param string $attribute
@param mixed $value
@param mixed $parameters
@return bool | entailment |
protected function getPresentCount($attributes)
{
$count = 0;
foreach ($attributes as $key) {
if (Arr::get($this->data, $key) || Arr::get($this->files, $key)) {
$count++;
}
}
return $count;
} | Get the number of attributes in a list that are present.
@param array $attributes
@return int | entailment |
protected function validateSame($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'same');
$other = Arr::get($this->data, $parameters[0]);
return (isset($other) && $value == $other);
} | Validate that two attributes match.
@param string $attribute
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function validateSize($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'size');
return $this->getSize($attribute, $value) == $parameters[0];
} | Validate the size of an attribute.
@param string $attribute
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function validateExists($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'exists');
list($connection, $table) = $this->parseTable($parameters[0]);
// The second parameter position holds the name of the column that should be
// verified as existing. If this parameter is not specified we will guess
// that the columns being "verified" shares the given attribute's name.
$column = isset($parameters[1]) ? $parameters[1] : $attribute;
$expected = (is_array($value)) ? count($value) : 1;
return $this->getExistCount($connection, $table, $column, $value, $parameters) >= $expected;
} | Validate the existence of an attribute value in a database table.
@param string $attribute
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function validateMimes($attribute, $value, $parameters)
{
if (! $this->isAValidFileInstance($value)) {
return false;
}
return $value->getPath() != '' && in_array($value->guessExtension(), $parameters);
} | Validate the MIME type of a file upload attribute is in a set of MIME types.
@param string $attribute
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function validateRegex($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'regex');
return preg_match($parameters[0], $value);
} | Validate that an attribute passes a regular expression check.
@param string $attribute
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function validateDateFormat($attribute, $value, $parameters)
{
$this->requireParameterCount(1, $parameters, 'date_format');
$parsed = date_parse_from_format($parameters[0], $value);
return $parsed['error_count'] === 0 && $parsed['warning_count'] === 0;
} | Validate that an attribute matches a date format.
@param string $attribute
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function validateBeforeWithFormat($format, $value, $parameters)
{
$param = $this->getValue($parameters[0]) ?: $parameters[0];
return $this->checkDateTimeOrder($format, $value, $param);
} | Validate the date is before a given date with a given format.
@param string $format
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function validateAfterWithFormat($format, $value, $parameters)
{
$param = $this->getValue($parameters[0]) ?: $parameters[0];
return $this->checkDateTimeOrder($format, $param, $value);
} | Validate the date is after a given date with a given format.
@param string $format
@param mixed $value
@param array $parameters
@return bool | entailment |
protected function checkDateTimeOrder($format, $before, $after)
{
$before = $this->getDateTimeWithOptionalFormat($format, $before);
$after = $this->getDateTimeWithOptionalFormat($format, $after);
return ($before && $after) && ($after > $before);
} | Given two date/time strings, check that one is after the other.
@param string $format
@param string $before
@param string $after
@return bool | entailment |
protected function getMessage($attribute, $rule)
{
$lowerRule = Str::camel($rule);
$inlineMessage = $this->getInlineMessage($attribute, $lowerRule);
// First we will retrieve the custom message for the validation rule if one
// exists. If a custom validation message is being used we'll return the
// custom message, otherwise we'll keep searching for a valid message.
if (! is_null($inlineMessage)) {
return $inlineMessage;
}
$customKey = "validation.custom.{$attribute}.{$lowerRule}";
$customMessage = $this->config->get($customKey);
// First we check for a custom defined validation message for the attribute
// and rule. This allows the developer to specify specific messages for
// only some attributes and rules that need to get specially formed.
if (! is_null($customMessage)) {
return $customMessage;
}
// If the rule being validated is a "size" rule, we will need to gather the
// specific error message for the type of attribute being validated such
// as a number, file or string which all have different message types.
else if (in_array($rule, $this->sizeRules)) {
return $this->getSizeMessage($attribute, $rule);
}
// Finally, if no developer specified messages have been set, and no other
// special messages apply for this rule, we will just pull the default
// messages out of the translator service for this validation rule.
$key = "validation.{$lowerRule}";
if (! is_null($value = $this->config->get($key))) {
return $value;
}
$lowerRule = Str::snake($rule);
return $this->getInlineMessage(
$attribute, $lowerRule, $this->fallbackMessages
) ?: $key;
} | Get the validation message for an attribute and rule.
@param string $attribute
@param string $rule
@return string | entailment |
protected function getInlineMessage($attribute, $lowerRule, $source = null)
{
$source = $source ?: $this->customMessages;
$keys = array("{$attribute}.{$lowerRule}", $lowerRule);
// First we will check for a custom message for an attribute specific rule
// message for the fields, then we will check for a general custom line
// that is not attribute specific. If we find either we'll return it.
foreach ($keys as $key) {
if (isset($source[$key])) {
return $source[$key];
}
}
} | Get the inline message for a rule if it exists.
@param string $attribute
@param string $lowerRule
@param array $source
@return string | entailment |
protected function getSizeMessage($attribute, $rule)
{
$lowerRule = Str::camel($rule);
// There are three different types of size validations. The attribute may be
// either a number, file, or string so we will check a few things to know
// which type of value it is and return the correct line for that type.
$type = $this->getAttributeType($attribute);
$key = "validation.{$lowerRule}.{$type}";
return $this->config->get($key, $key);
} | Get the proper error message for an attribute and size rule.
@param string $attribute
@param string $rule
@return string | entailment |
protected function getAttributeType($attribute)
{
// We assume that the attributes present in the file array are files so that
// means that if the attribute does not have a numeric rule and the files
// list doesn't have it we'll just consider it a string by elimination.
if ($this->hasRule($attribute, $this->numericRules)) {
return 'numeric';
} else if ($this->hasRule($attribute, array('Array'))) {
return 'array';
} else if (array_key_exists($attribute, $this->files)) {
return 'file';
}
return 'string';
} | Get the data type of the given attribute.
@param string $attribute
@return string | entailment |
protected function doReplacements($message, $attribute, $rule, $parameters)
{
$message = str_replace(':attribute', $this->getAttribute($attribute), $message);
$replacer = Str::snake($rule);
if (isset($this->replacers[$replacer])) {
$message = $this->callReplacer($message, $attribute, $replacer, $parameters);
} else if (method_exists($this, $replacer = "replace{$rule}")) {
$message = call_user_func(array($this, $replacer), $message, $attribute, $rule, $parameters);
}
return $message;
} | Replace all error message place-holders with actual values.
@param string $message
@param string $attribute
@param string $rule
@param array $parameters
@return string | entailment |
protected function getAttribute($attribute)
{
// The developer may dynamically specify the array of custom attributes
// on this Validator instance. If the attribute exists in this array
// it takes precedence over all other ways we can pull attributes.
if (isset($this->customAttributes[$attribute])) {
return $this->customAttributes[$attribute];
}
$key = "validation.attributes.{$attribute}";
// We allow for the developer to specify language lines for each of the
// attributes allowing for more displayable counterparts of each of
// the attributes. This provides the ability for simple formats.
if (! is_null($line = $this->config->get($key))) {
return $line;
}
// If no language line has been specified for the attribute all of the
// underscores are removed from the attribute name and that will be
// used as default versions of the attribute's displayable names.
return str_replace('_', ' ', Str::snake($attribute));
} | Get the displayable name of the attribute.
@param string $attribute
@return string | entailment |
public function getDisplayableValue($attribute, $value)
{
if (isset($this->customValues[$attribute][$value])) {
return $this->customValues[$attribute][$value];
}
$key = "validation.values.{$attribute}.{$value}";
if (! is_null($line = $this->config->get($key))) {
return $line;
}
return $value;
} | Get the displayable name of the value.
@param string $attribute
@param mixed $value
@return string | entailment |
protected function replaceRequiredIf($message, $attribute, $rule, $parameters)
{
$parameters[1] = $this->getDisplayableValue($parameters[0], Arr::get($this->data, $parameters[0]));
$parameters[0] = $this->getAttribute($parameters[0]);
return str_replace(array(':other', ':value'), $parameters, $message);
} | Replace all place-holders for the required_if rule.
@param string $message
@param string $attribute
@param string $rule
@param array $parameters
@return string | entailment |
protected function replaceSame($message, $attribute, $rule, $parameters)
{
return str_replace(':other', $this->getAttribute($parameters[0]), $message);
} | Replace all place-holders for the same rule.
@param string $message
@param string $attribute
@param string $rule
@param array $parameters
@return string | entailment |
protected function replaceBefore($message, $attribute, $rule, $parameters)
{
if (! (strtotime($parameters[0]))) {
return str_replace(':date', $this->getAttribute($parameters[0]), $message);
}
return str_replace(':date', $parameters[0], $message);
} | Replace all place-holders for the before rule.
@param string $message
@param string $attribute
@param string $rule
@param array $parameters
@return string | entailment |
protected function parseArrayRule(array $rules)
{
$rule = Arr::get($rules, 0);
return array(
Str::studly(trim($rule)), array_slice($rules, 1)
);
} | Parse an array based rule.
@param array $rules
@return array | entailment |
protected function callClassBasedExtension($callback, $parameters)
{
list($class, $method) = explode('@', $callback);
$instance = $this->container->make($class);
return call_user_func_array(array($instance, $method), $parameters);
} | Call a class based validator extension.
@param string $callback
@param array $parameters
@return bool | entailment |
protected function callReplacer($message, $attribute, $rule, $parameters)
{
$callback = $this->replacers[$rule];
if ($callback instanceof Closure) {
return call_user_func_array($callback, func_get_args());
} else if (is_string($callback)) {
return $this->callClassBasedReplacer($callback, $message, $attribute, $rule, $parameters);
}
} | Call a custom validator message replacer.
@param string $message
@param string $attribute
@param string $rule
@param array $parameters
@return string | entailment |
protected function callClassBasedReplacer($callback, $message, $attribute, $rule, $parameters)
{
list($class, $method) = explode('@', $callback);
$instance = $this->container->make($class);
return call_user_func_array(array($instance, $method), array_slice(func_get_args(), 1));
} | Call a class based validator message replacer.
@param string $callback
@param string $message
@param string $attribute
@param string $rule
@param array $parameters
@return string | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.