sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public static function add_to_repo($repository_path, $files = null) { $repo = new pakeMercurial($repository_path); $repo->add($files); return $repo; }
one-time operations
entailment
public function handle_options($options = null) { $this->opt = new pakeGetopt(self::$OPTIONS); $this->opt->parse($options); foreach ($this->opt->get_options() as $opt => $value) { $this->do_option($opt, $value); } }
Read and handle the command line options.
entailment
public function have_pakefile() { $is_windows = (strtolower(substr(PHP_OS, 0, 3)) == 'win'); $here = getcwd(); foreach ($this->PAKEFILES as $file) { $path_includes_directory = basename($file) !== $file; if ($path_includes_directory) { if ($is_windows) { $is_absolute_path = ($file[0] == '\\' or $file[0] == '/' or mb_ereg('^[A-Za-z]+:', $file) === 1); } else { $is_absolute_path = $file[0] == '/'; } } else { $is_absolute_path = false; } if ($is_absolute_path) { $filepath = $file; } else { $filepath = $here . DIRECTORY_SEPARATOR . $file; } if (file_exists($filepath)) { $this->pakefile = realpath($filepath); return true; } } return false; }
If a match is found, it is copied into @pakefile.
entailment
public function do_option($opt, $value) { switch ($opt) { case 'interactive': $this->interactive = true; break; case 'dry-run': $this->verbose = true; $this->nowrite = true; $this->dryrun = true; $this->trace = true; break; case 'help': $this->help(); exit(); case 'libdir': set_include_path($value.PATH_SEPARATOR.get_include_path()); break; case 'nosearch': $this->nosearch = true; break; case 'prereqs': $this->show_prereqs = true; break; case 'quiet': $this->verbose = false; break; case 'pakefile': $this->PAKEFILES = array($value); break; case 'require': require $value; break; case 'import': pake_import($value); break; case 'tasks': $this->show_tasks = true; break; case 'trace': $this->trace = true; $this->verbose = true; break; case 'usage': $this->usage(); exit(); case 'verbose': $this->verbose = true; break; case 'force-tty': define('PAKE_FORCE_TTY', true); break; case 'full-width': $this->full_width = true; break; case 'version': $this->showVersion(); exit(); default: throw new pakeException('Unknown option: '.$opt); } }
Do the option defined by +opt+ and +value+.
entailment
public function usage($hint_about_help = true) { echo self::$EXEC_NAME." [-f pakefile] {options} targets…\n"; if (true === $hint_about_help) { echo 'Try "'; echo pakeColor::colorize(self::$EXEC_NAME.' help', 'INFO'); echo '" for more information'."\n"; } }
Display the program usage line.
entailment
public function help() { $this->usage(false); echo "\n"; echo "available options:"; echo "\n"; foreach (self::$OPTIONS as $option) { list($long, $short, $mode, $comment) = $option; if ($mode == pakeGetopt::REQUIRED_ARGUMENT) { if (preg_match('/\b([A-Z]{2,})\b/', $comment, $match)) $long .= '='.$match[1]; } printf(" %-20s", pakeColor::colorize($long, 'INFO')); if (!empty($short)) { printf(" (%s)", pakeColor::colorize($short, 'INFO')); } printf("\n %s\n", $comment); } }
Display the pake command line help.
entailment
public function display_tasks_and_comments() { $width = 0; $tasks = pakeTask::get_tasks(); foreach ($tasks as $name => $task) { $w = strlen(pakeTask::get_mini_task_name($name)); if ($w > $width) $width = $w; } $width += mb_strlen(pakeColor::colorize(' ', 'INFO')); echo "available ".self::$EXEC_NAME." tasks:\n"; // display tasks $has_alias = false; ksort($tasks); foreach ($tasks as $name => $task) { if ($task->get_alias()) { $has_alias = true; } if (!$task->get_alias() and $task->get_comment()) { $mini_name = pakeTask::get_mini_task_name($name); printf(' %-'.$width.'s > %s'."\n", pakeColor::colorize($mini_name, 'INFO'), $task->get_comment().($mini_name != $name ? ' ['.$name.']' : '')); } } if ($has_alias) { print("\ntask aliases:\n"); // display aliases foreach ($tasks as $name => $task) { if ($task->get_alias()) { $mini_name = pakeTask::get_mini_task_name($name); printf(' %-'.$width.'s = '.self::$EXEC_NAME.' %s'."\n", pakeColor::colorize(pakeTask::get_mini_task_name($name), 'INFO'), $task->get_alias().($mini_name != $name ? ' ['.$name.']' : '')); } } } echo "\n".'Try "'; echo pakeColor::colorize(self::$EXEC_NAME.' help taskname', 'INFO'); echo '" to get detailed information about task'."\n\n"; }
Display the tasks and dependencies.
entailment
public function display_prerequisites() { foreach (pakeTask::get_tasks() as $name => $task) { echo self::$EXEC_NAME." ".pakeTask::get_mini_task_name($name)."\n"; foreach ($task->get_prerequisites() as $prerequisite) { echo " $prerequisite\n"; } } }
Display the tasks and prerequisites
entailment
public static function run_help($task, $args) { if (count($args) == 0) { self::get_instance()->help(); return; } $victim_name = $args[0]; $task_name = pakeTask::taskname_from_abbreviation($victim_name); $victim = null; foreach (pakeTask::get_tasks() as $name => $task) { if ($task_name == $name or $task_name == pakeTask::get_mini_task_name($name)) { $victim = $task; break; } } if (null === $victim) { throw new pakeException("Couldn't find documentation for {$task_name}"); } $title = 'Documentation for "'.$task_name.'" task'; pake_echo($title); pake_echo(str_repeat('=', mb_strlen($title))); pake_echo($victim->get_comment()."\n"); pake_echo($victim->get_help()); }
show documentation; use "pake help taskname" to see detailed documentation on task @param string $task @param string $args @throws pakeException @author Alexey Zakhlestin
entailment
public function findNextToken($matcher) { $nextToken = $this->nextToken; while (null !== $nextToken) { if ($nextToken->matches($matcher)) { return new Some($nextToken); } $nextToken = $nextToken->nextToken; } return None::create(); }
Finds the next token that satisfies the passed matcher. Eligible matchers are: - T_??? constants such as T_WHITESPACE - Literal values such as ";" - A Closure which receives an AbstractToken as first argument - Some special built-in matchers: "END_OF_LINE", "END_OF_NAME" (see matches()) @param string|integer|\Closure $matcher @return Option<AbstractToken>
entailment
public function findPreviousToken($matcher) { $previousToken = $this->previousToken; while (null !== $previousToken) { if ($previousToken->matches($matcher)) { return new Some($previousToken); } $previousToken = $previousToken->previousToken; } return None::create(); }
Finds the previous token that satisfies the passed matcher. Eligible matchers are: - T_??? constants such as T_WHITESPACE - Literal values such as ";" - A Closure which receives an AbstractToken as first argument - Some special built-in matchers: "END_OF_LINE", "END_OF_NAME", etc. (see matches()) @param string|integer|\Closure $matcher @return Option<AbstractToken>
entailment
public function getAttribute($key) { if ( ! isset($this->attributes[$key])) { return None::create(); } return new Some($this->attributes[$key]); }
@param string $key @return Option<*>
entailment
public function getIndentation() { $indentation = $this->getLineIndentation(); if($this->isFirstTokenOnLine() && $this->matches(T_WHITESPACE)) { $indentation = ''; } return $indentation . str_repeat(' ', $this->getStartColumn() - strlen($indentation)); }
Returns the indentation necessary to reach the start of this token on a new line. It is important to note that this also supports smart tabs as it uses whatever is used for indenting the current lines, and only then pads this with spaces. @return string
entailment
public function getContentUntil(AbstractToken $token) { if ($this === $token) { return ''; } $content = $this->getContent(); $next = $this->nextToken; while ($next && $next !== $token) { $content .= $next->getContent(); $next = $next->nextToken; } if (null === $next) { throw new \RuntimeException(sprintf('Could not find token "%s".', $token)); } return $content; }
Returns the content from this Token until the passed token. The content of this token is included, and the content of the passed token is excluded. @param \JMS\CodeReview\Analysis\PhpParser\TokenStream\AbstractToken $token @return string
entailment
public function getLineIndentation() { $first = $this->getFirstTokenOnLine(); if ( ! $first->matches(T_WHITESPACE)) { return ''; } return $first->getContentUntil($first->findNextToken('NO_WHITESPACE')->get()); }
Returns the indentation used on the current line. @return string
entailment
public final function matches($matcher) { // Handle negations of matchers. if (is_string($matcher) && substr($matcher, 0, 3) === 'NO_') { return ! $this->matches(substr($matcher, 3)); } // Handle some special cases. if ($matcher === 'WHITESPACE_OR_COMMENT') { return $this->matches(T_WHITESPACE) || $this->matches(T_COMMENT) || $this->matches(T_DOC_COMMENT); } else if ($matcher === 'COMMENT') { return $this->matches(T_COMMENT) || $this->matches(T_DOC_COMMENT); } else if ($matcher === 'WHITESPACE') { return $this->matches(T_WHITESPACE); } else if ($matcher === 'END_OF_LINE') { return $this->isLastTokenOnLine(); } else if ($matcher === 'END_OF_NAME') { return ! $this->matches(T_STRING) && ! $this->matches(T_NS_SEPARATOR); } else if ($matcher === 'END_OF_CALL') { $opened = 0; $matcher = function(AbstractToken $token) use (&$opened) { switch (true) { case $token->matches(')'): return 0 === ($opened--); case $token->matches('('): $opened += 1; // fall through default: return false; } }; } if ($matcher instanceof \Closure) { return $matcher($this); } return $this->matchesInternal($matcher); }
Returns whether this token matches the given token. Note that the passed token is not an instance of AbstractToken, but either a string (representing a literal), or an integer (representing the value for one of PHPs T_??? constants). TODO: We should probably add a full-fledged expression syntax. @param string|integer|\Closure $matcher @return boolean
entailment
public function create(Schema $schema) { $currentDbSchema = $this->connection->getSchemaManager()->createSchema(); $dbSchema = new DBALSchema( $currentDbSchema->getTables(), $currentDbSchema->getSequences(), $this->connection->getSchemaManager()->createSchemaConfig() ); foreach ($schema->types() as $type) { $tableName = $this->tableName($schema->name(), $type->name()); if ($dbSchema->hasTable($tableName)) { throw DoctrineStorageException::tableAlreadyExists($tableName); } $this->createTable($dbSchema, $schema->name(), $type); } $queries = $dbSchema->toSql($this->connection->getDatabasePlatform()); $this->executeQueries($queries); }
@param Schema $schema @throws DoctrineStorageException
entailment
public function findBy(string $schema, string $typeName, array $criteria = []) : array { $builder = $this->connection->createQueryBuilder(); $builder->select('*'); $builder->from($this->tableName($schema, $typeName)); $builder->setMaxResults(1); foreach ($criteria as $field => $value) { $builder->andWhere(sprintf('%1$s = :%1$s', $field)); $builder->setParameter($field, $value); } return $builder->execute()->fetch(\PDO::FETCH_ASSOC) ?: []; }
Needs to return metadata in following format: [ 'id' => 'e94e4c36-3ffb-49b6-b8a5-973fa5c4aee6', 'sku' => 'DUMPLIE_SKU_1', 'name' => 'Product name' ] Key 'id' is required. @param string $schema @param string $typeName @param array $criteria @return array
entailment
public function has(string $schema, string $typeName, string $id) : bool { return !!$this->connection->createQueryBuilder() ->select('id') ->from($this->tableName($schema, $typeName)) ->where('id = :id') ->setParameter('id', $id) ->execute() ->fetchColumn(); }
@param string $schema @param string $typeName @param string $id @return bool
entailment
private function createTable(DBALSchema $schema, string $schemaName, TypeSchema $type) { $table = $schema->createTable($this->tableName($schemaName, $type->name())); $table->addColumn('id', 'guid'); $table->setPrimaryKey(['id']); foreach ($type->getDefinitions(['id']) as $field => $definition) { $this->typeRegistry->map($schemaName, $table, $field, $definition); } }
@param DBALSchema $schema @param string $schemaName @param TypeSchema $type @throws DoctrineStorageException
entailment
private function executeQueries(array $queries) { foreach ($queries as $query) { $this->connection->prepare($query)->execute(); } }
@param array $queries @throws \Doctrine\DBAL\DBALException
entailment
protected function doExecute() { $service = $this->findCall($this->input->getArgument('name'), $this->getOptions()); $service->run($this->output); }
{@inheritDoc}
entailment
private function findCall($name, array $options = []) { $tasks = array_keys($this->container->findTaggedServiceIds('bldr')); $services = []; foreach ($tasks as $serviceName) { /** @var TaskInterface|AbstractTask $service */ $service = $this->container->get($serviceName); if ($service instanceof AbstractTask) { $service->configure(); } if (method_exists($service, 'setEventDispatcher')) { $service->setEventDispatcher($this->container->get('bldr.dispatcher')); } foreach ($options as $name => $value) { $service->setParameter($name, $value); } if (method_exists($service, 'validate')) { $service->validate(); } if ($service->getName() === $name) { $services[] = $service; } } if (sizeof($services) > 1) { throw new \Exception("Multiple calls exist with the '{$name}' tag."); } if (sizeof($services) === 0) { throw new \Exception("No task type found for {$name}."); } return $services[0]; }
@param string $name @param array $options @throws \Exception @return TaskInterface|AbstractTask
entailment
private function getOptions() { $inputString = (string) $this->input; $options = []; // Remove the first two arguments from the array (c/call and the name) $content = explode(' ', $inputString, 3); if (sizeof($content) > 2 && strpos($inputString, '=') === false) { throw new \Exception("Option syntax should contain an equal sign. Ex: --executable=php"); } if (sizeof($content) > 2 && strpos($inputString, '--') === false) { throw new \Exception("Option syntax should contain double dashes. Ex: --executable=php"); } // Parse out all of the options $pieces = explode('--', $content[2]); array_shift($pieces); foreach ($pieces as $piece) { $piece = trim($piece); list($name, $value) = explode('=', $piece, 2); if (strpos($value, "'[") === 0 && strpos($value, "]'") === (strlen($value) - 2)) { $csv = trim(str_replace(['[', ']'], '', $value), "'"); $value = str_getcsv($csv, ','); } $options[$name] = $value; } return $options; }
This method takes the Argv, and parses out all the options passed. @return array @throws \Exception
entailment
public function getBySku(SKU $SKU): Product { if (isset($this->products[(string) $SKU])) { return $this->products[(string) $SKU]; } throw ProductNotFound::bySku($SKU); }
@param SKU $SKU @return Product @throws ProductNotFound - when product with given SKU were not found
entailment
private function registerBreadcrumbsService() { $this->singleton(Contracts\Breadcrumbs::class, function ($app) { /** @var \Illuminate\Contracts\Config\Repository $config */ $config = $app['config']; return new Breadcrumbs( $config->get('breadcrumbs.template.supported', []), $config->get('breadcrumbs.template.default', '') ); }); }
Register the Breadcrumbs service.
entailment
public function compile() { if (null !== $this->parameterBag) { $blocks = $this->getCoreBlocks(); $blocks = array_merge($blocks, $this->getThirdPartyBlocks()); foreach ($blocks as $block) { $this->prepareBlock($block); } } Config::read($this); parent::compile(); }
Compiles the container with third party blocks
entailment
public function getThirdPartyBlocks() { /** @var Application $application */ $application = $this->get('application'); $embeddedComposer = $application->getEmbeddedComposer(); $config = $embeddedComposer->getExternalComposerConfig(); $loadBlock = $config->has('block-loader') ? $config->get('block-loader') : '.bldr/blocks.yml'; $blockFile = $embeddedComposer->getExternalRootDirectory().DIRECTORY_SEPARATOR.$loadBlock; if (!file_exists($blockFile)) { return []; } $blockNames = Yaml::parse(file_get_contents($blockFile)); if (null === $blockNames) { return []; } $blocks = []; foreach ($blockNames as $block) { $blocks[] = new $block(); } return $blocks; }
Gets all the third party blocks from .bldr/blocks.yml @return array
entailment
public static function invalidAddress(string $value, string $valueName) : InvalidArgumentException { return new self(sprintf('"%s" is not valid "%s"', $value, $valueName)); }
@param string $value @param string $valueName @return InvalidArgumentException
entailment
public function performEvent($eventName, $eventData = null) { $url = $this->url() . '/command/' . $eventName; $response = $this->api->post($url, $eventData); $this->data = (array) $response->data; return $this; }
Makes a POST request to /billogram/{id}/command/{event}. @param $eventName @param null $eventData @return $this
entailment
public function sendReminder($method = null) { if ($method) { if (!in_array($method, array('Email', 'Letter'))) throw new InvalidFieldValueError("'method' must be either " . "'Email' or 'Letter'"); return $this->performEvent('remind', array('method' => $method)); } return $this->performEvent('remind'); }
Manually send a reminder if the billogram is overdue. @param null $method @return $this @throws \Billogram\Api\Exceptions\InvalidFieldValueError
entailment
public function resend($method = null) { if ($method) { if (!in_array($method, array('Email', 'Letter'))) throw new InvalidFieldValueError("'method' must be either " . "'Email' or 'Letter'"); return $this->performEvent('resend', array('method' => $method)); } return $this->performEvent('resend'); }
Resend a billogram via Email or Letter. @param null $method @return $this @throws \Billogram\Api\Exceptions\InvalidFieldValueError
entailment
public function getInvoicePdf($letterId = null, $invoiceNo = null) { $params = array(); if ($letterId) $params['letter_id'] = $letterId; if ($invoiceNo) $params['invoice_no'] = $invoiceNo; $response = $this->api->get( $this->url() . '.pdf', $params, 'application/json' ); return base64_decode($response->data->content); }
Returns the PDF-file content for a specific billogram, invoice or letter document. Will throw a ObjectNotFoundError with message 'Object not available yet' if the PDF has not yet been generated. @param null $letterId @param null $invoiceNo @return string @throws \Billogram\Api\Exceptions\ObjectNotFoundError
entailment
public function getAttachmentPdf() { $response = $this->api->get( $this->url() . '/attachment.pdf', null, 'application/json' ); return base64_decode($response->data->content); }
Returns the PDF-file content for the billogram's attachment. @return string
entailment
public function attachPdf($filepath) { $content = file_get_contents($filepath); $filename = basename($filepath); return $this->performEvent('attach', array('filename' => $filename, 'content' => base64_encode($content))); }
Attach a PDF to the billogram. @param $filepath @return $this
entailment
public function register() { $container = $this->getContainer(); $config = $container->get('config'); $container->share(AdapterInterface::class, function () use ($config, $container) { return new LeagueAdapter([ 'clientId' => $config->get('client_id'), 'clientSecret' => $config->get('client_secret'), 'redirectUri' => $config->get('redirect_url'), ], [ 'httpClient' => $container->get(Client::class) ]); }); if ($config->get('session_store') === NativeSessionStore::class) { $container->share(DataStoreInterface::class, function () { return new NativeSessionStore(); }); } $container->share(RedirectLoginHelper::class, function () use ($container) { return new RedirectLoginHelper( $container->get(AdapterInterface::class), $container->get(DataStoreInterface::class) ); }); }
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 getForCart(CartId $cartId) : Checkout { if (!$this->existsForCart($cartId)) { throw new CheckoutNotFoundException; } return $this->checkouts[(string) $cartId]; }
@param CartId $cartId @return Checkout @throws CheckoutNotFoundException
entailment
public function removeForCart(CartId $cartId) { if (!$this->existsForCart($cartId)) { throw new CheckoutNotFoundException; } unset($this->checkouts[(string) $cartId]); }
@param CartId $cartId @throws CheckoutNotFoundException
entailment
public function request($method, $uri, array $parameters = []) { try { $response = $this->guzzle->request($method, $uri, $parameters); } catch (ClientException $e) { if (!$e->hasResponse()) { throw $e; } throw $this->resolveExceptionClass($e); } catch (Exception $e) { throw $e; } return Response::createFromJson(json_decode($response->getBody()->getContents(), true)); }
{@inheritDoc}
entailment
public function execute(InputInterface $input, OutputInterface $output) { $output->writeln('Updating thread comments average note...'); $this->getThreadManager()->updateAverageNote(); $output->writeln('<info>done!</info>'); }
{@inheritdoc}
entailment
public static function settings($settings = null) { if ($settings) { //set mode self::$settings = self::mergeSettings(self::$settings, $settings); } else { //get mode } //always return settings return self::$settings; }
Config setter & getter This serves as a settings setter and getter at the same time
entailment
protected static function mergeSettings($Arr1, $Arr2) { foreach ($Arr2 as $key => $Value) { if (array_key_exists($key, $Arr1) && is_array($Value)) { $Arr1[$key] = self::mergeSettings($Arr1[$key], $Arr2[$key]); } else { $Arr1[$key] = $Value; } } return $Arr1; }
method for merging setting files
entailment
public static function subpackage_settings($subpackage) { $s = self::settings(); if (isset($s[$subpackage])) { return $s[$subpackage]; } }
Getter for subpackage specific settings @param string $subpackage @return array
entailment
public static function subpackage_enabled($subpackage) { $s = self::subpackage_settings($subpackage); if ($s) { //settings need to be an array if (is_array($s)) { if (isset($s['enabled'])) { if ($s['enabled'] == true) { return true; } else { return false; } } else { //if 'enabled' is not defined, the package is enabled - as per definition above return true; } } else { return false; } } else { return false; } }
Getter that checks if a specific subpackage is enabled A subpackage is seen as being enabled if 1. it exists in setting 2. it a) either doesn't have an 'enabled' attribute (then it's enabled by default) b) or has an 'enabled' attribute that's set to true @param string $subpackage @return boolean
entailment
public static function subpackage_setting($subpackage, $setting) { $s = self::subpackage_settings($subpackage); if (isset($s[$setting])) { return $s[$setting]; } }
Getter for a specific setting from a subpackage @param string $subpackage @param string $setting
entailment
public static function init($settings = null) { if (is_array($settings)) { //merging settings (and setting the global settings) //settings should be submitted via an array $settings = self::settings($settings); } else { $settings = self::settings(); } if ($settings['enabled']) { $ssversion = self::subpackage_settings('ssversion'); //Enabling calendars if (self::subpackage_enabled('calendars')) { if ($ssversion == '3.0') { Object::add_extension('Event', 'EventCalendarExtension'); } else { Event::add_extension('EventCalendarExtension'); } $s = self::subpackage_settings('calendars'); if ($s['colors']) { if ($ssversion == '3.0') { Object::add_extension('Calendar', 'CalendarColorExtension'); } else { Calendar::add_extension('CalendarColorExtension'); } } if ($s['shading']) { if ($ssversion == '3.0') { Object::add_extension('Calendar', 'ShadedCalendarExtension'); } else { Calendar::add_extension('ShadedCalendarExtension'); } } } //Enabling categories if (self::subpackage_enabled('categories')) { if ($ssversion == '3.0') { Object::add_extension('Event', 'EventCategoryExtension'); } else { Event::add_extension('EventCategoryExtension'); } } //Enabling Event Page if (self::subpackage_setting('pagetypes', 'enable_eventpage')) { if ($ssversion == '3.0') { Object::add_extension('Event', 'EventHasEventPageExtension'); } else { Event::add_extension('EventHasEventPageExtension'); } } //Enabling debug mode if (self::subpackage_enabled('debug')) { if ($ssversion == '3.0') { Object::add_extension('Event', 'EventDebugExtension'); } else { Event::add_extension('EventDebugExtension'); } } //Enabling registrations if (self::subpackage_enabled('registrations')) { if ($ssversion == '3.0') { Object::add_extension('Event', 'EventRegistrationExtension'); } else { Event::add_extension('EventRegistrationExtension'); } } //Adding URL Segment extension to Calendar (currently done for all but could be made configurable later) Object::add_extension('Calendar', 'DoURLSegmentExtension'); if ($ssversion == '3.0') { Object::add_extension('Calendar', 'DoURLSegmentExtension'); } else { Calendar::add_extension('DoURLSegmentExtension'); } } }
Calendar initialization Should be called from the project _config.php file @param array|null $settings
entailment
public function getPropertyTypeName($typeInteger) { $refl = new \ReflectionClass('PHPCR\PropertyType'); foreach ($refl->getConstants() as $key => $value) { if ($typeInteger == $value) { return $key; } } }
Return the name of a property from its enumeration (i.e. the value of its CONSTANT). @return string
entailment
public function formatQueryResult(QueryResultInterface $result, OutputInterface $output, $elapsed) { $table = new Table($output); $table->setHeaders(array_merge([ 'Path', ], $result->getColumnNames())); foreach ($result->getRows() as $row) { $values = array_merge([ $row->getPath(), ], $row->getValues()); foreach ($values as &$value) { if ($value instanceof \DateTime) { $value = $value->format('c'); continue; } $value = $this->textHelper->truncate($value, 255); } $table->addRow($values); } $table->render($output); if (true === $this->config['show_execution_time_query']) { $output->writeln(sprintf( '%s rows in set (%s sec)', count($result->getRows()), number_format($elapsed, $this->config['execution_time_expansion'])) ); } }
Render a table with the results of the given QueryResultInterface.
entailment
public function get(string $typeName) : TypeSchema { if (!array_key_exists($typeName, $this->types)) { throw NotFoundException::model($typeName); } return $this->types[$typeName]; }
@param string $typeName @return TypeSchema @throws NotFoundException
entailment
public function init() { $this->registerPhpcrCommands(); if ($this->container->getMode() === PhpcrShell::MODE_EMBEDDED_SHELL) { $this->registerShellCommands(); } }
{@inheritdoc}
entailment
public static function type($name) { $finder = new pakeFinder(); if (strtolower(substr($name, 0, 3)) == 'dir') { $finder->type = 'directory'; } else { if (strtolower($name) == 'any') { $finder->type = 'any'; } else { $finder->type = 'file'; } } return $finder; }
Factory, which prepares new pakeFinder objects Sets the type of elements to return. @param string "directory" or "file" or "any" (for both file and directory) @return pakeFinder
entailment
private function to_regex($str) { if ($str[0] == '/' && $str[strlen($str) - 1] == '/') { return $str; } else { return pakeGlobToRegex::glob_to_regex($str); } }
/* glob, patterns (must be //) or strings
entailment
private function pattern_to_regex($pattern) { if (substr($pattern, -1) == '/') { $pattern .= '**'; } $regex = '|^'; foreach (explode('/', $pattern) as $i => $piece) { if ($i > 0) { $regex .= preg_quote('/', '|'); } if ('**' == $piece) { $regex .= '.*'; } else { $regex .= str_replace(array('?', '*'), array('[^/]', '[^/]*'), $piece); } } $regex .= '$|'; return $regex; }
converts ant-pattern to PCRE regex @param string $pattern @return string
entailment
public function pattern() { $patterns = func_get_args(); foreach (func_get_args() as $pattern) { $this->patterns[] = $this->pattern_to_regex($pattern); } return $this; }
Mimics ant pattern matching. @see http://ant.apache.org/manual/dirtasks.html#patterns @return pakeFinder
entailment
public function not_pattern() { $patterns = func_get_args(); foreach (func_get_args() as $pattern) { $this->not_patterns[] = $this->pattern_to_regex($pattern); } return $this; }
Mimics ant pattern matching. (negative match) @see http://ant.apache.org/manual/dirtasks.html#patterns @return pakeFinder
entailment
public function name() { $args = func_get_args(); $this->names = array_merge($this->names, $this->args_to_array($args)); return $this; }
Adds rules that files must match. You can use patterns (delimited with / sign), globs or simple strings. $finder->name('*.php') $finder->name('/\.php$/') // same as above $finder->name('test.php') @return pakeFinder
entailment
public function not_name() { $args = func_get_args(); $this->names = array_merge($this->names, $this->args_to_array($args, true)); return $this; }
Adds rules that files must not match. @see ->name() @return pakeFinder
entailment
public function size() { $args = func_get_args(); for ($i = 0; $i < count($args); $i++) { $this->sizes[] = new pakeNumberCompare($args[$i]); } return $this; }
Adds tests for file sizes. $finder->size('> 10K'); $finder->size('<= 1Ki'); $finder->size(4); @return pakeFinder
entailment
public function prune() { $args = func_get_args(); $this->prunes = array_merge($this->prunes, $this->args_to_array($args)); return $this; }
Traverses no further. @return pakeFinder
entailment
public function discard() { $args = func_get_args(); $this->discards = array_merge($this->discards, $this->args_to_array($args)); return $this; }
Discards elements that matches. @return pakeFinder
entailment
public function exec() { $args = func_get_args(); for ($i = 0; $i < count($args); $i++) { if (is_array($args[$i]) && !method_exists($args[$i][0], $args[$i][1])) { throw new pakeException('Method ' . $args[$i][1] . ' does not exist for object ' . $args[$i][0]); } else { if (!is_array($args[$i]) && !function_exists($args[$i])) { throw new pakeException('Function ' . $args[$i] . ' does not exist.'); } } $this->execs[] = $args[$i]; } return $this; }
Executes function or method for each element. Element match if functino or method returns true. $finder->exec('myfunction'); $finder->exec(array($object, 'mymethod')); @return pakeFinder
entailment
public function in() { $files = array(); $here_dir = getcwd(); $numargs = func_num_args(); $arg_list = func_get_args(); // first argument is an array? if ($numargs == 1 && is_array($arg_list[0])) { $arg_list = $arg_list[0]; $numargs = count($arg_list); } $dirs = array(); for ($i = 0; $i < $numargs; $i++) { if ($argDirs = glob($arg_list[$i])) { $dirs = array_merge($dirs, $argDirs); } } foreach ($dirs as $dir) { $real_dir = realpath($dir); // absolute path? if (!self::isPathAbsolute($real_dir)) { $dir = $here_dir . DIRECTORY_SEPARATOR . $real_dir; } else { $dir = $real_dir; } if (!is_dir($real_dir)) { continue; } $this->search_dir = $dir; if ($this->relative) { $files = array_merge($files, str_replace($dir . DIRECTORY_SEPARATOR, '', $this->search_in($dir))); } else { $files = array_merge($files, $this->search_in($dir)); } } return array_unique($files); }
Searches files and directories which match defined rules. @return array list of files and directories
entailment
public function run(OutputInterface $output) { /** @type DebugFormatterHelper $debugFormatter */ $debugFormatter = $this->getHelperSet()->get('debug_formatter'); $arguments = $this->resolveProcessArgs(); $builder = new ProcessBuilder($arguments); $process = $builder->getProcess(); if (null !== $dispatcher = $this->getEventDispatcher()) { $event = new PreExecuteEvent($this, $process); $dispatcher->dispatch(Event::PRE_EXECUTE, $event); if ($event->isPropagationStopped()) { return true; } } 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('cwd')) { $process->setWorkingDirectory($this->getParameter('cwd')); } if (get_class($this) === 'Bldr\Block\Execute\Task\ExecuteTask') { $output->writeln( ['', sprintf(' <info>[%s]</info> - <comment>Starting</comment>', $this->getName()), ''] ); } if ($output->getVerbosity() === OutputInterface::VERBOSITY_VERBOSE || $this->getParameter('dry_run')) { $output->writeln(' // '.$process->getCommandLine()); } if ($this->getParameter('dry_run')) { return true; } 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("<fg=blue>==============================\n</fg=blue>"); $output->writeln( $debugFormatter->start( spl_object_hash($process), $process->getCommandLine() ) ); $process->run( function ($type, $buffer) use ($output, $debugFormatter, $process) { if ($this->getParameter('raw')) { $output->write($buffer, false, OutputInterface::OUTPUT_RAW); return; } $output->write( $debugFormatter->progress( spl_object_hash($process), $buffer, Process::ERR === $type ) ); } ); $output->writeln( $debugFormatter->stop( spl_object_hash($process), $process->getCommandLine(), $process->isSuccessful() ) ); $output->writeln("<fg=blue>==============================</fg=blue>"); if (null !== $dispatcher) { $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()); } }
{@inheritDoc}
entailment
public function get($objectId) { $response = $this->api->get($this->url($objectId)); $className = $this->objectClass; return new $className($this->api, $this, $response->data); }
Finds an object by id $objectId and returns an object. @param $objectId @return \Billogram\Api\Objects\SimpleObject
entailment
public function create($data) { $response = $this->api->post($this->url(), $data); $className = $this->objectClass; return new $className($this->api, $this, $response->data); }
Makes a POST request to the API and creates a new object. @param $data @return \Billogram\Api\Objects\SimpleObject
entailment
public function url($object = null) { if (is_object($object)) { $objectIdField = $this->objectIdField; return $this->urlName . '/' . $object->$objectIdField; } elseif ($object) { return $this->urlName . '/' . $object; } return $this->urlName; }
Formats and returns a URL to an object or object id. @param null $object @return string
entailment
public function assertNodeIsVersionable(NodeInterface $node) { if (!$this->nodeHasMixinType($node, 'mix:versionable')) { throw new \OutOfBoundsException(sprintf( 'Node "%s" is not versionable', $node->getPath() )); } }
Return true if the given node is versionable.
entailment
public function init() { NestableAsset::register($this->getView()); if ($this->dataProvider !== null) { $this->prepareItems(); } if ($this->items === null) { throw new InvalidConfigException('The "dataProvider" property or "items" property must be set at least one.'); } Html::addCssClass($this->options, $this->rootClass); if (!ArrayHelper::keyExists('id', $this->options)) { $this->options['id'] = uniqid('w_'); } }
Initializes the widget.
entailment
public function save() { $this->getHandler()->write($this->getId(), serialize($this->attributes)); $this->started = false; }
Save the session data to storage. @return bool
entailment
public function has($key): bool { return $this->exists($key) && null !== $this->attributes[$key]; }
Checks if an a key is present and not null. @param string|array $key @return bool
entailment
public function migrate($destroy = false): bool { if ($destroy) { $this->getHandler()->destroy($this->getId()); } $this->setId($this->generateSessionId()); return true; }
Generate a new session ID for the session. @param bool $destroy @return bool @throws \RuntimeException
entailment
public function setRequestOnHandler($request) { if ($this->handlerNeedsRequest()) { /** @var NeedRequestInterface $handler */ $handler = $this->getHandler(); $handler->setRequest($request); } }
Set the request on the handler instance. @param \Swoft\Http\Message\Server\Request $request @return void
entailment
protected function render() { if ($this->isShort) { return $this->renderShort(); } elseif ($this->isOpened) { return $this->renderOpened(); } else { return $this->renderTag(); } }
[@inheritdoc}
entailment
private function calculateTextColor($color) { $c = str_replace('#', '', $color); $rgb[0] = hexdec(substr($c, 0, 2)); $rgb[1] = hexdec(substr($c, 2, 2)); $rgb[2] = hexdec(substr($c, 4, 2)); if ($rgb[0]+$rgb[1]+$rgb[2]<382) { return '#fff'; } else { return '#000'; } }
Text Color calculation From http://www.splitbrain.org/blog/2008-09/18-calculating_color_contrast_with_php Here is a discussion on that topic: http://stackoverflow.com/questions/1331591/given-a-background-color-black-or-white-text @param type $color @return string
entailment
public function getColorWithHash() { $color = $this->owner->Color; if (strpos($color, '#') === false) { return '#' . $color; } else { return $color; } }
Getter that always returns the color with a hash As the standard Silverstripe color picker seems to save colors without a hash, this just makes sure that colors are always returned with a hash - whether they've been saved with or without one
entailment
public function request($method, $uri, array $parameters = []) { $file = file_get_contents($this->mapRequestToFile($method, $uri, $parameters)); return Response::createFromJson(json_decode($file, true)); }
{@inheritDoc}
entailment
protected function mapRequestToFile($method, $uri, $parameters) { $filename = strtolower($method).'_'; $filename .= $this->cleanPath($uri); $suffix = $this->mapRequestParameters($parameters); return $this->fixturesPath.$filename.$suffix.'.json'; }
Parse the correct filename from the request. @param string $method @param string $uri @param array $parameters @return string
entailment
protected function cleanPath($uri) { $urlPath = parse_url($uri, PHP_URL_PATH); $uri = str_replace('v1/', '', $urlPath); $path = preg_replace('/(\/\w{10}$|self|\d*)/', '', $uri); return trim(preg_replace('/\/{1,2}|\-/', '_', $path), '_'); }
Removes any unwanted suffixes and values from a URL path. @param $uri @return string
entailment
protected function mapRequestParameters($parameters) { if (empty($parameters) || !array_key_exists('query', $parameters)) { return ''; } $exclude = [ 'q', 'count', 'min_id', 'max_id', 'min_tag_id', 'max_tag_id', 'lat', 'lng', 'distance', 'text', 'max_like_id', 'action', 'cursor', 'access_token', ]; $modifiers = array_except($parameters['query'], $exclude); $return = implode('_', array_keys($modifiers)); return rtrim("_$return", '_'); }
Parses any filename properties from the request parameters. @param $parameters @return string
entailment
public function catchAll(...$args) { // Get the current route and see if it matches a content/file $path = $this->di->get("request")->getRoute(); $file1 = ANAX_INSTALL_PATH . "/content/{$path}.md"; $file2 = ANAX_INSTALL_PATH . "/content/{$path}/index.md"; $file = is_file($file1) ? $file1 : null; $file = is_file($file2) ? $file2 : $file; if (!$file) { return; } // Check that file is really in the right place $real = realpath($file); $base = realpath(ANAX_INSTALL_PATH . "/content/"); if (strncmp($base, $real, strlen($base))) { return; } // Get content from markdown file $content = file_get_contents($file); $content = $this->di->get("textfilter")->parse( $content, ["frontmatter", "variable", "shortcode", "markdown", "titlefromheader"] ); // Add content as a view and then render the page $page = $this->di->get("page"); $page->add("anax/v2/article/default", [ "content" => $content->text, "frontmatter" => $content->frontmatter, ]); return $page->render($content->frontmatter); }
Render a page using flat file content. @param array $args as a variadic to catch all arguments. @return mixed as null when flat file is not found and otherwise a complete response object with content to render. @SuppressWarnings(PHPMD.UnusedFormalParameter)
entailment
public function assemble(array $config, ContainerBuilder $container) { $this->addService('bldr_filesystem.abstract', 'Bldr\Block\Filesystem\Task\FilesystemTask') ->setAbstract(true) ; $namespace = 'Bldr\Block\Filesystem\Task\\'; $this->addDecoratedTask('bldr_filesystem.remove', $namespace.'RemoveTask', 'bldr_filesystem.abstract'); $this->addDecoratedTask('bldr_filesystem.mkdir', $namespace.'MkdirTask', 'bldr_filesystem.abstract'); $this->addDecoratedTask('bldr_filesystem.touch', $namespace.'TouchTask', 'bldr_filesystem.abstract'); $this->addDecoratedTask('bldr_filesystem.dump', $namespace.'DumpTask', 'bldr_filesystem.abstract'); }
{@inheritDoc}
entailment
private function getFacetParams(array $facetBuilders) { $facetParams = []; $facetBuilders = $this->filterNewFacetBuilders($facetBuilders); foreach ($facetBuilders as $facetBuilder) { $identifier = spl_object_hash($facetBuilder); $facetParams[$identifier] = $this->facetBuilderVisitor->visitBuilder( $facetBuilder, null ); } return $facetParams; }
@param \eZ\Publish\API\Repository\Values\Content\Query\FacetBuilder[] $facetBuilders @return array
entailment
private function getOldFacetParams(array $facetBuilders) { $facetParamsGrouped = array_map( function ($facetBuilder) { return $this->facetBuilderVisitor->visitBuilder($facetBuilder, spl_object_hash($facetBuilder)); }, $this->filterOldFacetBuilders($facetBuilders) ); return $this->formatOldFacetParams($facetParamsGrouped); }
Converts an array of facet builder objects to a Solr query parameters representation. This method uses spl_object_hash() to get id of each and every facet builder, as this is expected by {@link \EzSystems\EzPlatformSolrSearchEngine\ResultExtractor}. @param \eZ\Publish\API\Repository\Values\Content\Query\FacetBuilder[] $facetBuilders @return array
entailment
public static function createFromJson(array $response) { $meta = array_key_exists('meta', $response) ? $response['meta'] : ['code' => 200]; $data = array_key_exists('data', $response) ? $response['data'] : $response; $pagination = array_key_exists('pagination', $response) ? $response['pagination'] : []; return new static($meta, $data, $pagination); }
Creates a new instance of :php:class:`Response` from a JSON-decoded response body. @param array $response @return static
entailment
public function getRaw($key = null) { return $key === null ? $this->raw : $this->raw[$key]; }
Gets the JSON-decoded raw response. @param string|null $key @return array
entailment
public function get() { return $this->isCollection($this->data) ? new Collection($this->data) : $this->data; }
Gets the response body. If the response contains multiple records, a ``Collection`` is returned. @return array|Collection
entailment
public function merge(Response $response) { $meta = $response->getRaw('meta'); $data = $response->get(); $pagination = $response->hasPages() ? $response->getRaw('pagination') : []; $old = $this->get(); if ($this->isCollection($old) && $this->isCollection($data)) { $old = !($old instanceof Collection) ?: $old->toArray(); $new = !($data instanceof Collection) ?: $data->toArray(); return new Response($meta, array_merge($old, $new), $pagination); } if ($this->isRecord($old) && $this->isRecord($data)) { return new Response($meta, [$old, $data], $pagination); } throw new IncompatibleResponseException('The response contents cannot be merged'); }
Merges the contents of this response with ``$response`` and returns a new :php:class:`Response` instance. @param Response $response @return Response @throws IncompatibleResponseException
entailment
protected function isCollection($data) { $isCollection = false; if ($data === null) { return $isCollection; } if (!$this->isRecord($data)) { $isCollection = true; } return $isCollection; }
Tests the current response data to see if one or more records were returned. @param array|Collection $data @return bool
entailment
protected function isRecord($data) { if ($data instanceof Collection) { return false; } $keys = array_keys($data); return (in_array('id', $keys, true) || in_array('name', $keys, true)); }
Tests the current response data to see if a single record was returned. @param array|Collection $data @return bool
entailment
public function updateNodeSet(RowInterface $row, $propertyData) { $node = $row->getNode($propertyData['selector']); $value = $propertyData['value']; if ($value instanceof FunctionOperand) { $value = $propertyData['value']; $value = $value->execute($this->functionMapSet, $row); } $node->setProperty($propertyData['name'], $value); }
Update a node indicated in $propertyData in $row. @param PHPCR\Query\RowInterface @param array
entailment
public function doRegister($data, $form) { $r = new EventRegistration(); $form->saveInto($r); $EventDetails = Event::get()->byID($r->EventID); if ($EventDetails->TicketsRequired) { $r->AmountPaid = ($r->AmountPaid/100); } $r->write(); $from = Email::getAdminEmail(); $to = $r->Email; $bcc = $EventDetails->RSVPEmail; $subject = "Event Registration - ".$EventDetails->Title." - ".date("d/m/Y H:ia"); $body = ""; $email = new Email($from, $to, $subject, $body, null, null, $bcc); $email->setTemplate('EventRegistration'); $email->send(); exit; }
Register action @param type $data @param type $form @return \SS_HTTPResponse
entailment
protected function registerBreadcrumbs($container, array $item = []) { $this->setBreadcrumbsContainer($container); breadcrumbs()->register('main', function(Builder $bc) use ($item) { if (empty($item)) { $item = $this->getBreadcrumbsHomeItem(); } $bc->push($item['title'], $item['url'], $item['data'] ?? []); }); }
Register a breadcrumb. @param string $container @param array $item
entailment
protected function loadBreadcrumbs() { breadcrumbs()->register($this->breadcrumbsContainer, function(Builder $bc) { $bc->parent('main'); if ( ! empty($this->breadcrumbsItems)) { foreach ($this->breadcrumbsItems as $crumb) { $bc->push($crumb['title'], $crumb['url'], $crumb['data'] ?? []); } } }); }
Load all breadcrumbs.
entailment
protected function addBreadcrumbRoute($title, $route, array $parameters = [], array $data = []) { return $this->addBreadcrumb($title, route($route, $parameters), $data); }
Add breadcrumb with route. @param string $title @param string $route @param array $parameters @param array $data @return self
entailment
protected function generateSig($endpoint, array $params, $secret) { $sig = $endpoint; ksort($params); foreach ($params as $key => $val) { $sig .= "|$key=$val"; } return hash_hmac('sha256', $sig, $secret, false); }
Generates a ``sig`` value for a request. @param string $endpoint @param array $params @param string $secret @return string
entailment
public function parse($value) { $this->currentLineNb = -1; $this->currentLine = ''; $this->lines = explode("\n", $this->cleanup($value)); if (function_exists('mb_internal_encoding') && ((int) ini_get('mbstring.func_overload')) & 2) { $mbEncoding = mb_internal_encoding(); mb_internal_encoding('UTF-8'); } $data = array(); while ($this->moveToNextLine()) { if ($this->isCurrentLineEmpty()) { continue; } // tab? if (preg_match('#^\t+#', $this->currentLine)) { throw new InvalidArgumentException(sprintf('A YAML file cannot contain tabs as indentation at line %d (%s).', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } $isRef = $isInPlace = $isProcessed = false; if (preg_match('#^\-((?P<leadspaces>\s+)(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) { if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } // array if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[] = $parser->parse($this->getNextEmbedBlock()); } else { if (isset($values['leadspaces']) && ' ' == $values['leadspaces'] && preg_match('#^(?P<key>'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"\{].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $values['value'], $matches)) { // this is a compact notation element, add to next block and parse $c = $this->getRealCurrentLineNb(); $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $block = $values['value']; if (!$this->isNextLineIndented()) { $block .= "\n".$this->getNextEmbedBlock($this->getCurrentLineIndentation() + 2); } $data[] = $parser->parse($block); } else { $data[] = $this->parseValue($values['value']); } } } else if (preg_match('#^(?P<key>'.sfYamlInline::REGEX_QUOTED_STRING.'|[^ \'"].*?) *\:(\s+(?P<value>.+?))?\s*$#u', $this->currentLine, $values)) { $key = sfYamlInline::parseScalar($values['key']); if ('<<' === $key) { if (isset($values['value']) && '*' === substr($values['value'], 0, 1)) { $isInPlace = substr($values['value'], 1); if (!array_key_exists($isInPlace, $this->refs)) { throw new InvalidArgumentException(sprintf('Reference "%s" does not exist at line %s (%s).', $isInPlace, $this->getRealCurrentLineNb() + 1, $this->currentLine)); } } else { if (isset($values['value']) && $values['value'] !== '') { $value = $values['value']; } else { $value = $this->getNextEmbedBlock(); } $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $parsed = $parser->parse($value); $merged = array(); if (!is_array($parsed)) { throw new InvalidArgumentException(sprintf("YAML merge keys used with a scalar value instead of an array at line %s (%s)", $this->getRealCurrentLineNb() + 1, $this->currentLine)); } else if (isset($parsed[0])) { // Numeric array, merge individual elements foreach (array_reverse($parsed) as $parsedItem) { if (!is_array($parsedItem)) { throw new InvalidArgumentException(sprintf("Merge items must be arrays at line %s (%s).", $this->getRealCurrentLineNb() + 1, $parsedItem)); } $merged = array_merge($parsedItem, $merged); } } else { // Associative array, merge $merged = array_merge($merge, $parsed); } $isProcessed = $merged; } } else if (isset($values['value']) && preg_match('#^&(?P<ref>[^ ]+) *(?P<value>.*)#u', $values['value'], $matches)) { $isRef = $matches['ref']; $values['value'] = $matches['value']; } if ($isProcessed) { // Merge keys $data = $isProcessed; } // hash else if (!isset($values['value']) || '' == trim($values['value'], ' ') || 0 === strpos(ltrim($values['value'], ' '), '#')) { // if next line is less indented or equal, then it means that the current value is null if ($this->isNextLineIndented()) { $data[$key] = null; } else { $c = $this->getRealCurrentLineNb() + 1; $parser = new sfYamlParser($c); $parser->refs =& $this->refs; $data[$key] = $parser->parse($this->getNextEmbedBlock()); } } else { if ($isInPlace) { $data = $this->refs[$isInPlace]; } else { $data[$key] = $this->parseValue($values['value']); } } } else { // 1-liner followed by newline if (2 == count($this->lines) && empty($this->lines[1])) { $value = sfYamlInline::load($this->lines[0]); if (is_array($value)) { $first = reset($value); if ('*' === substr($first, 0, 1)) { $data = array(); foreach ($value as $alias) { $data[] = $this->refs[substr($alias, 1)]; } $value = $data; } } if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } return $value; } switch (preg_last_error()) { case PREG_INTERNAL_ERROR: $error = 'Internal PCRE error on line'; break; case PREG_BACKTRACK_LIMIT_ERROR: $error = 'pcre.backtrack_limit reached on line'; break; case PREG_RECURSION_LIMIT_ERROR: $error = 'pcre.recursion_limit reached on line'; break; case PREG_BAD_UTF8_ERROR: $error = 'Malformed UTF-8 data on line'; break; case PREG_BAD_UTF8_OFFSET_ERROR: $error = 'Offset doesn\'t correspond to the begin of a valid UTF-8 code point on line'; break; default: $error = 'Unable to parse line'; } throw new InvalidArgumentException(sprintf('%s %d (%s).', $error, $this->getRealCurrentLineNb() + 1, $this->currentLine)); } if ($isRef) { $this->refs[$isRef] = end($data); } } if (isset($mbEncoding)) { mb_internal_encoding($mbEncoding); } return empty($data) ? null : $data; }
Parses a YAML string to a PHP value. @param string $value A YAML string @return mixed A PHP value @throws InvalidArgumentException If the YAML is not valid
entailment
protected function getNextEmbedBlock($indentation = null) { $this->moveToNextLine(); if (null === $indentation) { $newIndent = $this->getCurrentLineIndentation(); if (!$this->isCurrentLineEmpty() && 0 == $newIndent) { throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } } else { $newIndent = $indentation; } $data = array(substr($this->currentLine, $newIndent)); while ($this->moveToNextLine()) { if ($this->isCurrentLineEmpty()) { if ($this->isCurrentLineBlank()) { $data[] = substr($this->currentLine, $newIndent); } continue; } $indent = $this->getCurrentLineIndentation(); if (preg_match('#^(?P<text> *)$#', $this->currentLine, $match)) { // empty line $data[] = $match['text']; } else if ($indent >= $newIndent) { $data[] = substr($this->currentLine, $newIndent); } else if (0 == $indent) { $this->moveToPreviousLine(); break; } else { throw new InvalidArgumentException(sprintf('Indentation problem at line %d (%s)', $this->getRealCurrentLineNb() + 1, $this->currentLine)); } } return implode("\n", $data); }
Returns the next embed block of YAML. @param integer $indentation The indent level at which the block is to be read, or null for default @return string A YAML string
entailment
protected function loadFile($file) { if (!stream_is_local($file)) { throw new InvalidArgumentException(sprintf('This is not a local file "%s".', $file)); } if (!file_exists($file)) { throw new InvalidArgumentException(sprintf('The service file "%s" is not valid.', $file)); } if (null === $this->jsonParser) { $this->jsonParser = new Json(); } return $this->validate($this->jsonParser->decode(file_get_contents($file), true), $file); }
Loads the Json File @param string $file @throws \Zend\Json\Exception\RuntimeException @throws \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException @return array
entailment
public function getRecentMedia($id, $minId = null, $maxId = null) { $params = ['query' => [ 'min_id' => $minId, 'max_id' => $maxId, ]]; return $this->client->request('GET', "locations/$id/media/recent", $params); }
Get a list of recent media objects from a given location. @param string $id The ID of the location @param string|null $minId Return media before this min_id @param string|null $maxId Return media after this max_id @return Response @link https://www.instagram.com/developer/endpoints/locations/#get_locations_media_recent
entailment
public function search($latitude, $longitude, $distance = 1000) { $params = ['query' => [ 'lat' => $latitude, 'lng' => $longitude, 'distance' => $distance, ]]; return $this->client->request('GET', 'locations/search', $params); }
Search for a location by geographic coordinate. @param int $latitude Latitude of the center search coordinate. If used, ``$longitude`` is required @param int $longitude Longitude of the center search coordinate. If used, ``$latitude`` is required @param int $distance The distance in metres. Default is ``1000``m, max distance is 5km @return Response @link https://www.instagram.com/developer/endpoints/locations/#get_locations_search
entailment