sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function orHaving($column, $operator = null, $value = null)
{
return $this->having($column, $operator, $value, 'or');
} | Add a "or having" clause to the query.
@param string $column
@param string $operator
@param string $value
@return \Nova\Database\Query\Builder|static | entailment |
public function havingRaw($sql, array $bindings = array(), $boolean = 'and')
{
$type = 'raw';
$this->havings[] = compact('type', 'sql', 'boolean');
$this->addBinding($bindings, 'having');
return $this;
} | Add a raw having clause to the query.
@param string $sql
@param array $bindings
@param string $boolean
@return $this | entailment |
public function orderBy($column, $direction = 'asc')
{
$property = $this->unions ? 'unionOrders' : 'orders';
$direction = strtolower($direction) == 'asc' ? 'asc' : 'desc';
$this->{$property}[] = compact('column', 'direction');
return $this;
} | Add an "order by" clause to the query.
@param string $column
@param string $direction
@return $this | entailment |
public function orderByRaw($sql, $bindings = array())
{
$type = 'raw';
$this->orders[] = compact('type', 'sql');
$this->addBinding($bindings, 'order');
return $this;
} | Add a raw "order by" clause to the query.
@param string $sql
@param array $bindings
@return $this | entailment |
public function union($query, $all = false)
{
if ($query instanceof Closure) {
call_user_func($query, $query = $this->newQuery());
}
$this->unions[] = compact('query', 'all');
return $this->mergeBindings($query);
} | Add a union statement to the query.
@param \Nova\Database\Query\Builder|\Closure $query
@param bool $all
@return \Nova\Database\Query\Builder|static | entailment |
public function remember($minutes, $key = null)
{
list($this->cacheMinutes, $this->cacheKey) = array($minutes, $key);
return $this;
} | Indicate that the query results should be cached.
@param \DateTime|int $minutes
@param string $key
@return $this | entailment |
public function pluck($column)
{
$result = (array) $this->first(array($column));
return count($result) > 0 ? reset($result) : null;
} | Pluck a single column's value from the first result of a query.
@param string $column
@return mixed | entailment |
public function get($columns = array('*'))
{
if (! is_null($this->cacheMinutes)) return $this->getCached($columns);
return $this->getFresh($columns);
} | Execute the query as a "select" statement.
@param array $columns
@return array|static[] | entailment |
public function getFresh($columns = array('*'))
{
if (is_null($this->columns)) $this->columns = $columns;
return $this->processor->processSelect($this, $this->runSelect());
} | Execute the query as a fresh "select" statement.
@param array $columns
@return array|static[] | entailment |
public function getCached($columns = array('*'))
{
if (is_null($this->columns)) $this->columns = $columns;
//
list($key, $minutes) = $this->getCacheInfo();
$cache = $this->getCache();
$callback = $this->getCacheCallback($columns);
if ($minutes < 0) {
return $cache->rememberForever($key, $callback);
}
return $cache->remember($key, $minutes, $callback);
} | Execute the query as a cached "select" statement.
@param array $columns
@return array | entailment |
protected function getCache()
{
$cache = $this->connection->getCacheManager()->driver($this->cacheDriver);
return $this->cacheTags ? $cache->tags($this->cacheTags) : $cache;
} | Get the cache object with tags assigned, if applicable.
@return \Nova\Cache\CacheManager | entailment |
protected function getListSelect($column, $key)
{
$select = is_null($key) ? array($column) : array($column, $key);
if (($dot = strpos($select[0], '.')) !== false) {
$select[0] = substr($select[0], $dot + 1);
}
return $select;
} | Get the columns that should be used in a list array.
@param string $column
@param string $key
@return array | entailment |
public function implode($column, $glue = null)
{
if (is_null($glue)) return implode($this->lists($column));
return implode($glue, $this->lists($column));
} | Concatenate values of a given column as a string.
@param string $column
@param string $glue
@return string | entailment |
public function paginate($perPage = 15, $columns = array('*'), $pageName = 'page', $page = null)
{
if (is_null($page)) {
$page = Paginator::resolveCurrentPage($pageName);
}
$path = Paginator::resolveCurrentPath($pageName);
//
$total = $this->getPaginationCount();
if ($total > 0) {
$results = $this->forPage($page, $perPage)->get($columns);
} else {
$results = collect();
}
return new Paginator($results, $total, $perPage, $page, compact('path', 'pageName'));
} | Paginate the given query into a paginator.
@param int $perPage
@param array $columns
@param string $pageName
@param int|null $page
@return \Nova\Pagination\Paginator | entailment |
protected function backupFieldsForCount()
{
foreach (array('orders', 'limit', 'offset') as $field) {
$this->backups[$field] = $this->{$field};
$this->{$field} = null;
}
} | Backup certain fields for a pagination count.
@return void | entailment |
public function exists()
{
$limit = $this->limit;
$result = $this->limit(1)->count() > 0;
$this->limit($limit);
return $result;
} | Determine if any rows exist for the current query.
@return bool | entailment |
public function delete($id = null)
{
if (! is_null($id)) $this->where('id', '=', $id);
$sql = $this->grammar->compileDelete($this);
return $this->connection->delete($sql, $this->getBindings());
} | Delete a record from the database.
@param mixed $id
@return int | entailment |
public function mergeWheres($wheres, $bindings)
{
$this->wheres = array_merge((array) $this->wheres, (array) $wheres);
$this->bindings['where'] = array_values(array_merge($this->bindings['where'], (array) $bindings));
} | Merge an array of where clauses and bindings.
@param array $wheres
@param array $bindings
@return void | entailment |
public function mergeBindings(Builder $query)
{
$this->bindings = array_merge_recursive($this->bindings, $query->bindings);
return $this;
} | Merge an array of bindings into our bindings.
@param \Nova\Database\Query\Builder $query
@return $this | entailment |
public function backup(Profile $profile, $clear = false)
{
$scratchDir = $profile->getScratchDir();
$processor = $profile->getProcessor();
$filesystem = new Filesystem();
if ($clear) {
$this->logger->info('Clearing scratch directory...');
$filesystem->remove($scratchDir);
}
if (!is_dir($scratchDir)) {
$filesystem->mkdir($scratchDir);
}
$this->logger->info('Beginning backup...');
foreach ($profile->getSources() as $source) {
$source->fetch($scratchDir, $this->logger);
}
$filename = $processor->process($scratchDir, $profile->getNamer(), $this->logger);
try {
$backups = $this->sendToDestinations($profile, $filename);
} catch (\Exception $e) {
$processor->cleanup($filename, $this->logger);
throw $e;
}
$processor->cleanup($filename, $this->logger);
$this->logger->info('Done.');
return new BackupCollection($backups);
} | @param Profile $profile
@param bool $clear
@return BackupCollection
@throws \Exception | entailment |
private function sendToDestinations(Profile $profile, $filename)
{
$backups = array();
foreach ($profile->getDestinations() as $destination) {
$backup = $destination->push($filename, $this->logger);
$size = $backup->getSize();
if (class_exists('\\ByteUnits\\System')) {
$size = \ByteUnits\parse($size)->format('B');
}
$this->logger->info(
sprintf('Backup created for destination "%s" at: "%s" ', $destination->getName(), $backup->getKey()),
array(
'size' => $size,
'created_at' => $backup->getCreatedAt()->format('Y-m-d H:i:s'),
)
);
$backups[] = $backup;
}
return $backups;
} | @param Profile $profile
@param string $filename
@return Backup[] | entailment |
public static function fromCommand(CommandInterface $command, Response $response)
{
$errors = json_decode($response->getBody(true), true);
$type = $errors['error']['type'];
$message = isset($errors['error']['message']) ? $errors['error']['message'] : 'Unknown error';
$code = isset($errors['error']['code']) ? $errors['error']['code'] : null;
// We can trigger very specific exception based on the type and code
if ($type === 'card_error') {
$exception = new CardErrorException($message, $response->getStatusCode());
} elseif ($type === 'invalid_request_error' && $code === 'rate_limit') {
$exception = new ApiRateLimitException($message, $response->getStatusCode());
} else {
$exception = new static($message, $response->getStatusCode());
}
$exception->setRequest($command->getRequest());
$exception->setResponse($response);
return $exception;
} | {@inheritDoc} | entailment |
public function hasHeader($name) : bool
{
$name = $this->normalizeHeaderName($name);
return ! empty($this->headers[$name]);
} | {@inheritDoc} | entailment |
public function getHeaderLine($name) : string
{
$name = $this->normalizeHeaderName($name);
if (empty($this->headers[$name]))
{
return '';
}
return \implode(', ', $this->headers[$name]);
} | {@inheritDoc} | entailment |
public function withHeader($name, $value) : MessageInterface
{
$this->validateHeaderName($name);
$this->validateHeaderValue($value);
$name = $this->normalizeHeaderName($name);
$value = $this->normalizeHeaderValue($value);
$clone = clone $this;
$clone->headers[$name] = $value;
return $clone;
} | {@inheritDoc} | entailment |
public function withAddedHeader($name, $value) : MessageInterface
{
$this->validateHeaderName($name);
$this->validateHeaderValue($value);
$name = $this->normalizeHeaderName($name);
$value = $this->normalizeHeaderValue($value);
if (! empty($this->headers[$name]))
{
$value = \array_merge($this->headers[$name], $value);
}
$clone = clone $this;
$clone->headers[$name] = $value;
return $clone;
} | {@inheritDoc} | entailment |
public function withoutHeader($name) : MessageInterface
{
$name = $this->normalizeHeaderName($name);
$clone = clone $this;
unset($clone->headers[$name]);
return $clone;
} | {@inheritDoc} | entailment |
protected function validateProtocolVersion($protocolVersion) : void
{
if (! \is_string($protocolVersion))
{
throw new \InvalidArgumentException('HTTP protocol version must be a string');
}
else if (! \preg_match('/^\d(?:\.\d)?$/', $protocolVersion))
{
throw new \InvalidArgumentException(\sprintf('The given protocol version "%s" is not valid', $protocolVersion));
}
} | Validates the given protocol version
@param mixed $protocolVersion
@return void
@throws \InvalidArgumentException
@link https://tools.ietf.org/html/rfc7230#section-2.6
@link https://tools.ietf.org/html/rfc7540 | entailment |
protected function validateHeaderName($headerName) : void
{
if (! \is_string($headerName))
{
throw new \InvalidArgumentException('Header name must be a string');
}
else if (! \preg_match(HeaderInterface::RFC7230_TOKEN, $headerName))
{
throw new \InvalidArgumentException(\sprintf('The given header name "%s" is not valid', $headerName));
}
} | Validates the given header name
@param mixed $headerName
@return void
@throws \InvalidArgumentException
@link https://tools.ietf.org/html/rfc7230#section-3.2 | entailment |
protected function validateHeaderValue($headerValue) : void
{
if (\is_string($headerValue))
{
$headerValue = [$headerValue];
}
if (! \is_array($headerValue) || [] === $headerValue)
{
throw new \InvalidArgumentException('Header value must be a string or not an empty array');
}
foreach ($headerValue as $oneOf)
{
if (! \is_string($oneOf))
{
throw new \InvalidArgumentException('Header value must be a string or an array containing only strings');
}
else if (! \preg_match(HeaderInterface::RFC7230_FIELD_VALUE, $oneOf))
{
throw new \InvalidArgumentException(\sprintf('The given header value "%s" is not valid', $oneOf));
}
}
} | Validates the given header value
@param mixed $headerValue
@return void
@throws \InvalidArgumentException
@link https://tools.ietf.org/html/rfc7230#section-3.2 | entailment |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
{
// Fix Chrome ico request bug
if ($request->getUri()->getPath() === '/favicon.ico') {
throw new NotAcceptableException('access favicon.ico');
}
return $handler->handle($request);
} | fix the bug of chrome
Process an incoming server request and return a response, optionally delegating
response creation to a handler.
@param \Psr\Http\Message\ServerRequestInterface $request
@param \Psr\Http\Server\RequestHandlerInterface $handler
@return \Psr\Http\Message\ResponseInterface
@throws \Swoft\Http\Server\Exception\NotAcceptableException | entailment |
public function run()
{
\Artify\Artify\Models\Role::create([
'slug' => 'admin',
'name' => 'Administrator',
'permissions' => [
'view-post' => true,
'update-post' => true,
'delete-post' => true,
'create-post' => true,
'approve-post' => true,
'create-tag' => true,
'update-tag' => true,
'delete-tag' => true,
'view-tag' => true,
'view-comment' => true,
'update-comment' => true,
'delete-comment' => true,
'create-comment' => true,
'approve-comment' => true,
'view-reply' => true,
'update-reply' => true,
'delete-reply' => true,
'create-reply' => true,
'approve-reply' => true,
'upgrade-user' => true,
'downgrade-user' => true,
],
]);
\Artify\Artify\Models\Role::create([
'slug' => 'moderator',
'name' => 'Moderator',
'permissions' => [
'create-post' => true,
'view-post' => true,
'delete-post' => true,
'update-post' => true,
'approve-post' => false,
'create-tag' => true,
'update-tag' => true,
'view-tag' => true,
'delete-tag' => true,
'create-comment' => true,
'update-comment' => true,
'delete-comment' => true,
'view-comment' => true,
'approve-comment' => true,
'create-reply' => true,
'update-reply' => true,
'delete-reply' => true,
'view-reply' => true,
'approve-reply' => true,
'upgrade-user' => false,
'downgrade-user' => false,
],
]);
\Artify\Artify\Models\Role::create([
'name' => 'Normal User',
'slug' => 'user',
'permissions' => [
'create-post' => false,
'view-post' => true,
'update-post' => false,
'delete-post' => false,
'approve-post' => false,
'create-tag' => false,
'view-tag' => false,
'update-tag' => false,
'delete-tag' => false,
'create-comment' => true,
'update-comment' => true,
'view-comment' => true,
'delete-comment' => true,
'approve-comment' => false,
'create-reply' => true,
'update-reply' => true,
'view-reply' => true,
'delete-reply' => true,
'approve-reply' => false,
'upgrade-user' => false,
'downgrade-user' => false,
],
]);
} | Run the database seeds.
@return void | entailment |
public function createRequest(string $method, $uri) : RequestInterface
{
if (! ($uri instanceof UriInterface))
{
$uri = (new UriFactory)
->createUri($uri);
}
$body = (new StreamFactory)
->createStream();
return (new Request)
->withMethod($method)
->withUri($uri)
->withBody($body);
} | {@inheritDoc} | entailment |
protected function getAliasedPivotColumns()
{
$defaults = array($this->foreignKey, $this->otherKey);
$columns = array();
foreach (array_merge($defaults, $this->pivotColumns) as $column) {
$columns[] = $this->table.'.'.$column.' as pivot_'.$column;
}
return array_unique($columns);
} | Get the pivot columns for the relation.
@return array | entailment |
protected function setJoin($query = null)
{
$query = $query ?: $this->query;
$baseTable = $this->related->getTable();
$key = $baseTable.'.'.$this->related->getKeyName();
$query->join($this->table, $key, '=', $this->getOtherKey());
return $this;
} | Set the join clause for the relation query.
@param \Nova\Database\ORM\Builder|null
@return $this | entailment |
protected function setWhere()
{
$foreign = $this->getForeignKey();
$this->query->where($foreign, '=', $this->parent->getKey());
return $this;
} | Set the where clause for the relation query.
@return $this | entailment |
public function addEagerConstraints(array $models)
{
$this->query->whereIn($this->getForeignKey(), $this->getKeys($models));
} | Set the constraints for an eager load of the relation.
@param array $models
@return void | entailment |
public function touch()
{
$key = $this->getRelated()->getKeyName();
$columns = $this->getRelatedFreshUpdate();
$ids = $this->getRelatedIds();
if (count($ids) > 0) {
$this->getRelated()->newQuery()->whereIn($key, $ids)->update($columns);
}
} | Touch all of the related models for the relationship.
E.g.: Touch all roles associated with this user.
@return void | entailment |
public function getRelatedIds()
{
$related = $this->getRelated();
$fullKey = $related->getQualifiedKeyName();
return $this->getQuery()->select($fullKey)->lists($related->getKeyName());
} | Get all of the IDs for the related models.
@return array | entailment |
public function saveMany(array $models, array $joinings = array())
{
foreach ($models as $key => $model) {
$this->save($model, (array) array_get($joinings, $key), false);
}
$this->touchIfTouching();
return $models;
} | Save an array of new models and attach them to the parent model.
@param array $models
@param array $joinings
@return array | entailment |
public function attach($id, array $attributes = array(), $touch = true)
{
if ($id instanceof Model) $id = $id->getKey();
$query = $this->newPivotStatement();
$query->insert($this->createAttachRecords((array) $id, $attributes));
if ($touch) $this->touchIfTouching();
} | Attach a model to the parent.
@param mixed $id
@param array $attributes
@param bool $touch
@return void | entailment |
public function detach($ids = array(), $touch = true)
{
if ($ids instanceof Model) $ids = (array) $ids->getKey();
$query = $this->newPivotQuery();
$ids = (array) $ids;
if (count($ids) > 0) {
$query->whereIn($this->otherKey, (array) $ids);
}
if ($touch) $this->touchIfTouching();
$results = $query->delete();
return $results;
} | Detach models from the relationship.
@param int|array $ids
@param bool $touch
@return int | entailment |
public function touchIfTouching()
{
if ($this->touchingParent()) $this->getParent()->touch();
if ($this->getParent()->touches($this->relationName)) $this->touch();
} | If we're touching the parent model, touch.
@return void | entailment |
protected function guessInverseRelation()
{
$relation = Str::plural(class_basename($this->getParent()));
return Str::camel($relation);
} | Attempt to guess the name of the inverse of the relation.
@return string | entailment |
protected function newPivotQuery()
{
$query = $this->newPivotStatement();
foreach ($this->pivotWheres as $whereArgs) {
call_user_func_array([$query, 'where'], $whereArgs);
}
return $query->where($this->foreignKey, $this->parent->getKey());
} | Create a new query builder for the pivot table.
@return \Nova\Database\Query\Builder | entailment |
protected function execute(InputInterface $input, OutputInterface $output)
{
$inputs = array_merge($input->getArguments(), $input->getOptions());
$parameters = array();
//
$reflection = new ReflectionFunction($this->callback);
foreach ($reflection->getParameters() as $parameter) {
if (isset($inputs[$parameter->name])) {
$parameters[$parameter->name] = $inputs[$parameter->name];
}
}
return $this->container->call(
$this->callback->bindTo($this, $this), $parameters
);
} | Execute the console command.
@param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return mixed | entailment |
public function register()
{
$commands = array(
'PackageList',
'PackageMigrate',
'PackageMigrateRefresh',
'PackageMigrateReset',
'PackageMigrateRollback',
'PackageMigrateStatus',
'PackageSeed',
'PackageOptimize',
//
'PackageMake',
'ConsoleMake',
'ControllerMake',
'EventMake',
'JobMake',
'ListenerMake',
'MiddlewareMake',
'ModelMake',
'NotificationMake',
'PolicyMake',
'ProviderMake',
'MigrationMake',
'RequestMake',
'SeederMake',
);
foreach ($commands as $command) {
$method = 'register' .$command .'Command';
call_user_func(array($this, $method));
}
} | Register the application services. | entailment |
protected function registerPackageMigrateCommand()
{
$this->app->singleton('command.package.migrate', function ($app)
{
return new PackageMigrateCommand($app['migrator'], $app['packages']);
});
$this->commands('command.package.migrate');
} | Register the Package:migrate command. | entailment |
protected function registerPackageMigrateResetCommand()
{
$this->app->singleton('command.package.migrate.reset', function ($app)
{
return new PackageMigrateResetCommand($app['packages'], $app['files'], $app['migrator']);
});
$this->commands('command.package.migrate.reset');
} | Register the Package:migrate:reset command. | entailment |
protected function registerPackageMigrateRollbackCommand()
{
$this->app->singleton('command.package.migrate.rollback', function ($app)
{
return new PackageMigrateRollbackCommand($app['migrator'], $app['packages']);
});
$this->commands('command.package.migrate.rollback');
} | Register the Package:migrate:rollback command. | entailment |
protected function registerPackageMigrateStatusCommand()
{
$this->app->singleton('command.package.migrate.status', function ($app)
{
return new PackageMigrateStatusCommand($app['migrator'], $app['packages']);
});
$this->commands('command.package.migrate.status');
} | Register the Package:migrate:reset command. | entailment |
private function registerPackageMakeCommand()
{
$this->app->bindShared('command.make.package', function ($app)
{
return new PackageMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package');
} | Register the make:package command. | entailment |
private function registerConsoleMakeCommand()
{
$this->app->bindShared('command.make.package.console', function ($app)
{
return new ConsoleMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.console');
} | Register the make:package:console command. | entailment |
private function registerControllerMakeCommand()
{
$this->app->bindShared('command.make.package.controller', function ($app)
{
return new ControllerMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.controller');
} | Register the make:package:controller command. | entailment |
private function registerEventMakeCommand()
{
$this->app->bindShared('command.make.package.event', function ($app)
{
return new EventMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.event');
} | Register the make:package:event command. | entailment |
private function registerJobMakeCommand()
{
$this->app->bindShared('command.make.package.job', function ($app)
{
return new JobMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.job');
} | Register the make:package:job command. | entailment |
private function registerListenerMakeCommand()
{
$this->app->bindShared('command.make.package.listener', function ($app)
{
return new ListenerMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.listener');
} | Register the make:package:listener command. | entailment |
private function registerMiddlewareMakeCommand()
{
$this->app->bindShared('command.make.package.middleware', function ($app)
{
return new MiddlewareMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.middleware');
} | Register the make:package:middleware command. | entailment |
private function registerModelMakeCommand()
{
$this->app->bindShared('command.make.package.model', function ($app)
{
return new ModelMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.model');
} | Register the make:package:model command. | entailment |
private function registerNotificationMakeCommand()
{
$this->app->bindShared('command.make.package.notification', function ($app)
{
return new NotificationMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.notification');
} | Register the make:package:notification command. | entailment |
private function registerPolicyMakeCommand()
{
$this->app->bindShared('command.make.package.policy', function ($app)
{
return new PolicyMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.policy');
} | Register the make:package:policy command. | entailment |
private function registerProviderMakeCommand()
{
$this->app->bindShared('command.make.package.provider', function ($app)
{
return new ProviderMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.provider');
} | Register the make:module:provider command. | entailment |
private function registerMigrationMakeCommand()
{
$this->app->bindShared('command.make.package.migration', function ($app)
{
return new MigrationMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.migration');
} | Register the make:package:migration command. | entailment |
private function registerRequestMakeCommand()
{
$this->app->bindShared('command.make.package.request', function ($app)
{
return new RequestMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.request');
} | Register the make:module:provider command. | entailment |
private function registerSeederMakeCommand()
{
$this->app->bindShared('command.make.package.seeder', function ($app)
{
return new SeederMakeCommand($app['files'], $app['packages']);
});
$this->commands('command.make.package.seeder');
} | Register the make:package:seeder command. | entailment |
public function fetch($scratchDir, LoggerInterface $logger)
{
$logger->info(sprintf('Running mysqldump for: %s', $this->database));
$processBuilder = new ProcessBuilder();
$processBuilder->setTimeout($this->timeout);
if (null !== $this->sshHost && null !== $this->sshUser) {
$processBuilder->add('ssh');
$processBuilder->add(sprintf('%s@%s', $this->sshUser, $this->sshHost));
$processBuilder->add(sprintf('-p %s', $this->sshPort));
}
$processBuilder->add('mysqldump');
$processBuilder->add(sprintf('-u%s', $this->user));
if (null !== $this->host) {
$processBuilder->add(sprintf('-h%s', $this->host));
}
if (null !== $this->password) {
$processBuilder->add(sprintf('-p%s', $this->password));
}
$processBuilder->add($this->database);
$process = $processBuilder->getProcess();
$process->run();
if (!$process->isSuccessful()) {
throw new \RuntimeException($process->getErrorOutput());
}
file_put_contents(sprintf('%s/%s.sql', $scratchDir, $this->database), $process->getOutput());
} | {@inheritdoc} | entailment |
public function add($name, $html, $folderId = null) {
$payload = array(
'name' => $name,
'html' => $html,
'folder_id' => $folderId
);
$apiCall = 'templates/add';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data,true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return isset($data['template_id']) ? $data['template_id'] : false;
} | Create a new user template, NOT campaign content. These templates can then be applied while creating campaigns.
@link http://apidocs.mailchimp.com/api/2.0/templates/add.php
@param string $name the name for the template - names must be unique and a max of 50 bytes
@param string $html a string specifying the entire template to be created. This is NOT campaign conten
@param int $folderId optional the folder to put this template in.
@return int template_id on success
@throws MailchimpAPIException | entailment |
public function listAll($types = array(), $filters = array()) {
$payload = array(
'types' => $types,
'filters' => $filters
);
$apiCall = 'templates/list';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data,true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return $data;
} | Retrieve various templates available in the system, allowing some thing similar to our template gallery to be created.
@link http://apidocs.mailchimp.com/api/2.0/templates/list.php
@param array $types optional the types of templates to return
@param array $filters optional options to control how inactive templates are returned, if at all
@return array
@throws MailchimpAPIException | entailment |
public function info($type = 'user') {
$payload = array(
'template_id' => $this->templateId,
'type' => $type
);
$apiCall = 'templates/info';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data,true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return $data;
} | Pull details for a specific template to help support editing
@link http://apidocs.mailchimp.com/api/2.0/templates/info.php
@param string $type optional the template type to load - one of 'user', 'gallery', 'base', defaults to user.
@return array
@throws MailchimpAPIException | entailment |
public function update( $options = array()) {
$payload = array(
'template_id' => $this->templateId,
'values' => $options
);
$apiCall = 'templates/update';
$data = $this->requestMonkey($apiCall, $payload);
$data = json_decode($data,true);
if (isset($data['error']))
throw new MailchimpAPIException($data);
else
return true;
} | Replace the content of a user template, NOT campaign content.
@link http://apidocs.mailchimp.com/api/2.0/templates/update.php
@param array $options the values to updates - while both are optional, at least one should be provided. Both can be updated at the same time.
@return boolean true on success
@throws MailchimpAPIException | entailment |
public function getByName($name) {
$templates = $this->listAll();
if (empty($templates['user']))
return false;
foreach ($templates['user'] as $template) {
if ($template['name'] === $name) {
return $template['id'];
}
}
return false;
} | Get template id by Name
@param type $name name of the template
@return int|boolean $id template_id or false | entailment |
public function handle($request, Closure $next)
{
$dispatcher = $this->app['assets.dispatcher'];
return $dispatcher->dispatch($request) ?: $next($request);
} | Handle an incoming request.
@param \Nova\Http\Request $request
@param \Closure $next
@return mixed | entailment |
public function withStatus($statusCode, $reasonPhrase = '') : ResponseInterface
{
$this->validateStatusCode($statusCode);
$this->validateReasonPhrase($reasonPhrase);
if ('' === $reasonPhrase)
{
$reasonPhrase = PHRASES[$statusCode] ?? 'Unknown Status Code';
}
$clone = clone $this;
$clone->statusCode = $statusCode;
$clone->reasonPhrase = $reasonPhrase;
return $clone;
} | {@inheritDoc} | entailment |
protected function validateStatusCode($statusCode) : void
{
if (! \is_int($statusCode))
{
throw new \InvalidArgumentException('HTTP status-code must be an integer');
}
else if (! ($statusCode >= 100 && $statusCode <= 599))
{
throw new \InvalidArgumentException(\sprintf('The given status-code "%d" is not valid', $statusCode));
}
} | Validates the given status-code
@param mixed $statusCode
@return void
@throws \InvalidArgumentException
@link https://tools.ietf.org/html/rfc7230#section-3.1.2 | entailment |
protected function validateReasonPhrase($reasonPhrase) : void
{
if (! \is_string($reasonPhrase))
{
throw new \InvalidArgumentException('HTTP reason-phrase must be a string');
}
else if (! \preg_match(HeaderInterface::RFC7230_FIELD_VALUE, $reasonPhrase))
{
throw new \InvalidArgumentException(\sprintf('The given reason-phrase "%s" is not valid', $reasonPhrase));
}
} | Validates the given reason-phrase
@param mixed $reasonPhrase
@return void
@throws \InvalidArgumentException
@link https://tools.ietf.org/html/rfc7230#section-3.1.2 | entailment |
public function register()
{
$this->app->singleton('command.languages.update', function ($app)
{
return new LanguagesUpdateCommand($app['language'], $app['files']);
});
$this->commands('command.languages.update');
} | Register the service provider.
@return void | entailment |
public function handle($request, Closure $next)
{
$guards = array_slice(func_get_args(), 2);
$this->authenticate($guards);
return $next($request);
} | Handle an incoming request.
@param \Nova\Http\Request $request
@param \Closure $next
@return mixed | entailment |
protected function authenticate(array $guards)
{
if (empty($guards)) {
return $this->auth->authenticate();
}
foreach ($guards as $guard) {
$auth = $this->auth->guard($guard);
if ($auth->check()) {
return $this->auth->shouldUse($guard);
}
}
throw new AuthenticationException('Unauthenticated.', $guards);
} | Determine if the user is logged in to any of the given guards.
@param array $guards
@return void
@throws \Nova\Auth\AuthenticationException | entailment |
public function handle() {
$os = (substr(php_uname('a'), 0, 3));
$name = (strtoupper($os) !== 'WIN') ? posix_getpwuid(posix_geteuid())['name'] : 'windows user';
$time = (\Carbon\Carbon::now()->format('A') === 'AM') ? 'Morning' : 'Evening';
$this->info("Good $time $name , Let's set a couple of things.");
$this->call('vendor:publish', ['--provider' => ArtifyServiceProvider::class]);
$this->info('Tip : You can modify the config/artify.php manually');
$this->info('the default column in charge of permissions within your role model is named permissions, change it or leave blank.');
$structure = $this->choice('Ehum Ehum, what sturcture do you follow ?', ['ADR', 'MVC'], 'MVC');
if ($structure === 'ADR') {
config(['artify.adr.enabled' => true]);
config(['artify.adr.domains' => []]);
$this->call('adr:install');
} else {
config(['artify.adr.enabled' => false]);
}
config(['artify.permissions_column' => 'permissions']);
if ($this->confirm('Do you use multi tenancy for this project ?')) {
config(['artify.is_multi_tenancy' => true]);
$tenant = $this->ask('Enter the class (namespaced) of the file which in charge of the tenancy.');
config()->set('artify.tenant', $tenant);
app()->bind(Tenant::class, $tenant);
$this->filesystem->makeDirectory(database_path('migrations/tenant'), 0755, true, true);
}
if ($this->argument('duration') && $this->option('cache')) {
config(['artify.cache.enabled' => true, 'artify.cache.duration' => (int) $this->argument('duration')]);
} else {
config(['artify.cache.enabled' => false, 'artify.cache.duration' => 10]);
}
$configRunTimeContent = var_export(config('artify'), true);
$this->filesystem->put(config_path('artify.php'), '');
$configRunTimeContent = str_replace(['array (', ')'], ['[', ']'], $configRunTimeContent);
$this->filesystem->put(config_path('artify.php'), "<?php\n\n return " . $configRunTimeContent . ';');
$this->info('Everything is set, Enjoy Being an Artifier');
} | Execute the console command.
@return mixed | entailment |
public function authorize($ability, $arguments = array())
{
list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments);
$gate = App::make('Nova\Auth\Access\GateInterface');
return $this->authorizeAtGate($gate, $ability, $arguments);
} | Authorize a given action against a set of arguments.
@param mixed $ability
@param mixed|array $arguments
@return \Nova\Auth\Access\Response
@throws \Symfony\Component\HttpKernel\Exception\HttpException | entailment |
public function authorizeForUser($user, $ability, $arguments = array())
{
list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments);
$gate = App::make('Nova\Auth\Access\GateInterface')->forUser($user);
return $this->authorizeAtGate($gate, $ability, $arguments);
} | Authorize a given action for a user.
@param \Nova\Auth\UserInterface|mixed $user
@param mixed $ability
@param mixed|array $arguments
@return \Nova\Auth\Access\Response
@throws \Symfony\Component\HttpKernel\Exception\HttpException | entailment |
public function authorizeAtGate(GateInterface $gate, $ability, $arguments)
{
try {
return $gate->authorize($ability, $arguments);
}
catch (UnauthorizedException $e) {
$exception = $this->createGateUnauthorizedException($ability, $arguments, $e->getMessage(), $e);
throw $exception;
}
} | Authorize the request at the given gate.
@param \Nova\Auth\Access\GateInterface $gate
@param mixed $ability
@param mixed|array $arguments
@return \Nova\Auth\Access\Response
@throws \Symfony\Component\HttpKernel\Exception\HttpException | entailment |
protected function parseAbilityAndArguments($ability, $arguments)
{
if (is_string($ability) && (strpos($ability, '\\') === false)) {
return array($ability, $arguments);
}
list(,, $caller) = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
return array($this->normalizeGuessedAbilityName($caller['function']), $ability);
} | Guesses the ability's name if it wasn't provided.
@param mixed $ability
@param mixed|array $arguments
@return array | entailment |
protected function normalizeGuessedAbilityName($ability)
{
$map = $this->resourceAbilityMap();
return isset($map[$ability]) ? $map[$ability] : $ability;
} | Normalize the ability name that has been guessed from the method name.
@param string $ability
@return string | entailment |
protected function createGateUnauthorizedException($ability, $arguments, $message = null, $previousException = null)
{
$message = $message ?: __d('nova', 'This action is unauthorized.');
return new HttpException(403, $message, $previousException);
} | Throw an unauthorized exception based on gate results.
@param string $ability
@param mixed|array $arguments
@param string $message
@param \Exception $previousException
@return \Symfony\Component\HttpKernel\Exception\HttpException | entailment |
public function find($name)
{
if (isset($this->views[$name])) {
return $this->views[$name];
}
if ($this->hasHintInformation($name = trim($name))) {
return $this->views[$name] = $this->findNamedPathView($name);
}
return $this->views[$name] = $this->findInPaths($name, $this->paths);
} | Get the fully qualified location of the view.
@param string $name
@return string | entailment |
protected function findNamedPathView($name)
{
list($namespace, $view) = $this->getNamespaceSegments($name);
$paths = $this->hints[$namespace];
if (Str::endsWith($path = head($this->paths), DS .'Overrides')) {
$path = $path .DS .'Packages' .DS .$namespace;
if (! in_array($path, $paths) && $this->files->isDirectory($path)) {
array_unshift($paths, $path);
}
}
return $this->findInPaths($view, $paths);
} | Get the path to a template with a named path.
@param string $name
@return string | entailment |
protected function getNamespaceSegments($name)
{
$segments = explode(static::HINT_PATH_DELIMITER, $name);
if (count($segments) != 2) {
throw new \InvalidArgumentException("View [$name] has an invalid name.");
}
if ( ! isset($this->hints[$segments[0]])) {
throw new \InvalidArgumentException("No hint path defined for [{$segments[0]}].");
}
return $segments;
} | Get the segments of a template with a named path.
@param string $name
@return array
@throws \InvalidArgumentException | entailment |
protected function findInPaths($name, array $paths)
{
foreach ($paths as $path) {
foreach ($this->getPossibleViewFiles($name) as $fileName) {
$viewPath = $path .DS .$fileName;
if ($this->files->exists($viewPath)) {
return $viewPath;
}
}
}
throw new \InvalidArgumentException("View [$name] not found.");
} | Find the given view in the list of paths.
@param string $name
@param array $paths
@return string
@throws \InvalidArgumentException | entailment |
public function overridesFrom($namespace)
{
if (! isset($this->hints[$namespace])) {
return;
}
$paths = $this->hints[$namespace];
// The folder of Views Override should be located in the same directory with the Views one.
// For example: <BASEPATH>/themes/Bootstrap/Views -> <BASEPATH>/themes/Bootstrap/Override
$path = dirname(head($paths)) .DS .'Overrides';
if (! in_array($path, $this->paths) && $this->files->isDirectory($path)) {
// If there was previously added another Views overriding path, we will remove it.
if (Str::endsWith(head($this->paths), DS .'Overrides')) {
array_shift($this->paths);
}
array_unshift($this->paths, $path);
}
} | Prepend a path specified by its namespace.
@param string $namespace
@return void | entailment |
public function call(Job $job, array $data)
{
$command = $this->setJobInstanceIfNecessary(
$job, unserialize($data['command'])
);
$this->dispatcher->dispatchNow(
$command, $handler = $this->resolveHandler($job, $command)
);
if (! $job->isDeleted()) {
$job->delete();
}
} | Handle the queued job.
@param \Nova\Queue\Job $job
@param array $data
@return void | entailment |
public function failed(array $data)
{
$command = unserialize($data['command']);
if (method_exists($command, 'failed')) {
$command->failed($e);
}
} | Call the failed method on the job instance.
@param array $data
@return void | entailment |
public function pop($queue = null)
{
$queue = $this->getQueue($queue);
$job = $this->pheanstalk->watchOnly($queue)->reserve(0);
if ($job instanceof Pheanstalk_Job) {
return new BeanstalkdJob($this->container, $this->pheanstalk, $job, $queue);
}
} | Pop the next job off of the queue.
@param string $queue
@return \Nova\Queue\Jobs\Job|null | entailment |
public function deleteMessage($queue, $id)
{
$this->pheanstalk->useTube($this->getQueue($queue))->delete($id);
} | Delete a message from the Beanstalk queue.
@param string $queue
@param string $id
@return void | entailment |
public static function make($app)
{
$app->boot();
$console = with($console = new static('Nova Framework', $app::VERSION))
->setContainer($app)
->setAutoExit(false);
$app->instance('forge', $console);
return $console;
} | Create a new Console application.
@param \Nova\Foundation\Application $app
@return \Nova\Console\Application | entailment |
public function boot()
{
$path = $this->container['path'] .DS .'Console' .DS .'Bootstrap.php';
if (is_readable($path)) require $path;
// If the event dispatcher is set on the application, we will fire an event
// with the Nova instance to provide each listener the opportunity to
// register their commands on this application before it gets started.
if (isset($this->container['events'])) {
$events = $this->container['events'];
$events->dispatch('forge.start', array($this));
}
return $this;
} | Boot the Console application.
@return $this | entailment |
public function handle($input, $output = null)
{
try {
return $this->run($input, $output);
}
catch (Exception $e) {
$this->manageException($output, $e);
return 1;
}
catch (Throwable $e) {
$this->manageException($output, new FatalThrowableError($e));
return 1;
}
} | Run the console application.
@param \Symfony\Component\Console\Input\InputInterface $input
@param \Symfony\Component\Console\Output\OutputInterface $output
@return int | entailment |
protected function manageException(OutputInterface $output, Exception $e)
{
$handler = $this->getExceptionHandler();
$handler->report($e);
$handler->renderForConsole($output, $e);
} | Report and render the given exception.
@param \Symfony\Component\Console\Output\OutputInterface $output
@param \Exception $e
@return void | entailment |
public function call($command, array $parameters = array(), OutputInterface $output = null)
{
$parameters['command'] = $command;
// Unless an output interface implementation was specifically passed to us we
// will use the "NullOutput" implementation by default to keep any writing
// suppressed so it doesn't leak out to the browser or any other source.
$output = $output ?: new NullOutput;
$input = new ArrayInput($parameters);
return $this->find($command)->run($input, $output);
} | Run an Nova console command by name.
@param string $command
@param array $parameters
@param \Symfony\Component\Console\Output\OutputInterface $output
@return void | entailment |
public function add(SymfonyCommand $command)
{
if ($command instanceof Command) {
$command->setContainer($this->container);
}
return $this->addToParent($command);
} | Add a command to the console.
@param \Symfony\Component\Console\Command\Command $command
@return \Symfony\Component\Console\Command\Command | entailment |
Subsets and Splits