sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function hasOneThrough( $referenceModel, $intermediaryModel, $intermediaryCurrentForeignKey = null, $intermediaryReferenceForeignKey = null ) { return (new Relations\HasOneThrough( new Relations\Maps\Intermediary($this, $referenceModel, $intermediaryModel, $intermediaryCurrentForeignKey, $intermediaryReferenceForeignKey) ))->getResult(); }
RelationTrait::hasOneThrough @param string|Model $referenceModel @param string|Model $intermediaryModel @param string|null $intermediaryCurrentForeignKey @param string|null $intermediaryReferenceForeignKey @param string|null $primaryKey @return bool|\O2System\Framework\Models\Sql\DataObjects\Result
entailment
protected function hasMany($referenceModel, $foreignKey = null) { return (new Relations\HasMany( new Relations\Maps\Reference($this, $referenceModel, $foreignKey) ))->getResult(); }
RelationTrait::hasMany Has Many is a one to many relationship, is used to define relationships where a single reference model owns any amount of others relation model. @param string|Model $referenceModel String of table name or AbstractModel @param string|null $foreignKey @return Result|bool
entailment
protected function hasManyThrough( $referenceModel, $intermediaryModel, $intermediaryCurrentForeignKey = null, $intermediaryReferenceForeignKey = null ) { return (new Relations\HasManyThrough( new Relations\Maps\Intermediary($this, $referenceModel, $intermediaryModel, $intermediaryCurrentForeignKey, $intermediaryReferenceForeignKey) ))->getResult(); }
RelationTrait::hasManyThrough @param string|Model $referenceModel @param string|Model $intermediaryModel @param string|null $intermediaryCurrentForeignKey @param string|null $intermediaryReferenceForeignKey @param string|null $primaryKey @return bool|\O2System\Framework\Models\Sql\DataObjects\Result
entailment
public function setText($text) { $this->entity->setEntityName($text); $this->textContent->push($text); return $this; }
Alert::setText @param string $text @return static
entailment
public function render() { if ($this->dismissible) { $this->attributes->addAttributeClass('alert-dismissible'); $button = new Element('button'); $button->entity->setEntityName('button-dismiss'); $button->attributes->addAttribute('type', 'button'); $button->attributes->addAttributeClass('close'); $button->attributes->addAttribute('data-dismiss', 'alert'); $button->attributes->addAttribute('aria-label', 'close'); $icon = new Element('span'); $icon->entity->setEntityName('button-dismiss-icon'); $icon->attributes->addAttribute('aria-hidden', true); $icon->textContent->push('&times;'); $button->childNodes->push($icon); } $output[] = $this->open(); if (isset($button)) { $output[] = $button; } if ($this->heading instanceof Element) { $this->heading->tagName = 'h4'; $this->heading->attributes->addAttributeClass('alert-heading'); $output[] = $this->heading; } if ($this->textContent->count()) { $content = PHP_EOL . implode('', $this->textContent->getArrayCopy()) . PHP_EOL; if ($this->heading instanceof Element) { $content = '<p>' . $content . '</p>'; } $DOMDocument = new \DOMDocument(); libxml_use_internal_errors(true); $DOMDocument->loadHTML($content, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD); libxml_clear_errors(); $links = $DOMDocument->getElementsByTagName('a'); if ($links->length > 0) { foreach ($links as $link) { $class = $link->getAttribute('class'); $class = $class . ' alert-link'; $link->setAttribute('class', trim($class)); } $content = $DOMDocument->saveHTML(); } $output[] = $content; } if ($this->hasChildNodes()) { if ($this->textContent->count() == 0) { $output[] = PHP_EOL; } foreach ($this->childNodes as $childNode) { if ($childNode instanceof Link) { $childNode->attributes->addAttributeClass('alert-link'); } $output[] = $childNode . PHP_EOL; } } $output[] = $this->close(); return implode(PHP_EOL, $output); }
Alert::render @return string
entailment
public function style($style) { if (in_array($style, ['arrow', 'dot', 'bar'])) { $this->attributes->removeAttributeClass('breadcrumb-*'); $this->attributes->addAttributeClass('breadcrumb-' . $style); } return $this; }
Breadcrumb::style @param string $style @return static
entailment
protected function insertRecordSets(array &$sets) { $timestamp = $this->unixTimestamp === true ? strtotime(date('Y-m-d H:i:s')) : date('Y-m-d H:i:s'); if(is_null($this->recordUser)) { if(globals()->offsetExists('account')) { $this->setRecordUser(globals()->account->id); } } if ( ! isset($sets[ 'record_status' ])) { $sets[ 'record_status' ] = $this->recordStatus; } if (empty($this->primaryKeys)) { $primaryKey = isset($this->primaryKey) ? $this->primaryKey : 'id'; if (isset($sets[ $primaryKey ])) { if (empty($sets[ $primaryKey ])) { unset($sets[ $primaryKey ]); } } if (empty($sets[ $primaryKey ])) { if ( ! isset($sets[ 'record_create_user' ])) { $sets[ 'record_create_user' ] = $this->recordUser; } if ( ! isset($sets[ 'record_create_timestamp' ])) { $sets[ 'record_create_timestamp' ] = $timestamp; } elseif ($this->unixTimestamp) { $sets[ 'record_create_timestamp' ] = strtotime($sets[ 'record_create_timestamp' ]); } } } else { foreach ($this->primaryKeys as $primaryKey) { if (empty($sets[ $primaryKey ])) { if ( ! isset($sets[ 'record_create_user' ])) { $sets[ 'record_create_user' ] = $this->recordUser; } if ( ! isset($sets[ 'record_create_timestamp' ])) { $sets[ 'record_create_timestamp' ] = $timestamp; } elseif ($this->unixTimestamp) { $sets[ 'record_create_timestamp' ] = strtotime($sets[ 'record_create_timestamp' ]); } } } } if ( ! isset($sets[ 'record_update_user' ])) { $sets[ 'record_update_user' ] = $this->recordUser; } if ( ! isset($sets[ 'record_update_timestamp' ])) { $sets[ 'record_update_timestamp' ] = $timestamp; } elseif ($this->unixTimestamp) { $sets[ 'record_update_timestamp' ] = strtotime($sets[ 'record_update_timestamp' ]); } if ( ! isset($sets[ 'record_ordering' ]) && $this->recordOrdering === true) { $sets[ 'record_ordering' ] = $this->getRecordOrdering(); } }
RecordTrait::insertRecordSets @param array $sets
entailment
protected function updateRecordSets(array &$sets) { if(is_null($this->recordUser)) { if(globals()->offsetExists('account')) { $this->setRecordUser(globals()->account->id); } } if ( ! isset($sets[ 'record_status' ])) { $sets[ 'record_status' ] = $this->recordStatus; } if ( ! isset($sets[ 'record_update_user' ])) { $sets[ 'record_update_user' ] = $this->recordUser; } $timestamp = $this->unixTimestamp === true ? strtotime(date('Y-m-d H:i:s')) : date('Y-m-d H:i:s'); if ( ! isset($sets[ 'record_update_timestamp' ])) { $sets[ 'record_update_timestamp' ] = $timestamp; } }
RecordTrait::updateRecordSets @param array $sets
entailment
protected function mappingIntermediaryModel($intermediaryModel) { if ($intermediaryModel instanceof Model) { $this->intermediaryModel = $intermediaryModel; $this->intermediaryTable = $intermediaryModel->table; $this->intermediaryPrimaryKey = $this->intermediaryModel->primaryKey; } elseif (class_exists($intermediaryModel)) { $this->intermediaryModel = models($intermediaryModel); $this->intermediaryTable = $this->intermediaryModel->table; $this->intermediaryPrimaryKey = $this->intermediaryModel->primaryKey; } else { $this->intermediaryModel = new class extends Model { }; $this->intermediaryModel->table = $this->referenceTable = $intermediaryModel; } }
Intermediary::mappingIntermediaryModel @param string|\O2System\Framework\Models\Sql\Model $intermediaryModel
entailment
public function getParent($id) { if ($parent = $this->qb ->from($this->table) ->where($this->parentKey, $id) ->get(1)) { if ($parent->count() == 1) { return $parent; } } return false; }
AdjacencyTrait::getParent @param int $id @return bool|\O2System\Framework\Models\Sql\DataObjects\Result\Row
entailment
public function getChilds($idParent) { if ($childs = $this->qb ->from($this->table) ->where($this->parentKey, $idParent) ->get()) { if ($childs->count() > 0) { return $childs; } } return false; }
AdjacencyTrait::getChilds @param int $idParent @return bool|\O2System\Framework\Models\Sql\DataObjects\Result
entailment
public function get(string $key, $default = null) { //get value from memcached $value = $this->memcached->get($key); //check if value was retrived if ($value === false) { return $default; } return $value; }
Fetches a value from the cache. @param string $key The unique key of this item in the cache. @param mixed $default Default value to return if the key does not exist. @return mixed The value of the item from the cache, or $default in case of cache miss.
entailment
public function has(string $key): bool { return ($this->memcached->get($key) !== false) ? true : false; }
Determines whether an item is present in the cache. NOTE: It is recommended that has() is only to be used for cache warming type purposes and not to be used within your live applications operations for get/set, as this method is subject to a race condition where your has() will return true and immediately after, another script can remove it making the state of your app out of date. @param string $key The cache item key. @return bool
entailment
public function execute() { $options = input()->get(); if (empty($options)) { $_GET[ 'switch' ] = 'ON'; $_GET[ 'mode' ] = 'default'; $_GET[ 'lifetime' ] = 300; $_GET[ 'title' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_TITLE')); $_GET[ 'message' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_MESSAGE')); } else { $_GET[ 'mode' ] = 'default'; $_GET[ 'lifetime' ] = 300; $_GET[ 'title' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_TITLE')); $_GET[ 'message' ] = language()->getLine(strtoupper('CLI_MAINTENANCE_MESSAGE')); } parent::execute(); if ($this->optionSwitch === 'ON') { if (cache()->hasItem('maintenance')) { $maintenanceInfo = cache()->getItem('maintenance')->get(); output()->write( (new Format()) ->setContextualClass(Format::DANGER) ->setString(language()->getLine('CLI_MAINTENANCE_ALREADY_STARTED', [ $maintenanceInfo[ 'mode' ], $maintenanceInfo[ 'datetime' ], date('r', strtotime($maintenanceInfo[ 'datetime' ]) + $maintenanceInfo[ 'lifetime' ]), $maintenanceInfo[ 'title' ], $maintenanceInfo[ 'message' ], ])) ->setNewLinesAfter(1) ); } else { output()->write( (new Format()) ->setContextualClass(Format::WARNING) ->setString(language()->getLine('CLI_MAINTENANCE_STARTED', [ $datetime = date('r'), $this->optionLifetime, $this->optionMode, $this->optionTitle, $this->optionMessage, ])) ->setNewLinesAfter(1) ); cache()->save(new Item('maintenance', [ 'datetime' => $datetime, 'lifetime' => $this->optionLifetime, 'mode' => $this->optionMode, 'title' => $this->optionTitle, 'message' => $this->optionMessage, ], $this->optionLifetime)); } } elseif ($this->optionSwitch === 'OFF') { if (cache()->hasItem('maintenance')) { output()->write( (new Format()) ->setContextualClass(Format::DANGER) ->setString(language()->getLine('CLI_MAINTENANCE_STOPPED', [ $this->optionMode, date('r'), ])) ->setNewLinesAfter(1) ); cache()->deleteItem('maintenance'); } else { output()->write( (new Format()) ->setContextualClass(Format::DANGER) ->setString(language()->getLine('CLI_MAINTENANCE_INACTIVE')) ->setNewLinesAfter(1) ); } } }
Maintenance::execute @throws \Exception
entailment
protected static function discover_channel($channel_name) { $cfg = PEAR2\Pyrus\Config::current(); $registry = $cfg->channelregistry; if (isset($registry[$channel_name])) return; // already registered $channel_file = new PEAR2\Pyrus\ChannelFile('http://'.$channel_name.'/channel.xml', false ,true); $registry[] = $channel_file; }
helpers
entailment
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { $this->config = $this->sessionManager->getConfig(); $this->sessionHandled = true; $isSessionAvailable = $request instanceof Request && $this->sessionConfigured(); // If a session driver has been configured, we will need to start the session here // so that the data is ready for an application. Note that the Laravel sessions // do not make use of PHP "native" sessions in any way since they are crappy. if ($isSessionAvailable) { $this->sessionManager->setSession($session = $this->startSession($request)); // TODO move collect garbage to timer $this->collectGarbage($session); } $response = $handler->handle($request); // Again, if the session has been configured we will need to close out the session // so that the attributes may be persisted to some storage medium. We will also // add the session identifier cookie to the application response headers now. if ($isSessionAvailable) { $this->storeCurrentUrl($request, $session); $response = $this->addCookieToResponse($request, $response, $session); // Save session after response // TODO use coroutine task to save the session data $this->save(); } return $response; }
Process an incoming server request and return a response, optionally delegating response creation to a handler. @param \Psr\Http\Message\ServerRequestInterface $request @param \Psr\Http\Server\RequestHandlerInterface $handler @return \Psr\Http\Message\ResponseInterface @throws \RuntimeException @throws \InvalidArgumentException
entailment
protected function storeCurrentUrl(Request $request, SessionInterface $session) { if ($request->getMethod() === 'GET') { $session->setPreviousUrl($request->fullUrl()); } }
Store the current URL for the request if necessary. @param Request $request @param SessionInterface $session
entailment
private function addCookieToResponse(Request $request, Response $response, SessionInterface $session): Response { $uri = $request->getUri(); $path = '/'; $domain = $uri->getHost(); $secure = strtolower($uri->getScheme()) === 'https'; $httpOnly = true; return $response->withCookie(new Cookie($session->getName(), $session->getId(), $this->getCookieExpirationDate(), $path, $domain, $secure, $httpOnly)); }
Add the session cookie to the response· @param Request $request @param Response $response @param SessionInterface $session @return Response @throws \InvalidArgumentException
entailment
protected function getCookieExpirationDate() { if (!empty($this->config['expire_on_close'])) { $expirationDate = 0; } else { $expirationDate = Carbon::now()->addMinutes(5 * 60); } return $expirationDate; }
Get the session lifetime in seconds. @return \DateTimeInterface|int
entailment
private function replaceExtractedValuesByLoadedValues(SearchResult $searchResult) { $valueObjectMapById = $this->loadValueObjectMapById($searchResult); foreach ($searchResult->searchHits as $index => $searchHit) { $id = $this->getValueObjectId($searchHit->valueObject); if (array_key_exists($id, $valueObjectMapById)) { $searchHit->valueObject = $valueObjectMapById[$id]; } else { unset($searchResult->searchHits[$index]); --$searchResult->totalCount; } } return $searchResult; }
@param \eZ\Publish\API\Repository\Values\Content\Search\SearchResult $searchResult @return \eZ\Publish\API\Repository\Values\Content\Search\SearchResult
entailment
private function loadValueObjectMapById(SearchResult $searchResult) { if (!isset($searchResult->searchHits[0])) { return []; } $idList = $this->extractIdList($searchResult); if ($searchResult->searchHits[0]->valueObject instanceof ContentInfo) { return $this->loadContentInfoMapByIdList($idList); } return $this->loadLocationMapByIdList($idList); }
@param \eZ\Publish\API\Repository\Values\Content\Search\SearchResult $searchResult @return array|\eZ\Publish\SPI\Persistence\Content\ContentInfo[]
entailment
private function loadLocationMapByIdList(array $locationIdList) { if (method_exists($this->locationHandler, 'loadList')) { return $this->locationHandler->loadList($locationIdList); } $locationList = []; foreach ($locationIdList as $locationId) { try { $locationList[$locationId] = $this->locationHandler->load($locationId); } catch (NotFoundException $e) { // do nothing } } return $locationList; }
@param array $locationIdList @return array|\eZ\Publish\SPI\Persistence\Content\ContentInfo[]
entailment
public function extractHit($hit) { if ($hit->document_type_id === 'content') { return $this->contentHandler->loadContentInfo($hit->content_id_id); } if ($hit->document_type_id === 'location') { return $this->locationHandler->load($hit->location_id_id); } throw new RuntimeException( "Extracting documents of type '{$hit->document_type_id}' is not handled." ); }
{@inheritdoc} @throws \RuntimeException If search $hit could not be handled @throws \eZ\Publish\API\Repository\Exceptions\NotFoundException
entailment
public function load(array $configs, ContainerBuilder $container) { $activatedBundlesMap = $container->getParameter('kernel.bundles'); $loader = new Loader\YamlFileLoader( $container, new FileLocator(__DIR__ . '/../../lib/Resources/config/') ); if (array_key_exists('EzPublishLegacySearchEngineBundle', $activatedBundlesMap)) { $loader->load('search/legacy.yml'); } if (array_key_exists('EzSystemsEzPlatformSolrSearchEngineBundle', $activatedBundlesMap)) { $loader->load('search/solr.yml'); } $loader->load('search/common.yml'); $loader->load('persistence.yml'); $this->processExtensionConfiguration($configs, $container); }
@param array $configs @param \Symfony\Component\DependencyInjection\ContainerBuilder $container @throws \Exception
entailment
public function updateAverageNote() { $commentTableName = $this->em->getClassMetadata($this->commentManager->getClass())->table['name']; $threadTableName = $this->em->getClassMetadata($this->getClass())->table['name']; $this->em->getConnection()->beginTransaction(); $this->em->getConnection()->query(sprintf('UPDATE %s t SET t.average_note = 0', $threadTableName)); $this->em->getConnection()->query(sprintf( 'UPDATE %s t, (SELECT c.thread_id, avg(c.note) as avg_note FROM %s as c WHERE c.private <> 1 GROUP BY c.thread_id) as comments_note SET t.average_note = comments_note.avg_note WHERE t.id = comments_note.thread_id AND t.is_commentable <> 0', $threadTableName, $commentTableName)); $this->em->getConnection()->commit(); }
Updates the threads average note from comments notes.
entailment
private function format_trace_flags() { $flags = array(); if (!$this->already_invoked) { $flags[] = 'first_time'; } if (!$this->is_needed()) { $flags[] = 'not_needed'; } return (count($flags)) ? '('.join(', ', $flags).')' : ''; }
Format the trace flags for display.
entailment
public static function get_mini_task_name($task_name) { $is_method_task = strpos($task_name, '::'); return ((false !== $is_method_task) ? substr($task_name, $is_method_task + 2) : $task_name); }
removes classname and colons, if those are present abc => abc abc::def => def @param string $task_name @return string
entailment
public static function abbrev(array $options) { $abbrevs = array(); $table = array(); foreach ($options as $option) { $short_option = pakeTask::get_mini_task_name($option); for ($len = (strlen($short_option)); $len > 0; --$len) { $abbrev = substr($short_option, 0, $len); if (!array_key_exists($abbrev, $table)) $table[$abbrev] = 1; else ++$table[$abbrev]; $seen = $table[$abbrev]; if ($seen == 1) { // we're the first word so far to have this abbreviation. $abbrevs[$abbrev] = array($option); } elseif ($seen == 2) { // we're the second word to have this abbreviation, so we can't use it. //unset($abbrevs[$abbrev]); $abbrevs[$abbrev][] = $option; } else { // we're the third word to have this abbreviation, so skip to the next word. continue; } } } // Non-abbreviations always get entered, even if they aren't unique foreach ($options as $option) { $abbrevs[$option] = array($option); } return $abbrevs; }
gets array of words as input and returns array, where shortened words are keys and arrays of corresponding full-words are values. For example: input: array('abc', 'abd') output: array('a' => array('abc', 'abd'), 'ab' => array('abc', 'abd'), 'abc' => array('abc'), 'abd' => array('abd')) @param array $options @return array @author Jimi Dini
entailment
public function run(OutputInterface $output) { $this->output = $output; if (get_class($this) === ParallelTask::class) { $this->output->writeln( ['', sprintf(' <info>[%s]</info> - <comment>Starting</comment>', $this->getName()), ''] ); } $output->writeln("<fg=blue>==============================\n</fg=blue>"); /** @type Process[] $processes */ $processes = []; foreach ($this->resolveCommands() as $command) { $processes[] = $this->runCommand($command); } $this->waitForCommandsToFinish($processes); /** @type DebugFormatterHelper $debugFormatter */ $debugFormatter = $this->getHelperSet()->get('debug_formatter'); foreach ($processes as $process) { $output->writeln( [ "", $debugFormatter->stop( spl_object_hash($process), $process->getCommandLine(), $process->isSuccessful() ) ] ); if (null !== $dispatcher = $this->getEventDispatcher()) { $event = new PostExecuteEvent($this, $process); $dispatcher->dispatch(Event::POST_EXECUTE, $event); } if (!in_array($process->getExitCode(), $this->getParameter('successCodes'))) { throw new TaskRuntimeException($this->getName(), $process->getErrorOutput()); } } $output->writeln("<fg=blue>==============================\n</fg=blue>"); }
{@inheritDoc}
entailment
private function runCommand(Process $process) { $output = $this->output; /** @type DebugFormatterHelper $debugFormatter */ $debugFormatter = $this->getHelperSet()->get('debug_formatter'); if (null !== $dispatcher = $this->getEventDispatcher()) { $event = new PreExecuteEvent($this, $process); $dispatcher->dispatch(Event::PRE_EXECUTE, $event); if ($event->isPropagationStopped()) { $output->writeln( ['', sprintf(' <info>[%s]</info> - <comment>Stopped</comment>', $this->getName()), ''] ); return true; } } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE || $this->getParameter('dry_run')) { $output->writeln(' // '.$process->getCommandLine()); } if ($this->getParameter('dry_run')) { return true; } if ($this->hasParameter('cwd')) { $process->setWorkingDirectory($this->getParameter('cwd')); } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERY_VERBOSE) { $output->writeln( sprintf( ' // Setting timeout for %d seconds.', $this->getParameter('timeout') ) ); } $process->setTimeout($this->getParameter('timeout') !== 0 ? $this->getParameter('timeout') : null); if ($this->hasParameter('output')) { $append = $this->hasParameter('append') && $this->getParameter('append') ? 'a' : 'w'; $stream = fopen($this->getParameter('output'), $append); $output = new StreamOutput($stream, StreamOutput::VERBOSITY_NORMAL, true); } $output->writeln( $debugFormatter->start( spl_object_hash($process), $process->getCommandLine() ) ); $process->start(); return $process; }
@param Process $process @return bool @throws TaskRuntimeException @throws \Bldr\Exception\BldrException @throws \Bldr\Exception\ParameterNotFoundException @throws \Bldr\Exception\RequiredParameterException
entailment
private function resolveCommands() { $commands = []; foreach ($this->getParameter('commands') as $cmd) { $commands[] = is_array($cmd) ? (new ProcessBuilder($cmd))->getProcess() : new Process($cmd); } return $commands; }
@return array|Process[] @throws \Bldr\Exception\ParameterNotFoundException @throws \Bldr\Exception\RequiredParameterException
entailment
private function read_php_argv() { global $argv; if (!is_array($argv)) { if (!@is_array($_SERVER['argv'])) { if (!@is_array($GLOBALS['HTTP_SERVER_VARS']['argv'])) { throw new pakeException("pakeGetopt: Could not read cmd args (register_argc_argv=Off?)."); } return $GLOBALS['HTTP_SERVER_VARS']['argv']; } return $_SERVER['argv']; } return $argv; }
Function from PEAR::Console_Getopt. Safely read the $argv PHP array across different PHP configurations. Will take care on register_globals and register_argc_argv ini directives @access public @return mixed the $argv PHP array
entailment
protected function doRequest($method, $apiMethod, array $data = []) { $url = $this->config['endpoint'] . $apiMethod; $data = $this->mergeData($this->createAuthData(), $data); $response = $this->getGuzzleClient()->request($method, $url, ['json' => $data]); $responseContent = \GuzzleHttp\json_decode($response->getBody()); if (!property_exists($responseContent, 'success') || !$responseContent->success) { throw new InvalidRequestException($method, $url, $data, $response); } return $responseContent; }
Send request to SalesManago API. @param string $method HTTP Method @param string $apiMethod API Method @param array $data Request data @return array
entailment
protected function createAuthData() { return [ 'clientId' => $this->config['client_id'], 'apiKey' => $this->config['api_key'], 'requestTime' => time(), 'sha' => sha1($this->config['api_key'] . $this->config['client_id'] . $this->config['api_secret']) ]; }
Returns an array of authentication data. @return array
entailment
private function mergeData(array $base, array $replacements) { return array_filter(array_merge($base, $replacements), function($value) { return $value !== null; }); }
Merge data and removing null values. @param array $base The array in which elements are replaced @param array $replacements The array from which elements will be extracted @return array
entailment
public function set($domain, $key, $value = null) { $this->validateDomain($domain); if (null !== $value) { $this->profile[$domain][$key] = $value; } else { $this->profile[$domain] = $key; } }
Set a domain configuration. @param string $domain @param $key @param array|null $value
entailment
public function get($domain, $key = null) { $this->validateDomain($domain); if (null === $key) { return new Config($this->profile[$domain]); } if (!isset($this->profile[$domain][$key])) { throw new \InvalidArgumentException(sprintf( 'Unknown key "%s" for profile domain "%s"', $key, $domain )); } return $this->profile[$domain][$key]; }
Get a domain configuration. @param string $domain @param string $key @throws \InvalidArgumentException @return array
entailment
public function getBySku(SKU $sku) : Product { if (!array_key_exists((string) $sku, $this->products)) { throw ProductNotFoundException::bySku($sku); } return $this->products[(string) $sku]; }
@param SKU $sku @return Product @throws ProductNotFoundException
entailment
public function visit(Criterion $criterion, CriterionVisitor $subVisitor = null) { $fieldNames = $this->getFieldNames($criterion); if (empty($fieldNames)) { throw new InvalidArgumentException( '$criterion->target', "No searchable fields found for the given criterion target '{$criterion->target}'." ); } $queries = []; foreach ($fieldNames as $fieldName) { $match = $criterion->value[0] === IsFieldEmptyCriterion::IS_EMPTY ? 'true' : 'false'; $queries[] = "{$fieldName}:{$match}"; } return '(' . implode(' OR ', $queries) . ')'; }
{@inheritdoc} @throws \eZ\Publish\Core\Base\Exceptions\InvalidArgumentException
entailment
protected function getFieldNames(Criterion $criterion) { $fieldDefinitionIdentifier = $criterion->target; $fieldMap = $this->contentTypeHandler->getSearchableFieldMap(); $fieldNames = []; foreach ($fieldMap as $contentTypeIdentifier => $fieldIdentifierMap) { if (!isset($fieldIdentifierMap[$fieldDefinitionIdentifier])) { continue; } $fieldNames[] = $this->fieldNameGenerator->getTypedName( $this->fieldNameGenerator->getName( 'is_empty', $fieldDefinitionIdentifier, $contentTypeIdentifier ), new BooleanField() ); } return $fieldNames; }
Return all field names for the given criterion. @param \eZ\Publish\API\Repository\Values\Content\Query\Criterion $criterion @return string[]
entailment
public function serialize($value) : string { if (!is_numeric($value)) { throw InvalidValueException::valueDoesNotMatchType($this, $value); } return (string) (float) $value; }
@param $value @return string @throws InvalidValueException
entailment
public static function coming_events($from = false) { $time = ($from ? strtotime($from) : mktime(0, 0, 0, date('m'), date('d'), date('Y'))); $sql = "(StartDateTime >= '".date('Y-m-d', $time)." 00:00:00')"; $events = PublicEvent::get()->where($sql); return $events; }
Get all coming public events
entailment
public static function coming_events_limited($from=false, $limit=30) { $events = self::coming_events($from)->limit($limit); return $events; }
Get all coming public events - with optional limit
entailment
public static function events_for_month($month) { $nextMonth = strtotime('last day of this month', strtotime($month)); $currMonthStr = date('Y-m-d', strtotime($month)); $nextMonthStr = date('Y-m-d', $nextMonth); $sql = "(StartDateTime BETWEEN '$currMonthStr' AND '$nextMonthStr')" . " OR " . "(EndDateTime BETWEEN '$currMonthStr' AND '$nextMonthStr')"; $events = PublicEvent::get() ->where($sql); return $events; }
Get events for a specific month Format: 2013-07 @param type $month
entailment
public static function add_preview_params($link,$object) { // Pass through if not logged in if(!Member::currentUserID()) { return $link; } $modifiedLink = ''; $request = Controller::curr()->getRequest(); if ($request && $request->getVar('CMSPreview')) { // Preserve the preview param for further links $modifiedLink = HTTP::setGetVar('CMSPreview', 1, $link); // Quick fix - multiple uses of setGetVar method double escape the ampersands $modifiedLink = str_replace('&amp;','&',$modifiedLink); // Add SubsiteID, if applicable if (!empty($object->SubsiteID)) { $modifiedLink = HTTP::setGetVar('SubsiteID', $object->SubsiteID, $modifiedLink); // Quick fix - multiple uses of setGetVar method double escape the ampersands $modifiedLink = str_replace('&amp;','&',$modifiedLink); } } return ($modifiedLink) ? $modifiedLink : $link; }
If applicable, adds preview parameters. ie. CMSPreview and SubsiteID. @param type $link @return type
entailment
public function assemble(array $config, ContainerBuilder $container) { $this->addTask( 'bldr_watch.watch', 'Bldr\Block\Watch\Task\WatchTask', [ new Reference('bldr.registry.job'), [ 'profiles' => $container->getParameter('profiles'), 'jobs' => $container->getParameter('jobs') ] ] ); }
{@inheritDoc}
entailment
protected function assemble() { $assembled = $this->command; foreach ($this->arguments as $key => $value) { if (is_int($key) && false === strpos((string) $key, '-')) { $assembled .= ' '.escapeshellarg($value); continue; } $assembled .= ' '.escapeshellarg($key); $assembled .= ' '.escapeshellarg($value); } return $assembled; }
Assemble command and arguments. @return string
entailment
public function execute(Control $control, Context $context) { $context->command = $this->assemble(); $context->outputTail = exec(sprintf('(%s)2>&1', $context->command), $outputLines, $returnValue); $context->outputString = implode(PHP_EOL, $outputLines); $context->outputLines = $outputLines; $context->returnValue = $returnValue; if ($returnValue > 0) { throw new RuntimeException($context->outputTail); } }
{@inheritdoc}
entailment
public function assemble(array $config, SymfonyContainerBuilder $container) { $this->addTaskOptions($config, $this->originalConfiguration); $this->setParameter('name', $config['name']); $this->setParameter('description', $config['description']); $this->setParameter('profiles', $config['profiles']); $this->setParameter('jobs', $config['jobs']); $this->addService('bldr.dispatcher', 'Symfony\Component\EventDispatcher\EventDispatcher'); $this->addService('bldr.registry.job', 'Bldr\Registry\JobRegistry'); }
{@inheritDoc}
entailment
public function augmentSQL(SQLQuery &$query) { if (Subsite::$disable_subsite_filter) { return; } // Filter by subsite $ids = array((int) Subsite::currentSubsiteID()); // If configured to treat subsite 0 as global, include ID 0. if (Config::inst()->get('LeftAndMain', 'treats_subsite_0_as_global')) { $ids[] = 0; } $ids = implode(',', $ids); // The foreach is an ugly way of getting the first key foreach ($query->getFrom() as $tableName => $info) { $where = "\"$tableName\".\"SubsiteID\" IN ($ids)"; $query->addWhere($where); break; } }
Update any requests to limit the results to the current site
entailment
public function process(ContainerBuilder $container) { $useLoadingSearchResultExtractor = $container->getParameter( 'netgen_ez_platform_search_extra.use_loading_search_result_extractor' ); if ($useLoadingSearchResultExtractor === true) { return; } $serviceId = 'netgen.search.solr.result_extractor.native_override'; $decoratedServiceId = 'ezpublish.search.solr.result_extractor.native'; $container ->register($serviceId, NativeResultExtractor::class) ->setDecoratedService($decoratedServiceId) ->setArguments([ new Reference($serviceId . '.inner'), new Reference('ezpublish.search.solr.query.content.facet_builder_visitor.aggregate'), new Reference('ezpublish.search.solr.gateway.endpoint_registry'), ]); }
{@inheritdoc} @throws \Exception
entailment
public static function createEmbeddedShell(SessionInterface $session) { $container = new Container(self::MODE_EMBEDDED_SHELL); $container->get('phpcr.session_manager')->setSession(new PhpcrSession($session)); $application = $container->get('application'); return new Shell($application); }
Create a new embedded shell. @param SessionInterface $session @return Shell
entailment
public static function createEmbeddedApplication(SessionInterface $session) { $container = new Container(self::MODE_EMBEDDED_COMMAND); $container->get('phpcr.session_manager')->setSession(new PhpcrSession($session)); $application = $container->get('application'); return $application; }
Create a new (non-interactive) embedded application (e.g. for running single commands). @param SessionInterface $session @return EmbeddedApplication
entailment
public function handle(RemoveFromCart $command) { $cart = $this->carts->getById(new CartId($command->cartId())); $cart->remove(new SKU($command->sku())); }
@param RemoveFromCart $command @throws \Exception
entailment
public function map(string $schema, Table $table, string $name, FieldDefinition $definition) { foreach ($this->mapping as $mapping) { if ($mapping->maps($definition->type())) { $mapping->map($schema, $table, $name, $definition); return; } } throw DoctrineStorageException::unableToMapType($definition->type()); }
@param string $schema @param Table $table @param string $name @param FieldDefinition $definition @throws DoctrineStorageException
entailment
private function replaceColumnOperands($functionMap, RowInterface $row) { foreach ($this->arguments as $key => $value) { if ($value instanceof ColumnOperand) { $this->arguments[$key] = $row->getNode($value->getSelectorName())->getPropertyValue($value->getPropertyName()); } if ($value instanceof self) { $this->arguments[$key] = $value->execute($functionMap, $row, $value); } } }
Replace the Operand objects with their evaluations. @param array Array of function closures @param RowInterface $row
entailment
public function execute($functionMap, $row) { $this->replaceColumnOperands($functionMap, $row); $functionName = $this->getFunctionName(); if (!isset($functionMap[$functionName])) { throw new InvalidQueryException(sprintf('Unknown function "%s", known functions are "%s"', $functionName, implode(', ', array_keys($functionMap)) )); } $callable = $functionMap[$functionName]; $args = $this->getArguments(); array_unshift($args, $row); array_unshift($args, $this); $value = call_user_func_array($callable, $args); return $value; }
Evaluate the result of the function. @param array Array of function closures @param RowInterface $row
entailment
public function validateScalarArray($array) { if (!is_array($array)) { throw new \InvalidArgumentException(sprintf( 'Expected array value, got: %s', var_export($array, true) )); } foreach ($array as $key => $value) { if (false == is_scalar($value)) { throw new \InvalidArgumentException(sprintf( 'Cannot use an array as a value in a multivalue property. Value was: %s', var_export($array, true) )); } } }
Used as callback for closure functions. @param array Array of values which must be scalars @throws InvalidArgumentException
entailment
public function register() { $adapter = $this->getContainer()->get(AdapterInterface::class); $this->getContainer()->share('repo.user', new UsersRepository($adapter)); $this->getContainer()->share('repo.media', new MediaRepository($adapter)); $this->getContainer()->share('repo.comment', new CommentsRepository($adapter)); $this->getContainer()->share('repo.like', new LikesRepository($adapter)); $this->getContainer()->share('repo.tag', new TagsRepository($adapter)); $this->getContainer()->share('repo.location', new LocationsRepository($adapter)); }
Use the register method to register items with the container via the protected ``$this->container`` property or the ``getContainer`` method from the ``ContainerAwareTrait``. @return void
entailment
public function register($name, Closure $callback) { $this->checkCallbackName($name); $this->callbacks[$name] = $callback; return $this; }
Register a breadcrumb domain. @param string $name @param \Closure $callback @return self
entailment
public function render($name = null, ...$params) { return new HtmlString( view($this->getView(), [ 'breadcrumbs' => $this->generate($name, $params) ])->render() ); }
Render breadcrumbs items. @param string|null $name @param array $params @return \Illuminate\Support\HtmlString
entailment
public function generate($name, ...$params) { return (new Builder($this->callbacks)) ->call($name, $params) ->toArray(); }
Generate the breadcrumbs. @param string $name @param array $params @return array
entailment
private function checkTemplate($template) { if ( ! is_string($template)) { $type = gettype($template); throw new Exceptions\InvalidTypeException( "The default template name must be a string, $type given." ); } $template = strtolower(trim($template)); if ( ! array_key_exists($template, $this->supported)) { throw new Exceptions\InvalidTemplateException( "The template [$template] is not supported." ); } }
Check Template. @param string $template @throws Exceptions\InvalidTemplateException @throws Exceptions\InvalidTypeException
entailment
private function checkCallbackName(&$name) { if ( ! is_string($name)) { $type = gettype($name); throw new Exceptions\InvalidTypeException( "The callback name value must be a string, $type given." ); } $name = strtolower(trim($name)); }
Check Name. @param string $name @throws Exceptions\InvalidTypeException
entailment
public function getById(string $cartId): Checkout { $qb = $this->connection->createQueryBuilder(); $qb->select( 'id', 'billing_address_name', 'billing_address_street', 'billing_address_post_code', 'billing_address_city', 'billing_address_country_iso2code', 'shipping_address_name', 'shipping_address_street', 'shipping_address_post_code', 'shipping_address_city', 'shipping_address_country_iso2code' ) ->from('dumplie_customer_checkout') ->where('id = :id') ->setParameter('id', $cartId); $checkoutData = $this->connection->fetchAssoc($qb->getSQL(), $qb->getParameters()); if (empty($checkoutData)) { throw QueryException::cartNotFound($cartId); } return new Checkout( new CartId($cartId), new Address( $checkoutData['billing_address_name'], $checkoutData['billing_address_street'], $checkoutData['billing_address_post_code'], $checkoutData['billing_address_city'], $checkoutData['billing_address_country_iso2code'] ), new Address( $checkoutData['shipping_address_name'], $checkoutData['shipping_address_street'], $checkoutData['shipping_address_post_code'], $checkoutData['shipping_address_city'], $checkoutData['shipping_address_country_iso2code'] ) ); }
@param string $cartId @throws QueryException @return Checkout
entailment
private function getItemBySku(string $sku, int $quantity): CartItem { $qb = $this->connection->createQueryBuilder(); $qb->select('*') ->from('dumplie_inventory_product') ->where('sku = :sku') ->setParameter('sku', $sku); $itemData = $this->connection->fetchAssoc($qb->getSQL(), $qb->getParameters()); if (empty($itemData)) { throw QueryException::cartItemNotFound($sku); } return new CartItem( $itemData['sku'], $quantity, $itemData['price_amount'] / $itemData['price_precision'], $itemData['price_currency'], $this->mao->getBy([Metadata::FIELD_SKU => $itemData['sku']]) ); }
@param string $sku @param int $quantity @return CartItem @throws QueryException
entailment
public function doesCartWithIdExist(string $cartId): bool { $qb = $this->connection->createQueryBuilder(); $qb->select('COUNT(*)') ->from('dumplie_customer_cart') ->where('id = :id') ->setParameter('id', $cartId) ->getSQL(); return (bool)$this->connection->fetchColumn($qb->getSQL(), $qb->getParameters()); }
@param string $cartId @return bool
entailment
public function index() { $s = CalendarConfig::subpackage_settings('pagetypes'); $indexSetting = $s['calendarpage']['index']; if ($indexSetting == 'eventlist') { //return $this->returnTemplate(); return $this; } elseif ($indexSetting == 'calendarview') { return $this->calendarview()->renderWith(array('CalendarPage_calendarview', 'Page')); } }
Coming events
entailment
public function calendarview() { $s = CalendarConfig::subpackage_settings('pagetypes'); //Debug::dump($s); if (isset($s['calendarpage']['calendarview']) && $s['calendarpage']['calendarview']) { Requirements::javascript('calendar/thirdparty/fullcalendar/2.9.1/fullcalendar/lib/moment.min.js'); Requirements::javascript('calendar/thirdparty/fullcalendar/2.9.1/fullcalendar/fullcalendar.min.js'); Requirements::css('calendar/thirdparty/fullcalendar/2.9.1/fullcalendar/fullcalendar.min.css'); Requirements::css('calendar/thirdparty/fullcalendar/2.9.1/fullcalendar/fullcalendar.print.css', 'print'); //xdate - needed for some custom code - e.g. shading Requirements::javascript('calendar/thirdparty/xdate/xdate.js'); Requirements::javascript('calendar/javascript/fullcalendar/PublicFullcalendarView.js'); $url = CalendarHelper::add_preview_params($this->Link(),$this->data()); $fullcalendarjs = $s['calendarpage']['fullcalendar_js_settings']; $controllerUrl = CalendarHelper::add_preview_params($s['calendarpage']['controllerUrl'],$this->data()); //shaded events $shadedEvents = 'false'; $sC = CalendarConfig::subpackage_settings('calendars'); if ($sC['shading']) { $shadedEvents = 'true'; } //Calendar initialization (and possibility for later configuration options) Requirements::customScript(" (function($) { $(function () { //Initializing fullcalendar var cal = new PublicFullcalendarView($('#calendar'), '$url', { controllerUrl: '$controllerUrl', fullcalendar: { $fullcalendarjs }, shadedevents: $shadedEvents }); }); })(jQuery); "); return $this; } else { return $this->httpError(404); } }
Calendar View Renders the fullcalendar
entailment
public function detail($req) { $event = Event::get()->byID($req->param('ID')); if (!$event) { return $this->httpError(404); } return array( 'Event' => $event, ); }
Displays details of an event @param $req @return array
entailment
public function Events() { $action = $this->request->param('Action'); //Debug::dump($this->request->params()); //Normal & Registerable events $s = CalendarConfig::subpackage_settings('pagetypes'); $indexSetting = $s['calendarpage']['index']; if ($action == 'eventregistration' || $action == 'eventlist' || ($action == '' && $indexSetting == 'eventlist') ) { $events = CalendarHelper::events_for_month($this->CurrentMonth()); if ($action == 'eventregistration') { $events = $events ->filter('Registerable', 1); } return $events; } //Search if ($action == 'search') { $query = $this->SearchQuery(); $query = strtolower(addslashes($query)); //Debug::dump($query); $qarr = preg_split('/[ +]/', $query); $filter = ''; $first = true; foreach ($qarr as $qitem) { if (!$first) { $filter .= " AND "; } $filter .= " ( Title LIKE '%$qitem%' OR Details LIKE '%$qitem%' )"; $first = false; } //Debug::dump($filter); $events = CalendarHelper::all_events() ->where($filter); return $events; } //TODO below doesn't need to be that complicated... // $events = null; // if ($action == 'past') { // $events = CalendarHelper::past_events(); // } else { // if ($this->CurrentCategoryID()) { // $events = PublicEventCategory::get() // ->ByID($this->CurrentCategoryID()) // ->ComingEvents($this->CurrentDisplayDate()); // } else { // $events = CalendarHelper::coming_events($this->CurrentDisplayDate()); // } // } // // if ($this->CurrentCalendarID()) { // $events = $events->filter(array( // 'CalendarID' => $this->CurrentCalendarID() // )); // } // // $list = new PaginatedList($events, $this->request); // $list->setPageLength(10); // // return $list; }
Event list for "eventlist" mode @return type
entailment
public function CurrentCalendar() { $url = Convert::raw2url($this->request->param('ID')); $cal = PublicCalendar::get() ->filter('URLSegment', $url) ->First(); return $cal; }
Renders the current calendar, if a calenar link has been supplied via the url
entailment
public function run(OutputInterface $output) { foreach ($this->resolveFiles() as $file) { if ($this->fileSystem->exists($file)) { if (!$this->continueOnError()) { throw new TaskRuntimeException($this->getName(), "File `$file` already exist."); } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE) { $output->writeln( [ "", sprintf( "<error> [Error] Task: %s \n Message: %s</error>", $this->getName(), "File `$file` already exist." ), "" ] ); } continue; } $this->fileSystem->mkdir([$file]); $output->writeln( ["", sprintf(" <info>[%s]</info> - <comment>Creating %s</comment>", $this->getName(), $file), ""] ); } }
{@inheritdoc}
entailment
public function message($message, $type = 'alert') { $messages = []; if(!empty($message)) { // It loooked if exist any old messages if (!empty(session('noty.messages'))) { $messages = session('noty.messages'); } // Add last new message if it's not in array if(!collect(array_flatten($messages))->contains($message)){ $messages[] = [ 'text' => $message, 'type' => $type, ]; } } $this->session->flash('noty.messages', $messages); $this->session->flash('noty.config', $this->config); if(in_array($type, ['success', 'error', 'warning', 'information', 'notification'])) { $this->session->flash('noty.config.type', $type); } return $this; }
Flash a message. @param string $message @param string $type @return $this
entailment
public function register() { $this->mergeConfigFrom(__DIR__.'/../../config/laravel-noty.php', 'laravel-noty'); $this->app->bind(NotySessionStore::class); $this->app->singleton('noty', function () { return $this->app->make(NotyNotifier::class); }); }
Register bindings in the container. @return void
entailment
public function boot() { collect(glob(__DIR__ . '/Database/Schema/macros/*.php')) ->each(function($path) { require $path; }); /* A little hack to have Builder::hasMacro */ \Illuminate\Database\Eloquent\Builder::macro('hasMacro', function($name) { return isset(static::$macros[$name]); }); collect(glob(__DIR__ . '/Models/macros/*.php')) ->each(function($path) { require $path; }); }
Bootstrap the application services.
entailment
public function hasDescriptor($descriptor, $value = null) { $this->loadDescriptors(); $exists = array_key_exists($descriptor, $this->descriptors); if (false === $exists) { return false; } if (null === $value) { return true; } $descriptorValue = $this->descriptors[$descriptor]; // normalize if ($descriptorValue === 'true') { $descriptorValue = true; } if ($descriptorValue === 'false') { $descriptorValue = false; } if ($value === $descriptorValue) { return true; } return false; }
Return true if the sessionManager supports the given descriptor which relates to a descriptor key. @param string $descriptor
entailment
public function getMedia($id = 'self', $count = null, $minId = null, $maxId = null) { $params = ['query' => [ 'count' => $count, 'min_id' => $minId, 'max_id' => $maxId, ]]; return $this->client->request( 'GET', "users/$id/media/recent", $params ); }
Get the most recent media published by a user. @param string $id The ID of the user. Default is ``self`` @param int|null $count Count of media to return @param int|null $minId Return media later than this min_id @param int|null $maxId Return media earlier than this max_id @return Response @link https://instagram.com/developer/endpoints/users/#get_users_media_recent
entailment
public function getLikedMedia($count = null, $maxLikeId = null) { $params = ['query' => [ 'count' => $count, 'max_like_id' => $maxLikeId ]]; return $this->client->request( 'GET', 'users/self/media/liked', $params ); }
Get the list of recent media liked by the owner of the access token. @param int|null $count Count of media to return @param int|null $maxLikeId Return media liked before this id @return Response @link https://instagram.com/developer/endpoints/users/#get_users_feed_liked
entailment
public function search($query, $count = null) { $params = ['query' => [ 'q' => $query, 'count' => $count, ]]; return $this->client->request( 'GET', 'users/search', $params ); }
Get a list of users matching the query. @param string $query A query string to search for @param int|null $count Number of users to return @return Response @link https://instagram.com/developer/endpoints/users/#get_users_search
entailment
public function find($username) { $response = $this->search($username); foreach ($response->get() as $user) { if ($username === $user['username']) { return $this->get($user['id']); } } return null; }
Searches for and returns a single user's information. If no results are found, ``null`` is returned. @param string $username A username to search for @return Response|null
entailment
protected function bindDefaultTriggers() { $this->handlers[self::EVENT_INIT] = $this->fluentCallback([$this, 'handleInit']); $this->handlers[self::EVENT_FORK] = $this->fluentCallback([$this, 'handleFork']); $this->handlers[self::EVENT_START] = $this->fluentCallback([$this, 'handleStart']); }
Binds some callbacks as default triggers.
entailment
public function bind($event, callable $handler) { if (in_array($event, [self::EVENT_INIT, self::EVENT_FORK, self::EVENT_START])) { throw new InvalidArgumentException('You can not bind a callback for this event'); } parent::bind($event, $handler); }
{@inheritdoc} @throws InvalidArgumentException When event binding is forbidden.
entailment
public function handleInit(Control $control, Context $context) { if (! $context->pidfile instanceof Pidfile) { $context->pidfile = new Pidfile($control, $this->getOption('name'), $this->getOption('lock_dir')); } $context->isRunning = $context->pidfile->isActive(); $context->processId = $context->pidfile->getProcessId(); }
Default trigger for EVENT_INIT. @param Control $control @param Context $context
entailment
public function handleStart(Control $control, Context $context) { if (! $context->pidfile instanceof Pidfile) { throw new LogicException('Pidfile is not defined'); } // Activates the circular reference collector gc_enable(); // Callback for handle when process is terminated $control->signal()->prependHandler(SIGTERM, function () use ($context) { $this->setAsDying(); $context->pidfile->finalize(); }); $control->signal()->setHandler(SIGTSTP, SIG_IGN); $control->signal()->setHandler(SIGTTOU, SIG_IGN); $control->signal()->setHandler(SIGTTIN, SIG_IGN); $control->signal()->setHandler(SIGHUP, SIG_IGN); // Detach session $control->info()->detachSession(); // Reset umask @umask($this->getOption('umask')); // Update work directory @chdir($this->getOption('work_dir')); // Close file descriptors fclose(STDIN); fclose(STDOUT); fclose(STDERR); // Define process owner if (null !== ($userId = $this->getOption('user_id'))) { $control->info()->setUserId($userId); } // Define process group if (null !== ($groupId = $this->getOption('group_id'))) { $control->info()->setGroupId($groupId); } // Create new file descriptors $context->stdin = fopen($this->getOption('stdin'), 'r'); $context->stdout = fopen($this->getOption('stdout'), 'wb'); $context->stderr = fopen($this->getOption('stderr'), 'wb'); // Create pidfile $context->pidfile->initialize(); }
Default trigger for EVENT_START. - Activates the circular reference collector - Detach session - Reset umask - Update work directory - Close file descriptors - Define process owner, if any - Define process group, if any - Create new file descriptors - Create pidfile - Define pidfile cleanup @param Control $control @param Context $context
entailment
public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('notify'); $rootNode ->children() ->arrayNode('smtp') ->children() ->scalarNode('host')->isRequired()->end() ->integerNode('port')->end() ->enumNode('security') ->values([null, 'ssl']) ->end() ->scalarNode('username')->isRequired()->end() ->scalarNode('password')->isRequired()->end() ->end() ->end() ->end() ; return $treeBuilder; }
{@inheritDoc}
entailment
public function onBlock(BlockEvent $event) { $identifier = $event->getSetting('id', null); if (null === $identifier) { return; } $block = new Block(); $block->setId(uniqid()); $block->setSettings($event->getSettings()); $block->setType($this->blockService->getName()); $event->addBlock($block); }
Add blocks services to event. @param BlockEvent $event
entailment
public function addParameter($name, $required = false, $description = '', $default = null) { $this->parameters[$name] = [ 'name' => $name, 'required' => $required, 'description' => $description, 'default' => $default, 'value' => null ]; return $this; }
Adds a parameter to the definition of the Task @param string $name Name of the task parameter @param bool $required If true, task parameter is required @param string $description Description of the task parameter @param mixed $default Default value of the task parameter, null by default @return mixed
entailment
public function getParameters() { $parameters = []; foreach ($this->parameters as $name => $parameter) { $parameters[$name] = $this->getParameter($name); } return $parameters; }
{@inheritDoc}
entailment
public function getParameter($name, $validate = true) { if ($validate && !array_key_exists($name, $this->parameters)) { throw new ParameterNotFoundException($name); } $param = $this->parameters[$name]; $value = $param['value']; if (null === $value) { if (true === $param['required']) { throw new RequiredParameterException($name); } $value = $param['default']; } $value = $this->replaceTokens($value); return $value; }
{@inheritdoc} @throws ParameterNotFoundException @throws RequiredParameterException
entailment
public function hasParameter($name) { if (array_key_exists($name, $this->parameters)) { if (null !== $this->parameters[$name]['value']) { return true; } } return false; }
Returns true if the Task has a parameter with the given name, and the value is not null. Returns false otherwise. @param string $name @return bool
entailment
public function setParameter($name, $value) { if (!array_key_exists($name, $this->parameters)) { $this->addParameter($name, false, '', null); } $this->parameters[$name]['value'] = $value; }
{@inheritdoc}
entailment
public function validate() { foreach ($this->parameters as $name => $parameter) { if (null === $parameter['value']) { if (true === $parameter['required']) { throw new RequiredParameterException($name); } } } return true; }
{@inheritdoc}
entailment
private function replaceTokens($option) { if (is_array($option)) { $tokenizedOptions = []; foreach ($option as $key => $opt) { $tokenizedOptions[$key] = $this->replaceTokens($opt); } return $tokenizedOptions; } return preg_replace_callback( '/\$(.+)\$|\$\{(.+)\}/', function ($match) { $val = isset($match[2]) ? getenv($match[2]) : getenv($match[1]); return $val !== false ? $val : $match[0]; }, $option ); }
Tokenize the given option, if it is a string. @param mixed $option @return mixed
entailment
public function getPath(UriInterface $uri) { $path = trim($uri->getPath(), '/'); $parts = explode('/', $path); if ($parts[0] === 'v'.Client::API_VERSION) { unset($parts[0]); } return '/'.implode('/', $parts); }
Gets the path from a ``UriInterface`` instance after removing the version prefix. @param UriInterface $uri @return string
entailment
public function getQueryParams(UriInterface $uri, $exclude = ['sig'], $params = []) { parse_str($uri->getQuery(), $params); foreach ($exclude as $excludedParam) { if (array_key_exists($excludedParam, $params)) { unset($params[$excludedParam]); } } return $params; }
Gets the query parameters as an array from a ``UriInterface`` instance. @param UriInterface $uri @param array $exclude @param array $params @return array
entailment
public function url() { if ($this->urlName) return $this->urlName; if ($this->objectClass) return $this->objectClass->url($this); return null; }
Returns the API url where you can receive this object. @return null|string
entailment
public function refresh() { $response = $this->api->get($this->url()); $this->data = (array) $response->data; return $this; }
Makes a GET request and refreshes the local data with up-to-date info. @return $this
entailment
public function update($data) { $response = $this->api->put($this->url(), $data); $this->data = (array) $response->data; return $this; }
Updates the API object with $data. @param $data @return $this
entailment
public static function init($path) { pake_mkdirs($path); pake_sh(escapeshellarg(pake_which('hg')).' init -q '.escapeshellarg($path)); return new pakeMercurial($path); }
new mercurial-repo
entailment