sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function register() { $this->registerManager(); $this->registerWorker(); $this->registerListener(); $this->registerSubscriber(); $this->registerFailedJobServices(); $this->registerQueueClosure(); }
Register the service provider. @return void
entailment
protected function registerManager() { $this->app->bindShared('queue', function($app) { // Once we have an instance of the queue manager, we will register the various // resolvers for the queue connectors. These connectors are responsible for // creating the classes that accept queue configs and instantiate queues. $manager = new QueueManager($app); $this->registerConnectors($manager); return $manager; }); $this->app->singleton('queue.connection', function ($app) { return $app['queue']->connection(); }); }
Register the queue manager. @return void
entailment
protected function registerRedisConnector($manager) { $app = $this->app; $manager->addConnector('redis', function() use ($app) { return new RedisConnector($app['redis']); }); }
Register the Redis queue connector. @param \Nova\Queue\QueueManager $manager @return void
entailment
protected function registerIronConnector($manager) { $app = $this->app; $manager->addConnector('iron', function() use ($app) { return new IronConnector($app['encrypter'], $app['request']); }); $this->registerIronRequestBinder(); }
Register the IronMQ queue connector. @param \Nova\Queue\QueueManager $manager @return void
entailment
protected function registerFailedJobServices() { $this->app->bindShared('queue.failer', function($app) { $config = $app['config']['queue.failed']; if (isset($config['table'])) { return new DatabaseFailedJobProvider($app['db'], $config['database'], $config['table']); } else { return new NullFailedJobProvider(); } }); }
Register the failed job services. @return void
entailment
public function register() { $this->app->singleton('command.controller.make', function($app) { return new ControllerMakeCommand($app['files']); }); $this->app->singleton('command.middleware.make', function($app) { return new MiddlewareMakeCommand($app['files']); }); $this->app->singleton('command.route.list', function ($app) { return new RouteListCommand($app['router']); }); $this->commands('command.controller.make', 'command.middleware.make', 'command.route.list'); }
Register the service provider. @return void
entailment
public function url($page) { $paginator = $this->getPaginator(); // $pageName = $paginator->getPageName(); $query = array_merge( $paginator->getQuery(), array($pageName => $page) ); return $this->buildUrl( $paginator->getPath(), $query, $paginator->fragment() ); }
Resolve the URL for a given page number. @param int $page @return string
entailment
protected function buildUrl($path, array $query, $fragment) { if (! empty($query)) { $separator = Str::contains($path, '?') ? '&' : '?'; $path .= $separator .http_build_query($query, '', '&'); } if (! empty($fragment)) { $path .= '#' .$fragment; } return $path; }
Build the full query portion of a URL. @param string $path @param array $query @param string|null $fragment @return string
entailment
public function call(Job $job, array $data) { $handler = $this->setJobInstanceIfNecessary( $job, $this->container->make($data['class']) ); call_user_func_array( array($handler, $data['method']), unserialize($data['data']) ); if (! $job->isDeletedOrReleased()) { $job->delete(); } }
Handle the queued job. @param \Nova\Queue\Job $job @param array $data @return void
entailment
public function failed(array $data) { $handler = $this->container->make($data['class']); if (method_exists($handler, 'failed')) { call_user_func_array(array($handler, 'failed'), unserialize($data['data'])); } }
Call the failed method on the job instance. @param array $data @return void
entailment
public function load(ObjectManager $manager) { $category = new Category(); $category->setHeadline('Subscription'); $category->setIsActive(true); $category->setRank(0); $manager->persist($category); $this->addReference('category-subscription', $category); $category = new Category(); $category->setHeadline('Website'); $category->setIsActive(true); $category->setRank(1); $manager->persist($category); $this->addReference('category-website', $category); $manager->flush(); }
{@inheritDoc}
entailment
protected function createFileDriver() { $path = $this->app['config']['cache.path']; return $this->repository(new FileStore($this->app['files'], $path)); }
Create an instance of the file cache driver. @return \Nova\Cache\FileStore
entailment
protected function createMemcachedDriver() { $servers = $this->app['config']['cache.memcached']; $memcached = $this->app['memcached.connector']->connect($servers); return $this->repository(new MemcachedStore($memcached, $this->getPrefix())); }
Create an instance of the Memcached cache driver. @return \Nova\Cache\MemcachedStore
entailment
protected function createRedisDriver() { $redis = $this->app['redis']; return $this->repository(new RedisStore($redis, $this->getPrefix())); }
Create an instance of the Redis cache driver. @return \Nova\Cache\RedisStore
entailment
protected function createDatabaseDriver() { $connection = $this->getDatabaseConnection(); $encrypter = $this->app['encrypter']; // We allow the developer to specify which connection and table should be used // to store the cached items. We also need to grab a prefix in case a table // is being used by multiple applications although this is very unlikely. $table = $this->app['config']['cache.table']; $prefix = $this->getPrefix(); return $this->repository(new DatabaseStore($connection, $encrypter, $table, $prefix)); }
Create an instance of the database cache driver. @return \Nova\Cache\DatabaseStore
entailment
public function start() { $this->loadSession(); if (! $this->has('_token')) $this->regenerateToken(); return $this->started = true; }
{@inheritdoc}
entailment
protected function loadSession() { $this->attributes = $this->readFromHandler(); foreach (array_merge($this->bags, array($this->metaBag)) as $bag) { $this->initializeLocalBag($bag); $bag->initialize($this->bagData[$bag->getStorageKey()]); } }
Load the session data from the handler. @return void
entailment
protected function readFromHandler() { $data = $this->handler->read($this->getId()); return $data ? unserialize($data) : array(); }
Read the session data from the handler. @return array
entailment
protected function initializeLocalBag($bag) { $this->bagData[$bag->getStorageKey()] = $this->pull($bag->getStorageKey(), array()); }
Initialize a bag in storage if it doesn't exist. @param \Symfony\Component\HttpFoundation\Session\SessionBagInterface $bag @return void
entailment
public function setId($id) { if (! $this->isValidId($id)) { $id = $this->generateSessionId(); } $this->id = $id; }
{@inheritdoc}
entailment
protected function addBagDataToSession() { $bags = array_merge($this->bags, array($this->metaBag)); foreach ($bags as $bag) { $name = $bag->getStorageKey(); $this->put($name, $this->getBagData($name)); } }
Merge all of the bag data into the session. @return void
entailment
public function ageFlashData() { foreach ($this->get('flash.old', array()) as $old) { $this->forget($old); } $this->put('flash.old', $this->get('flash.new', array())); $this->put('flash.new', array()); }
Age the flash data for the session. @return void
entailment
public function getOldInput($key = null, $default = null) { $input = $this->get('_old_input', array()); // Input that is flashed to the session can be easily retrieved by the // developer, making repopulating old forms and the like much more // convenient, since the request's previous input is available. return array_get($input, $key, $default); }
Get the requested item from the flashed input array. @param string $key @param mixed $default @return mixed
entailment
public function replace(array $attributes) { foreach ($attributes as $key => $value) { $this->put($key, $value); } }
{@inheritdoc}
entailment
public function setX($x) { $this->x = MathUtil::capValue($x, 0, XyzColorInterface::REF_X); return $this; }
@param int $x @return $this
entailment
public function setY($y) { $this->y = MathUtil::capValue($y, 0, XyzColorInterface::REF_Y); return $this; }
@param int $y @return $this
entailment
public function setZ($z) { $this->z = MathUtil::capValue($z, 0, XyzColorInterface::REF_Z); return $this; }
@param int $z @return $this
entailment
protected function compileUpdateJoinWheres(Builder $query) { $joinWheres = array(); foreach ($query->joins as $join) { foreach ($join->clauses as $clause) { $joinWheres[] = $this->compileJoinConstraint($clause); } } return implode(' ', $joinWheres); }
Compile the "join" clauses for an update. @param \Nova\Database\Query\Builder $query @return string
entailment
public function apply(Builder $builder) { $model = $builder->getModel(); $builder->whereNull($model->getQualifiedDeletedAtColumn()); $this->extend($builder); }
Apply the scope to a given ORM query builder. @param \Nova\Database\ORM\Builder $builder @return void
entailment
public function remove(Builder $builder) { $column = $builder->getModel()->getQualifiedDeletedAtColumn(); $query = $builder->getQuery(); foreach ((array) $query->wheres as $key => $where) { if ($this->isSoftDeleteConstraint($where, $column)) { unset($query->wheres[$key]); $query->wheres = array_values($query->wheres); } } }
Remove the scope from the given ORM query builder. @param \Nova\Database\ORM\Builder $builder @return void
entailment
public function extend(Builder $builder) { foreach ($this->extensions as $extension) { $this->{"add{$extension}"}($builder); } $builder->onDelete(function(Builder $builder) { $column = $this->getDeletedAtColumn($builder); return $builder->update(array( $column => $builder->getModel()->freshTimestampString() )); }); }
Extend the query builder with the needed functions. @param \Nova\Database\ORM\Builder $builder @return void
entailment
protected function addForceDelete(Builder $builder) { $builder->macro('forceDelete', function(Builder $builder) { return $builder->getQuery()->delete(); }); }
Add the force delete extension to the builder. @param \Nova\Database\ORM\Builder $builder @return void
entailment
protected function addRestore(Builder $builder) { $builder->macro('restore', function(Builder $builder) { $builder->withTrashed(); return $builder->update(array($builder->getModel()->getDeletedAtColumn() => null)); }); }
Add the restore extension to the builder. @param \Nova\Database\ORM\Builder $builder @return void
entailment
public static function build(Configuration $configuration = null): DIContainer { if ($configuration === null) { $configuration = new Configuration(); } $defaultDefinitions = \array_merge( require __DIR__ . '/definitions.php', [Configuration::class => $configuration] ); $customDefinitions = self::parseDefinitions($configuration->getDefinitions()); return self::getContainerBuilder($configuration) ->addDefinitions($defaultDefinitions, ...$customDefinitions) ->build(); }
Build PHP-DI container. @param Configuration|null $configuration @throws \RuntimeException @return DIContainer
entailment
private static function getContainerBuilder(Configuration $configuration): DIContainerBuilder { $containerBuilder = new DIContainerBuilder($configuration->getContainerClass()); $containerBuilder->useAutowiring($configuration->doesUseAutowiring()); $containerBuilder->useAnnotations($configuration->doesUseAnnotations()); $containerBuilder->ignorePhpDocErrors($configuration->doesIgnorePhpDocErrors()); if ($configuration->doesUseDefinitionCache()) { $containerBuilder->enableDefinitionCache(); } if ($configuration->getWrapContainer() !== null) { $containerBuilder->wrapContainer($configuration->getWrapContainer()); } if ($configuration->getProxiesPath() !== null) { $containerBuilder->writeProxiesToFile(true, $configuration->getProxiesPath()); } if (!empty($configuration->getCompilationPath())) { $containerBuilder->enableCompilation( $configuration->getCompilationPath(), 'CompiledContainer', $configuration->getCompiledContainerClass() ); } return $containerBuilder; }
Get configured container builder. @param Configuration $configuration @return DIContainerBuilder
entailment
private static function parseDefinitions(array $definitions): array { if (\count($definitions) === 0) { return $definitions; } return \array_map( function ($definition) { if (\is_array($definition)) { return $definition; } return self::loadDefinitionsFromPath($definition); }, $definitions ); }
Parse definitions. @param array $definitions @throws \RuntimeException @return array
entailment
private static function loadDefinitionsFromPath(string $path): array { if (!\file_exists($path)) { throw new \RuntimeException(\sprintf('Path "%s" does not exist', $path)); } if (!\is_dir($path)) { return self::loadDefinitionsFromFile($path); } $definitions = []; foreach (\glob($path . '/*.php', \GLOB_ERR) as $file) { if (\is_file($file)) { $definitions[] = self::loadDefinitionsFromFile($file); } } return \count($definitions) === 0 ? [] : \array_merge(...$definitions); }
Load definitions from path. @param string $path @throws \RuntimeException @return array
entailment
private static function loadDefinitionsFromFile(string $file): array { if (!\is_file($file) || !\is_readable($file)) { // @codeCoverageIgnoreStart throw new \RuntimeException(\sprintf('"%s" must be a readable file', $file)); // @codeCoverageIgnoreEnd } $definitions = require $file; if (!\is_array($definitions)) { throw new \RuntimeException( \sprintf('Definitions file should return an array. "%s" returned', \gettype($definitions)) ); } return $definitions; }
Load definitions from file. @param string $file @throws \RuntimeException @return array
entailment
public function matches(Route $route, Request $request) { $regex = $route->getCompiled()->getHostRegex(); if (is_null($regex)) return true; return preg_match($regex, $request->getHost()); }
Validate a given rule against a route and request. @param \Nova\Routing\Route $route @param \Nova\Http\Request $request @return bool
entailment
public function setContent($content) { $this->original = $content; // If the content is "JSONable" we will set the appropriate header and convert // the content to JSON. This is useful when returning something like models // from routes that will be automatically transformed to their JSON form. if ($this->shouldBeJson($content)) { $this->headers->set('Content-Type', 'application/json'); $content = $this->morphToJson($content); } // If this content implements the "RenderableInterface", then we will call the // render method on the object so we will avoid any "__toString" exceptions // that might be thrown and have their errors obscured by PHP's handling. else if ($content instanceof RenderableInterface) { $content = $content->render(); } return parent::setContent($content); }
Set the content on the response. @param mixed $content @return $this
entailment
protected function createCookieDriver() { $lifetime = $this->app['config']['session.lifetime']; return $this->buildSession(new CookieSessionHandler($this->app['cookie'], $lifetime)); }
Create an instance of the "cookie" session driver. @return \Nova\Session\Store
entailment
protected function createCacheHandler($driver) { $minutes = $this->app['config']['session.lifetime']; return new CacheBasedSessionHandler($this->app['cache']->driver($driver), $minutes); }
Create the cache based session handler instance. @param string $driver @return \Nova\Session\CacheBasedSessionHandler
entailment
public function dumpAutoloads($extra = '') { $command = $this->findComposer() .' dump-autoload'; if (! empty($extra)) { $command = trim($command .' ' .$extra); } $process = $this->getProcess(); $process->setCommandLine($command); $process->run(); }
Regenerate the Composer autoloader files. @param string $extra @return void
entailment
protected function findComposer() { $composerPhar = $this->workingPath .DS .'composer.phar'; if ($this->files->exists($composerPhar)) { $executable = with(new PhpExecutableFinder)->find(false); return ProcessUtils::escapeArgument($executable) .' ' .$composerPhar; } return 'composer'; }
Get the composer command for the environment. @return string
entailment
public function load($environment = null) { foreach ($this->loader->load($environment) as $key => $value) { $_ENV[$key] = $value; $_SERVER[$key] = $value; putenv("{$key}={$value}"); } }
Load the server variables for a given environment. @param string $environment
entailment
protected function replaceClass($stub, $name) { $stub = parent::replaceClass($stub, $name); return str_replace('{{command}}', $this->option('command'), $stub); }
Replace the class name for the given stub. @param string $stub @param string $name @return string
entailment
public function save(Model $model) { $model->setAttribute($this->getPlainMorphType(), $this->morphClass); return parent::save($model); }
Attach a model instance to the parent model. @param \Nova\Database\ORM\Model $model @return \Nova\Database\ORM\Model
entailment
public function create(array $attributes) { $instance = $this->related->newInstance($attributes); $this->setForeignAttributesForCreate($instance); $instance->save(); return $instance; }
Create a new instance of the related model. @param array $attributes @return \Nova\Database\ORM\Model
entailment
protected function setForeignAttributesForCreate(Model $model) { $property = $this->getPlainForeignKey(); $model->{$property} = $this->getParentKey(); // $property = $this->getPlainMorphType(); $model->{$property} = $this->morphClass; }
Set the foreign ID and type for creating a related model. @param \Nova\Database\ORM\Model $model @return void
entailment
public function release($delay = 0) { $priority = Pheanstalk::DEFAULT_PRIORITY; $this->pheanstalk->release($this->job, $priority, $delay); }
Release the job back into the queue. @param int $delay @return void
entailment
public function package($package, $namespace = null, $path = null) { $namespace = $this->getPackageNamespace($package, $namespace); // $files = $this->app['files']; // In this method we will register the configuration package for the package // so that the configuration options cleanly cascade into the application // folder to make the developers lives much easier in maintaining them. $path = $path ?: $this->guessPackagePath(); // Register the Package Config path. $config = $path .DS .'Config'; if ($files->isDirectory($config)) { $this->app['config']->package($package, $config, $namespace); } // Register the Package Language path. $language = $path .DS .'Language'; if ($files->isDirectory($language)) { $this->app['language']->package($package, $language, $namespace); } // Register the Package Views path. $views = $this->app['view']; $appView = $this->getAppViewPath($package); if ($files->isDirectory($appView)) { $views->addNamespace($package, $appView); } $viewPath = $path .DS .'Views'; if ($files->isDirectory($viewPath)) { $views->addNamespace($package, $viewPath); } // Finally, register the Package Assets path. $this->registerPackageAssets($package, $namespace, $path); }
Register the package's component namespaces. @param string $package @param string $namespace @param string $path @return void
entailment
protected function registerPackageAssets($package, $namespace, $path) { $assets = dirname($path) .DS .'assets'; if ($this->app['files']->isDirectory($assets)) { list ($vendor) = explode('/', $package); $namespace = Str::snake($vendor, '-') .'/' .str_replace('_', '-', $namespace); $this->app['assets.dispatcher']->package($package, $assets, $namespace); } }
Register the package's assets. @param string $package @param string $namespace @param string $path @return void
entailment
public function guessPackagePath() { $reflection = new ReflectionClass($this); $path = $reflection->getFileName(); return realpath(dirname($path) .'/../'); }
Guess the package path for the provider. @return string
entailment
protected function publishes(array $paths, $group) { if (! array_key_exists($group, static::$publishes)) { static::$publishes[$group] = array(); } static::$publishes[$group] = array_merge(static::$publishes[$group], $paths); }
Register paths to be published by the publish command. @param array $paths @param string $group @return void
entailment
public static function pathsToPublish($group = null) { if (is_null($group)) { $paths = array(); foreach (static::$publishes as $class => $publish) { $paths = array_merge($paths, $publish); } return array_unique($paths); } else if (array_key_exists($group, static::$publishes)) { return static::$publishes[$group]; } return array(); }
Get the paths to publish. @param string|null $group @return array
entailment
public function hasItems() { if (count($this->data[1]) === 0) { return; } foreach ($this->data[1] as $key => $value) { $this->failIf( !$this->itemExists( array($this->data[0], array($key => $value)) ) ); } }
Assert an array has all key and value items. @syntax array ?:array has items ?:array
entailment
public function hasKey() { $this->failIf(!array_key_exists($this->data[1], $this->data[0])); return $this->data[0][$this->data[1]]; }
Assert an array has key, returns value. @syntax array ?:array has key ?:int,string @throws DidNotMatchException @return mixed
entailment
public function hasValues() { $keys = array_values($this->data[0]); foreach ($this->data[1] as $key) { $this->failIf((!in_array($key, $keys))); } }
Assert an array has several values in any order. @syntax array ?:array has values ?:array
entailment
public function send($notifiables, $notification) { $notifiables = $this->formatNotifiables($notifiables); if (! $notification instanceof ShouldQueueInterface) { return $this->sendNow($notifiables, $notification); } foreach ($notifiables as $notifiable) { $notificationId = Uuid::uuid4()->toString(); foreach ($notification->via($notifiable) as $channel) { $this->queueToNotifiable($notifiable, $notificationId, clone $notification, $channel); } } }
Send the given notification to the given notifiable entities. @param \Nova\Support\Collection|array|mixed $notifiables @param mixed $notification @return void
entailment
public function sendNow($notifiables, $notification, array $channels = null) { $notifiables = $this->formatNotifiables($notifiables); $original = clone $notification; foreach ($notifiables as $notifiable) { if (empty($viaChannels = $channels ?: $notification->via($notifiable))) { continue; } $notificationId = Uuid::uuid4()->toString(); foreach ((array) $viaChannels as $channel) { $this->sendToNotifiable($notifiable, $notificationId, clone $original, $channel); } } }
Send the given notification to the given notifiable entities. @param \Nova\Support\Collection|array|mixed $notifiables @param mixed $notification @param array|null $channels @return void
entailment
protected function shouldSendNotification($notifiable, $notification, $channel) { $result = $this->events->until( new NotificationSending($notifiable, $notification, $channel) ); return ($result !== false); }
Determines if the notification can be sent. @param mixed $notifiable @param mixed $notification @param string $channel @return bool
entailment
protected function queueToNotifiable($notifiable, $id, $notification, $channel) { $notification->id = $id; $job = with(new SendQueuedNotifications($notifiable, $notification, array($channel))) ->onConnection($notification->connection) ->onQueue($notification->queue) ->delay($notification->delay); $this->bus->dispatch($job); }
Queue the given notification to the given notifiable via a channel. @param mixed $notifiable @param string $id @param mixed $notification @param string $channel @return void
entailment
protected function formatNotifiables($notifiables) { if ((! $notifiables instanceof Collection) && ! is_array($notifiables)) { $items = array($notifiables); if ($notifiables instanceof Model) { return new ModelCollection($items); } return $items; } return $notifiables; }
Format the notifiables into a Collection / array if necessary. @param mixed $notifiables @return ModelCollection|array
entailment
public function between() { $this->failIf($this->data[0] < $this->data[1]); $this->failIf($this->data[0] > $this->data[2]); return $this->data[0]; }
A number must be between two values (inclusive), returns value. @return mixed @throws DidNotMatchException @syntax ?:number is between ?:number and ?:number
entailment
public function notBetween() { $this->failIf( $this->data[0] >= $this->data[1] && $this->data[0] <= $this->data[2] ); }
A number must not be between two values (inclusive). @syntax ?:number is not between ?:number and ?:number @return bool
entailment
public function read($sessionId) { $cookie = $this->getSessionCookie($sessionId); return $this->request->cookies->get($cookie) ?: ''; }
{@inheritDoc}
entailment
public function write($sessionId, $data) { $cookie = $this->getSessionCookie($sessionId); $this->cookies->queue($cookie, $data, $this->minutes); }
{@inheritDoc}
entailment
public function destroy($sessionId) { $cookie = $this->getSessionCookie($sessionId); $this->cookies->queue($this->cookies->forget($cookie)); }
{@inheritDoc}
entailment
public function increment($key, $value = 1) { $this->store->increment($this->taggedItemKey($key), $value); }
Increment the value of an item in the cache. @param string $key @param mixed $value @return void
entailment
public function decrement($key, $value = 1) { $this->store->decrement($this->taggedItemKey($key), $value); }
Increment the value of an item in the cache. @param string $key @param mixed $value @return void
entailment
public function forever($key, $value) { $this->store->forever($this->taggedItemKey($key), $value); }
Store an item in the cache indefinitely. @param string $key @param mixed $value @return void
entailment
public function daemon($connection, $queue, $delay = 0, $memory = 128, $sleep = 3, $maxTries = 0) { $lastRestart = $this->getTimestampOfLastQueueRestart(); while (true) { if (! $this->daemonShouldRun($connection, $queue)) { $this->sleep($sleep); } else { $this->runNextJob($connection, $queue, $delay, $sleep, $maxTries); } if ($this->daemonShouldQuit()) { $this->kill(); } // Check if the daemon should be stopped. else if ($this->memoryExceeded($memory) || $this->queueShouldRestart($lastRestart)) { $this->stop(); } } }
Listen to the given queue in a loop. @param string $connection @param string $queue @param int $delay @param int $memory @param int $sleep @param int $maxTries @return array
entailment
protected function daemonShouldRun($connection, $queue) { if ($this->manager->isDownForMaintenance()) { return false; } $result = $this->events->until('nova.queue.looping', array($connection, $queue)); return ($result !== false); }
Determine if the daemon should process on this iteration. @param string $connection @param string $queue @return bool
entailment
public function runNextJob($connection, $queue = null, $delay = 0, $sleep = 3, $maxTries = 0) { $job = $this->getNextJob( $this->manager->connection($connection), $queue ); // If we're able to pull a job off of the stack, we will process it and // then immediately return back out. If there is no job on the queue // we will "sleep" the worker for the specified number of seconds. if (! is_null($job)) { return $this->runJob($job, $connection, $maxTries, $delay); } $this->sleep($sleep); return array('job' => null, 'failed' => false); }
Listen to the given queue. @param string $connection @param string $queue @param int $delay @param int $sleep @param int $maxTries @return array
entailment
protected function getNextJob($connection, $queue) { try { if (is_null($queue)) { return $connection->pop(); } foreach (explode(',', $queue) as $queue) { if (! is_null($job = $connection->pop($queue))) { return $job; } } } catch (Exception $e) { $this->handleException($e); } catch (Throwable $e) { $this->handleException(new FatalThrowableError($e)); } }
Get the next job from the queue connection. @param \Nova\Queue\Queue $connection @param string $queue @return \Nova\Queue\Job|null
entailment
protected function runJob($job, $connection, $maxTries, $delay) { try { return $this->process($connection, $job, $maxTries, $delay); } catch (Exception $e) { $this->handleException($e); } catch (Throwable $e) { $this->handleException(new FatalThrowableError($e)); } }
Process the given job. @param \Illuminate\Contracts\Queue\Job $job @param string $connection @param \Illuminate\Queue\WorkerOptions $options @return void
entailment
protected function handleException($e) { if (isset($this->exceptions)) { $this->exceptions->report($e); } if ($this->causedByLostConnection($e)) { $this->shouldQuit = true; } }
Handle an exception that occurred while handling a job. @param \Exception $e @return void
entailment
public function process($connection, Job $job, $maxTries = 0, $delay = 0) { if (($maxTries > 0) && ($job->attempts() > $maxTries)) { return $this->logFailedJob($connection, $job); } // First we will raise the before job event and fire off the job. Once it is done // we will see if it will be auto-deleted after processing and if so we will go // ahead and run the delete method on the job. Otherwise we will just keep moving. try { $this->raiseBeforeJobEvent($connection, $job); $job->handle(); if ($job->autoDelete()) { $job->delete(); } $this->raiseAfterJobEvent($connection, $job); return array('job' => $job, 'failed' => false); } // If we catch an exception, we will attempt to release the job back onto // the queue so it is not lost. This will let is be retried at a later // time by another listener (or the same one). We will do that here. catch (Exception $e) { if (! $job->isDeleted()) { $job->release($delay); } throw $e; } catch (Throwable $e) { if (! $job->isDeleted()) { $job->release($delay); } throw $e; } }
Process a given job from the queue. @param string $connection @param \Nova\Queue\Job $job @param int $maxTries @param int $delay @return void @throws \Exception
entailment
protected function raiseBeforeJobEvent($connection, Job $job) { if (isset($this->events)) { $this->events->dispatch('nova.queue.processing', array($connection, $job)); } }
Raise the before queue job event. @param string $connection @param \Nova\Queue\Job $job @return void
entailment
protected function raiseAfterJobEvent($connection, Job $job) { if (isset($this->events)) { $this->events->dispatch('nova.queue.processed', array($connection, $job)); } }
Raise the after queue job event. @param string $connection @param \Nova\Queue\Job $job @return void
entailment
protected function raiseFailedJobEvent($connection, Job $job) { if (isset($this->events)) { $this->events->dispatch('nova.queue.failed', array($connection, $job)); } }
Raise the failed queue job event. @param string $connection @param \Nova\Queue\Job $job @return void
entailment
public static function setSerializeHandler() { $formats = [ 'php_serialize', 'php', 'php_binary', ]; // First, try php_serialize since that's the only one that doesn't suck in some way. \Wikimedia\suppressWarnings(); ini_set( 'session.serialize_handler', 'php_serialize' ); \Wikimedia\restoreWarnings(); if ( ini_get( 'session.serialize_handler' ) === 'php_serialize' ) { return 'php_serialize'; } // Next, just use the current format if it's supported. $format = ini_get( 'session.serialize_handler' ); if ( in_array( $format, $formats, true ) ) { return $format; } // Last chance, see if any of our supported formats are accepted. foreach ( $formats as $format ) { \Wikimedia\suppressWarnings(); ini_set( 'session.serialize_handler', $format ); \Wikimedia\restoreWarnings(); if ( ini_get( 'session.serialize_handler' ) === $format ) { return $format; } } throw new \DomainException( 'Failed to set serialize handler to a supported format.' . ' Supported formats are: ' . implode( ', ', $formats ) . '.' ); }
Try to set session.serialize_handler to a supported format This may change the format even if the current format is also supported. @return string Format set @throws \\DomainException
entailment
public static function encode( array $data ) { $format = ini_get( 'session.serialize_handler' ); if ( !is_string( $format ) ) { throw new \UnexpectedValueException( 'Could not fetch the value of session.serialize_handler' ); } switch ( $format ) { case 'php': return self::encodePhp( $data ); case 'php_binary': return self::encodePhpBinary( $data ); case 'php_serialize': return self::encodePhpSerialize( $data ); default: throw new \DomainException( "Unsupported format \"$format\"" ); } }
Encode a session array to a string, using the format in session.serialize_handler @param array $data Session data @return string|null Encoded string, or null on failure @throws \\DomainException
entailment
public static function decode( $data ) { if ( !is_string( $data ) ) { throw new \InvalidArgumentException( '$data must be a string' ); } $format = ini_get( 'session.serialize_handler' ); if ( !is_string( $format ) ) { throw new \UnexpectedValueException( 'Could not fetch the value of session.serialize_handler' ); } switch ( $format ) { case 'php': return self::decodePhp( $data ); case 'php_binary': return self::decodePhpBinary( $data ); case 'php_serialize': return self::decodePhpSerialize( $data ); default: throw new \DomainException( "Unsupported format \"$format\"" ); } }
Decode a session string to an array, using the format in session.serialize_handler @param string $data Session data. Use the same caution in passing user-controlled data here that you would to PHP's unserialize function. @return array|null Data, or null on failure @throws \\DomainException @throws \\InvalidArgumentException
entailment
private static function serializeValue( $value ) { try { return serialize( $value ); } catch ( \Exception $ex ) { self::$logger->error( 'Value serialization failed: ' . $ex->getMessage() ); return null; } }
Serialize a value with error logging @param mixed $value @return string|null
entailment
private static function unserializeValue( &$string ) { $error = null; set_error_handler( function ( $errno, $errstr ) use ( &$error ) { $error = $errstr; return true; } ); $ret = unserialize( $string ); restore_error_handler(); if ( $error !== null ) { self::$logger->error( 'Value unserialization failed: ' . $error ); return [ false, null ]; } $serialized = serialize( $ret ); $l = strlen( $serialized ); if ( substr( $string, 0, $l ) !== $serialized ) { self::$logger->error( 'Value unserialization failed: read value does not match original string' ); return [ false, null ]; } $string = substr( $string, $l ); return [ true, $ret ]; }
Unserialize a value with error logging @param string &$string On success, the portion used is removed @return array ( bool $success, mixed $value )
entailment
public static function encodePhp( array $data ) { $ret = ''; foreach ( $data as $key => $value ) { if ( strcmp( $key, intval( $key ) ) === 0 ) { self::$logger->warning( "Ignoring unsupported integer key \"$key\"" ); continue; } if ( strcspn( $key, '|!' ) !== strlen( $key ) ) { self::$logger->error( "Serialization failed: Key with unsupported characters \"$key\"" ); return null; } $v = self::serializeValue( $value ); if ( $v === null ) { return null; } $ret .= "$key|$v"; } return $ret; }
Encode a session array to a string in 'php' format @note Generally you'll use self::encode() instead of this method. @param array $data Session data @return string|null Encoded string, or null on failure
entailment
public static function decodePhp( $data ) { if ( !is_string( $data ) ) { throw new \InvalidArgumentException( '$data must be a string' ); } $ret = []; while ( $data !== '' && $data !== false ) { $i = strpos( $data, '|' ); if ( $i === false ) { if ( substr( $data, -1 ) !== '!' ) { self::$logger->warning( 'Ignoring garbage at end of string' ); } break; } $key = substr( $data, 0, $i ); $data = substr( $data, $i + 1 ); if ( strpos( $key, '!' ) !== false ) { self::$logger->warning( "Decoding found a key with unsupported characters: \"$key\"" ); } if ( $data === '' || $data === false ) { self::$logger->error( 'Unserialize failed: unexpected end of string' ); return null; } list( $ok, $value ) = self::unserializeValue( $data ); if ( !$ok ) { return null; } $ret[$key] = $value; } return $ret; }
Decode a session string in 'php' format to an array @note Generally you'll use self::decode() instead of this method. @param string $data Session data. Use the same caution in passing user-controlled data here that you would to PHP's unserialize function. @return array|null Data, or null on failure @throws \\InvalidArgumentException
entailment
public static function encodePhpBinary( array $data ) { $ret = ''; foreach ( $data as $key => $value ) { if ( strcmp( $key, intval( $key ) ) === 0 ) { self::$logger->warning( "Ignoring unsupported integer key \"$key\"" ); continue; } $l = strlen( $key ); if ( $l > 127 ) { self::$logger->warning( "Ignoring overlong key \"$key\"" ); continue; } $v = self::serializeValue( $value ); if ( $v === null ) { return null; } $ret .= chr( $l ) . $key . $v; } return $ret; }
Encode a session array to a string in 'php_binary' format @note Generally you'll use self::encode() instead of this method. @param array $data Session data @return string|null Encoded string, or null on failure
entailment
public static function decodePhpBinary( $data ) { if ( !is_string( $data ) ) { throw new \InvalidArgumentException( '$data must be a string' ); } $ret = []; while ( $data !== '' && $data !== false ) { $l = ord( $data[0] ); if ( strlen( $data ) < ( $l & 127 ) + 1 ) { self::$logger->error( 'Unserialize failed: unexpected end of string' ); return null; } // "undefined" marker if ( $l > 127 ) { $data = substr( $data, ( $l & 127 ) + 1 ); continue; } $key = substr( $data, 1, $l ); $data = substr( $data, $l + 1 ); if ( $data === '' || $data === false ) { self::$logger->error( 'Unserialize failed: unexpected end of string' ); return null; } list( $ok, $value ) = self::unserializeValue( $data ); if ( !$ok ) { return null; } $ret[$key] = $value; } return $ret; }
Decode a session string in 'php_binary' format to an array @note Generally you'll use self::decode() instead of this method. @param string $data Session data. Use the same caution in passing user-controlled data here that you would to PHP's unserialize function. @return array|null Data, or null on failure @throws \\InvalidArgumentException
entailment
public static function encodePhpSerialize( array $data ) { try { return serialize( $data ); } catch ( \Exception $ex ) { self::$logger->error( 'PHP serialization failed: ' . $ex->getMessage() ); return null; } }
Encode a session array to a string in 'php_serialize' format @note Generally you'll use self::encode() instead of this method. @param array $data Session data @return string|null Encoded string, or null on failure
entailment
public static function decodePhpSerialize( $data ) { if ( !is_string( $data ) ) { throw new \InvalidArgumentException( '$data must be a string' ); } $error = null; set_error_handler( function ( $errno, $errstr ) use ( &$error ) { $error = $errstr; return true; } ); $ret = unserialize( $data ); restore_error_handler(); if ( $error !== null ) { self::$logger->error( 'PHP unserialization failed: ' . $error ); return null; } // PHP strangely allows non-arrays to session_decode(), even though // that breaks $_SESSION. Let's not do that. if ( !is_array( $ret ) ) { self::$logger->error( 'PHP unserialization failed (value was not an array)' ); return null; } return $ret; }
Decode a session string in 'php_serialize' format to an array @note Generally you'll use self::decode() instead of this method. @param string $data Session data. Use the same caution in passing user-controlled data here that you would to PHP's unserialize function. @return array|null Data, or null on failure @throws \\InvalidArgumentException
entailment
public function beforeSpec(Spec $spec) { self::$testCase->setUp(); self::$result->startTest(self::$test); /** @var Closure $closure */ $closure = self::$testCase->getProperty($spec, 'closure'); // This will not be set for incomplete specs. if (!$closure) { return; } $suite = self::$testCase->getProperty($spec, 'suite'); $newSuite = new ProxySuite($spec->getTitle(), $closure, $suite); $reflection = new \ReflectionClass($suite); foreach ($reflection->getProperties() as $property) { $v = self::$testCase->getProperty($suite, $property->getName()); self::$testCase->setProperty($newSuite, $property->getName(), $v); } /** @noinspection PhpUndefinedMethodInspection */ $closure = $closure->bindTo($newSuite); self::$testCase->setProperty($spec, 'closure', $closure); }
Before executing an it() spec it should be setup like a test case. @param Spec $spec
entailment
public function afterSpec(Spec $spec) { $time = 0; if ($spec->isFailed()) { self::$result->addFailure( self::$test, new PHPUnit_Framework_AssertionFailedError( $spec->exception ), $time ); } elseif ($spec->isIncomplete()) { self::$result->addFailure( self::$test, new PHPUnit_Framework_IncompleteTestError( $spec->exception ), $time ); } self::$testCase->tearDown(); self::$result->endTest(self::$test, $time); }
After an it() spec we need to tear down the test case. @param Spec $spec
entailment
public function connect(array $config) { $ironConfig = array('token' => $config['token'], 'project_id' => $config['project']); if (isset($config['host'])) $ironConfig['host'] = $config['host']; $iron = new IronMQ($ironConfig); if (isset($config['ssl_verifypeer'])) { $iron->ssl_verifypeer = $config['ssl_verifypeer']; } return new IronQueue($iron, $this->request, $config['queue'], $config['encrypt']); }
Establish a queue connection. @param array $config @return \Nova\Queue\Contracts\QueueInterface
entailment
public function handle() { $this->info('Generating optimized class loader'); if ($this->option('psr')) { $this->composer->dumpAutoloads(); } else { $this->composer->dumpOptimized(); } $this->call('clear-compiled'); }
Execute the console command. @return void
entailment
public function getPrototype(ReflectionMethod $method) { $modifiers = implode(' ', Reflection::getModifierNames($method->getModifiers())); if ($this->hideAbstract) { $modifiers = str_replace('abstract ', '', $modifiers); } $parameters = array(); foreach ($method->getParameters() as $p) { $param = $this->getTypeHint($p); $param .= $this->getName($p); $param .= $this->getDefaultValue($p); $parameters[] = $param; } return $modifiers . ' function ' . $method->getName() . "(" . implode(', ', $parameters) . ")"; }
Get the prototype for the method. @param ReflectionMethod $method @return string
entailment
protected function setJoin(Builder $query = null) { $query = $query ?: $this->query; $foreignKey = $this->related->getTable().'.'.$this->related->getKeyName(); $localKey = $this->parent->getTable().'.'.$this->secondKey; $query->join($this->parent->getTable(), $localKey, '=', $foreignKey); }
Set the join clause on the query. @param \Nova\Database\ORM\Builder|null $query @return void
entailment
public function addEagerConstraints(array $models) { $table = $this->parent->getTable(); $this->query->whereIn($table .'.' .$this->firstKey, $this->getKeys($models, $this->localKey)); }
Set the constraints for an eager load of the relation. @param array $models @return void
entailment
public function register() { $packages = $this->repository->enabled(); $packages->each(function($properties) { $this->registerServiceProvider($properties); }); }
Register the Package service provider file from all Packages. @return mixed
entailment