sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function saturate($percent) { $color = $this->toHsl(); $saturation = $this->clamp(($color->saturation() + $percent) / 100); return $color->saturation($saturation * 100)->back($this); }
@param int $percent @return mixed
entailment
public function desaturate($percent) { $color = $this->toHsl(); $saturation = $this->clamp(($color->saturation() - $percent) / 100); return $color->saturation($saturation * 100)->back($this); }
@param int $percent @return mixed
entailment
public function brighten($percent) { $percent *= -1; $color = $this->toRgb(); $color->red(max(0, min(255, $color->red() - round(255 * ($percent / 100))))); $color->green(max(0, min(255, $color->green() - round(255 * ($percent / 100))))); $color->blue(max(0, min(255, $color->blue() - round(255 * ($percent / 100))))); return $color->back($this); }
@param int $percent @return mixed
entailment
public function lighten($percent) { $color = $this->toHsl(); $lightness = $this->clamp(($color->lightness() + $percent) / 100); return $color->lightness($lightness * 100)->back($this); }
@param int $percent @return mixed
entailment
public function darken($percent) { $color = $this->toHsl(); $lightness = $this->clamp(($color->lightness() - $percent) / 100); return $color->lightness($lightness * 100)->back($this); }
@param int $percent @return mixed
entailment
public function spin($percent) { $color = $this->toHsl(); $hue = ($color->hue() + $percent) % 360; return $color->hue($hue < 0 ? 360 + $hue : $hue)->back($this); }
@param int $percent @return mixed
entailment
public function mix(BaseColor $color, $percent = 50) { $first = $this->toRgb(); $second = $color->toRgb(); $weight = $percent / 100; $red = $first->red() * (1 - $weight) + $second->red() * $weight; $green = $first->green() * (1 - $weight) + $second->green() * $weight; $blue = $first->blue() * (1 - $weight) + $second->blue() * $weight; return $first->red($red)->green($green)->blue($blue)->back($this); }
@param \OzdemirBurak\Iris\BaseColor $color @param int $percent @return mixed
entailment
public function tint($percent = 50) { $clone = clone $this; $white = $clone->toRgb()->red(255)->green(255)->blue(255); return $this->mix($white, $percent); }
@param int $percent @return mixed
entailment
public function shade($percent = 50) { $clone = clone $this; $black = $clone->toRgb()->red(0)->green(0)->blue(0); return $this->mix($black, $percent); }
@param int $percent @return mixed
entailment
public static function fromArray(array $data, $filter = false){ $class = get_called_class(); $object = new static(); foreach($data as $key => $value){ if(!$filter || property_exists($class, $key)){ $object->$key = $value; } } return $object; }
Create a Struct from an associative array @param array $data associative array array('property'=>data) @param bool $filter (optional) if true, $data array keys which are not defined as properties in the Struct will be ignored @return Struct
entailment
public function reload() { // update application components to the latest version if (file_exists($this->lock_file)) { unlink($this->lock_file); } $this->composer = $this->factory->createComposer($this->getIO()); }
Reload Composer.
entailment
public function getPackageFromConfigFile($config) { if (!file_exists($config)) { throw new \RuntimeException('File "'.$config.'" not found'); } return $this->loader->load((new JsonFile($config))->read(), 'Composer\Package\RootPackage'); }
@throws \RuntimeException @param string $config @return RootPackage
entailment
public static function getVersionCompatible($version) { // {suffix:weight} $suffixes = [ 'dev' => 1, // composer suffix 'patch' => 2, 'alpha' => 3, 'beta' => 4, 'stable' => 5, // is not a real suffix. use it if suffix is not exists 'rc' => 6, ]; $reg = '/^v?(?<version>\d+\.\d+\.\d+)(?:-(?<suffix>dev|patch|alpha|beta|rc)(?<suffix_version>\d+)?)?$/i'; if (!preg_match($reg, $version, $match)) { return false; } // suffix version if (isset($match['suffix'])) { $suffix = $suffixes[strtolower($match['suffix'])].'.'; $suffix .= isset($match['suffix_version']) ? (int) $match['suffix_version'] : 1; } else { $suffix = $suffixes['stable'].'.0'; } return $match['version'].'.'.$suffix; }
Get version compatible. 3.2.1-RC2 => 3.2.1.6.2 @param string $version @return string|false
entailment
public static function find($code, $index = 0) { $code = strtolower($code); $colors = static::get(); return isset($colors[$code]) ? $colors[$code][$index] : $code; }
@param $code @param int $index @return string
entailment
public function boot() { $this->loadViewsFrom(__DIR__.'/../resources/views', 'Simplegrid'); $this->loadTranslationsFrom(__DIR__.'/../resources/lang', 'Simplegrid'); $this->publishes([ __DIR__.'/../config/rafwell-simplegrid.php' => config_path('rafwell-simplegrid.php'), ]); $this->publishes([ __DIR__.'/../public' => public_path('vendor/rafwell/simple-grid'), ]); //solve bug in translation pluralize //probably are a bug in laravel - https://stackoverflow.com/questions/31775626/why-does-laravels-trans-choice-always-show-the-singular-case if($this->app->getLocale()=='pt-BR') $this->app->setLocale('pt_BR'); }
Bootstrap the application services. @return void
entailment
protected function createMemcachedDriver(array $config) { $prefix = $this->getPrefix($config); // Extract Plus features from config $persistentConnectionId = array_get($config, 'persistent_id'); $customOptions = array_get($config, 'options', []); $saslCredentials = array_filter(array_get($config, 'sasl', [])); $memcached = $this->app['memcached.connector']->connect( $config['servers'], $persistentConnectionId, $customOptions, $saslCredentials ); return $this->repository(new MemcachedStore($memcached, $prefix)); }
Create an instance of the Memcached cache driver. @param array $config @return \Illuminate\Cache\MemcachedStore
entailment
public static function packageInKernel(PackageEvent $event) { self::addJobByOperationType( $event->getOperation(), function ($package) { return new AddKernel($package); }, function ($package) { return new RemoveKernel($package); } ); }
Add or remove package in kernel. @param PackageEvent $event
entailment
public static function packageInRouting(PackageEvent $event) { self::addJobByOperationType( $event->getOperation(), function ($package) { return new AddRouting($package); }, function ($package) { return new RemoveRouting($package); } ); }
Add or remove packages in routing. @param PackageEvent $event
entailment
public static function packageInConfig(PackageEvent $event) { self::addJobByOperationType( $event->getOperation(), function ($package) { return new AddConfig($package); }, function ($package) { return new RemoveConfig($package); } ); }
Add or remove packages in config. @param PackageEvent $event
entailment
public static function migratePackage(PackageEvent $event) { self::addJobByOperationType( $event->getOperation(), function ($package) { return new UpMigrate($package); }, function ($package) { return new DownMigrate($package); } ); }
Migrate packages. @param PackageEvent $event
entailment
public static function notifyPackage(PackageEvent $event) { self::addJobByOperationType( $event->getOperation(), function ($package) { return new InstalledPackageNotify($package); }, function ($package) { return new RemovedPackageNotify($package); }, function ($package) { return new UpdatedPackageNotify($package); } ); }
Notify listeners that the package has been installed/updated/removed. @param PackageEvent $event
entailment
protected static function addJobByOperationType( OperationInterface $operation, \Closure $install, \Closure $uninstall, \Closure $update = null ) { switch ($operation->getJobType()) { case 'install': self::getContainer()->addJob($install($operation->getPackage())); break; case 'uninstall': self::getContainer()->addJob($uninstall($operation->getPackage())); break; case 'update': $update = $update ?: $install; self::getContainer()->addJob($update($operation->getTargetPackage())); break; } }
Add job by operation type. @param OperationInterface $operation @param \Closure $install @param \Closure $update @param \Closure $uninstall
entailment
public static function notifyProjectInstall(Event $event) { self::getContainer()->addJob(new InstalledProjectNotify($event->getComposer()->getPackage())); }
Notify listeners that the project has been installed. @param Event $event
entailment
public static function notifyProjectUpdate(Event $event) { self::getContainer()->addJob(new UpdatedProjectNotify($event->getComposer()->getPackage())); }
Notify listeners that the project has been updated. @param Event $event
entailment
public static function installConfig() { if (!file_exists(self::getRootDir().'config/vendor_config.yml')) { file_put_contents(self::getRootDir().'config/vendor_config.yml', ''); } if (!file_exists(self::getRootDir().'config/routing.yml')) { file_put_contents(self::getRootDir().'config/routing.yml', ''); } if (!file_exists(self::getRootDir().'bundles.php')) { file_put_contents(self::getRootDir().'bundles.php', "<?php\nreturn [\n];"); } // set memory_limit = 1G if (file_exists(self::getRootDir().'/../bin/php/php.ini')) { /* @var $manipulator PhpIni */ $manipulator = self::getContainer()->getManipulator('php.ini'); $limit = $manipulator->get('memory_limit') ?: '1G'; $limit = is_array($limit) ? array_pop($limit) : $limit; if ($manipulator->byteStringToInt($limit) < 1073741824) { // < 1G $manipulator->set('memory_limit', '1G'); } } }
Install config files.
entailment
public static function generateSecretKey() { // make parameters file if not exists touch(self::getRootDir().'/config/parameters.yml'); /* @var $manipulator Parameters */ $manipulator = self::getContainer()->getManipulator('parameters'); if (!$manipulator->get('secret')) { $manipulator->set('secret', SecretKey::generate()); } }
Make a unique secret key.
entailment
public static function migrateUp(Event $event) { $dir = self::getRootDir().'DoctrineMigrations'; if (self::isHaveMigrations($dir)) { self::repackMigrations($dir); self::executeCommand('doctrine:migrations:migrate --no-interaction', $event->getIO()); } }
Migrate all plugins to up. @param Event $event
entailment
public static function migrateDown(Event $event) { $dir = self::getRootDir().'cache/dev/DoctrineMigrations/'; if (self::isHaveMigrations($dir)) { file_put_contents( $dir.'migrations.yml', "migrations_namespace: 'Application\Migrations'\n". "migrations_directory: 'app/cache/dev/DoctrineMigrations/'\n". "table_name: 'migration_versions'" ); self::executeCommand( 'doctrine:migrations:migrate --no-interaction --configuration='.$dir.'migrations.yml 0', $event->getIO() ); } }
Migrate all plugins to down. @param Event $event
entailment
protected static function isHaveMigrations($dir) { if (!is_dir($dir)) { return false; } return (bool) Finder::create() ->in($dir) ->files() ->name('/Version\d{14}.*\.php/') ->count() ; }
@param string $dir @return bool
entailment
public static function clearCache(Event $event) { // to avoid errors due to the encrypted container forcibly clean the cache directory $dir = self::getRootDir().'cache/prod'; if (is_dir($dir)) { (new Filesystem())->remove($dir); } self::executeCommand('cache:clear --no-warmup --env=prod --no-debug', $event->getIO()); self::executeCommand('cache:clear --no-warmup --env=dev --no-debug', $event->getIO()); }
Clears the Symfony cache. @param \Composer\Script\Event $event
entailment
public function add($url, $description = NULL, array $events = array()){ return $this->request('add', array( 'url' => $url, 'description' => $description, 'events' => $events )); }
Add a new webhook @param string $url the URL to POST batches of events @param string $description an optional description of the webhook @param string[] $events an optional list of events that will be posted to the webhook valid events: send, hard_bounce, soft_bounce, open, click, spam, unsub, reject @return array @link https://mandrillapp.com/api/docs/webhooks.JSON.html#method=add
entailment
public function update($id, $url, $description = NULL, array $events = array()){ return $this->request('update', array( 'id' => $id, 'url' => $url, 'description' => $description, 'events' => $events )); }
Update an existing webhook @param int $id the unique identifier of a webhook belonging to this account @param string $url the URL to POST batches of events @param string $description an optional description of the webhook @param string[] $events an optional list of events that will be posted to the webhook valid events: send, hard_bounce, soft_bounce, open, click, spam, unsub, reject @return array @link https://mandrillapp.com/api/docs/webhooks.JSON.html#method=update
entailment
public function onBootstrap(EventInterface $event) { /* @var $application \Zend\Mvc\Application */ $application = $event->getTarget(); $serviceManager = $application->getServiceManager(); $eventManager = $application->getEventManager(); $eventManager->attachAggregate($serviceManager->get('ZfrPrerender\Mvc\PrerenderListener')); }
{@inheritDoc}
entailment
public function activity($notifyEmail = NULL, $dateFrom = NULL, $dateTo = NULL, array $tags = array(), array $senders = array(), array $states = array(), array $apiKeys = array()){ return $this->request('activity', array( 'notify_email' => $notifyEmail, 'date_from' => $dateFrom, 'date_to' => $dateTo, 'tags' => $tags, 'senders' => $senders, 'states' => $states, 'api_keys' => $apiKeys )); }
Begins an export of your activity history. @param string $notifyEmail an optional email address to notify when the export job has finished @param string $dateFrom start date as a UTC string in YYYY-MM-DD HH:MM:SS format @param string $dateTo end date as a UTC string in YYYY-MM-DD HH:MM:SS format @param string[] $tags an array of tag names to narrow the export to; will match messages that contain ANY of the tags @param string[] $senders an array of senders to narrow the export to @param string[] $states an array of states to narrow the export to; messages with ANY of the states will be included @param string[] $apiKeys an array of api keys to narrow the export to; messsagse sent with ANY of the keys will be included @return array @link https://mandrillapp.com/api/docs/exports.JSON.html#method=activity
entailment
private function calculateVariablePercentOfMethods(array $methods, $variableName) { $methodCount = count($methods); if (0 === $methodCount) { return 0; } $methodsWithVariable = $this->getMethodsContainsVariable($methods, $variableName); return round(count($methodsWithVariable) / $methodCount * 100); }
@param array $methods @param string $variableName @return float
entailment
private function getMethodsContainsVariable(array $methods, $variableName) { $methodsWithVariable = []; foreach ($methods as $method) { $propertyPostfixes = $method->findChildrenOfType('PropertyPostfix'); /** @var AbstractNode $propertyPostfix */ foreach ($propertyPostfixes as $propertyPostfix) { $identifier = $propertyPostfix->getFirstChildOfType('Identifier'); if (null === $identifier) { continue; } if ($variableName === $identifier->getName()) { $methodsWithVariable[] = $method; break; } } } return $methodsWithVariable; }
@param AbstractNode[] $methods @param string $variableName @return AbstractNode[]
entailment
protected function getMemcached($connectionId, array $credentials, array $options) { $memcached = $this->createMemcachedInstance($connectionId); if (count($credentials) == 2) { $this->setCredentials($memcached, $credentials); } if (count($options)) { $memcached->setOptions($options); } return $memcached; }
Get a new Memcached instance. @param string|null $connectionId @param array $credentials @param array $options @return \Memcached
entailment
protected function setCredentials($memcached, $credentials) { list($username, $password) = $credentials; $memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, true); $memcached->setSaslAuthData($username, $password); }
Set the SASL credentials on the Memcached connection. @param \Memcached $memcached @param array $credentials @return void
entailment
public function add($id, $name = NULL, $notes = NULL, $customQuota = NULL){ return $this->request('add', array( 'id' => $id, 'name' => $name, 'notes' => $notes, 'custom_quota' => $customQuota )); }
Add a new subaccount @param string $id a unique identifier for the subaccount to be used in sending calls @param string $name an optional display name to further identify the subaccount @param string $notes optional extra text to associate with the subaccount @param int $customQuota an optional manual hourly quota for the subaccount. If not specified, Mandrill will manage this based on reputation. @return array @link https://mandrillapp.com/api/docs/subaccounts.JSON.html#method=add
entailment
public function update($id, $name = NULL, $notes = NULL, $customQuota = NULL){ return $this->request('update', array( 'id' => $id, 'name' => $name, 'notes' => $notes, 'custom_quota' => $customQuota )); }
Update an existing subaccount @param string $id he unique identifier of the subaccount to update @param string $name an optional display name to further identify the subaccount @param string $notes optional extra text to associate with the subaccount @param int $customQuota an optional manual hourly quota for the subaccount. If not specified, Mandrill will manage this based on reputation @return array @link https://mandrillapp.com/api/docs/subaccounts.JSON.html#method=update
entailment
protected function request($url, array $body = array()){ $baseUrl = self::BASE_URL; if(isset($this->baseUrl)){ $baseUrl = $this->baseUrl; } $client = new Client($baseUrl); $body['key'] = $this->apiKey; $section = explode('\\', get_called_class()); $section = strtolower(end($section)); $request = $client->post($section.'/'.$url.'.json', NULL, $body); try{ $response = $request->send(); $response = $response->getBody(); } catch(ServerErrorResponseException $e){ $response = json_decode($e->getResponse()->getBody(), true); throw new APIException($response['message'], $response['code'], $response['status'], $response['name'], $e); } return json_decode($response, true); }
Send a request to Mandrill. All requests are sent via HTTP POST. @param string $url @param array $body @throws Exception\APIException @return array
entailment
public function prerenderPage(MvcEvent $event) { $originalRequest = $event->getRequest(); if (!$this->shouldPrerenderPage($originalRequest)) { return; } $event->stopPropagation(true); $eventManager = $this->getEventManager(); // Trigger a pre-event (for creating a response from cache, for instance) $responses = $eventManager->trigger(PrerenderEvent::EVENT_PRERENDER_PRE, new PrerenderEvent($originalRequest)); if ($responses->last() instanceof HttpResponse) { return $responses->last(); } // Make the actual request to Prerender service $client = $this->getHttpClient(); $uri = rtrim($this->moduleOptions->getPrerenderUrl(), '/') . '/' . $originalRequest->getUriString(); $userAgent = $originalRequest->getHeaders()->get('User-Agent')->getFieldValue(); $client->setUri($uri) ->setMethod(HttpRequest::METHOD_GET); $request = $client->getRequest(); $request->getHeaders()->addHeaderLine('User-Agent', $userAgent) ->addHeaderLine('Accept-Encoding', 'gzip'); if ($prerenderToken = $this->moduleOptions->getPrerenderToken()) { $request->getHeaders()->addHeaderLine('X-Prerender-Token', $prerenderToken); } $response = $client->send($request); // Trigger a post-event (for putting in cache the response, for instance) $prerenderEvent = new PrerenderEvent($request, $response); $eventManager->trigger(PrerenderEvent::EVENT_PRERENDER_POST, $prerenderEvent); return $prerenderEvent->getResponse(); }
Pre-render the page @param MvcEvent $event @return void|ResponseInterface
entailment
public function shouldPrerenderPage(RequestInterface $request) { if (!$request instanceof HttpRequest) { return false; } // First, return false if User Agent is not a bot if (!$this->isCrawler($request)) { return false; } $uri = $request->getUriString(); // Then, return false if URI string contains an ignored extension foreach ($this->moduleOptions->getIgnoredExtensions() as $ignoredExtension) { if (strpos($uri, $ignoredExtension) !== false) { return false; } } // Then, return true if it is whitelisted (only if whitelist contains data) $whitelistUrls = $this->moduleOptions->getWhitelistUrls(); if (!empty($whitelistUrls) && !$this->isWhitelisted($uri, $whitelistUrls)) { return false; } // Finally, return false if it is blacklisted (or the referer) $referer = $request->getHeader('Referer') ? $request->getHeader('Referer')->getFieldValue() : null; $blacklistUrls = $this->moduleOptions->getBlacklistUrls(); if (!empty($blacklistUrls) && $this->isBlacklisted($uri, $referer, $blacklistUrls)) { return false; } return true; }
Is this request should be a prerender request? @param RequestInterface $request @return bool
entailment
protected function isCrawler(HttpRequest $request) { if (null !== $request->getQuery('_escaped_fragment_')) { return true; } $userAgent = strtolower($request->getHeader('User-Agent')->getFieldValue()); foreach ($this->moduleOptions->getCrawlerUserAgents() as $crawlerUserAgent) { if (strpos($userAgent, strtolower($crawlerUserAgent)) !== false) { return true; } } return false; }
Check if the request is made from a crawler To detect if a request comes from a bot, we have two strategies: 1. We first check if the "_escaped_fragment_" query param is defined. This is only implemented by some search engines (Google, Yahoo and Bing among others) 2. If not, we use the User-Agent string @param HttpRequest $request @return bool
entailment
protected function isWhitelisted($uri, array $whitelistUrls) { foreach ($whitelistUrls as $whitelistUrl) { $match = preg_match('`' . $whitelistUrl . '`i', $uri); if ($match > 0) { return true; } } return false; }
Check if the request is whitelisted @param string $uri @param array $whitelistUrls @return bool
entailment
protected function isBlacklisted($uri, $referer, array $blacklistUrls) { foreach ($blacklistUrls as $blacklistUrl) { $pattern = '`' . $blacklistUrl . '`i'; $match = preg_match($pattern, $uri) + preg_match($pattern, $referer); if ($match > 0) { return true; } } return false; }
Check if the request is blacklisted @param string $uri @param string $referer @param array $blacklistUrls @return bool
entailment
public function addBundle($bundle) { $bundle = $this->getBundleString($bundle); // not root bundle if (strpos($this->getKernal(), $bundle) === false) { $bundles = $this->getBundles(); if (!in_array($bundle, $bundles)) { $bundles[] = $bundle; $this->setBundles($bundles); } } }
Add bundle to kernal. @param string $bundle
entailment
public function removeBundle($bundle) { $bundles = $this->getBundles(); if (($key = array_search($this->getBundleString($bundle), $bundles)) !== false) { unset($bundles[$key]); $this->setBundles($bundles); } }
Remove bundle from kernal. @param string $bundle
entailment
protected function getKernal() { if (!$this->kernel) { $this->kernel = file_get_contents($this->kernel_filename); } return $this->kernel; }
Get AppKernal content. @return string
entailment
public function addPackage($package, $version) { $config = $this->getContent(); $config['require'][$package] = $version; $this->setContent($config); }
Add the package into composer requirements. @param string $package @param string $version
entailment
public function removePackage($package) { $config = $this->getContent(); if (isset($config['require'][$package])) { unset($config['require'][$package]); $this->setContent($config); } }
Remove the package from composer requirements. @param string $package
entailment
protected function getPackageOption($option) { $options = $this->package->getExtra(); if (isset($options[$option])) { return $options[$option]; } return ''; }
@param string $option @return string
entailment
protected function getPackageOptionFile($option) { $option = $this->getPackageOption($option); if ($option && file_exists($this->getPackageDir().$option)) { return $option; } return ''; }
@param string $option @return string
entailment
public function getPackageBundle() { // specific name if (($class = $this->getPackageOption('anime-db-bundle')) && class_exists($class)) { return $class; } // package with the bundle can contain the word a 'bundle' in the name $name = preg_replace('/(\/.+)[^a-z]bundle$/i', '$1', $this->package->getName()); // convert package name to bundle name $name = preg_replace('/[^a-zA-Z\/]+/', ' ', $name); $name = ucwords(str_replace('/', ' / ', $name)); list($vendor, $bundle) = explode('/', str_replace(' ', '', $name), 2); $classes = [ '\\'.$vendor.'\Bundle\\'.$bundle.'Bundle\\'.$vendor.$bundle.'Bundle', '\\'.$vendor.'\Bundle\\'.$bundle.'Bundle\\'.$bundle.'Bundle', ]; // vendor name can be contained in the bundle name // knplabs/knp-menu-bundle -> \Knp\Bundle\MenuBundle\KnpMenuBundle list(, $bundle) = explode('/', $name, 2); $bundle = trim($bundle); if (($pos = strpos($bundle, ' ')) !== false) { $vendor = substr($bundle, 0, $pos); $bundle = str_replace(' ', '', substr($bundle, $pos + 1)); $classes[] = '\\'.$vendor.'\Bundle\\'.$bundle.'Bundle\\'.$vendor.$bundle.'Bundle'; $classes[] = '\\'.$vendor.'\Bundle\\'.$bundle.'Bundle\\'.$bundle.'Bundle'; } foreach ($classes as $class) { if (class_exists($class)) { // cache the bundle class $options = $this->package->getExtra(); $options['anime-db-bundle'] = $class; $this->package->setExtra($options); return $class; } } return; }
Get the bundle from package. For example package name 'demo-vendor/foo-bar-bundle' converted to: \DemoVendor\Bundle\FooBarBundle\DemoVendorFooBarBundle \DemoVendor\Bundle\FooBarBundle\FooBarBundle \Foo\Bundle\BarBundle\FooBarBundle \Foo\Bundle\BarBundle\BarBundle @return string|null
entailment
public function getPackageCopy() { $copy = new Package( $this->package->getName(), $this->package->getVersion(), $this->package->getPrettyVersion() ); $copy->setType($this->package->getType()); $copy->setExtra($this->package->getExtra()); return $copy; }
Get a simple copy of the package. @return Package
entailment
protected function getRoutingNodeName() { $name = strtolower($this->getPackage()->getName()); // package with the bundle can contain the word a 'bundle' in the name $name = preg_replace('/(\/.+)[^a-z]bundle$/', '$1', $name); $name = preg_replace('/[^a-z_]+/', '_', $name); return $name; }
Get the routing node name from the package name. @return string
entailment
public function addResource($name, $bundle, $format, $path = 'routing') { $resource = '@'.$bundle.$path.'.'.$format; $yaml = $this->getContent(); if (!isset($yaml[$name]) || $yaml[$name]['resource'] != $resource) { $yaml[$name] = ['resource' => $resource]; $this->setContent($yaml); } }
Add a routing resource. @param string $name @param string $bundle @param string $format @param string $path
entailment
public function removeResource($name) { $yaml = $this->getContent(); if (isset($yaml[$name])) { unset($yaml[$name]); $this->setContent($yaml); } }
Remove a routing resource. @param string $name
entailment
public function add($name, $fromEmail = NULL, $fromName = NULL, $subject = NULL, $code = NULL, $text = NULL, $publish = true){ return $this->request('add', array( 'name' => $name, 'from_email' => $fromEmail, 'from_name' => $fromName, 'subject'=> $subject, 'code' => $code, 'text' => $text, 'publish' => $publish )); }
Add a new template @param string $name the name for the new template - must be unique @param string $fromEmail a default sending address for emails sent using this template @param string $fromName a default from name to be used @param string $subject a default subject line to be used @param string $code the HTML code for the template with mc:edit attributes for the editable elements @param string $text a default text part to be used when sending with this template @param bool $publish set to false to add a draft template without publishing @return array @link https://mandrillapp.com/api/docs/templates.JSON.html#method=add
entailment
protected function validate($code) { $color = str_replace(['rgb', '(', ')', ' '], '', DefinedColor::find($code, 1)); if (preg_match('/^(\d{1,3}),(\d{1,3}),(\d{1,3})$/', $color, $matches)) { if ($matches[1] > 255 || $matches[2] > 255 || $matches[3] > 255) { return false; } return $color; } return false; }
@param string $code @return string|bool
entailment
protected function initialize($color) { return list($this->red, $this->green, $this->blue) = explode(',', $color); }
@param string $color @return array
entailment
private function getH($max, $r, $g, $b, $d) { switch ($max) { case $r: $h = ($g - $b) / $d + ($g < $b ? 6 : 0); break; case $g: $h = ($b - $r) / $d + 2; break; case $b: $h = ($r - $g) / $d + 4; break; default: $h = $max; break; } return $h / 6; }
@param float $max @param float $r @param float $g @param float $b @param float $d @return float
entailment
protected function createCacheHandler($driver) { $store = $this->app['config']->get('session.store') ?: $driver; $minutes = $this->app['config']['session.lifetime']; return new CacheBasedSessionHandler(clone $this->app['cache']->store($store), $minutes); }
Create the cache based session handler instance. @param string $driver @return \Illuminate\Session\CacheBasedSessionHandler
entailment
protected function isDataStructure(ClassNode $node) { if (!preg_match($this->getRegex('dataStructureNamespaceRegex'), $node->getNamespaceName())) { return false; } if (!preg_match($this->getRegex('dataStructureClassNameRegex'), $node->getName())) { return false; } return true; }
@param ClassNode|ASTClass $node @return bool
entailment
public function red($red = null) { if ($red !== null) { $this->validateAndSet('red', $red); return $this; } return !empty($this->castsInteger) ? (int) $this->red : $this->red; }
@param int|string $red @return int|string|$this
entailment
public function green($green = null) { if ($green !== null) { $this->validateAndSet('green', $green); return $this; } return !empty($this->castsInteger) ? (int) $this->green : $this->green; }
@param float|int|string $green @return float|int|string|$this
entailment
public function blue($blue = null) { if ($blue !== null) { $this->validateAndSet('blue', $blue); return $this; } return !empty($this->castsInteger) ? (int) $this->blue : $this->blue; }
@param float|int|string $blue @return float|int|string|$this
entailment
public function sendRaw($rawMessage, array $to = array(), $mailFrom = NULL, $helo = NULL, $clientAddress = NULL){ return $this->request('send-raw', array( 'raw_message' => $rawMessage, 'to' => $to, 'mail_from' => $mailFrom, 'helo' => $helo, 'client_address' => $clientAddress )); }
Take a raw MIME document destined for a domain with inbound domains set up, and send it to the inbound hook exactly as if it had been sent over SMTP @param string $rawMessage the full MIME document of an email message @param string[] $to optionally define the recipients to receive the message - otherwise we'll use the To, Cc, and Bcc headers provided in the document @param string $mailFrom the address specified in the MAIL FROM stage of the SMTP conversation. Required for the SPF check. @param string $helo the identification provided by the client mta in the MTA state of the SMTP conversation. Required for the SPF check. @param string $clientAddress the remote MTA's ip address. Optional; required for the SPF check. @return array @link https://mandrillapp.com/api/docs/inbound.JSON.html#method=send-raw
entailment
public function getTags($repository) { /* @var $response Response */ $response = $this->client->get('repos/'.$repository.'/tags')->send(); return json_decode($response->getBody(true), true); }
@param string $repository @return array
entailment
public function getLastRelease($repository) { $last_version = ''; $last_tag = []; foreach ($this->getTags($repository) as $tag) { if (($version = Composer::getVersionCompatible($tag['name'])) && (!$last_version || version_compare($version, $last_version, '>=')) && version_compare($version, '1.0.0', '<') // v1.0.0 is BC ) { $last_version = $version; $last_tag = $tag; } } return $last_tag ?: false; }
@param string $repository @return array|false
entailment
protected function execute(InputInterface $input, OutputInterface $output) { /* @var $composer Composer */ $composer = $this->getContainer()->get('anime_db.composer'); $composer->setIO(new ConsoleIO($input, $output, $this->getHelperSet())); /* @var $github GitHub */ $github = $this->getContainer()->get('anime_db.client.github'); // search tag with new version of application $output->writeln('Search for a new version of the application'); $tag = $github->getLastRelease('anime-db/anime-db'); $tag['version'] = Composer::getVersionCompatible($tag['name']); $current_version = Composer::getVersionCompatible($composer->getRootPackage()->getPrettyVersion()); // update itself if ($tag && version_compare($tag['version'], $current_version) == 1) { $this->doUpdateItself($tag, $composer, $output); } else { $output->writeln('<info>Application has already been updated to the latest version</info>'); } unset($github, $tag, $current_version); // update from composer if ($composer->getInstaller()->run() === 0) { $output->writeln('<info>Update requirements has been completed</info>'); } else { $output->writeln('<error>During updating dependencies error occurred</error>'); } $output->writeln('<info>Updating the application has been completed<info>'); }
@param InputInterface $input @param OutputInterface $output @return bool
entailment
protected function rewriting($from) { $fs = $this->getContainer()->get('filesystem'); try { $fs->remove( Finder::create() ->files() ->ignoreUnreadableDirs() ->in($this->getContainer()->getParameter('kernel.root_dir').'/../src') ->in($this->getContainer()->getParameter('kernel.root_dir')) ); } catch (\Exception $e) { // ignore errors during the removal of the old application } // copy new version $fs->mirror( $from, $this->getContainer()->getParameter('kernel.root_dir').'/../', null, ['override' => true, 'copy_on_windows' => true] ); // remove downloaded files $fs->remove($from); }
Rewrite the application files. @param string $from
entailment
public function setGlobalMergeVars(array $vars){ $this->global_merge_vars = array(); foreach($vars as $name => $content){ $this->addGlobalMergeVar($name, $content); } return $this; }
Set all global merge variables. Will overwrite any currently set global merge variables. @param array $vars array('name1' => 'content1', 'name2' => 'content2') @return $this
entailment
public function addRecipient(Recipient $recipient){ $this->to[] = array( 'email' => $recipient->email, 'name' => $recipient->name, 'type' => $recipient->type ); $this->merge_vars[] = array( 'rcpt' => $recipient->email, 'vars' => $recipient->getMergeVars() ); $this->recipient_metadata[] = array( 'rcpt' => $recipient->email, 'values' => $recipient->getMetadata() ); return $this; }
Add a recipient to this message @param Recipient $recipient @return $this
entailment
public function getManipulator($name) { if (!isset($this->manipulators[$name])) { switch ($name) { case 'composer': $this->manipulators[$name] = new ComposerManipulator($this->root_dir.'/../composer.json'); break; case 'config': $this->manipulators[$name] = new ConfigManipulator($this->root_dir.'config/vendor_config.yml'); break; case 'kernel': $this->manipulators[$name] = new KernelManipulator( $this->root_dir.'bundles.php', $this->root_dir.'AppKernel.php' ); break; case 'routing': $this->manipulators[$name] = new RoutingManipulator($this->root_dir.'config/routing.yml'); break; case 'php.ini': $this->manipulators[$name] = new PhpIniManipulator($this->root_dir.'/../bin/php/php.ini'); break; case 'parameters': $this->manipulators[$name] = new ParametersManipulator($this->root_dir.'/config/parameters.yml'); break; default: throw new \InvalidArgumentException('Unknown manipulator: '.$name); } } return $this->manipulators[$name]; }
@param string $name @return ManipulatorInterface
entailment
public function execute() { // sort jobs by priority $jobs = []; ksort($this->jobs); foreach ($this->jobs as $priority_jobs) { $jobs = array_merge($jobs, $priority_jobs); } /* @var $job Job */ foreach ($jobs as $job) { $job->execute(); } }
Execute all jobs.
entailment
public function executeCommand($cmd, $timeout = 300) { $php = escapeshellarg($this->getPhp()); $process = new Process($php.' '.$this->root_dir.'console '.$cmd, $this->root_dir.'/../', null, null, $timeout); $process->run(function ($type, $buffer) { echo $buffer; }); if (!$process->isSuccessful()) { throw new \RuntimeException(sprintf('An error occurred when executing the "%s" command.', $cmd)); } }
@throws \RuntimeException @param string $cmd @param int $timeout
entailment
protected function getPhp() { if (is_null($this->php_path)) { $finder = new PhpExecutableFinder(); if (!($this->php_path = $finder->find())) { throw new \RuntimeException( 'The php executable could not be found, add it to your PATH environment variable and try again' ); } } return $this->php_path; }
Get path to php executable. @throws \RuntimeException @return string
entailment
public function start($args = null, $scheduler = false) { if ($args === null) { $this->outputTitle($scheduler ? 'Creating the scheduler worker' : 'Creating workers'); } else { $this->runtime = $args; } if ($scheduler) { if ($this->runtime['Scheduler']['enabled'] !== true) { $this->output->outputLine('Scheduler Worker is not enabled', 'failure'); return false; } if ($this->ResqueStatus->isRunningSchedulerWorker()) { $this->output->outputLine('The scheduler worker is already running', 'warning'); return false; } $args['type'] = 'scheduler'; } $pidFile = (isset($this->runtime['Fresque']['tmpdir']) ? $this->runtime['Fresque']['tmpdir'] : dirname(__DIR__) . DS . 'tmp' ) . DS . str_replace('.', '', microtime(true)); $count = $this->runtime['Default']['workers']; $this->debug('Will start ' . $count . ' workers'); for ($i = 1; $i <= $count; $i++) { $libraryPath = $scheduler ? $this->runtime['Scheduler']['lib'] : $this->runtime['Fresque']['lib']; $logFile = $scheduler ? $this->runtime['Scheduler']['log'] : $this->runtime['Log']['filename']; $resqueBin = $scheduler ? './bin/resque-scheduler.php' : $this->getResqueBinFile($this->runtime['Fresque']['lib']); $libraryPath = rtrim($libraryPath, '/'); // build environment variables string to be passed to the worker $env_vars = ""; foreach($this->runtime['Env'] as $env_name => $env_value) { // if only the name is supplied, we get the value from environment if (strlen($env_value) == 0) { $env_value = getenv($env_name); } $env_vars .= $env_name . '=' . escapeshellarg($env_value) . " \\\n"; } $cmd = 'nohup ' . ($this->runtime['Default']['user'] !== $this->getProcessOwner() ? ('sudo -u '. escapeshellarg($this->runtime['Default']['user'])) : "") . " \\\n". 'bash -c "cd ' . escapeshellarg($libraryPath) . '; ' . " \\\n". $env_vars . (($this->runtime['Default']['verbose']) ? 'VVERBOSE' : 'VERBOSE') . '=true ' . " \\\n". 'QUEUE=' . escapeshellarg($this->runtime['Default']['queue']) . " \\\n". 'PIDFILE=' . escapeshellarg($pidFile) . " \\\n". 'APP_INCLUDE=' . escapeshellarg($this->runtime['Fresque']['include']) . " \\\n". 'RESQUE_PHP=' . escapeshellarg($this->runtime['Fresque']['lib'] . DS . 'lib' . DS . 'Resque.php') . " \\\n". 'INTERVAL=' . escapeshellarg($this->runtime['Default']['interval']) . " \\\n". 'REDIS_BACKEND=' . escapeshellarg($this->runtime['Redis']['host'] . ':' . $this->runtime['Redis']['port']) . " \\\n". 'REDIS_DATABASE=' . escapeshellarg($this->runtime['Redis']['database']) . " \\\n". 'REDIS_NAMESPACE=' . escapeshellarg($this->runtime['Redis']['namespace']) . " \\\n". 'REDIS_PASSWORD=' . escapeshellarg($this->runtime['Redis']['password']) . " \\\n". 'COUNT=' . 1 . " \\\n". 'LOGHANDLER=' . escapeshellarg($this->runtime['Log']['handler']) . " \\\n". 'LOGHANDLERTARGET=' . escapeshellarg($this->runtime['Log']['target']) . " \\\n". 'php ' . escapeshellarg($resqueBin) . " \\\n"; $cmd .= ' >> '. escapeshellarg($logFile).' 2>&1" >/dev/null 2>&1 &'; $this->debug('Starting worker (' . $i . ')'); $this->debug("Running command :\n\t" . str_replace("\n", "\n\t", $cmd)); $this->exec($cmd); $this->output->outputText($scheduler ? 'Starting scheduler worker ' : 'Starting worker '); $success = false; $attempt = 7; while ($attempt-- > 0) { for ($x = 0; $x < 3; $x++) { $this->output->outputText(".", 0); usleep(self::$checkStartedWorkerBufferTime); } if (false !== $pid = $this->checkStartedWorker($pidFile)) { $success = true; $this->output->outputLine(' Done', 'success'); $this->debug('Registering worker #' . $pid . ' to list of active workers'); $workerSettings = $this->runtime; $workerSettings['workers'] = 1; if ($scheduler) { $this->ResqueStatus->registerSchedulerWorker($pid); } $this->ResqueStatus->addWorker($pid, $workerSettings); break; } } if (!$success) { $this->output->outputLine(' Fail', 'failure'); } } if ($args === null) { $this->output->outputLine(); } }
Start workers @return void
entailment
public function stop() { $ResqueStatus = $this->ResqueStatus; $this->debug('Searching for active workers'); $options = new SendSignalCommandOptions(); $options->title = 'Stopping workers'; $options->noWorkersMessage = 'There is no workers to stop'; $options->allOption = 'Stop all workers'; $options->selectMessage = 'Worker to stop'; $options->actionMessage = 'stopping'; $options->workers = call_user_func(self::$Resque_Worker. '::all'); $options->signal = $this->input->getOption('force')->value === true ? 'TERM' : 'QUIT'; $options->successCallback = function ($pid, $workerName) use ($ResqueStatus) { $ResqueStatus->removeWorker($pid); }; $options->schedulerWorkerActionMessage = 'Stopping the Scheduler Worker'; $options->schedulerWorkerAction = function($worker) use ($ResqueStatus) { $ResqueStatus->unregisterSchedulerWorker(); }; $this->sendSignal($options); }
Stop workers @return void
entailment
public function pause() { $ResqueStatus = $this->ResqueStatus; $activeWorkers = call_user_func(self::$Resque_Worker . '::all'); array_walk( $activeWorkers, function (&$worker) { return $worker = (string)$worker; } ); $pausedWorkers = call_user_func(array($this->ResqueStatus, 'getPausedWorker')); $this->debug('Searching for active workers'); $options = new SendSignalCommandOptions(); $options->title = 'Pausing workers'; $options->noWorkersMessage = 'There is no workers to pause'; $options->allOption = 'Pause all workers'; $options->selectMessage = 'Worker to pause'; $options->actionMessage = 'pausing'; $options->workers = array_diff($activeWorkers, $pausedWorkers); $options->signal = 'USR2'; $options->successCallback = function ($pid, $workerName) use ($ResqueStatus) { $ResqueStatus->setPausedWorker($workerName); }; $options->schedulerWorkerActionMessage = 'Pausing the Scheduler Worker'; $this->sendSignal($options); }
Pause workers @return void
entailment
public function resume() { $ResqueStatus = $this->ResqueStatus; $this->debug('Searching for paused workers'); $options = new SendSignalCommandOptions(); $options->title = 'Resuming workers'; $options->noWorkersMessage = 'There is no paused workers to resume'; $options->allOption = 'Resume all workers'; $options->selectMessage = 'Worker to resume'; $options->actionMessage = 'resuming'; $options->workers = call_user_func(array($this->ResqueStatus, 'getPausedWorker')); $options->signal = 'CONT'; $options->successCallback = function ($pid, $workerName) use ($ResqueStatus) { $ResqueStatus->setPausedWorker($workerName, false); }; $options->schedulerWorkerActionMessage = 'Resuming the Scheduler Worker'; $this->sendSignal($options); }
Resume workers @return void
entailment
public function sendSignal($options) { $this->outputTitle($options->title); $force = $this->input->getOption('force')->value; $all = $this->input->getOption('all')->value; if ($force) { $this->debug("'FORCE' option detected"); } if ($all) { $this->debug("'ALL' option detected"); } if (!isset($options->formatListItem)) { $resqueStats = $this->ResqueStats; $ResqueStatus = $this->ResqueStatus; $fresque = $this; $listFormatter = function ($worker) use ($resqueStats, $ResqueStatus, $fresque) { return sprintf( '%s, started %s ago', $ResqueStatus->isSchedulerWorker($worker) ? '**Scheduler Worker**' : $worker, $fresque->formatDateDiff(call_user_func_array(array($resqueStats, 'getWorkerStartDate'), array($worker))) ); }; } else { $listFormatter = $option->formatListItem; } if (empty($options->workers)) { $this->output->outputLine($options->noWorkersMessage, 'failure'); } else { sort($options->workers); $this->debug('Found ' . $options->getWorkersCount() . ' workers'); $workerIndex = array(); if (!$all && $options->getWorkersCount() > 1) { $i = 1; $menuItems = array(); foreach ($options->workers as $worker) { $menuItems[$i++] = $listFormatter($worker); } $menuItems['all'] = $options->allOption; $index = $this->getUserChoice( $options->listTitle, $options->selectMessage . ':', $menuItems ); if ($index === 'all') { $workerIndex = range(1, $options->getWorkersCount()); } else { $workerIndex[] = $index; } } else { $workerIndex = range(1, $options->getWorkersCount()); } foreach ($workerIndex as $index) { $worker = $options->workers[$index - 1]; list($hostname, $pid, $queue) = explode(':', (string)$worker); $this->debug('Sending -' . $options->signal . ' signal to process ID ' . $pid); if ($this->runtime['Scheduler']['enabled'] === true && $this->ResqueStatus->isSchedulerWorker($worker)) { if (isset($options->schedulerWorkerAction)) { $f = $options->schedulerWorkerAction; $f($worker); } $this->output->outputText($options->schedulerWorkerActionMessage . ' ... '); } else { $this->output->outputText($options->actionMessage . ' ' . $pid . ' ... '); } $killResponse = $this->kill($options->signal, $pid); $options->onSuccess($pid, (string)$worker); if ($killResponse['code'] === 0) { $this->output->outputLine('Done', 'success'); } else { $this->output->outputLine($killResponse['message'], 'failure'); } } } $this->output->outputLine(); }
Send a Signal to a worker system process @since 1.2.0 @return void
entailment
public function load() { $this->outputTitle('Loading predefined workers'); $debug = $this->debug; if (!isset($this->runtime['Queues']) || empty($this->runtime['Queues'])) { $this->output->outputLine("You have no configured workers to load.\n", 'failure'); } else { $this->output->outputLine(sprintf('Loading %s workers', count($this->runtime['Queues']))); $config = $this->config; foreach ($this->runtime['Queues'] as $queue) { $queue['config'] = $config; $queue['debug'] = $debug; $this->loadSettings('load', $queue); $this->start($this->runtime); } } if ($this->runtime['Scheduler']['enabled'] === true) { $this->startscheduler(array('debug' => $debug)); } $this->output->outputLine(); }
Load workers from configuration @return void
entailment
public function restart() { $workers = $this->ResqueStatus->getWorkers(); $this->outputTitle('Restarting workers'); if (!empty($workers)) { $this->stop(); foreach ($workers as $worker) { if (isset($worker['type']) && $worker['type'] === 'scheduler') { $this->startScheduler($worker); } else { $this->start($worker); } } } else { $this->output->outputLine('No workers to restart', 'failure'); } $this->output->outputLine(); }
Restart all workers @return void
entailment
public function tail() { $logs = array(); $i = 1; $workers = $this->ResqueStatus->getWorkers(); foreach ($workers as $worker) { if ($worker['Log']['filename'] != '') { $logs[] = $worker['Log']['filename']; } if ($worker['Log']['handler'] == 'RotatingFile') { $fileInfo = pathinfo($worker['Log']['target']); $pattern = $fileInfo['dirname'] . DS . $fileInfo['filename'] . '-*' . (!empty($fileInfo['extension']) ? '.' . $fileInfo['extension'] : ''); $logs = array_merge($logs, glob($pattern)); } } $logs = array_values(array_unique($logs)); $this->outputTitle('Tailing log file'); if (empty($logs)) { $this->output->outputLine('No log file to tail', 'failure'); return; } elseif (count($logs) == 1) { $index = 1; } else { $menuOptions = new \ezcConsoleMenuDialogOptions( array( 'text' => 'Log files list', 'selectText' => 'Log to tail :', 'validator' => new DialogMenuValidator(array_combine(range(1, count($logs)), $logs)) ) ); $menuDialog = new \ezcConsoleMenuDialog($this->output, $menuOptions); do { $menuDialog->display(); } while ($menuDialog->hasValidResult() === false); $index = $menuDialog->getResult(); } $this->output->outputLine('Tailing ' . $logs[$index - 1], 'subtitle'); $this->tailCommand($logs[$index - 1]); }
Tail a log file If more than one log file exists, will display a menu dialog with a list of log files to choose from. @return void
entailment
public function enqueue() { $this->outputTitle('Queuing a job'); $args = $this->input->getArguments(); if (count($args) >= 2) { $queue = array_shift($args); $class = array_shift($args); $result = call_user_func_array(self::$Resque . '::enqueue', array($queue, $class, $args)); $this->output->outputLine('The job was enqueued successfully', 'success'); $this->output->outputLine('Job ID : #' . $result . "\n"); } else { $this->output->outputLine('Enqueue takes at least 2 arguments', 'failure'); $this->output->outputLine('Usage : enqueue <queue> <job> <args>'); $this->output->outputLine(' queue <string> Name of the queue'); $this->output->outputLine(' job <string> Job class name'); $this->output->outputLine(' args <string> Comma separated list of arguments'); $this->output->outputLine(); } }
Add a job to a queue @return void
entailment
public function stats() { $workers = call_user_func(array($this->ResqueStats, 'getWorkers')); // List of all queues $queues = array_unique(call_user_func(array($this->ResqueStats, 'getQueues'))); // List of queues monitored by a worker $activeQueues = array(); foreach ($workers as $worker) { $tokens = explode(':', $worker); $activeQueues = array_merge($activeQueues, explode(',', array_pop($tokens))); } $this->outputTitle('Resque statistics'); $this->output->outputLine(); $this->output->outputLine('Jobs Stats', 'subtitle'); $this->output->outputLine(' ' . sprintf('Processed Jobs : %10s', number_format(\Resque_Stat::get('processed')))); $this->output->outputLine(' ' . sprintf('Failed Jobs : %10s', number_format(\Resque_Stat::get('failed'))), 'failure'); if ($this->runtime['Scheduler']['enabled'] === true) { $this->output->outputLine(' ' . sprintf('Scheduled Jobs : %10s', number_format(\ResqueScheduler\Stat::get()))); } $this->output->outputLine(); $count = array(); $this->output->outputLine('Queues Stats', 'subtitle'); for ($i = count($queues) - 1; $i >= 0; --$i) { $count[$queues[$i]] = call_user_func_array(array($this->ResqueStats, 'getQueueLength'), array($queues[$i])); if (!in_array($queues[$i], $activeQueues) && $count[$queues[$i]] == 0) { unset($queues[$i]); } } $this->output->outputLine(' ' . sprintf('Queues count : %d', count($queues))); foreach ($queues as $queue) { $this->output->outputText(sprintf("\t- %-20s : %10s pending jobs", $queue, number_format($count[$queue]))); if (!in_array($queue, $activeQueues)) { $this->output->outputText(' (unmonitored queue)', 'failure'); } $this->output->outputText("\n"); } $this->output->outputLine(); $this->output->outputLine('Workers Stats', 'subtitle'); $this->output->outputLine(' Active Workers : ' . count($workers)); $schedulerWorkers = array(); if (!empty($workers)) { $pausedWorkers = call_user_func(array($this->ResqueStatus, 'getPausedWorker')); foreach ($workers as $worker) { if ($this->runtime['Scheduler']['enabled'] === true && $this->ResqueStatus->isSchedulerWorker($worker)) { $schedulerWorkers[] = $worker; continue; } $this->output->outputText(' Worker : ' . $worker, 'bold'); if (in_array((string)$worker, $pausedWorkers)) { $this->output->outputText(' (Paused)', 'success'); } $this->output->outputText("\n"); $startDate = call_user_func_array(array($this->ResqueStats, 'getWorkerStartDate'), array($worker)); $this->output->outputLine( ' - Started on : ' . $startDate ); $this->output->outputLine( ' - Uptime : ' . $this->formatDateDiff(new \DateTime($startDate)) ); $this->output->outputLine(' - Processed Jobs : ' . $worker->getStat('processed')); $worker->getStat('failed') == 0 ? $this->output->outputLine(' - Failed Jobs : ' . $worker->getStat('failed')) : $this->output->outputLine(' - Failed Jobs : ' . $worker->getStat('failed'), 'failure'); } } $this->output->outputLine("\n"); if (!empty($schedulerWorkers)) { $this->output->outputText(ucwords(' scheduler worker'), 'bold'); if (in_array((string)$schedulerWorkers[0], $pausedWorkers)) { $this->output->outputText(' (Paused)', 'success'); } $this->output->outputText("\n"); foreach ($schedulerWorkers as $worker) { $schedulerWorker = new \ResqueScheduler\ResqueScheduler(); $delayedJobCount = $schedulerWorker->getDelayedQueueScheduleSize(); $this->output->outputLine(' - Started on : ' . call_user_func_array(array($this->ResqueStats, 'getWorkerStartDate'), array($worker))); $this->output->outputLine(' - Delayed Jobs : ' . number_format($delayedJobCount)); if ($delayedJobCount > 0) { $this->output->outputLine(' - Next Job on : ' . strftime('%a %b %d %H:%M:%S %Z %Y', $schedulerWorker->nextDelayedTimestamp())); } } $this->output->outputLine("\n"); } elseif ($this->runtime['Scheduler']['enabled'] === true) { $jobsCount = \ResqueScheduler\ResqueScheduler::getDelayedQueueScheduleSize(); if ($jobsCount > 0) { $this->output->outputLine(" ************ " . 'Alert' . " ************", 'failure'); $this->output->outputLine(" " . 'The Scheduler Worker is not running', 'bold'); $this->output->outputLine(" " . 'But there is still ' . number_format($jobsCount) . ' scheduled jobs left in its queue'); $this->output->outputLine(" ********************************", 'failure'); $this->output->outputLine("\n"); } } }
Print some stats about the workers @return void
entailment
public function reset() { $this->debug('Emptying the worker database'); $this->ResqueStatus->clearWorkers(); $this->debug('Unregistering the scheduler worker'); $this->ResqueStatus->unregisterSchedulerWorker(); $this->output->outputLine('Fresque state has been reseted', 'success'); }
Reset worker statuses @since 1.2.0 @return void
entailment
public function loadSettings($command, $args = null) { $options = ($args === null) ? $this->input->getOptionValues(true) : $args; $this->config = isset($options['config']) ? $options['config'] : '.'.DS.'fresque.ini'; if (!file_exists($this->config)) { $this->output->outputLine("The config file '$this->config' was not found", 'failure'); return false; } $this->debug = isset($options['debug']) ? $options['debug'] : false; $this->runtime = parse_ini_file($this->config, true); if (!isset($this->runtime['type'])) { $this->runtime['type'] = 'regular'; } $settings = array( 'Redis' => array( 'host', 'port', 'database', 'namespace', ), 'Fresque' => array( 'lib', 'include', ), 'Default' => array( 'queue', 'interval', 'workers', 'user', 'verbose', ), 'Log' => array( 'filename', 'handler', 'target', ), 'Scheduler' => array( 'enabled', 'lib', 'log', 'interval', 'handler', 'target' ), 'Env' => array() ); foreach ($settings as $scope => $param_names) { foreach ($param_names as $option) { if (isset($options[$option])) { $this->runtime[$scope][$option] = $options[$option]; } } } if (isset($this->runtime['Queues']) && !empty($this->runtime['Queues'])) { foreach ($this->runtime['Queues'] as $name => $options) { if (!isset($this->runtime['Queues'][$name]['queue'])) { $this->runtime['Queues'][$name]['queue'] = $name; } } } $this->runtime['Default']['verbose'] = ($this->input->getOption('verbose')->value) ? $this->input->getOption('verbose')->value : $this->settings['Default']['verbose']; $this->runtime['Scheduler']['enabled'] = (bool)$this->runtime['Scheduler']['enabled']; if ($this->runtime['Scheduler']['enabled']) { if (!empty($this->runtime['Scheduler']['handler']) && $this->runtime['Scheduler']['type'] === 'scheduler') { $this->runtime['Log']['handler'] = $this->runtime['Scheduler']['handler']; } if (!empty($this->runtime['Scheduler']['target']) && $this->runtime['Scheduler']['type'] === 'scheduler') { $this->runtime['Log']['target'] = $this->runtime['Scheduler']['target']; } if (!empty($this->runtime['Scheduler']['interval'])) { $this->runtime['Default']['interval'] = $this->runtime['Scheduler']['interval']; } } // Shutdown application if there is error in the config if ($command !== 'test') { $results = $this->testConfig(); if (!empty($results)) { $fail = false; foreach ($results as $name => $mess) { if ($mess !== true) { $fail = true; $this->output->outputLine($mess, 'failure'); } } if ($fail) { $this->output->outputLine(); return false; } } } return true; }
Convert options from various source to formatted options understandable by Fresque @return bool true if settings contains no errors
entailment
public function help($command = null) { $this->outputTitle('Welcome to Fresque'); $this->output->outputLine('Fresque '. Fresque::VERSION .' by Wan Chen (Kamisama) (2013)'); if (!array_key_exists($command, $this->commandTree) && $command !== null && ($command !== '--help' && $command !== '-h') ) { $this->output->outputLine("\nUnrecognized command : " . $command, 'failure'); } $this->output->outputLine(); $this->output->outputLine("Available commands\n", 'subtitle'); foreach ($this->commandTree as $name => $opt) { $this->output->outputText($name . str_repeat(' ', 15 - strlen($name)), 'bold'); $this->output->outputText($opt['help'] . "\n"); } $this->output->outputLine("\nUse <command> --help to get more infos about a command\n"); }
Print help/welcome message @since 1.2.0 @return void
entailment
public function outputTitle($title, $primary = true) { $l = strlen($title); if ($primary) { $this->output->outputLine(str_repeat('-', $l), 'title'); } $this->output->outputLine($title, $primary ? 'title' : 'subtitle'); if ($primary) { $this->output->outputLine(str_repeat('-', $l), 'title'); } }
Print a pretty title @param string $title The title to print @param bool $primary True to print a big title, else print a small title @since 1.0.0 @return void
entailment
public function formatDateDiff($start, $end = null) { if (!($start instanceof \DateTime)) { $start = new \DateTime($start); } if ($end === null) { $end = new \DateTime(); } if (!($end instanceof \DateTime)) { $end = new \DateTime($start); } $interval = $end->diff($start); $doPlural = function ( $nb, $str ) { return $nb>1?$str.'s':$str; }; $format = array(); if ($interval->y !== 0) { $format[] = '%y ' . $doPlural($interval->y, 'year'); } if ($interval->m !== 0) { $format[] = '%m ' . $doPlural($interval->m, 'month'); } if ($interval->d !== 0) { $format[] = '%d ' . $doPlural($interval->d, 'day'); } if ($interval->h !== 0) { $format[] = '%h ' . $doPlural($interval->h, 'hour'); } if ($interval->i !== 0) { $format[] = '%i ' . $doPlural($interval->i, 'minute'); } if ($interval->s !== 0) { if (!count($format)) { return 'less than a minute'; } else { $format[] = '%s ' . $doPlural($interval->s, 'second'); } } // We use the two biggest parts if (count($format) > 1) { $format = array_shift($format) . ' and '.array_shift($format); } else { $format = array_pop($format); } // Prepend 'since ' or whatever you like return $interval->format($format); }
A sweet interval formatting, will use the two biggest interval parts. On small intervals, you get minutes and seconds. On big intervals, you get months and days. Only the two biggest parts are used. @param \DateTime $start @param \DateTime|null $end @codeCoverageIgnore @link http://www.php.net/manual/en/dateinterval.format.php @return string
entailment
private function absolutePath($path) { if (substr($path, 0, 2) === './') { $path = dirname(__DIR__) . DS . substr($path, 2); } elseif (substr($path, 0, 1) !== '/' || substr($path, 0, 3) === '../') { $path = dirname(__DIR__) . DS . $path; } return rtrim($path, DS); }
Return the absolute path to a file @param string $path Path to convert @return string Absolute path to the file
entailment
protected function getResqueBinFile($base) { $paths = array( 'bin' . DS . 'resque', 'bin' . DS . 'resque.php', 'resque.php' ); foreach ($paths as $path) { if (file_exists($base . DS . $path)) { return '.' . DS . $path; } } return '.' . DS . 'resque.php'; }
Return the php-resque executable file Maintain backward compatibility, as newer version of php-resque has that file in another location @param String $base Php-resque folder path @since 1.1.6 @return String Relative path to php-resque executable file
entailment
protected function kill($signal, $pid) { $output = array(); $message = exec(sprintf(($this->runtime['Default']['user'] !== $this->getProcessOwner() ? ('sudo -u '. escapeshellarg($this->runtime['Default']['user'])) . ' ' : "") . '/bin/kill -%s %s 2>&1', $signal, $pid), $output, $code); return array('code' => $code, 'message' => $message); }
Send a signal to a process @param String $signal Signal to send @param int $pid PID of the process @codeCoverageIgnore @since 1.2.0 @return array with the code and message returned by the command
entailment
protected function checkStartedWorker($pidFile) { $pid = false; if (file_exists($pidFile) && false !== $pid = file_get_contents($pidFile)) { unlink($pidFile); return (int)$pid; } return false; }
Check the content of the PID file created by the worker to retrieve its process PID @param string $path Path to the PID file @codeCoverageIgnore @since 1.2.0 @return false|int The worker process ID, or false if error
entailment
protected function getUserChoice($listTitle, $selectMessage, $menuItems) { $menuOptions = new \ezcConsoleMenuDialogOptions( array( 'text' => $listTitle, 'selectText' => $selectMessage, 'validator' => new DialogMenuValidator($menuItems) ) ); $menuDialog = new \ezcConsoleMenuDialog($this->output, $menuOptions); do { $menuDialog->display(); } while ($menuDialog->hasValidResult() === false); return $menuDialog->getResult(); }
Display a Dialog menu, and retrieve the user selection @param string $listTitle Title of the menu dialog @param string $selectMessage Select option message @param array $menuItems The menu contents @codeCoverageIgnore @since 1.2.0 @return int The index in the menu that was selected
entailment
protected function initialize($color) { return list($this->hue, $this->saturation, $this->lightness) = explode(',', $color); }
@param string $color @return array
entailment
public function setPool($ip, $pool, $createPool = false){ return $this->request('set-pool', array( 'ip' => $ip, 'pool' => $pool, 'create_pool' => $createPool )); }
Moves a dedicated IP to a different pool. @param string $ip a dedicated ip address @param string $pool the name of the new pool to add the dedicated ip to @param bool $createPool whether to create the pool if it does not exist; if false and the pool does not exist, an Unknown_Pool will be thrown. @return array @link https://mandrillapp.com/api/docs/ips.JSON.html#method=set-pool
entailment