sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function run() { // Get 'onlyMimes' value from GET parameter $filter = Yii::$app->request->getQueryParam('filter'); if (!empty($filter)) { $this->settings['onlyMimes'] = is_string($filter) ? StringHelper::explode($filter) : $filter; } // disable resize in popup window $this->settings['resizable'] = false; return $this->controller->renderFile('@alexantr/elfinder/views/elfinder.php', [ 'connectorRoute' => $this->connectorRoute, 'settings' => $this->settings, ]); }
{@inheritdoc}
entailment
public function getHolidaysByYear($year) { $easter = $this->getEasterDates($year); $holidays = array( // National Fixed '01-01' => $this->createData('Confraternização Universal'), '04-21' => $this->createData('Tiradentes'), '05-01' => $this->createData('Dia do Trabalhador'), '09-07' => $this->createData('Dia da Pátria'), '10-12' => $this->createData('Nossa Senhora Aparecida'), '11-02' => $this->createData('Finados'), '11-15' => $this->createData('Proclamação da República'), '12-25' => $this->createData('Natal'), // National Variable (and Optional) $easter['shroveTuesday']->format(self::DATE_FORMAT) => $this->createData('Carnaval'), $easter['goodFriday']->format(self::DATE_FORMAT) => $this->createData('Sexta-Feira Santa'), $easter['corpusChristi']->format(self::DATE_FORMAT) => $this->createData('Corpus Christi'), ); // Acre State $this->setHolidayForState($holidays, '01-23', self::STATE_AC, 'Dia do Evangélico'); $this->setHolidayForState($holidays, '03-08', self::STATE_AC, 'Alusivo ao Dia Internacional da Mulher'); $this->setHolidayForState($holidays, '06-15', self::STATE_AC, 'Aniversário do Estado'); $this->setHolidayForState($holidays, '09-05', self::STATE_AC, 'Feriado Estadual'); // Dia da Amazônia $this->setHolidayForState($holidays, '11-17', self::STATE_AC, 'Assinatura do Tratado de Petrópolis'); // Opt // Alagoas State $this->setHolidayForState($holidays, '06-24', self::STATE_AL, 'São João'); $this->setHolidayForState($holidays, '06-29', self::STATE_AL, 'São Pedro'); $this->setHolidayForState($holidays, '09-16', self::STATE_AL, 'Emancipação Política'); $this->setHolidayForState($holidays, '11-20', self::STATE_AL, 'Dia da Consciência Negra'); // Amapá State $this->setHolidayForState($holidays, '03-19', self::STATE_AP, 'São José'); $this->setHolidayForState($holidays, '09-13', self::STATE_AP, 'Criação do Território Federal'); // Amazonas State // Elevação do Amazonas à Categoria de Província $this->setHolidayForState($holidays, '09-05', self::STATE_AM, 'Feriado Estadual'); $this->setHolidayForState($holidays, '11-20', self::STATE_AM, 'Dia da Consciência Negra'); // Bahia State $this->setHolidayForState($holidays, '07-02', self::STATE_BA, 'Independência da Bahia'); // Ceará State $this->setHolidayForState($holidays, '03-25', self::STATE_CE, 'Data da Abolição da Escravidão no Ceará'); // Distrito Federal District $this->setHolidayForState($holidays, '04-21', self::STATE_DF, 'Fundação de Brasília'); $this->setHolidayForState($holidays, '11-30', self::STATE_DF, 'Dia do Evangélico'); // Espírito Santo State (Without Holidays) // Goiás State (Without Holidays) // Maranhão State $this->setHolidayForState($holidays, '07-28', self::STATE_MA, 'Adesão do Maranhão à Independência do Brasil'); // Mato Grosso State $this->setHolidayForState($holidays, '11-20', self::STATE_MT, 'Dia da Consciência Negra'); // Mato Grosso do Sul State $this->setHolidayForState($holidays, '10-11', self::STATE_MS, 'Criação do Estado'); // Minas Gerais State $this->setHolidayForState($holidays, '04-21', self::STATE_MG, 'Data Magna do Estado'); // Pará State $this->setHolidayForState($holidays, '08-15', self::STATE_PA, 'Adesão do Grão-Pará à Independência do Brasil'); // Paraíba State $this->setHolidayForState( $holidays, '07-26', self::STATE_PB, 'Homenagem à Memória do Ex-Presidente João Pessoa' ); $this->setHolidayForState($holidays, '08-05', self::STATE_PB, 'Fundação do Estado'); // Paraná State $this->setHolidayForState($holidays, '12-19', self::STATE_PR, 'Emancipação Política'); // Pernambuco State $this->setHolidayForState( $holidays, (new DateTime(sprintf('%s-03 first sunday', $year)))->format(self::DATE_FORMAT), self::STATE_PE, 'Revolução Pernambucana' ); // Piauí State $this->setHolidayForState($holidays, '10-19', self::STATE_PI, 'Dia do Piauí'); // Rio de Janeiro State $this->setHolidayForState($holidays, '04-23', self::STATE_RJ, 'São Jorge'); $this->setHolidayForState($holidays, '11-20', self::STATE_RJ, 'Dia da Consciência Negra'); // Rio Grande do Norte State $this->setHolidayForState($holidays, '10-03', self::STATE_RN, 'Mártires de Cunhaú e Uruaçu'); // Rio Grande do Sul State $this->setHolidayForState($holidays, '09-20', self::STATE_RS, 'Proclamação da República Rio-Grandense'); // Rondônia State $this->setHolidayForState($holidays, '01-04', self::STATE_RO, 'Criação do Estado'); $this->setHolidayForState($holidays, '06-18', self::STATE_RO, 'Dia do Evangélico'); // Roraima State $this->setHolidayForState($holidays, '10-05', self::STATE_RR, 'Criação do Estado'); // Santa Catarina State $this->setHolidayForState($holidays, '07-09', self::STATE_SC, 'Revolução Constitucionalista'); $this->setHolidayForState($holidays, '11-25', self::STATE_SC, 'Santa Catarina de Alexandria'); // São Paulo State $this->setHolidayForState($holidays, '07-09', self::STATE_SP, 'Revolução Constitucionalista'); // Sergipe State $this->setHolidayForState($holidays, '07-08', self::STATE_SE, 'Emancipação Política'); // Tocantins State $this->setHolidayForState($holidays, '03-18', self::STATE_TO, 'Autonomia do Estado'); $this->setHolidayForState($holidays, '09-08', self::STATE_TO, 'Padroeira do Estado'); $this->setHolidayForState($holidays, '10-05', self::STATE_TO, 'Criação do Estado'); return $holidays; }
{@inheritdoc}
entailment
private function setHolidayForState(&$holidays, $day, $state, $name) { // Exists? if (! array_key_exists($day, $holidays)) { // Initialized as State Holiday $holidays[$day] = $this->createData($name, []); } // Is a state holiday? if (is_array($holidays[$day]['states'])) { // Include Current State $holidays[$day]['states'][] = $state; } }
Set Holiday for State This method was created because Brazilian national holidays may conflict with state holidays. For example, "2017-06-15" is a national variable holiday called "Corpus Christi", and is an Acre state fixed holiday called "Aniversário do Estado". In these cases, national holiday will be consider more important. @param array $holidays Holidays Dataset @param string $day Day @param string $state State Name @param string $name Holiday Name
entailment
public function timezone() { $params = array( $this->database, $this->user, $this->password ); return $this->getClient('common')->call('timezone_get', $params); }
Get timezone @return string Current timezone
entailment
public function search($model, $data, $offset = 0, $limit = 100) { $params = $this->buildParams(array( $model, 'search', $data, $offset, $limit )); $response = $this->getClient('object')->call('execute', $params); return $response; }
Search models @param string $model Model @param array $data Array of criteria @param integer $offset Offset @param integer $limit Max results @return array Array of model id's
entailment
public function create($model, $data) { $params = $this->buildParams(array( $model, 'create', $data )); $response = $this->getClient('object')->call('execute', $params); return $response; }
Create model @param string $model Model @param array $data Array of fields with data (format: ['field' => 'value']) @return integer Created model id
entailment
public function read($model, $ids, $fields = array()) { $params = $this->buildParams(array( $model, 'read', $ids, $fields )); $response = $this->getClient('object')->call('execute', $params); return $response; }
Read model(s) @param string $model Model @param array $ids Array of model id's @param array $fields Index array of fields to fetch, an empty array fetches all fields @return array An array of models
entailment
public function unlink($model, $ids) { $params = $this->buildParams(array( $model, 'unlink', $ids )); return $this->getClient('object')->call('execute', $params); }
Unlink model(s) @param string $model Model @param array $ids Array of model id's @return boolean True is successful
entailment
public function getReport($model, $ids, $type = 'qweb-pdf') { $params = $this->buildParams(array( $model, $ids, array( 'model' => $model, 'id' => $ids[0], 'report_type' => $type ) )); $client = $this->getClient('report'); $reportId = $client->call('report', $params); $state = false; while (!$state) { $report = $client->call( 'report_get', $this->buildParams(array($reportId)) ); $state = $report['state']; if (!$state) { sleep(1); } } return base64_decode($report['result']); }
Get report for model @param string $model Model @param array $ids Array of id's, for this method it should typically be an array with one id @param string $type Report type @return mixed A report file
entailment
protected function buildParams(array $params) { return array_merge(array( $this->database, $this->uid(), $this->password ), $params); }
Build parameters @param array $params Array of params to append to the basic params @return array
entailment
protected function getClient($path = null) { if ($path === null) { return $this->client; } if ($this->path === $path) { return $this->client; } $this->path = $path; $this->client = new XmlRpcClient($this->host . '/' . $path, $this->httpClient); // The introspection done by the Zend XmlRpc client is probably specific // to Zend XmlRpc servers. To prevent polution of the Odoo logs with errors // resulting from this introspection calls we disable it. $this->client->setSkipSystemLookup(true); return $this->client; }
Get XmlRpc Client This method returns an XmlRpc Client for the requested endpoint. If no endpoint is specified or if a client for the requested endpoint is already initialized, the last used client will be returned. @param null|string $path The api endpoint @return XmlRpcClient
entailment
protected function uid() { if ($this->uid === null) { $client = $this->getClient('common'); $this->uid = $client->call('login', array( $this->database, $this->user, $this->password )); } return $this->uid; }
Get uid @return int $uid
entailment
public function getHolidaysByYear($year) { $easter = $this->getEasterDates($year); $midSummerDay = $this->getMidSummerDay($year); $allSaintsDay = $this->getAllSaintsDay($year); return array( '01-01' => $this->createData('Nyårsdagen'), '01-05' => $this->createData('Trettondagsafton', array('halfday' => true)), '01-06' => $this->createData('Trettondedag jul'), '04-30' => $this->createData('Valborgsmässoafton', array('halfday' => true)), '05-01' => $this->createData('Första maj'), '06-06' => $this->createData('Sveriges nationaldag'), '12-24' => $this->createData('Julafton'), '12-25' => $this->createData('Juldagen'), '12-26' => $this->createData('Annandag jul'), '12-31' => $this->createData('Nyårsafton'), // Variable dates $easter['maundyThursday']->format(self::DATE_FORMAT) => $this->createData('Skärtorsdagen', array('halfday' => true)), $easter['goodFriday']->format(self::DATE_FORMAT) => $this->createData('Långfredagen'), $easter['saturday']->format(self::DATE_FORMAT) => $this->createData('Påskafton'), $easter['easterSunday']->format(self::DATE_FORMAT) => $this->createData('Påskdagen'), $easter['easterMonday']->format(self::DATE_FORMAT) => $this->createData('Annandag påsk'), $easter['ascensionDay']->format(self::DATE_FORMAT) => $this->createData('Kristi himmelsfärdsdag'), $easter['pentecostSaturday']->format(self::DATE_FORMAT) => $this->createData('Pingstafton'), $easter['pentecostSunday']->format(self::DATE_FORMAT) => $this->createData('Pingstdagen'), $midSummerDay->format(self::DATE_FORMAT) => $this->createData('Midsommardagen'), $midSummerDay->modify('-1 day')->format(self::DATE_FORMAT) => $this->createData('Midsommarafton'), $allSaintsDay->format(self::DATE_FORMAT) => $this->createData('Alla helgons dag'), $allSaintsDay->modify('-1 day')->format(self::DATE_FORMAT) => $this->createData('Allhelgonaafton', array('halfday' => true)) ); }
@param int $year @return array
entailment
public function init() { parent::init(); if ($this->clientRoute === null) { throw new InvalidConfigException('Client route must be specified.'); } if (empty($this->buttonOptions['id'])) { $this->buttonOptions['id'] = $this->options['id'] . '_button'; } if ($this->buttonTag == 'button') { $this->buttonOptions['type'] = 'button'; } if (empty($this->previewOptions['id'])) { $this->previewOptions['id'] = $this->options['id'] . '_preview'; } if (!empty($this->filter)) { $this->options['data']['filter'] = is_string($this->filter) ? $this->filter : Json::encode($this->filter); } if ($this->multiple) { $this->options['data']['multiple'] = '1'; } }
{@inheritdoc} @throws InvalidConfigException
entailment
public function run() { if ($this->textarea) { $this->template = $this->textareaTemplate; if (!isset($this->options['rows'])) { $this->options['rows'] = $this->textareaRows; } } $replace = []; if ($this->hasModel()) { if ($this->textarea) { $replace['{input}'] = Html::activeTextarea($this->model, $this->attribute, $this->options); } else { $replace['{input}'] = Html::activeTextInput($this->model, $this->attribute, $this->options); } } else { if ($this->textarea) { $replace['{input}'] = Html::textarea($this->name, $this->value, $this->options); } else { $replace['{input}'] = Html::textInput($this->name, $this->value, $this->options); } } $replace['{button}'] = Html::tag($this->buttonTag, $this->buttonText, $this->buttonOptions); // preview $replace['{preview}'] = Html::tag($this->previewTag, '', $this->previewOptions); if (is_callable($this->preview)) { $value = null; if ($this->hasModel()) { $value = Html::getAttributeValue($this->model, $this->attribute); } else { $value = $this->value; } if ($value !== null) { $replace['{preview}'] = Html::tag($this->previewTag, call_user_func($this->preview, $value), $this->previewOptions); } } $view = $this->getView(); HelperAsset::register($view); $buttonId = $this->buttonOptions['id']; $route = $this->createRoute(); $url = Url::toRoute($route); $view->registerJs("alexantr.elFinder.registerSelectButton('$buttonId', '$url');", View::POS_END); return strtr($this->template, $replace); }
{@inheritdoc}
entailment
protected function createRoute() { $route = (array)$this->clientRoute; $route['id'] = $this->options['id']; if (!empty($this->filter)) { $route['filter'] = $this->filter; } if ($this->multiple) { $route['multiple'] = 1; } return $route; }
Creates route to elFinder client @return array
entailment
public function build($name, $arg1 = null, $arg2 = null, $arg3 = null, $arg4 = null) { $class = $this->getClass($name); if ($class) { return new $class($arg1, $arg2, $arg3, $arg4); } return null; }
Create an instance of some class
entailment
public function getDirectives() { return array( new Directives\Dummy, new Directives\CodeBlock, new Directives\Raw, new Directives\Replace, new Directives\Toctree, new Directives\Document, new Directives\RedirectionTitle, ); }
Gets the available directives
entailment
public function renderRenderable(RootRenderableInterface $formRuntime): string { if (!$formRuntime instanceof FormRuntime) { throw new FusionException(sprintf('Expected instance of FormRuntime, got %s', is_object($formRuntime) ? get_class($formRuntime) : gettype($formRuntime)), 1503932881); } $formRuntime->beforeRendering($this->formRuntime); $renderingOptions = $this->formRuntime->getRenderingOptions(); if (isset($renderingOptions['_fusionRuntime'])) { $fusionRuntime = $renderingOptions['_fusionRuntime']; if (!$fusionRuntime instanceof Runtime) { throw new FusionException(sprintf('Expected instance of FusionRuntime, got %s', is_object($fusionRuntime) ? get_class($fusionRuntime) : gettype($fusionRuntime)), 1503932883); } $fusionRuntime->pushContext('formRuntime', $this->formRuntime); $output = $fusionRuntime->render('neos_form'); $fusionRuntime->popContext(); return $output; } $fusionView = new FusionView(); $fusionView->setControllerContext($this->controllerContext); $fusionView->disableFallbackView(); $fusionView->setPackageKey('Neos.Form.FusionRenderer'); $fusionView->setFusionPathPatterns([ $this->packageManager->getPackage('Neos.Fusion')->getResourcesPath() . 'Private/Fusion', $this->packageManager->getPackage('Neos.Form.FusionRenderer')->getResourcesPath() . 'Private/Fusion/Core', $this->packageManager->getPackage('Neos.Form.FusionRenderer')->getResourcesPath() . 'Private/Fusion/ContainerElements', $this->packageManager->getPackage('Neos.Form.FusionRenderer')->getResourcesPath() . 'Private/Fusion/Elements', ]); $fusionView->setFusionPath('neos_form'); $fusionView->assign('formRuntime', $formRuntime); return $fusionView->render(); }
Renders the given $formRuntime using Fusion If the $formRuntime specifies a "_fusionRuntime" rendering option that FusionRuntime will be used, otherwise a new FusionView is instantiated. @param RootRenderableInterface $formRuntime @return string @throws FusionException
entailment
public function getHolidaysByYear($year) { $easter = $this->getEasterDates($year); $greatPrayerDay = clone $easter['easterSunday']; $greatPrayerDay->modify('+26 days'); $holidays = array( '01-01' => $this->createData('Nytår'), '12-25' => $this->createData('1. Juledag'), '12-26' => $this->createData('2. Juledag'), // Variable dates $easter['maundyThursday']->format(self::DATE_FORMAT) => $this->createData('Skærtorsdag'), $easter['goodFriday']->format(self::DATE_FORMAT) => $this->createData('Langfredag'), $easter['easterSunday']->format(self::DATE_FORMAT) => $this->createData('Påskedag'), $easter['easterMonday']->format(self::DATE_FORMAT) => $this->createData('2. Påskedag'), $greatPrayerDay->format(self::DATE_FORMAT) => $this->createData('Store Bededag'), $easter['ascensionDay']->format(self::DATE_FORMAT) => $this->createData('Kristi Himmelfartsdag'), $easter['pentecostSunday']->format(self::DATE_FORMAT) => $this->createData('Pinsedag'), $easter['pentecostMonday']->format(self::DATE_FORMAT) => $this->createData('2. Pinsedag') ); return $holidays; }
@param int $year @return mixed
entailment
public function getHolidaysByYear($year) { $easter = $this->getEasterDates($year); $mothersDay = date('m-d', strtotime('second Sunday of May '. $year)); $holidays = array( '01-01' => $this->createData('Jaunais Gads'), '05-01' => $this->createData('Darba svētki'), '05-04' => $this->createData('Latvijas Republikas Neatkarības atjaunošanas diena'), $mothersDay => $this->createData('Mātes diena'), '06-23' => $this->createData('Līgo Diena'), '06-24' => $this->createData('Jāņi'), '11-18' => $this->createData('Latvijas Republikas proklamēšanas diena'), '12-24' => $this->createData('Ziemassvētku vakars'), '12-25' => $this->createData('Ziemassvētki'), '12-26' => $this->createData('Otrie Ziemassvētki'), '12-31' => $this->createData('Vecgada vakars'), // Easter dates $easter['goodFriday']->format(self::DATE_FORMAT) => $this->createData('Lielā Piektdiena'), $easter['easterSunday']->format(self::DATE_FORMAT) => $this->createData('Lieldienas'), $easter['easterMonday']->format(self::DATE_FORMAT) => $this->createData('Otrās Lieldienas'), ); return $holidays; }
Getting non-working holidays @param int $year @return mixed
entailment
public function process(Parser $parser, $node, $variable, $data, array $options) { $document = $parser->getDocument(); $processNode = $this->processNode($parser, $variable, $data, $options); if ($processNode) { if ($variable) { $environment = $parser->getEnvironment(); $environment->setVariable($variable, $processNode); } else { $document->addNode($processNode); } } if ($node) { $document->addNode($node); } }
This is the function called by the parser to process the directive, it can be overloaded to do anything with the document, like tweaking nodes or change the environment The node that directly follows the directive is also passed to it @param $parser the calling parser @param $node the node that follows the directive @param $variable the variable name of the directive @param $data the data of the directive (following ::) @param $ptions the array of options for this directive
entailment
public function processNode(Parser $parser, $variable, $data, array $options) { $this->processAction($parser, $variable, $data, $options); return null; }
This can be overloaded to write a directive that just create one node for the document, which is common The arguments are the same that process
entailment
public function parseLink($line) { // Links if (preg_match('/^\.\. _`(.+)`: (.+)$/mUsi', $line, $match)) { $this->environment->setLink($match[1], $match[2]); return true; } if (preg_match('/^\.\. _(.+): (.+)$/mUsi', $line, $match)) { $this->environment->setLink($match[1], $match[2]); return true; } // Short anonymous links if (preg_match('/^__ (.+)$/mUsi', trim($line), $match)) { $url = $match[1]; $this->environment->setLink('_', $url); return true; } // Anchor link if (preg_match('/^\.\. _(.+):$/mUsi', trim($line), $match)) { $anchor = $match[1]; $this->document->addNode($this->kernel->build('Nodes\AnchorNode', $anchor)); $this->environment->setLink($anchor, '#'.$anchor); return true; } return false; }
Try to parse a link definition @param string $line @return bool
entailment
protected function prepareCode() { if (!$this->buffer) { return false; } $lastLine = trim($this->buffer[count($this->buffer)-1]); if (strlen($lastLine) >= 2) { if (substr($lastLine, -2) == '::') { if (trim($lastLine) == '::') { array_pop($this->buffer); } else { $this->buffer[count($this->buffer)-1] = substr($lastLine, 0, -1); } return true; } } return false; }
Tells if the current buffer is announcing a block of code @return bool
entailment
protected function isSpecialLine($line) { if (strlen($line) < 3) { return false; } $letter = $line[0]; $environment = $this->environment; if (!in_array($letter, $environment::$letters)) { return false; } for ($i=1; $i<strlen($line); $i++) { if ($line[$i] != $letter) { return false; } } return $letter; }
Tell if a line is a special separating line for title and separators, returns the depth of the special line @param string $line @return bool
entailment
protected function findTableChars($line) { $lineChar = $line[0]; $spaceChar = null; for ($i=0; $i<strlen($line); $i++) { if ($line[$i] != $lineChar) { if ($spaceChar == null) { $spaceChar = $line[$i]; } else { if ($line[$i] != $spaceChar) { return false; } } } } return array($lineChar, $spaceChar); }
Finding the table chars @param string $line @return array|bool
entailment
protected function parseTableLine($line) { $header = false; $pretty = false; $line = trim($line); if (!strlen($line)) { return false; } // Finds the table chars $chars = $this->findTableChars($line); if (!$chars) { return false; } if ($chars[0] == Environment::$prettyTableJoint && $chars[1] == Environment::$prettyTableLetter) { $pretty = true; $chars = array(Environment::$prettyTableLetter, Environment::$prettyTableJoint); } else if ($chars[0] == Environment::$prettyTableJoint && $chars[1] == Environment::$prettyTableHeader) { $pretty = true; $header = true; $chars = array(Environment::$prettyTableHeader, Environment::$prettyTableJoint); } else { if (!($chars[0] == Environment::$tableLetter && $chars[1] == ' ')) { return false; } } $parts = array(); $separator = false; // Crawl the line to match those chars for ($i=0; $i<strlen($line); $i++) { if ($line[$i] == $chars[0]) { if (!$separator) { $parts[] = $i; $separator = true; } } else { if ($line[$i] == $chars[1]) { $separator = false; } else { return false; } } } if (count($parts) > 1) { return array( $header, $pretty, $parts ); } return false; }
If the given line is a table line, this will returns the parts of the given line, i.e the offset of the separators ====================== ========= =========== 0 23 33 +---------------------+---------+-----------+ 1 23 33 @param string $line @return mixed
entailment
protected function parseListLine($line) { $depth = 0; for ($i=0; $i<strlen($line); $i++) { $char = $line[$i]; if ($char == ' ') { $depth++; } else if ($char == "\t") { $depth += 2; } else { break; } } if (preg_match('/^((\*|\-)|([\d#]+)\.) (.+)$/', trim($line), $match)) { return array( 'prefix' => $line[$i], 'ordered' => ($line[$i] == '*' || $line[$i] == '-') ? false : true, 'depth' => $depth, 'text' => array($match[4]) ); } return false; }
Parses a list line @param string $line the string line @return array containing: - true if the list is ordered, false else - the depth of the list - the text of the first line without the tick
entailment
protected function isListLine($line) { // A buffer is a list if at least the first line is a list-style $listLine = $this->parseListLine($line); if ($listLine) { return $listLine['depth'] == 0 || !$this->isCode; } return false; }
Is the given line a list line ? @param string $line @return bool true if the given line is a list line
entailment
public function pushListLine($line, $flush = false) { if (trim($line)) { $infos = $this->parseListLine($line); if ($infos) { if ($this->lineInfo) { $this->lineInfo['text'] = $this->createSpan($this->lineInfo['text']); $this->buffer->addLine($this->lineInfo); } $this->lineInfo = $infos; } else { if ($this->listFlow || $line[0] == ' ') { $this->lineInfo['text'][] = $line; } else { $flush = true; } } $this->listFlow = true; } else { $this->listFlow = false; } if ($flush) { if ($this->lineInfo) { $this->lineInfo['text'] = $this->createSpan($this->lineInfo['text']); $this->buffer->addLine($this->lineInfo); $this->lineInfo = null; } return false; } return true; }
Push a line to the current list node buffer @param string $line @param bool $flush @return bool
entailment
protected function initDirective($line) { if (preg_match('/^\.\. (\|(.+)\| |)([^\s]+)::( (.*)|)$/mUsi', $line, $match)) { $this->directive = array( 'variable' => $match[2], 'name' => $match[3], 'data' => trim($match[4]), 'options' => array() ); return true; } return false; }
Get current directive if the buffer contains one .. |variable| name:: data :option: value :otherOption: otherValue @param string $line @return false if this is not a directive, else an array containing : - variable: the variable name of the directive - name: the directive name - data: the data of the directive - options: an array of all the options and their values
entailment
protected function directiveAddOption($line) { if (preg_match('/^(\s+):(.+): (.*)$/mUsi', $line, $match)) { $this->directive['options'][$match[2]] = trim($match[3]); return true; } else if (preg_match('/^(\s+):(.+):(\s*)$/mUsi', $line, $match)) { $value = trim($match[3]); $this->directive['options'][$match[2]] = true; return true; } else { return false; } }
Try to add an option line to the current directive, returns true if sucess and false if failure @param string $line
entailment
protected function getCurrentDirective() { if (!$this->directive) { $this->getEnvironment()->getErrorManager()->error('Asking for current directive, but there is not'); } $name = $this->directive['name']; if (isset($this->directives[$name])) { return $this->directives[$name]; } else { $message = 'Unknown directive: '.$name; $message .= ' in '.$this->getFilename().' line '.$this->getCurrentLine(); $this->getEnvironment()->getErrorManager()->error($message); return null; } }
Gets the current directive @return Directive
entailment
protected function flush() { $node = null; $this->isCode = false; if ($this->buffer) { switch ($this->state) { case self::STATE_TITLE: $data = implode("\n", $this->buffer); $level = $this->environment->getLevel($this->specialLetter); $token = $this->environment->createTitle($level); $node = $this->kernel->build('Nodes\TitleNode', $this->createSpan($data), $level, $token); break; case self::STATE_SEPARATOR: $level = $this->environment->getLevel($this->specialLetter); $node = $this->kernel->build('Nodes\SeparatorNode', $level); break; case self::STATE_CODE: $node = $this->kernel->build('Nodes\CodeNode', $this->buffer); break; case self::STATE_BLOCK: $node = $this->kernel->build('Nodes\QuoteNode', $this->buffer); $data = $node->getValue(); $subParser = $this->getSubParser(); $document = $subParser->parseLocal($data); $node->setValue($document); break; case self::STATE_LIST: $this->pushListLine(null, true); $node = $this->buffer; break; case self::STATE_TABLE: $node = $this->buffer; $node->finalize($this); break; case self::STATE_NORMAL: $this->isCode = $this->prepareCode(); $node = $this->kernel->build('Nodes\ParagraphNode', $this->createSpan($this->buffer)); break; } } if ($this->directive) { $currentDirective = $this->getCurrentDirective(); if ($currentDirective) { $currentDirective->process($this, $node, $this->directive['variable'], $this->directive['data'], $this->directive['options']); } $node = null; } $this->directive = null; if ($node) { $this->document->addNode($node); } $this->init(); }
Flushes the current buffer to create a node
entailment
protected function parseLine(&$line) { switch ($this->state) { case self::STATE_BEGIN: if (trim($line)) { if ($this->isListLine($line)) { $this->state = self::STATE_LIST; $this->buffer = $this->kernel->build('Nodes\ListNode'); $this->lineInfo = null; $this->listFlow = true; return false; } else if ($this->isBlockLine($line)) { if ($this->isCode) { $this->state = self::STATE_CODE; } else { $this->state = self::STATE_BLOCK; } return false; } else if ($this->isDirective($line)) { $this->state = self::STATE_DIRECTIVE; $this->buffer = array(); $this->flush(); $this->initDirective($line); } else if ($this->parseLink($line)) { return true; } else if ($parts = $this->parseTableLine($line)) { $this->state = self::STATE_TABLE; $this->buffer = $this->kernel->build('Nodes\TableNode', $parts); } else { $this->state = self::STATE_NORMAL; return false; } } break; case self::STATE_LIST: if (!$this->pushListLine($line)) { $this->flush(); $this->state = self::STATE_BEGIN; return false; } break; case self::STATE_TABLE: if (!trim($line)) { $this->flush(); $this->state = self::STATE_BEGIN; } else { $parts = $this->parseTableLine($line); if (!$this->buffer->push($parts, $line)) { $this->flush(); $this->state = self::STATE_BEGIN; return false; } } break; case self::STATE_NORMAL: if (trim($line)) { $specialLetter = $this->isSpecialLine($line); if ($specialLetter) { $this->specialLetter = $specialLetter; $lastLine = array_pop($this->buffer); if ($lastLine) { $this->buffer = array($lastLine); $this->state = self::STATE_TITLE; } else { $this->buffer[] = $line; $this->state = self::STATE_SEPARATOR; } $this->flush(); $this->state = self::STATE_BEGIN; } else { if ($this->isDirective($line)) { $this->flush(); $this->state = self::STATE_BEGIN; return false; } if ($this->isComment($line)) { $this->flush(); $this->state = self::STATE_COMMENT; } else { $this->buffer[] = $line; } } } else { $this->flush(); $this->state = self::STATE_BEGIN; } break; case self::STATE_COMMENT: $isComment = false; if (!$this->isComment($line) && (!trim($line) || $line[0] != ' ')) { $this->state = self::STATE_BEGIN; return false; } break; case self::STATE_BLOCK: case self::STATE_CODE: if (!$this->isBlockLine($line)) { $this->flush(); $this->state = self::STATE_BEGIN; return false; } else { $this->buffer[] = $line; } break; case self::STATE_DIRECTIVE: if (!$this->directiveAddOption($line)) { if ($this->isDirective($line)) { $this->flush(); $this->initDirective($line); } else { $directive = $this->getCurrentDirective(); $this->isCode = $directive ? $directive->wantCode() : false; $this->state = self::STATE_BEGIN; return false; } } break; default: $this->getEnvironment()->getErrorManager()->error('Parser ended in an unexcepted state'); } return true; }
Process one line @param string $line the line string
entailment
public function includeFileAllowed($path) { if (!$this->includeAllowed) { return false; } if (!@is_readable($path)) { return false; } if (empty($this->includeRoot)) { return true; } $real = realpath($path); foreach (explode(':', $this->includeRoot) as $root) { if (strpos($real, $root) === 0) { return true; } } return false; }
Is this file allowed to be included? @param $path @return bool
entailment
public function includeFiles($document) { $environment = $this->getEnvironment(); $parser = $this; return preg_replace_callback('/^\.\. include:: (.+)$/m', function($match) use ($parser, $environment) { $path = $environment->absoluteRelativePath($match[1]); if ($parser->includeFileAllowed($path)) { return $parser->includeFiles(file_get_contents($path)); } else { return ''; } }, $document); }
Include all files described in $document and returns the new string of the given document with includes processed
entailment
protected function parseLines($document) { // Including files $document = str_replace("\r\n", "\n", $document); $document = "\n$document\n"; $document = $this->includeFiles($document); // Removing UTF-8 BOM $bom = "\xef\xbb\xbf"; $document = str_replace($bom, '', $document); $lines = explode("\n", $document); $this->state = self::STATE_BEGIN; foreach ($lines as $n => $line) { $this->currentLine = $n; while (!$this->parseLine($line)); } // Document is flushed twice to trigger the directives $this->flush(); $this->flush(); }
Process all the lines of a document string @param string $document the string (content) of the document
entailment
public function setIncludePolicy($allow, $directory = null) { $this->includeAllowed = !empty($allow); if ($directory !== null) { $this->includeRoot = (string) $directory; } return $this; }
Allow/disallow includes, or restrict them to a directory @param bool $allow @param string $directory @return self
entailment
public function getHolidaysByYear($year) { $easter = $this->getEasterDates($year); $repentanceDay = $this->getDayOfRepentance($year); // 500th anniversay of the Reformation // @see https://de.wikipedia.org/wiki/Reformationstag#Deutschland if (2017 === $year) { $reformationDayStates = null; } else { $reformationDayStates = array( self::STATE_BB, self::STATE_MV, self::STATE_SN, self::STATE_ST, self::STATE_TH, self::STATE_SH, self::STATE_HH, self::STATE_NI, self::STATE_HB ); } $holidays = array( // Fixed dates '01-01' => $this->createData('Neujahr'), '05-01' => $this->createData('Tag der Arbeit'), '10-03' => $this->createData('Tag der Deutschen Einheit'), '12-25' => $this->createData('1. Weihnachtstag'), '12-26' => $this->createData('2. Weihnachtstag'), // Fixed with states '01-06' => $this->createData('Heilige Drei Könige', array( self::STATE_BW, self::STATE_BY, self::STATE_ST, )), '10-31' => $this->createData('Reformationstag', $reformationDayStates), '11-01' => $this->createData('Allerheiligen', array( self::STATE_BW, self::STATE_BY, self::STATE_NW, self::STATE_RP, self::STATE_SL, )), // Variable dates $easter['goodFriday']->format(self::DATE_FORMAT) => $this->createData('Karfreitag'), $easter['easterSunday']->format(self::DATE_FORMAT) => $this->createData('Ostersonntag', array( self::STATE_BB, self::STATE_HE, )), $easter['easterMonday']->format(self::DATE_FORMAT) => $this->createData('Ostermontag'), $easter['ascensionDay']->format(self::DATE_FORMAT) => $this->createData('Christi Himmelfahrt'), $easter['pentecostSunday']->format(self::DATE_FORMAT) => $this->createData('Pfingstsonntag', array( self::STATE_BB, self::STATE_HE, )), $easter['pentecostMonday']->format(self::DATE_FORMAT) => $this->createData('Pfingstmontag'), // Variable with states $easter['corpusChristi']->format(self::DATE_FORMAT) => $this->createData('Fronleichnam', array( self::STATE_BW, self::STATE_BY, self::STATE_HE, self::STATE_NW, self::STATE_RP, self::STATE_SL, )), $repentanceDay->format(self::DATE_FORMAT) => $this->createData('Buß- und Bettag', array( self::STATE_SN )) ); return $holidays; }
@param int $year @return array
entailment
public function getTocs() { $tocs = array(); $nodes = $this->getNodes(function($node) { return $node instanceof TocNode; }); foreach ($nodes as $toc) { $files = $toc->getFiles(); foreach ($files as &$file) { $file = $this->environment->canonicalUrl($file); } $tocs[] = $files; } return $tocs; }
Get the table of contents of the document
entailment
public function getTitles() { $titles = array(); $levels = array(&$titles); foreach ($this->nodes as $node) { if ($node instanceof TitleNode) { $level = $node->getLevel(); $text = (string)$node->getValue(); $redirection = $node->getTarget(); $value = $redirection ? array($text, $redirection) : $text; if (isset($levels[$level-1])) { $parent = &$levels[$level-1]; $element = array($value, array()); $parent[] = $element; $levels[$level] = &$parent[count($parent)-1][1]; } } } return $titles; }
Gets the titles hierarchy in arrays, for instance : array( array('Main title', array( array('Sub title', array()), array('Sub title 2', array(), array(array('Redirection', 'target'), array(), ) )
entailment
public function getHolidayByDate(\DateTime $date, $state = null) { $day = $date->format(self::DATE_FORMAT); $holidays = $this->getHolidaysByYear(intval($date->format('Y'))); if (isset($holidays[$day])) { $holiday = $this->createModelFromData($holidays[$day], $date); if (!$this->hasState($holiday, $state)) { $holiday = null; } return $holiday; } return null; }
@param \DateTime $date @param string $state @return Holiday
entailment
protected function createModelFromData(array $data, \DateTime $date) { $holiday = new Holiday( $data['name'], $date, $data['states'] ); return $holiday; }
@param array $data @param \DateTime $date @return Holiday
entailment
protected function hasState(Holiday $holiday, $state = null) { if ($state === null) { return true; } $states = $holiday->getStates(); if (empty($states)) { return true; } if (is_array($states) && in_array($state, $states)) { return true; } return false; }
@param Holiday $holiday @param string $state @return bool
entailment
public function isHoliday($iso, $date = 'now', $state = null) { return ($this->getHoliday($iso, $date, $state) !== null); }
Checks wether a given date is a holiday This method can be used to check whether a specific date is a holiday in a specified country and state @param string $iso @param \DateTime|string $date @param string $state @return bool
entailment
public function getHoliday($iso, $date = 'now', $state = null) { $iso = $this->getIsoCode($iso); $date = $this->getDateTime($date); $provider = $this->getProvider($iso); $holiday = $provider->getHolidayByDate($date, $state); return $holiday; }
Provides detailed information about a specific holiday @param string $iso @param \DateTime|string $date @param string $state @return Holiday|null
entailment
public function pre_commit() { if ( file_exists( self::MARKER_FILE ) ) { unlink( self::MARKER_FILE ); } $hash = md5( file_get_contents( 'README.md' ) ); shell_exec( 'vendor/bin/wp scaffold package-readme . --force > /dev/null 2>&1' ); if ( $hash === md5( file_get_contents( 'README.md' ) ) ) { return; } shell_exec( 'touch ' . self::MARKER_FILE ); }
Try to regenerate the README.md file and memorize whether changes were detected. @since 0.1.0
entailment
public function validate($entity, $context = null) : bool { if (!$entity instanceof AuditEvent) { throw new \LogicException('The Entity to validate must be an instance of \Fei\Service\Audit\Entity\AuditEvent'); } return parent::validate($entity, $context); }
@param mixed $entity @param null $context @return bool @throws \LogicException @throws \ObjectivePHP\Validation\Exception\ValidationException
entailment
public function transform(AuditEvent $auditEvent): array { return array( 'id' => $auditEvent->getId(), 'reported_at' => $auditEvent->getReportedAt()->format(\DateTime::ISO8601), 'level' => (int) $auditEvent->getLevel(), 'namespace' => $auditEvent->getNamespace(), 'message' => $auditEvent->getMessage(), 'backtrace' => $auditEvent->getBackTrace(), 'user' => $auditEvent->getUser(), 'server' => $auditEvent->getServer(), 'command' => $auditEvent->getCommand(), 'origin' => $auditEvent->getOrigin(), 'category' => (int) $auditEvent->getCategory(), 'env' => $auditEvent->getEnv(), 'context' => $auditEvent->getContext(), ); }
@param AuditEvent $auditEvent @return array
entailment
public function setReportedAt($reportedAt) : AuditEvent { if (\is_string($reportedAt)) { $reportedAt = new \DateTime($reportedAt); } $this->reportedAt = $reportedAt; return $this; }
@param $reportedAt @return AuditEvent
entailment
public function setNamespace($namespace) : AuditEvent { $parts = explode('/', $namespace); foreach ($parts as &$part) { $part = Snake::case($part, '-'); } $namespace = implode('/', $parts); $namespace = '/' . trim($namespace, '/'); $this->namespace = $namespace; return $this; }
@param string $namespace @return AuditEvent
entailment
public static function fromV1ToV2(array $context): array { if (array_key_exists('key', $context) && !\is_array($context['key']) && array_key_exists('value', $context) ) { $context = [$context]; } if (count($context) === 1 && !\is_int(key($context))) { $context = [$context]; } $result = []; foreach ($context as $item) { if (\is_array($item) && array_key_exists('key', $item) && !\is_array($item['key']) && array_key_exists('value', $item) ) { $result[$item['key']] = $item['value']; } elseif (\is_array($item) && count($item) === 1 && !isset($result[key($item)])) { $result[key($item)] = current($item); } } return $result; }
@param array $context @return array
entailment
public static function fromV2ToV1(array $context): array { $result = []; foreach ($context as $key => $value) { $result[] = ['key' => $key, 'value' => $value]; } return $result; }
@param array $context @return array
entailment
protected function orderHandler($order_parameter) { list($order, $seed) = $this->getOrderAndSeed($order_parameter); $this->arguments['order'] = $order; $this->arguments['seed'] = $seed; }
Only called when 'order' argument is used. @param string $order_parameter The order argument passed in command line.
entailment
private function getOrderAndSeed($order) { @list($order, $seed) = explode(':', $order, 2); if (empty($seed)) { $seed = $this->getRandomSeed(); } if (!is_numeric($seed)) { $this->showError("Could not use '$seed' as seed."); } return array($order, $seed); }
Parses arguments to know if random order is desired, and if seed was chosen. @param string $order String from command line parameter. @return array
entailment
public function isAllowed(RolesAwareInterface $client) { return ($this->acl) ? $this->acl->isAllowed($client) : false; }
Convenience/Shortcut authorization method for services: Checks if the role-aware client passed is allowed (authorized) to use the service. @param RolesAwareInterface $client @return bool
entailment
protected function extractCompletions($response) { $aggregations = isset($response['aggregations']) ? $response['aggregations'] : []; return array_map(function ($option) { return $option['key']; }, $aggregations['autocomplete']['buckets']); }
Extract autocomplete options @param $response @return array
entailment
protected function printFooter(\PHPUnit\Framework\TestResult $result): void { parent::printFooter($result); $this->writeNewLine(); $this->write("Randomized with seed: {$this->seed}"); $this->writeNewLine(); }
Just add to the output the seed used to randomize the test suite. @param PHPUnit\Framework\TestResult $result
entailment
public function getPermissions() { if ($this->permissions instanceOf PermissionsStorageInterface) { return $this->permissions; } elseif ( is_array($this->permissions) ) { $this->setPermissions( new PermissionsStorage($this->permissions) ); } else { $this->setPermissions( new PermissionsStorage ); } return $this->permissions; }
Returns an instance of PermissionsStorageInterface If none is set, a blank PermissionsStorage will be set and returned. @return \tomkyle\Permissions\PermissionsStorage @uses $permissions @uses setPermissions() @uses \tomkyle\Permissions\PermissionsStorage
entailment
public function parse($input) { $this->inValuePath = false; $this->lexer->setInput($input); $this->lexer->moveNext(); $node = null; if ($this->mode->equals(Mode::FILTER)) { $node = $this->disjunction(); } else { $node = $this->path(); } $this->match(null); return $node; }
@param string $input @return Ast\Node
entailment
private function isName($value, $token) { if (!$token) { return false; } if (!$token->is(Tokens::T_NAME)) { return false; } if (is_array($value)) { foreach ($value as $v) { if (strcasecmp($token->getValue(), $v) === 0) { return true; } } return false; } return strcasecmp($token->getValue(), $value) === 0; }
@param string|string[] $value @param Token|null $token @return bool
entailment
private function randomizeSuiteThatContainsOtherSuites($suite, $seed) { $order = 0; foreach ($suite->tests() as $test) { if ($test instanceof \PHPUnit\Framework\TestSuite && $this->testSuiteContainsOtherSuites($test)) { $this->randomizeSuiteThatContainsOtherSuites($test, $seed); } if ($test instanceof \PHPUnit\Framework\TestSuite) { $this->randomizeSuite($test, $seed, $this->order); } $this->order++; } return $this->randomizeSuite($suite, $seed, $this->order, false); }
Randomize each Test Suite inside the main Test Suite. @param [type] $suite Main Test Suite to randomize. @param [type] $seed Seed to use. @return \PHPUnit\Framework\Test
entailment
private function randomizeSuite($suite, $seed, $order = 0, $fix_depends = true) { $reflected = new \ReflectionObject($suite); $property = $reflected->getProperty('tests'); $property->setAccessible(true); $property->setValue($suite, $this->randomizeTestsCases($suite->tests(), $seed, $order, $fix_depends)); return $suite; }
Randomize the test cases inside a TestSuite, with the given seed. @param \PHPUnit\Framework\Test $suite Test suite to randomize. @param integer $seed Seed to be used for the random funtion. @param integer $order Arbitrary value to "salt" the seed. @param bool $fix_depends [=false] @return \PHPUnit\Framework\Test
entailment
private function fixDependencies(array $tests) { $tests_dependencies = $tests_methods = []; foreach ($tests as $i => $test) { $reflected = new \ReflectionObject($test); $name_field = $dependencies_field = null; while ($reflected = $reflected->getParentClass()) { try { if (empty($dependencies_field)) { $dependencies_field = $reflected->getProperty('dependencies'); $dependencies_field->setAccessible(true); } if (empty($name_field)) { $name_field = $reflected->getProperty('name'); $name_field->setAccessible(true); } } catch (\ReflectionException $e ){ //do nothing } } if (empty($name_field)) { return $tests; } $tests_methods[$name_field->getValue($test)] = $i; if (empty($dependencies = $dependencies_field->getValue($test))){ continue; } foreach ($dependencies as $dependency) { $tests_dependencies[$name_field->getValue($test)] = $dependency; } } if (empty($tests_dependencies)) { return $tests; } $new_order = $this->setOrder($tests_dependencies, $tests_methods); $new_tests_order = []; foreach ($new_order as $test_name) { $new_tests_order[] = $tests[$tests_methods[$test_name]]; } return $new_tests_order; }
fix tests order because of @depends annotations @param array $tests TestCases to randomize. @return array Fixed randomized array
entailment
private function setOrder($tests_dependencies, $tests_methods) { $new_order = []; foreach ($tests_methods as $method_name => $order) { if (isset($tests_dependencies[$method_name]) && !in_array($tests_dependencies[$method_name], $new_order)) { $new_order[] = $tests_dependencies[$method_name]; $this->isDependant($new_order, $tests_dependencies, $tests_methods, $tests_dependencies[$method_name]); } if (!in_array($method_name, $new_order)) { $new_order[] = $method_name; } } return $new_order; }
preapare test methods required order @param array $tests_dependencies tests dependencies array @param array $tests_methods tests (shuffled) array @return array array
entailment
private function isDependant(&$new_order, $tests_dependencies, $tests_methods, $method) { foreach ($tests_dependencies as $dependant => $depends) { if ($method == $dependant && !in_array($depends, $new_order)) { array_splice($new_order, array_search($method, $new_order), 0, [$depends]); $this->isDependant($new_order, $tests_dependencies, $tests_methods, $depends); } } }
check if dependant method has another dependant method (recursive) @param array $new_order tests fixed (shuflled, with dependencies) array @param array $tests_dependencies tests dependencies array @param array $tests_methods tests (shuffled) array @return void
entailment
public static function fromString($string) { $string = trim($string); if (!$string) { throw new \InvalidArgumentException('Empty attribute path'); } $colonPos = strrpos($string, ':'); if ($colonPos !== false) { $schema = substr($string, 0, $colonPos); $path = substr($string, $colonPos + 1); } else { $schema = null; $path = $string; } $parts = explode('.', $path); $attributePath = new static(); $attributePath->schema = $schema; foreach ($parts as $part) { $attributePath->add($part); } return $attributePath; }
@param string $string @return AttributePath
entailment
public function setId($id) { // blacklist if (!(is_string($id) and filter_var($id, \FILTER_VALIDATE_INT) !== false) and !is_int($id)) { throw new \InvalidArgumentException( "Integer ID expected." ); } $this->id = (int) trim($id); return $this; }
Sets the role ID. @param int $id @return RoleAbstract Fluent Interface @uses $id @throws InvalidArgumentException If parameter is not integer-like.
entailment
public function intersect(RolesStorageInterface $roles) { $res = array_intersect($roles->getArrayCopy(), $this->getArrayCopy()); return (!empty($res)); }
Checks if the given RolesStorage has any intersections with this RolesStorage, i.e. if the user has one of the roles stored in this object. @param RolesStorageInterface $roles RolesStorage @return bool @uses RolesStorageInterface::getRoles()
entailment
public function contains( $id ) { $iterator = $this->getIterator(); $role_id = ($id instanceOf RoleInterface) ? $id->getId() : $id; while ($iterator->valid()) { if ($iterator->current() == $role_id) { return true; } $iterator->next(); } return false; }
Checks if the given Role ID exists in the RolesStorage ArrayObject, i.e. if the client is assigned to this role. @param int|RoleInterface $id RoleInterface instance or role ID @return bool
entailment
public function searchAction(NodeInterface $node) { /* @var FusionView $view */ $view = $this->view; $view->setFusionPath('ajaxSearch'); $view->assign('value', $node); }
@param NodeInterface $node @return void
entailment
public function get($key, $default = null) { $this->validateKey($key); $value = $this->doctrineCache->fetch($key); if ($value === false) { // Doctrine cache returns `false` when cache doesn't contain, but also `false` if the value stored is // `false`, so check to see if the cache contains the key; if so, we probably meant to return `false` if ($this->doctrineCache->contains($key)) { return false; } return $default; } return $value; }
{@inheritDoc}
entailment
public function set($key, $value, $ttl = null) : bool { $this->validateKey($key); if ($ttl === null) { return $this->doctrineCache->save($key, $value); } if ($ttl instanceof \DateInterval) { $ttl = $this->convertDateIntervalToInteger($ttl); } if (!is_int($ttl)) { throw InvalidArgumentException::fromKeyAndInvalidTTL($key, $ttl); } if ($ttl <= 0) { return $this->delete($key); } return $this->doctrineCache->save($key, $value, $ttl); }
{@inheritDoc}
entailment
public function delete($key) : bool { $this->validateKey($key); return $this->doctrineCache->delete($key); }
{@inheritDoc}
entailment
public function has($key) : bool { $this->validateKey($key); return $this->doctrineCache->contains($key); }
{@inheritDoc}
entailment
public function getRoles() { if ($this->roles instanceOf RolesStorageInterface) { return $this->roles; } $this->setRoles( new RolesStorage( $this->roles ) ); return $this->roles; }
Returns an instance of RolesStorageInterface containing all roles the client is assigned to. Id none is defined, an (empty) RolesStorage will be set, configured with the roles refined in `$roles` member array. @return RolesStorageInterface @uses $roles
entailment
private function startServer() { if ($this->resource !== null) { return; } $this->writeln(PHP_EOL); $this->writeln('Starting PhantomJS Server.'); $command = $this->getCommand(); if ($this->config['debug']) { $this->writeln(PHP_EOL); // Output the generated command. $this->writeln('Generated PhantomJS Command:'); $this->writeln($command); $this->writeln(PHP_EOL); } $descriptorSpec = [ ['pipe', 'r'], ['file', $this->getLogDir() . 'phantomjs.output.txt', 'w'], ['file', $this->getLogDir() . 'phantomjs.errors.txt', 'a'], ]; $this->resource = proc_open($command, $descriptorSpec, $this->pipes, null, null, ['bypass_shell' => true]); if (!is_resource($this->resource) || !proc_get_status($this->resource)['running']) { proc_close($this->resource); throw new ExtensionException($this, 'Failed to start PhantomJS server.'); } // Wait till the server is reachable before continuing. $max_checks = 10; $checks = 0; $this->write('Waiting for the PhantomJS server to be reachable.'); while (true) { if ($checks >= $max_checks) { throw new ExtensionException($this, 'PhantomJS server never became reachable.'); } $fp = @fsockopen('127.0.0.1', $this->config['port'], $errCode, $errStr, 10); if ($fp) { $this->writeln(''); $this->writeln('PhantomJS server now accessible.'); fclose($fp); break; } $this->write('.'); $checks++; // Wait before checking again. sleep(1); } // Clear progress line writing. $this->writeln(''); }
Start PhantomJS server. @throws \Codeception\Exception\ExtensionException
entailment
private function stopServer() { if ($this->resource !== null) { $this->write('Stopping PhantomJS Server.'); // Wait till the server has been stopped. $max_checks = 10; for ($i = 0; $i < $max_checks; $i++) { // If we're on the last loop, and it's still not shut down, just // unset resource to allow the tests to finish. if ($i === $max_checks - 1 && proc_get_status($this->resource)['running'] === true) { $this->writeln(''); $this->writeln('Unable to properly shutdown PhantomJS server.'); unset($this->resource); break; } // Check if the process has stopped yet. if (proc_get_status($this->resource)['running'] === false) { $this->writeln(''); $this->writeln('PhantomJS server stopped.'); unset($this->resource); break; } foreach ($this->pipes as $pipe) { if (is_resource($pipe)) { fclose($pipe); } } // Terminate the process. // Note: Use of SIGINT adds dependency on PCTNL extension so we // use the integer value instead. proc_terminate($this->resource, 2); $this->write('.'); // Wait before checking again. sleep(1); } } }
Stop PhantomJS server.
entailment
private function getCommandParameters() { // Map our config options to PhantomJS options. $mapping = [ 'port' => '--webdriver', 'proxy' => '--proxy', 'proxyType' => '--proxy-type', 'proxyAuth' => '--proxy-auth', 'webSecurity' => '--web-security', 'ignoreSslErrors' => '--ignore-ssl-errors', 'sslProtocol' => '--ssl-protocol', 'sslCertificatesPath' => '--ssl-certificates-path', 'remoteDebuggerPort' => '--remote-debugger-port', 'remoteDebuggerAutorun' => '--remote-debugger-autorun', 'cookiesFile' => '--cookies-file', 'diskCache' => '--disk-cache', 'maxDiskCacheSize' => '--max-disk-cache-size', 'loadImages' => '--load-images', 'localStoragePath' => '--local-storage-path', 'localStorageQuota' => '--local-storage-quota', 'localToRemoteUrlAccess' => '--local-to-remote-url-access', 'outputEncoding' => '--output-encoding', 'scriptEncoding' => '--script-encoding', 'webdriverLoglevel' => '--webdriver-loglevel', 'webdriverLogfile' => '--webdriver-logfile', ]; $params = []; foreach ($this->config as $configKey => $configValue) { if (!empty($mapping[$configKey])) { if (is_bool($configValue)) { // Make sure the value is true/false and not 1/0. $configValue = $configValue ? 'true' : 'false'; } $params[] = $mapping[$configKey] . '=' . $configValue; } } return implode(' ', $params); }
Build the parameters for our command. @return string All parameters separated by spaces.
entailment
private function getCommand() { // Prefix command with exec on non Windows systems to ensure that we // receive the correct pid. // See http://php.net/manual/en/function.proc-get-status.php#93382 $commandPrefix = $this->isWindows() ? '' : 'exec '; return $commandPrefix . escapeshellarg(realpath($this->config['path'])) . ' ' . $this->getCommandParameters(); }
Get PhantomJS command. @return string Command to execute.
entailment
public function suiteInit(SuiteEvent $e) { // Check if PhantomJS should only be started for specific suites. if (isset($this->config['suites'])) { if (is_string($this->config['suites'])) { $suites = [$this->config['suites']]; } else { $suites = $this->config['suites']; } // If the current suites aren't in the desired array, return without // starting PhantomJS. if (!in_array($e->getSuite()->getBaseName(), $suites, true) && !in_array($e->getSuite()->getName(), $suites, true)) { return; } } // Start the PhantomJS server. $this->startServer(); }
Suite Init. @param \Codeception\Event\SuiteEvent $e The event with suite, result and settings. @throws \Codeception\Exception\ExtensionException
entailment
public function handle(Request $request, Closure $next, MediaTypeGuard $guard = null) { // $guard = $guard ?? app(MediaTypeGuard::class); if (!$guard->validateExistingContentType($request) || !$guard->hasCorrectHeadersForData($request)) { $errors = (new ErrorCollection())->add(ErrorFactory::buildUnsupportedMediaType()); $encoder = Encoder::instance([], new EncoderOptions(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); return new Response($encoder->encodeErrors($errors), 415, ['Content-Type' => $guard->getContentType()]); } if (!$guard->hasCorrectlySetAcceptHeader($request)) { $errors = (new ErrorCollection())->add(ErrorFactory::buildUnacceptable()); $encoder = Encoder::instance([], new EncoderOptions(JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES)); return new Response($encoder->encodeErrors($errors), 406, ['Content-Type' => $guard->getContentType()]); } $response = $next($request); $response->header('Content-Type', $guard->getContentType()); return $response; }
Adds support for the Server Responsibilities section of content negotiation spec for json-api. @see http://jsonapi.org/format/#content-negotiation
entailment
public function filter(ProxyQueryInterface $query, $alias, $field, $data) { if (!$data || !\is_array($data) || !\array_key_exists('type', $data) || !\array_key_exists('value', $data)) { return; } if (\is_array($data['value'])) { $values = []; foreach ($data['value'] as $v) { if (!\in_array($v, [BooleanType::TYPE_NO, BooleanType::TYPE_YES], true)) { continue; } $values[] = (BooleanType::TYPE_YES === $v); } if (0 === \count($values)) { return; } $queryBuilder = new \Elastica\Query\Builder(); $queryBuilder ->fieldOpen('terms') ->field($field, $values) ->fieldClose(); $query->addMust($queryBuilder); } else { if (!\in_array($data['value'], [BooleanType::TYPE_NO, BooleanType::TYPE_YES], true)) { return; } $queryBuilder = new \Elastica\Query\Builder(); $queryBuilder ->fieldOpen('term') ->field($field, (BooleanType::TYPE_YES === $data['value'])) ->fieldClose(); $query->addMust($queryBuilder); } }
{@inheritdoc}
entailment
public function asJavascript() { return implode("\n ", array_map(function ($push) { return '_paq.push([' . implode(', ', array_map(function ($item) { if ($item instanceof RawExpression) { return $item->value; } // JSON encoding is used to escape data injected into javascript return json_encode($item); }, $push)) . ']);'; }, $this->pushs)); }
Creates the javascript output for the _paq.push() calls @return string
entailment
public function execute(array $params = [], $hydrationMode = null) { // TODO find method names // Sorted field and sort order $sortBy = $this->getSortBy(); $sortOrder = $this->getSortOrder(); if ($sortBy && $sortOrder) { $this->query->setSort([$sortBy => ['order' => strtolower($sortOrder)]]); } return $this->finder->createPaginatorAdapter( $this->query, [ Search::OPTION_SIZE => $this->getMaxResults(), Search::OPTION_FROM => $this->getFirstResult(), ] ); }
{@inheritdoc}
entailment
public function setSortBy($parentAssociationMappings, $fieldMapping) { $alias = ''; foreach ((array) $parentAssociationMappings as $associationMapping) { $alias .= $associationMapping['fieldName'].'.'; } $this->sortBy = $alias.$fieldMapping['fieldName']; return $this; }
{@inheritdoc}
entailment
public function addShould($args) { $this->boolQuery->addShould($args); $this->query = new \Elastica\Query($this->boolQuery); }
Add should part to query. @param AbstractQuery|array $args Should query @return ElasticaProxyQuery
entailment
public static function displayFilename (FtpFile $file, FtpWidget $context) { if ($context->allowNavigation && self::isDir($file)) { $dir = $context->baseFolder."/".$file->filename; if ($context->baseFolder == "/") { $dir = "/".$file->filename; } if ($file->filename == '..') { $dir = str_replace('\\', '/', dirname($context->baseFolder)); } $arr = array_merge([""], $_GET, [$context->navKey => $dir]); return \yii\helpers\Html::a($file->filename, $arr); } else { return $file->filename; } }
Build filename for FtpWidget. @param FtpFile $file Current {@link FtpFile} @param FtpWidget $context Current displayable widget @return string Displayed filename
entailment
public function setExpiry(int $expires = null):AccessToken{ $now = time(); if($expires!== null){ $expires = intval($expires); } $this->expires = self::EOL_UNKNOWN; if($expires === 0 || $expires === self::EOL_NEVER_EXPIRES){ $this->expires = self::EOL_NEVER_EXPIRES; } elseif($expires > $now){ $this->expires = $expires; } elseif($expires > 0 && $expires < self::EXPIRY_MAX){ $this->expires = $now + $expires; } return $this; }
@param int $expires @return \chillerlan\OAuth\Core\AccessToken|\chillerlan\Settings\SettingsContainerInterface
entailment
protected function checkState(string $state = null):void{ if(empty($state) || !$this->storage->hasCSRFState($this->serviceName)){ throw new ProviderException('invalid state for '.$this->serviceName); } $knownState = $this->storage->getCSRFState($this->serviceName); if(!hash_equals($knownState, $state)){ throw new ProviderException('invalid CSRF state: '.$this->serviceName.' '.$state); } }
@param string|null $state @return void @throws \chillerlan\OAuth\Core\ProviderException
entailment
protected function setState(array $params):array{ if(!isset($params['state'])){ $params['state'] = sha1(random_bytes(256)); } $this->storage->storeCSRFState($this->serviceName, $params['state']); return $params; }
@param array $params @return array
entailment
public function getAuthURL(array $params = null):UriInterface{ $params = array_merge( $params ?? [], ['oauth_token' => $this->getRequestToken()->accessToken] ); return $this->uriFactory->createUri(Psr7\merge_query($this->authURL, $params)); }
@param array $params @return \Psr\Http\Message\UriInterface
entailment
protected function parseTokenResponse(ResponseInterface $response, bool $checkCallbackConfirmed = null):AccessToken{ parse_str(Psr7\decompress_content($response), $data); if(!$data || !is_array($data)){ throw new ProviderException('unable to parse token response'); } elseif(isset($data['error'])){ throw new ProviderException('error retrieving access token: '.$data['error']); } elseif(!isset($data['oauth_token']) || !isset($data['oauth_token_secret'])){ throw new ProviderException('invalid token'); } if($checkCallbackConfirmed && (!isset($data['oauth_callback_confirmed']) || $data['oauth_callback_confirmed'] !== 'true')){ throw new ProviderException('oauth callback unconfirmed'); } $token = new AccessToken([ 'provider' => $this->serviceName, 'accessToken' => $data['oauth_token'], 'accessTokenSecret' => $data['oauth_token_secret'], 'expires' => AccessToken::EOL_NEVER_EXPIRES, ]); unset($data['oauth_token'], $data['oauth_token_secret']); $token->extraParams = $data; $this->storage->storeAccessToken($this->serviceName, $token); return $token; }
@param \Psr\Http\Message\ResponseInterface $response @param bool|null $checkCallbackConfirmed @return \chillerlan\OAuth\Core\AccessToken|\chillerlan\Settings\SettingsContainerInterface @throws \chillerlan\OAuth\Core\ProviderException
entailment
protected function getSignature(string $url, array $params, string $method, string $accessTokenSecret = null):string{ $parseURL = parse_url($url); if(!isset($parseURL['host']) || !isset($parseURL['scheme']) || !in_array($parseURL['scheme'], ['http', 'https'], true)){ throw new ProviderException('getSignature: invalid url'); } parse_str($parseURL['query'] ?? '', $query); $signatureParams = array_merge($query, $params); if(isset($signatureParams['oauth_signature'])){ unset($signatureParams['oauth_signature']); } $key = implode('&', Psr7\r_rawurlencode([$this->options->secret, $accessTokenSecret ?? ''])); $data = Psr7\r_rawurlencode([ strtoupper($method ?? 'POST'), $parseURL['scheme'].'://'.$parseURL['host'].($parseURL['path'] ?? ''), Psr7\build_http_query($signatureParams), ]); return base64_encode(hash_hmac('sha1', implode('&', $data), $key, true)); }
@param string $url @param array $params @param string $method @param string $accessTokenSecret @return string @throws \chillerlan\OAuth\Core\ProviderException
entailment
public function getAccessToken(string $token, string $verifier):AccessToken{ $request = $this->requestFactory ->createRequest('POST', Psr7\merge_query($this->accessTokenURL, ['oauth_verifier' => $verifier])) ->withHeader('Accept-Encoding', 'identity') ; $request = $this->getRequestAuthorization($request, $this->storage->getAccessToken($this->serviceName)); return $this->parseTokenResponse($this->http->sendRequest($request)); }
@param string $token @param string $verifier @return \chillerlan\OAuth\Core\AccessToken|\chillerlan\Settings\SettingsContainerInterface
entailment
public function getRequestAuthorization(RequestInterface $request, AccessToken $token):RequestInterface{ $uri = $request->getUri(); parse_str($uri->getQuery(), $query); $parameters = [ 'oauth_consumer_key' => $this->options->key, 'oauth_nonce' => $this->nonce(), 'oauth_signature_method' => 'HMAC-SHA1', 'oauth_timestamp' => (new DateTime)->format('U'), 'oauth_token' => $token->accessToken, 'oauth_version' => '1.0', ]; $parameters['oauth_signature'] = $this->getSignature( (string)$uri->withQuery('')->withFragment(''), array_merge($query, $parameters), $request->getMethod(), $token->accessTokenSecret ); if(isset($query['oauth_session_handle'])){ $parameters['oauth_session_handle'] = $query['oauth_session_handle']; } return $request->withHeader('Authorization', 'OAuth '.Psr7\build_http_query($parameters, true, ', ', '"')); }
@param \Psr\Http\Message\RequestInterface $request @param \chillerlan\OAuth\Core\AccessToken $token @return \Psr\Http\Message\RequestInterface
entailment
public function authorize( string $action, $object, array $source = null ) { if ($this->request()->user()->cant($action, $object)) { throw new RequestFailedAuthorization( new Error( $id = null, $link = new Link('https://tools.ietf.org/html/rfc7231#section-6.5.3'), $status = '403', $code = null, $title = 'Forbidden', $desc = 'Access is denied for one or more of the specified resources', $source, $meta = null ) ); } return true; }
Ensure that a requested operation is authorized. If not, throw an exception. This requires a registered Policy. If no policy is defined, the framework will throw InvalidArgumentException. See also: https://laravel.com/docs/master/authorization http://jsonapi.org/format/#errors @param string $action Desired action; must match a policy method name. @param mixed $object Target object; class must match a policy. @param array $source Reference to source of error in request. @return bool True on success; throws exception on failure. @throws RequestFailedAuthorization TODO: use a UUID for the source?
entailment
public function addFilter(DatagridInterface $datagrid, $type, FieldDescriptionInterface $fieldDescription, AdminInterface $admin) { return $this->getAdminDatagridBuilder($admin, $datagrid instanceof Datagrid)->addFilter( $datagrid, $type, $fieldDescription, $admin ); }
{@inheritdoc}
entailment