sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function addOption($name, $shortcut = null, $mode = null, $description = '', $default = null) { if (empty($name)) { throw new \InvalidArgumentException('An option name cannot be empty.'); } if (null === $mode) { $mode = self::VALUE_NONE; } elseif (!is_int($mode) || $mode > 15 || $mode < 1) { throw new \InvalidArgumentException(sprintf('Option mode "%s" is not valid.', $mode)); } $this->options[] = [$name, $shortcut, $mode, $description, $default]; }
Adds a new command option. @param string $name The option name @param string|array $shortcut The shortcuts, can be null, a string of shortcuts delimited by | or an array of shortcuts @param int $mode The option mode: One of the VALUE_* constants @param string $description A description text @param mixed $default The default value (must be null for self::VALUE_REQUIRED or self::VALUE_NONE) @throws \InvalidArgumentException If name is empty or option mode is invalid or incompatible
entailment
public function callInitialize() { foreach ($this->pluginCollection as $plugin) { $subscriber = new EventSubscriber(); $plugin->initialize($subscriber); $this->eventSubscriberPlugins[] = [$plugin, $subscriber]; $this->addListeners($plugin, $subscriber); } }
Invokes initialize method for each plugin registered.
entailment
public function tearDown() { foreach ($this->eventSubscriberPlugins as list($plugin, $eventSubscriber)) { $this->removeListeners($plugin, $eventSubscriber); } }
Releases resources like event listeners.
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $options = [ 'no-dev' => !$input->getOption('dev'), 'no-scripts' => !$input->getOption('no-scripts'), ]; $this->initialMessage($io); $packageManager = $this->getPackageManager(getcwd(), $io); $packageManager->removePackage( $input->getArgument('packages'), $input->getOption('dev') ); try { $packageManager->update($options); } catch (\Exception $e) { $io->error('Removing failed. Reverting changes...'); $packageManager->addPackage( $input->getArgument('packages'), $input->getOption('dev') ); $io->write('Changes reverted successfully!'); $io->newLine(); return 1; } $io->success('Plugins and themes removed'); }
{@inheritdoc}
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $packageManager = $this->getPackageManager($input->getArgument('path'), $io); $generator = new ThemeGenerator($packageManager); $generator->setSkeletonDirs([$this->getSkeletonsDir()]); $this->startingMessage( $io, $input->getArgument('package'), $packageManager->getRootDirectory() ); $options = [ 'prefer-source' => $input->getOption('prefer-source'), 'repository' => $input->getOption('repository'), ]; $generator->generate( $packageManager->getRootDirectory(), $input->getArgument('package'), $input->getOption('force'), $options ); $this->updateRequirementsMessage($io); $options = array_merge($options, [ 'no-dev' => !$input->getOption('dev'), 'no-scripts' => $input->getOption('no-scripts'), ]); if ($input->getOption('prefer-lock') === true) { $packageManager->install($options); } else { $packageManager->update($options); } $packageManager->rewritingSelfVersionDependencies(); $this->okMessage($io); }
{@inheritdoc}
entailment
protected function startingMessage(ConsoleIO $io, $packageName, $siteDir) { $io->newLine(); $io->write(sprintf( '<comment>Installing theme: "%s" in "%s" folder</comment>', $packageName, $siteDir )); $io->newLine(); }
Writes the staring messages. @param ConsoleIO $io Spress IO @param string $template The template
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $io = new ConsoleIO($input, $output); $pmOptions = [ 'dry-run' => $input->getOption('dry-run'), 'prefer-source' => $input->getOption('prefer-source'), 'no-dev' => !$input->getOption('dev'), 'no-scripts' => !$input->getOption('no-scripts'), ]; $this->initialMessage($io); $packageManager = $this->getPackageManager('./', $io); if ($input->getOption('prefer-lock') === true) { $packageManager->install($pmOptions, $input->getArgument('packages')); } else { $packageManager->update($pmOptions, $input->getArgument('packages')); } }
{@inheritdoc}
entailment
public function generateItems(ItemInterface $templateItem, array $collections) { $result = []; $options = $this->getAttributesResolver($templateItem); if ($options['max_page'] < 1) { throw new AttributeValueException('Items per page value must be great than 0.', 'max_page', $templateItem->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE)); } $providerName = $this->providerToCollection($options['provider']); $templateItemPath = $templateItem->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE); $providerItems = $this->getProviderItems($collections, $providerName, $templateItemPath); if (empty($options['sort_by']) === false) { $providerItems = $this->sortItemsByAttribute($providerItems, $options['sort_by'], $options['sort_type']); } $pages = (new ArrayWrapper($providerItems))->paginate($options['max_page']); $totalPages = count($pages); $totalItems = count($providerItems); $templatePath = dirname($templateItem->getPath(Item::SNAPSHOT_PATH_RELATIVE)); if ($templatePath === '.') { $templatePath = ''; } foreach ($pages as $page => $items) { $previousPage = $page > 1 ? $page - 1 : null; $previousPagePath = $this->getPageRelativePath($templatePath, $options['permalink'], $previousPage); $previousPageUrl = $this->getPagePermalink($previousPagePath); $nextPage = $page === $totalPages ? null : $page + 1; $nextPagePath = $this->getPageRelativePath($templatePath, $options['permalink'], $nextPage); $nextPageUrl = $this->getPagePermalink($nextPagePath); $pageAttr = new ArrayWrapper($templateItem->getAttributes()); $pageAttr->set('pagination.per_page', $options['max_page']); $pageAttr->set('pagination.total_items', $totalItems); $pageAttr->set('pagination.total_pages', $totalPages); $pageAttr->set('pagination.page', $page); $pageAttr->set('pagination.previous_page', $previousPage); $pageAttr->set('pagination.previous_page_path', $previousPagePath); $pageAttr->set('pagination.previous_page_url', $previousPageUrl); $pageAttr->set('pagination.next_page', $nextPage); $pageAttr->set('pagination.next_page_path', $nextPagePath); $pageAttr->set('pagination.next_page_url', $nextPageUrl); $pageAttr->remove('permalink'); $pagePath = $this->getPageRelativePath($templatePath, $options['permalink'], $page); $permalink = $this->getPagePermalink($pagePath); $item = new PaginationItem($templateItem->getContent(), $pagePath, $pageAttr->getArray()); $item->setPageItems($items); $item->setPath($pagePath, Item::SNAPSHOT_PATH_RELATIVE); $item->setPath($permalink, Item::SNAPSHOT_PATH_PERMALINK); $result[] = $item; } return $result; }
{@inheritdoc} @throws Yosymfony\Spress\Core\ContentManager\Exception\AttributeValueException if bad attribute value
entailment
public function get($section, $key, $default = null) { $this->checksValidTypes($default); if (isset($this->metadata[$section]) === true && array_key_exists($key, $this->metadata[$section])) { return $this->metadata[$section][$key]; } return $default; }
{@inheritdoc}
entailment
public function set($section, $key, $value) { $this->checksValidTypes($value); if (isset($this->metadata[$section]) === false) { $this->metadata[$section] = []; } $this->metadata[$section][$key] = $value; }
{@inheritdoc}
entailment
public function remove($section, $key = null) { if ($key === null) { $this->metadata[$section] = []; } if (isset($this->metadata[$section]) === true) { unset($this->metadata[$section][$key]); } if (count($this->metadata[$section]) === 0) { unset($this->metadata[$section]); } }
{@inheritdoc}
entailment
public function buildFromConfigArray(array $config) { $dsm = new DataSourceManager(); foreach ($config as $dataSourceName => $data) { if (false === isset($data['class'])) { throw new \RuntimeException(sprintf('Expected param "class" at the configuration of the data source: "%s".', $dataSourceName)); } $classname = $data['class']; $arguments = true === isset($data['arguments']) ? $data['arguments'] : []; if (count($this->parameterKeys) > 0 && count($arguments) > 0) { $arguments = $this->resolveArgumentsParameters($arguments); } if (false === class_exists($classname)) { throw new \RuntimeException(sprintf('Data source "%s" class not found: "%s".', $dataSourceName, $classname)); } $ds = new $classname($arguments); $dsm->addDataSource($dataSourceName, $ds); } return $dsm; }
Build a data source manager with data sources loaded from config array. Config array structure: .Array ( [data_source_name_1] => Array ( [class] => Yosymfony\Spress\Core\DataSource\Filesystem\FilesystemDataSource [arguments] => Array ( [source_root] => %site_dir%/src ) ) [data_source_name_2] => Array ( ) ) @param array $config Configuration array with data about data sources @return \Yosymfony\Spress\Core\DataSource\DataSourceManager @throws \RuntimeException if params "class" not found or the class pointed by "class" params not exists
entailment
protected function resolveArgumentsParameters(array $arguments) { foreach ($arguments as $argument => &$value) { if (is_string($value) === false || preg_match('/%[\S_\-]+%/', $value, $matches) === false) { continue; } $name = $matches[0]; if (array_key_exists($name, $this->parameters) === false) { continue; } if (is_string($this->parameters[$name])) { $value = str_replace($name, $this->parameters[$name], (string) $value); continue; } $value = $this->parameters[$name]; } return $arguments; }
Resolve parameters in arguments. @param array $arguments @return array
entailment
public function add($key, $value) { if ($this->has($key) === false) { $this->set($key, $value); } return $this->array; }
Adds an element using "dot" notation if doesn't exists. You can to escape a dot in a key surrendering with brackets: "[.]". @param $key @param $value @return array
entailment
public function get($key, $default = null) { $array = $this->array; $unescapedKey = $this->unescapeDotKey($key); if (isset($array[$unescapedKey])) { return $array[$unescapedKey]; } foreach (explode('.', $this->escapedDotKeyToUnderscore($key)) as $segment) { $segment = $this->underscoreDotKeyToDot($segment); if (is_array($array) === false || array_key_exists($segment, $array) === false) { return $default; } $array = $array[$segment]; } return $array; }
Gets a value from a deeply nested array using "dot" notation. You can to escape a dot in a key surrendering with brackets: "[.]". e.g: $a->get('site.data') or $a->get('site.pages.index[.]html') @param string $key @param mixed $default @return mixed
entailment
public function has($key) { $array = $this->array; if (empty($array) || is_null($key)) { return false; } if (array_key_exists($this->unescapeDotKey($key), $array)) { return true; } foreach (explode('.', $this->escapedDotKeyToUnderscore($key)) as $segment) { $segment = $this->underscoreDotKeyToDot($segment); if (is_array($array) === false || array_key_exists($segment, $array) === false) { return false; } $array = $array[$segment]; } return true; }
Checks if an item exists in using "dot" notation. You can to escape a dot in a key surrendering with brackets: "[.]". @param string $key @return bool
entailment
public function paginate($maxPerPage, $initialPage = 1, $key = null) { $result = []; $page = $initialPage; $array = $this->array; if ($maxPerPage <= 0) { return $result; } if (is_null($key) === false) { $array = $this->get($key); } $arrCount = count($array); for ($offset = 0; $offset < $arrCount;) { $slice = array_slice($array, $offset, $maxPerPage, true); $result[$page] = $slice; ++$page; $offset += count($slice); } return $result; }
Paginates the array. @param int $maxPerPage Max items per page. If this value is minor than 1 the result will be an empty array @param int $initialPage Initial page. Page 1 by default @param string $key Element to paginate using "dot" notation @return array A list of pages with an array of elements associated with each page
entailment
public function remove($key) { $array = &$this->array; if (is_null($key)) { return $array; } $keys = explode('.', $this->escapedDotKeyToUnderscore($key)); while (count($keys) > 1) { $key = $this->underscoreDotKeyToDot(array_shift($keys)); if (isset($array[$key]) === false || is_array($array[$key]) === false) { $array[$key] = []; } $array = &$array[$key]; } unset($array[$this->underscoreDotKeyToDot(array_shift($keys))]); return $this->array; }
Removes an item using "dot" notation. @param string $key @return array
entailment
public function sort($key = null, callable $callback = null) { $elements = is_null($key) === true ? $this->array : $this->get($key); $sortCallback = is_null($callback) === false ? $callback : function ($element1, $element2) { if ($element1 == $element2) { return 0; } return ($element1 < $element2) ? -1 : 1; }; uasort($elements, $sortCallback); return $elements; }
Sorts the array (ascendant by default). @param string $key Element to sort using "dot" notation. You can to escape a dot in a key surrendering with brackets: "[.]" @param callable $callback Callback should be a function with the following signature: ```php function($element1, $element2) { // returns -1, 0 or 1 } ``` @return array
entailment
public function sortBy(callable $callback, $key = null, $options = SORT_REGULAR, $isDescending = false) { $elements = []; $sourceElements = is_null($key) === true ? $this->array : $this->get($key); foreach ($sourceElements as $key => $value) { $elements[$key] = $callback($key, $value); } $isDescending ? arsort($elements, $options) : asort($elements, $options); foreach (array_keys($elements) as $key) { $elements[$key] = $sourceElements[$key]; } return $elements; }
Sort the array sing the given callback. @param callable $callback Callback should be a function with the following signature: ```php function($key, $value) { // return $processedValue; } ``` @param string $key Element to sort using "dot" notation. You can to escape a dot in a key surrendering with brackets: "[.]" @param int $options See sort_flags at http://php.net/manual/es/function.sort.php @param bool $isDescending @return array
entailment
public function where(callable $filter) { $filtered = []; foreach ($this->array as $key => $value) { if ($filter($key, $value) === true) { $filtered[$key] = $value; } } return $filtered; }
Filter using the given callback function. @param callable $filter The filter function should be a function with the following signature: ```php function($key, $value) { // returns true if the value is matching your criteria. } ``` @return array
entailment
public function toAscii($removeUnsupported = true) { $str = $this->str; foreach ($this->getChars() as $key => $value) { $str = str_replace($value, $key, $str); } if ($removeUnsupported) { $str = preg_replace('/[^\x20-\x7E]/u', '', $str); } return $str; }
Transliterate a UTF-8 value to ASCII. @param bool $removeUnsupported Whether or not to remove the unsupported characters @return string
entailment
public function slug($separator = '-') { $str = $this->toAscii(); $flip = $separator == '-' ? '_' : '-'; $str = str_replace('.', $separator, $str); $str = preg_replace('!['.preg_quote($flip).']+!u', $separator, $str); $str = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($str)); $str = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $str); return trim($str, $separator); }
Generate a URL friendly "slug". @param string $separator @return string
entailment
public function deletePrefix($prefix) { if ($this->startWith($prefix) === true) { return substr($this->str, strlen($prefix)); } return $this->str; }
Deletes a prefix of the string. @param string $prefix The prefix @return string The string without prefix
entailment
public function deleteSufix($sufix) { if ($this->endWith($sufix) === true) { return substr($this->str, 0, -strlen($sufix)); } return $this->str; }
Deletes a sufix of the string. @param string $sufix The sufix @return string The string without sufix
entailment
protected function getChars() { if (isset($this->chars) === true) { return $this->chars; } $this->chars = [ 'a' => [ 'à', 'á', 'ả', 'ã', 'ạ', 'ă', 'ắ', 'ằ', 'ẳ', 'ẵ', 'ặ', 'â', 'ấ', 'ầ', 'ẩ', 'ẫ', 'ậ', 'ä', 'ā', 'ą', 'å', 'α', 'ά', 'ἀ', 'ἁ', 'ἂ', 'ἃ', 'ἄ', 'ἅ', 'ἆ', 'ἇ', 'ᾀ', 'ᾁ', 'ᾂ', 'ᾃ', 'ᾄ', 'ᾅ', 'ᾆ', 'ᾇ', 'ὰ', 'ά', 'ᾰ', 'ᾱ', 'ᾲ', 'ᾳ', 'ᾴ', 'ᾶ', 'ᾷ', 'а', 'أ', ], 'b' => ['б', 'β', 'Ъ', 'Ь', 'ب'], 'c' => ['ç', 'ć', 'č', 'ĉ', 'ċ'], 'd' => ['ď', 'ð', 'đ', 'ƌ', 'ȡ', 'ɖ', 'ɗ', 'ᵭ', 'ᶁ', 'ᶑ', 'д', 'δ', 'د', 'ض', ], 'e' => ['é', 'è', 'ẻ', 'ẽ', 'ẹ', 'ê', 'ế', 'ề', 'ể', 'ễ', 'ệ', 'ë', 'ē', 'ę', 'ě', 'ĕ', 'ė', 'ε', 'έ', 'ἐ', 'ἑ', 'ἒ', 'ἓ', 'ἔ', 'ἕ', 'ὲ', 'έ', 'е', 'ё', 'э', 'є', 'ə', ], 'f' => ['ф', 'φ', 'ف'], 'g' => ['ĝ', 'ğ', 'ġ', 'ģ', 'г', 'ґ', 'γ', 'ج'], 'h' => ['ĥ', 'ħ', 'η', 'ή', 'ح', 'ه'], 'i' => ['í', 'ì', 'ỉ', 'ĩ', 'ị', 'î', 'ï', 'ī', 'ĭ', 'į', 'ı', 'ι', 'ί', 'ϊ', 'ΐ', 'ἰ', 'ἱ', 'ἲ', 'ἳ', 'ἴ', 'ἵ', 'ἶ', 'ἷ', 'ὶ', 'ί', 'ῐ', 'ῑ', 'ῒ', 'ΐ', 'ῖ', 'ῗ', 'і', 'ї', 'и', ], 'j' => ['ĵ', 'ј', 'Ј'], 'k' => ['ķ', 'ĸ', 'к', 'κ', 'Ķ', 'ق', 'ك'], 'l' => ['ł', 'ľ', 'ĺ', 'ļ', 'ŀ', 'л', 'λ', 'ل'], 'm' => ['м', 'μ', 'م'], 'n' => ['ñ', 'ń', 'ň', 'ņ', 'ʼn', 'ŋ', 'ν', 'н', 'ن'], 'o' => ['ó', 'ò', 'ỏ', 'õ', 'ọ', 'ô', 'ố', 'ồ', 'ổ', 'ỗ', 'ộ', 'ơ', 'ớ', 'ờ', 'ở', 'ỡ', 'ợ', 'ø', 'ō', 'ő', 'ŏ', 'ο', 'ὀ', 'ὁ', 'ὂ', 'ὃ', 'ὄ', 'ὅ', 'ὸ', 'ό', 'ö', 'о', 'و', 'θ', ], 'p' => ['п', 'π'], 'r' => ['ŕ', 'ř', 'ŗ', 'р', 'ρ', 'ر'], 's' => ['ś', 'š', 'ş', 'с', 'σ', 'ș', 'ς', 'س', 'ص'], 't' => ['ť', 'ţ', 'т', 'τ', 'ț', 'ت', 'ط'], 'u' => ['ú', 'ù', 'ủ', 'ũ', 'ụ', 'ư', 'ứ', 'ừ', 'ử', 'ữ', 'ự', 'ü', 'û', 'ū', 'ů', 'ű', 'ŭ', 'ų', 'µ', 'у', ], 'v' => ['в'], 'w' => ['ŵ', 'ω', 'ώ'], 'x' => ['χ'], 'y' => ['ý', 'ỳ', 'ỷ', 'ỹ', 'ỵ', 'ÿ', 'ŷ', 'й', 'ы', 'υ', 'ϋ', 'ύ', 'ΰ', 'ي', ], 'z' => ['ź', 'ž', 'ż', 'з', 'ζ', 'ز'], 'aa' => ['ع'], 'ae' => ['æ'], 'ch' => ['ч'], 'dj' => ['ђ', 'đ'], 'dz' => ['џ'], 'gh' => ['غ'], 'kh' => ['х', 'خ'], 'lj' => ['љ'], 'nj' => ['њ'], 'oe' => ['œ'], 'ps' => ['ψ'], 'sh' => ['ш'], 'shch' => ['щ'], 'ss' => ['ß'], 'th' => ['þ', 'ث', 'ذ', 'ظ'], 'ts' => ['ц'], 'ya' => ['я'], 'yu' => ['ю'], 'zh' => ['ж'], '(c)' => ['©'], 'A' => ['Á', 'À', 'Ả', 'Ã', 'Ạ', 'Ă', 'Ắ', 'Ằ', 'Ẳ', 'Ẵ', 'Ặ', 'Â', 'Ấ', 'Ầ', 'Ẩ', 'Ẫ', 'Ậ', 'Ä', 'Å', 'Ā', 'Ą', 'Α', 'Ά', 'Ἀ', 'Ἁ', 'Ἂ', 'Ἃ', 'Ἄ', 'Ἅ', 'Ἆ', 'Ἇ', 'ᾈ', 'ᾉ', 'ᾊ', 'ᾋ', 'ᾌ', 'ᾍ', 'ᾎ', 'ᾏ', 'Ᾰ', 'Ᾱ', 'Ὰ', 'Ά', 'ᾼ', 'А', ], 'B' => ['Б', 'Β'], 'C' => ['Ç', 'Ć', 'Č', 'Ĉ', 'Ċ'], 'D' => ['Ď', 'Ð', 'Đ', 'Ɖ', 'Ɗ', 'Ƌ', 'ᴅ', 'ᴆ', 'Д', 'Δ'], 'E' => ['É', 'È', 'Ẻ', 'Ẽ', 'Ẹ', 'Ê', 'Ế', 'Ề', 'Ể', 'Ễ', 'Ệ', 'Ë', 'Ē', 'Ę', 'Ě', 'Ĕ', 'Ė', 'Ε', 'Έ', 'Ἐ', 'Ἑ', 'Ἒ', 'Ἓ', 'Ἔ', 'Ἕ', 'Έ', 'Ὲ', 'Е', 'Ё', 'Э', 'Є', 'Ə', ], 'F' => ['Ф', 'Φ'], 'G' => ['Ğ', 'Ġ', 'Ģ', 'Г', 'Ґ', 'Γ'], 'H' => ['Η', 'Ή'], 'I' => ['Í', 'Ì', 'Ỉ', 'Ĩ', 'Ị', 'Î', 'Ï', 'Ī', 'Ĭ', 'Į', 'İ', 'Ι', 'Ί', 'Ϊ', 'Ἰ', 'Ἱ', 'Ἳ', 'Ἴ', 'Ἵ', 'Ἶ', 'Ἷ', 'Ῐ', 'Ῑ', 'Ὶ', 'Ί', 'И', 'І', 'Ї', ], 'K' => ['К', 'Κ'], 'L' => ['Ĺ', 'Ł', 'Л', 'Λ', 'Ļ'], 'M' => ['М', 'Μ'], 'N' => ['Ń', 'Ñ', 'Ň', 'Ņ', 'Ŋ', 'Н', 'Ν'], 'O' => ['Ó', 'Ò', 'Ỏ', 'Õ', 'Ọ', 'Ô', 'Ố', 'Ồ', 'Ổ', 'Ỗ', 'Ộ', 'Ơ', 'Ớ', 'Ờ', 'Ở', 'Ỡ', 'Ợ', 'Ö', 'Ø', 'Ō', 'Ő', 'Ŏ', 'Ο', 'Ό', 'Ὀ', 'Ὁ', 'Ὂ', 'Ὃ', 'Ὄ', 'Ὅ', 'Ὸ', 'Ό', 'О', 'Θ', 'Ө', ], 'P' => ['П', 'Π'], 'R' => ['Ř', 'Ŕ', 'Р', 'Ρ'], 'S' => ['Ş', 'Ŝ', 'Ș', 'Š', 'Ś', 'С', 'Σ'], 'T' => ['Ť', 'Ţ', 'Ŧ', 'Ț', 'Т', 'Τ'], 'U' => ['Ú', 'Ù', 'Ủ', 'Ũ', 'Ụ', 'Ư', 'Ứ', 'Ừ', 'Ử', 'Ữ', 'Ự', 'Û', 'Ü', 'Ū', 'Ů', 'Ű', 'Ŭ', 'Ų', 'У', ], 'V' => ['В'], 'W' => ['Ω', 'Ώ'], 'X' => ['Χ'], 'Y' => ['Ý', 'Ỳ', 'Ỷ', 'Ỹ', 'Ỵ', 'Ÿ', 'Ῠ', 'Ῡ', 'Ὺ', 'Ύ', 'Ы', 'Й', 'Υ', 'Ϋ', ], 'Z' => ['Ź', 'Ž', 'Ż', 'З', 'Ζ'], 'AE' => ['Æ'], 'CH' => ['Ч'], 'DJ' => ['Ђ'], 'DZ' => ['Џ'], 'KH' => ['Х'], 'LJ' => ['Љ'], 'NJ' => ['Њ'], 'PS' => ['Ψ'], 'SH' => ['Ш'], 'SHCH' => ['Щ'], 'SS' => ['ẞ'], 'TH' => ['Þ'], 'TS' => ['Ц'], 'YA' => ['Я'], 'YU' => ['Ю'], 'ZH' => ['Ж'], ' ' => ["\xC2\xA0", "\xE2\x80\x80", "\xE2\x80\x81", "\xE2\x80\x82", "\xE2\x80\x83", "\xE2\x80\x84", "\xE2\x80\x85", "\xE2\x80\x86", "\xE2\x80\x87", "\xE2\x80\x88", "\xE2\x80\x89", "\xE2\x80\x8A", "\xE2\x80\xAF", "\xE2\x81\x9F", "\xE3\x80\x80", ], ]; return $this->chars; }
Gets the conversion table. @return array
entailment
public function getCollectionForItem(ItemInterface $item) { foreach ($this->colectionItemCollection as $name => $collection) { $itemPath = $item->getPath(ItemInterface::SNAPSHOT_PATH_RELATIVE).'/'; $collectionPath = $collection->getPath().'/'; if (strpos($itemPath, $collectionPath) === 0) { return $collection; } } return $this->colectionItemCollection->get('pages'); }
Collection matching of a item. @return \Yosymfony\Spress\Core\ContentManager\Collection\CollectionInterface
entailment
public function add($name, ItemInterface $item) { if (isset($this->relationships[$name]) === false) { $this->relationships[$name] = []; } unset($this->relationships[$name][$item->getId()]); $this->relationships[$name][$item->getId()] = $item; }
Adds a relationship. @param string $name The relationship name @param Yosymfony\Spress\Core\DataSource\ItemInterface $item An item
entailment
public function remove($name, ItemInterface $item) { unset($this->relationships[$name][$item->getId()]); if (count($this->relationships[$name]) === 0) { unset($this->relationships[$name]); } }
Removes a relationship from the collection. @param string $name The relationship name
entailment
public function addItem(ItemInterface $item) { if ($this->hasItem($item->getId()) === true) { throw new \RuntimeException(sprintf('A previous item exists with the same id: "%s".', $item->getId())); } $this->items[$item->getId()] = $item; }
Adds a new item. @param Yosymfony\Spress\Core\DataSource\ItemInterface $item @throws RuntimeException If a previous item exists with the same id
entailment
public function addLayout(ItemInterface $item) { if ($this->hasLayout($item->getId()) === true) { throw new \RuntimeException(sprintf('A previous layout item exists with the same id: "%s".', $item->getId())); } $this->layouts[$item->getId()] = $item; }
Adds a new layout item. @param Yosymfony\Spress\Core\DataSource\ItemInterface $item @throws RuntimeException If a previous layout item exists with the same id
entailment
public function addInclude(ItemInterface $item) { if ($this->hasInclude($item->getId()) === true) { throw new \RuntimeException(sprintf('A previous include item exists with the same id: "%s".', $item->getId())); } $this->includes[$item->getId()] = $item; }
Adds a new include item. @param Yosymfony\Spress\Core\DataSource\ItemInterface $item @throws RuntimeException If a previous include item exists with the same id
entailment
public function up() { Schema::create( 'admin_activations', function ( Blueprint $table ) { $table->increments( 'id' ); $table->integer( 'user_id' )->unsigned(); $table->string( 'code' ); $table->boolean( 'completed' )->default( 0 ); $table->timestamp( 'completed_at' )->nullable(); $table->timestamps(); $table->engine = 'InnoDB'; } ); Schema::create( 'admin_persistences', function ( Blueprint $table ) { $table->increments( 'id' ); $table->integer( 'user_id' )->unsigned(); $table->string( 'code' ); $table->timestamps(); $table->engine = 'InnoDB'; $table->unique( 'code' ); } ); Schema::create( 'admin_reminders', function ( Blueprint $table ) { $table->increments( 'id' ); $table->integer( 'user_id' )->unsigned(); $table->string( 'code' ); $table->boolean( 'completed' )->default( 0 ); $table->timestamp( 'completed_at' )->nullable(); $table->timestamps(); $table->engine = 'InnoDB'; } ); Schema::create( 'admin_roles', function ( Blueprint $table ) { $table->increments( 'id' ); $table->string( 'slug' ); $table->string( 'name' ); $table->text( 'permissions' )->nullable(); $table->timestamps(); $table->engine = 'InnoDB'; $table->unique( 'slug' ); } ); Schema::create( 'admin_role_users', function ( Blueprint $table ) { $table->integer( 'user_id' )->unsigned(); $table->integer( 'role_id' )->unsigned(); $table->nullableTimestamps(); $table->engine = 'InnoDB'; $table->primary( [ 'user_id', 'role_id' ] ); } ); Schema::create( 'admin_throttle', function ( Blueprint $table ) { $table->increments( 'id' ); $table->integer( 'user_id' )->unsigned()->nullable(); $table->string( 'type' ); $table->string( 'ip' )->nullable(); $table->timestamps(); $table->engine = 'InnoDB'; $table->index( 'user_id' ); } ); Schema::create( 'admin_users', function ( Blueprint $table ) { $table->increments( 'id' ); $table->string( 'email' ); $table->string( 'password' ); $table->text( 'permissions' )->nullable(); $table->timestamp( 'last_login' )->nullable(); $table->string( 'first_name' )->nullable(); $table->string( 'last_name' )->nullable(); $table->timestamps(); $table->engine = 'InnoDB'; $table->unique( 'email' ); } ); }
Run the migrations. @return void
entailment
public function createRedirectResponse(Request $request, $path, $status = 302) { return new RedirectResponse($this->httpUtils->generateUri($request, $path), $status); }
@param Request $request @param string $path @param int $status @return RedirectResponse @throws \LogicException @throws \InvalidArgumentException
entailment
public function createSignedRedirectResponse(Request $request, $path, $status = 302) { return new RedirectResponse($this->httpUtils->generateUri($request, $this->uriSigner->sign($path)), $status); }
@param Request $request @param string $path @param int $status @return RedirectResponse @throws \LogicException @throws \InvalidArgumentException
entailment
public function register() { $this->registerPersistences(); $this->registerUsers(); $this->registerRoles(); $this->registerCheckpoints(); $this->registerReminders(); $this->registerSentinel(); }
{@inheritDoc}
entailment
protected function registerPersistences() { $this->registerSession(); $this->registerCookie(); $this->app->singleton( 'sentinel.persistence', function ( $app ) { return new IlluminatePersistenceRepository( $app['sentinel.session'], $app['sentinel.cookie'], Persistence::class ); } ); }
Registers the persistences. @return void
entailment
protected function registerUsers() { $this->registerHasher(); $this->app->singleton( 'sentinel.users', function ( $app ) { return new IlluminateUserRepository( $app['sentinel.hasher'], $app['events'], User::class ); } ); }
Registers the users. @return void
entailment
protected function registerCheckpoints() { $this->registerActivationCheckpoint(); $this->registerThrottleCheckpoint(); $this->app->singleton( 'sentinel.checkpoints', function ( $app ) { return [ $app["sentinel.checkpoint.throttle"], $app["sentinel.checkpoint.activation"] ]; } ); }
Registers the checkpoints. @return void @throws \InvalidArgumentException
entailment
protected function registerThrottling() { $this->app->singleton( 'sentinel.throttling', function ( $app ) { $config = $app['config']->get( 'arbory.auth.throttling' ); $globalInterval = array_get( $config, 'global.interval' ); $globalThresholds = array_get( $config, 'global.thresholds' ); $ipInterval = array_get( $config, 'ip.interval' ); $ipThresholds = array_get( $config, 'ip.thresholds' ); $userInterval = array_get( $config, 'user.interval' ); $userThresholds = array_get( $config, 'user.thresholds' ); return new IlluminateThrottleRepository( Throttle::class, $globalInterval, $globalThresholds, $ipInterval, $ipThresholds, $userInterval, $userThresholds ); } ); }
Registers the throttle. @return void
entailment
protected function registerReminders() { $this->app->singleton( 'sentinel.reminders', function ( $app ) { return new IlluminateReminderRepository( $app['sentinel.users'], Reminder::class, $app['config']->get( 'arbory.auth.reminders.expires', 14400 ) ); } ); }
Registers the reminders. @return void
entailment
protected function garbageCollect() { $config = $this->app['config']->get( 'arbory.auth' ); $this->sweep( $this->app['sentinel.activations'], $config['activations']['lottery'] ); $this->sweep( $this->app['sentinel.reminders'], $config['reminders']['lottery'] ); }
Garbage collect activations and reminders. @return void
entailment
public function handle( $request, Closure $next ) { if( !$this->sentinel->check() ) { return $this->denied( $request ); } return $next( $request ); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
public function process(ContainerBuilder $container) { $parameter = $container->getParameter('krtv_single_sign_on_identity_provider.secret_parameter'); $container->getDefinition('krtv_single_sign_on_identity_provider.security.authentication.encoder') ->replaceArgument(0, $container->getParameter($parameter)); $container->getDefinition('krtv_single_sign_on_identity_provider.uri_signer') ->replaceArgument(0, $container->getParameter($parameter)); }
{@inheritDoc}
entailment
public function process(ContainerBuilder $container) { $container->getDefinition('krtv_single_sign_on_identity_provider.routing.loader') ->replaceArgument(0, $container->getParameter('krtv_single_sign_on_identity_provider.host')) ->replaceArgument(1, $container->getParameter('krtv_single_sign_on_identity_provider.login_path')) ->replaceArgument(2, $container->getParameter('krtv_single_sign_on_identity_provider.logout_path')); }
{@inheritDoc}
entailment
public function register() { $this->registerCacheRepository(); $this->registerLoader(); $this->app->singleton( 'translator', function ( Application $app ) { $trans = new Translator( $app['translation.loader'], $app->getLocale() ); $trans->setFallback( config( 'app.fallback_locale' ) ); return $trans; } ); $this->registerFileLoader(); $this->registerCacheFlusher(); $this->loadTranslationsFrom( __DIR__ . '/../../resources/lang', 'arbory' ); }
Register the service provider. @return void
entailment
protected function registerLoader() { $this->app->singleton('translation.loader', function (Application $app) { $defaultLocale = $app->getLocale(); $cacheTimeout = config('translator.cache.timeout', 60); $laravelFileLoader = new LaravelFileLoader($app['files'], base_path('/resources/lang')); $fileLoader = new FileLoader($defaultLocale, $laravelFileLoader); $databaseLoader = new DatabaseLoader($defaultLocale, $app->make(TranslationRepository::class)); $loader = new MixedLoader($defaultLocale, $databaseLoader, $fileLoader); return new CacheLoader($defaultLocale, $app['translation.cache.repository'], $loader, $cacheTimeout); }); }
Register the translation line loader. @return void
entailment
protected function registerFileLoader() { $app = $this->app; $defaultLocale = config( 'app.locale' ); $languageRepository = $app->make( LanguageRepository::class ); $translationRepository = $app->make( TranslationRepository::class ); $translationsPath = base_path( 'resources/lang' ); $command = new TranslationsLoaderCommand( $languageRepository, $translationRepository, $app['files'], $translationsPath, $defaultLocale ); $this->app['command.translator:load'] = $command; $this->commands( 'command.translator:load' ); }
Register the translator:load language file loader. @return void
entailment
public function registerCacheFlusher() { $command = new TranslationsCacheFlushCommand( $this->app['translation.cache.repository'], true ); $this->app['command.translator:flush'] = $command; $this->commands( 'command.translator:flush' ); }
Flushes the translation cache @return void
entailment
public function handle( $request, Closure $next ) { $targetModule = $this->resolveTargetModule( $request ); if( !$targetModule ) { throw new \RuntimeException( 'Could not find target module for route controller' ); } if( !$targetModule->isAuthorized() ) { return $this->denied( $request ); } return $next( $request ); }
Handle an incoming request. @param \Illuminate\Http\Request $request @param \Closure $next @return mixed
entailment
public function render() { $footer = Html::footer(); foreach( $this->getRows() as $row ) { $footer->append( $row->render() ); } if( $this->type ) { $footer->addClass( $this->type ); } return $footer; }
Get the evaluated contents of the object. @return Element
entailment
public function getDefaultResourceForLocale( $locale ) { $resource = null; if( $this->getValue() && !$this->getValue()->isEmpty() ) { foreach( $this->getValue() as $index => $item ) { if( $item->{$this->getModel()->getLocaleKey()} === $locale ) { $resource = $item; } } } return $resource; }
@see \Arbory\Base\Http\Controllers\Admin\SettingsController::getField @param $locale @return Model|null
entailment
public function render() { $tools = Html::div()->addClass( 'tools' ); foreach( $this->blocks() as $name => $content ) { $tools->append( Html::div( $content->toArray() )->addClass( $name ) ); } return $tools; }
Get the evaluated contents of the object. @return string
entailment
public function up() { Schema::table('nodes', function (Blueprint $table) { $table->unique('id'); $table->unique(['content_type', 'content_id']); $table->index('slug'); $table->index('parent_id'); $table->index('lft'); $table->index('rgt'); $table->index('active'); }); }
Run the migrations. @return void
entailment
public function down() { Schema::table('nodes', function (Blueprint $table) { $table->dropUnique('nodes_id_unique'); $table->dropUnique('nodes_content_type_content_id_unique'); $table->dropIndex('nodes_slug_index'); $table->dropIndex('nodes_parent_id_index'); $table->dropIndex('nodes_lft_index'); $table->dropIndex('nodes_rgt_index'); $table->dropIndex('nodes_active_index'); }); }
Reverse the migrations. @return void
entailment
public function getConfigTreeBuilder() { $builder = new TreeBuilder(); $builder->root('krtv_single_sign_on_identity_provider') ->children() ->scalarNode('host') ->isRequired() ->validate() ->ifTrue(function($v) { return preg_match('/^http(s?):\/\//', $v); }) ->thenInvalid('SSO host must only contain the host, and not the url scheme, eg: idp.domain.com') ->end() ->end() ->scalarNode('host_scheme') ->defaultValue('http') ->end() ->scalarNode('login_path') ->isRequired() ->end() ->scalarNode('logout_path') ->isRequired() ->end() ->arrayNode('services') ->info('Array of enabled ServiceProviders (SPs)') ->isRequired() ->prototype('scalar') ->end() ->end() ->scalarNode('otp_parameter') ->defaultValue('_otp') ->end() ->scalarNode('secret_parameter') ->defaultValue('secret') ->end() ->scalarNode('target_path_parameter') ->defaultValue('_target_path') ->end() ->scalarNode('service_parameter') ->defaultValue('service') ->end() ->scalarNode('service_extra_parameter') ->defaultValue('service_extra') ->end() ->end() ; return $builder; }
Generates the configuration tree builder. @return \Symfony\Component\Config\Definition\Builder\TreeBuilder The tree builder
entailment
public function register() { $this->app->singleton( SettingRegistry::class, function() { return new SettingRegistry(); } ); $this->app->singleton( 'arbory_settings', function() { return new Settings( $this->app[ SettingRegistry::class ] ); } ); }
{@inheritDoc}
entailment
public function boot() { $paths = [ __DIR__ . '/../../config/settings.php', config_path( 'settings.php' ) ]; foreach( $paths as $path ) { if( file_exists( $path ) ) { $this->app[ SettingRegistry::class ]->importFromConfig( include $path ); } } }
{@inheritDoc}
entailment
public function boot() { $this->registerResources(); $this->registerServiceProviders(); $this->registerAliases(); $this->registerModuleRegistry(); $this->registerCommands(); $this->registerRoutesAndMiddlewares(); $this->registerFields(); $this->registerGeneratorStubs(); $this->registerLocales(); $this->registerViewComposers(); $this->registerValidationRules(); $this->registerAssets(); $this->app->singleton( SecurityStrategy::class, function() { return $this->app->make( SessionSecurityService::class ); } ); $this->loadTranslationsFrom( __DIR__ . '/resources/lang', 'arbory' ); }
Bootstrap the application services. @return void
entailment
private function registerServiceProviders() { $this->app->register( ArboryTranslationServiceProvider::class ); $this->app->register( TranslatableServiceProvider::class ); $this->app->register( ArboryFileServiceProvider::class ); $this->app->register( ArboryAuthServiceProvider::class ); $this->app->register( GlideImageServiceProvider::class ); $this->app->register( AssetServiceProvider::class ); $this->app->register( SettingsServiceProvider::class ); $this->app->register( ExcelServiceProvider::class ); $this->app->register( FileManagerServiceProvider::class ); }
Register related service providers
entailment
private function registerAliases() { $aliasLoader = AliasLoader::getInstance(); // $aliasLoader->alias( 'TranslationCache', \Waavi\Translation\Facades\TranslationCache::class ); $aliasLoader->alias( 'Activation', \Cartalyst\Sentinel\Laravel\Facades\Activation::class ); $aliasLoader->alias( 'Reminder', \Cartalyst\Sentinel\Laravel\Facades\Reminder::class ); $aliasLoader->alias( 'Sentinel', \Cartalyst\Sentinel\Laravel\Facades\Sentinel::class ); $aliasLoader->alias( 'GlideImage', \Roboc\Glide\Support\Facades\GlideImage::class ); $aliasLoader->alias( 'Excel', \Maatwebsite\Excel\Facades\Excel::class ); }
Register related aliases
entailment
private function registerResources() { $configFilename = __DIR__ . '/../../config/arbory.php'; $this->mergeConfigFrom( $configFilename, 'arbory' ); $this->publishes( [ $configFilename => config_path( 'arbory.php' ) ], 'config' ); $this->publishes( [ __DIR__ . '/../../stubs/settings.stub' => config_path( 'settings.php' ) ], 'config' ); $this->publishes( [ __DIR__ . '/../../stubs/admin_routes.stub' => base_path( '/routes/admin.php' ) ], 'config' ); $this->publishes([ __DIR__ . '/../../resources/lang/' => base_path('resources/lang/vendor/arbory') ], 'lang'); $this->loadMigrationsFrom( __DIR__ . '/../../database/migrations' ); $this->loadViewsFrom( __DIR__ . '/../../resources/views', 'arbory' ); }
Publish configuration file.
entailment
private function registerRoutesAndMiddlewares() { /** * @var Router $router */ $router = $this->app[ 'router' ]; $router->middlewareGroup( 'admin', [ \App\Http\Middleware\EncryptCookies::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class, \Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class, \App\Http\Middleware\VerifyCsrfToken::class, \Illuminate\Routing\Middleware\SubstituteBindings::class, ArboryAdminHasAllowedIpMiddleware::class ] ); $router->aliasMiddleware( 'arbory.admin_auth', ArboryAdminAuthMiddleware::class ); $router->aliasMiddleware( 'arbory.admin_module_access', ArboryAdminModuleAccessMiddleware::class ); $router->aliasMiddleware( 'arbory.admin_quest', ArboryAdminGuestMiddleware::class ); $router->aliasMiddleware( 'arbory.admin_in_role', ArboryAdminInRoleMiddleware::class ); $router->aliasMiddleware( 'arbory.admin_has_access', ArboryAdminHasAccessMiddleware::class ); $router->aliasMiddleware( 'arbory.route_redirect', ArboryRouteRedirectMiddleware::class ); $router->aliasMiddleware( 'arbory.admin_has_allowed_ip', ArboryAdminHasAllowedIpMiddleware::class ); $this->app->booted( function( $app ) { $app[ Kernel::class ]->prependMiddleware( ArboryRouteRedirectMiddleware::class ); } ); $this->registerAdminRoutes(); $this->registerAppRoutes(); }
Load admin routes and register middleware
entailment
private function registerCommands() { $commands = [ 'arbory.seed' => SeedCommand::class, 'arbory.install' => InstallCommand::class, 'arbory.generator' => GeneratorCommand::class, 'arbory.generate' => GenerateCommand::class ]; foreach( $commands as $containerKey => $commandClass ) { $this->registerCommand( $containerKey, $commandClass ); } }
Register Arbory commands
entailment
private function registerModuleRegistry() { $this->app->singleton( 'arbory', function () { return new Admin( $this->app['sentinel'], new Menu(), new AssetPipeline() ); } ); $this->app->singleton( Admin::class, function () { return $this->app['arbory']; } ); }
Register Arbory module registry
entailment
private function registerFields() { $this->app->singleton( FieldTypeRegistry::class, function ( Application $app ) { $fieldTypeRegistry = new FieldTypeRegistry(); $fieldTypeRegistry->registerByType( 'integer', Hidden::class, 'int' ); $fieldTypeRegistry->registerByType( 'string', Text::class, 'string' ); $fieldTypeRegistry->registerByType( 'text', Textarea::class, 'string' ); $fieldTypeRegistry->registerByType( 'longtext', Richtext::class, 'string' ); $fieldTypeRegistry->registerByType( 'datetime', DateTime::class, 'string' ); $fieldTypeRegistry->registerByType( 'boolean', Checkbox::class, 'bool' ); $fieldTypeRegistry->registerByRelation( 'file', ArboryFile::class ); $fieldTypeRegistry->registerByRelation( 'image', ArboryImage::class ); $fieldTypeRegistry->registerByRelation( 'link', Link::class ); return $fieldTypeRegistry; } ); }
Register Arbory fields
entailment
private function registerGeneratorStubs() { $this->app->singleton( StubRegistry::class, function( Application $app ) { $stubRegistry = new StubRegistry(); $stubRegistry->registerStubs( $app[ Filesystem::class ], base_path( 'vendor/arbory/arbory/stubs' ) ); return $stubRegistry; } ); }
Register stubs used by generators
entailment
public function process(ContainerBuilder $container) { $services = array(); $activeServices = $container->getParameter('krtv_single_sign_on_identity_provider.services'); foreach ($container->findTaggedServiceIds('sso.service_provider') as $id => $attributes) { $name = $attributes[0]['service']; if (in_array($name, $activeServices)) { $services[$name] = $container->getDefinition($id); } } $container->getDefinition('krtv_single_sign_on_identity_provider.manager.service_manager') ->replaceArgument(3, $services); }
{@inheritDoc}
entailment
public function handle($request, Closure $next) { $redirect = Redirect::query(); $redirect->where('from_url', $request->url()); $redirect->orWhere('from_url', 'LIKE', '_' . $request->path() . '_'); $redirect = $redirect->first(['to_url', 'status']); if ($redirect) { return \Redirect::to($redirect->to_url, $redirect->status); } return $next($request); }
Handle an incoming request. @param Request $request @param \Closure $next @return RedirectResponse
entailment
public function handle( $request, Closure $next ) { if( $this->isAllowedIp( $request ) ) { return $next( $request ); } return abort( 403 ); }
Handle an incoming request. @param Request $request @param \Closure $next @return RedirectResponse|null
entailment
public function handle( $request, Closure $next ) { if( $this->sentinel->check() ) { if( $request->ajax() ) { $message = trans( 'arbory.admin_unauthorized', 'Unauthorized' ); return response()->json( [ 'error' => $message ], 401 ); } else { $firstAvailableModule = \Admin::modules()->first( function ( $module ) { return $module->isAuthorized(); } ); if( !$firstAvailableModule ) { throw new AccessDeniedHttpException(); } return redirect( $firstAvailableModule->url('index') ); } } return $next( $request ); }
Handle an incoming request. @param Request $request @param \Closure $next @return JsonResponse|RedirectResponse
entailment
public function up() { Schema::create( 'nodes', function ( Blueprint $table ) { $table->uuid( 'id' ); $table->string( 'name' ); $table->string( 'slug' ); $table->uuid( 'parent_id' )->nullable(); $table->integer( 'lft' )->nullable(); $table->integer( 'rgt' )->nullable(); $table->integer( 'depth' )->nullable(); $table->string( 'content_type' )->nullable(); $table->integer( 'content_id' )->nullable(); $table->integer( 'item_position' )->nullable(); $table->tinyInteger( 'active' )->default( 0 ); $table->string( 'locale', 6 )->nullable(); $table->timestamps(); } ); }
Run the migrations. @return void
entailment
public function findBySlug( $uri ) { $parts = explode( '/', trim( $uri, '/' ) ); $node = null; foreach( $parts as $depth => $part ) { $query = $this->newQuery()->where( 'depth', $depth )->where( 'slug', $part ); if( $node instanceof Node ) { $query->whereBetween( $node->getLeftColumnName(), array( $node->getLeft() + 1, $node->getRight() - 1 ) ); $query->whereBetween( $node->getRightColumnName(), array( $node->getLeft() + 1, $node->getRight() - 1 ) ); } $nodes = $query->get(); if( $nodes->count() !== 1 ) { break; } $node = $nodes->first(); } return $node; }
* @param $uri @return Node|null
entailment
public function save( array $options = [] ) { if( $this->exists ) { if( count( $this->getDirty() ) > 0 ) { // If $this->exists and dirty, parent::save() has to return true. If not, // an error has occurred. Therefore we shouldn't save the translations. if( parent::save( $options ) ) { return $this->saveTranslations(); } return false; } else { // If $this->exists and not dirty, parent::save() skips saving and returns // false. So we have to save the translations $saved = $this->saveTranslations(); if( $saved ) { $this->fireModelEvent( 'saved', false ); $this->fireModelEvent( 'updated', false ); } return $saved; } } elseif( parent::save( $options ) ) { // We save the translations only if the instance is saved in the database. return $this->saveTranslations(); } return false; }
@param array $options @return bool
entailment
protected function getTranslationOrNew( $locale ) { if( ( $translation = $this->getTranslation( $locale, false ) ) === null ) { $translation = $this->getNewTranslation( $locale ); } return $translation; }
@param string $locale @return \Illuminate\Database\Eloquent\Model|null
entailment
private function getFallbackLocale( $locale = null ) { if( $locale && $this->isLocaleCountryBased( $locale ) ) { return $this->getLanguageFromCountryBasedLocale( $locale ); } return Config::get( 'translatable.fallback_locale' ); }
@param string|null $locale @return string
entailment
public function scopeWithTranslation( Builder $query ) { $query->with( [ 'translations' => function( Relation $query ) { $query->where( $this->getTranslationsTable() . '.' . $this->getLocaleKey(), $this->locale() ); if( $this->isUsingTranslationFallback() ) { return $query->orWhere( $this->getTranslationsTable() . '.' . $this->getLocaleKey(), $this->getFallbackLocale() ); } }, ] ); }
This scope eager loads the translations for the default and the fallback locale only. We can use this as a shortcut to improve performance in our application. @param Builder $query
entailment
public function deleteTranslations( $locales = null ) { if( $locales === null ) { $this->translations()->delete(); } else { $locales = (array)$locales; $this->translations()->whereIn( $this->getLocaleKey(), $locales )->delete(); } // we need to manually "reload" the collection built from the relationship // otherwise $this->translations()->get() would NOT be the same as $this->translations $this->load( 'translations' ); }
Deletes all translations for this model. @param string|array|null $locales The locales to be deleted (array or single string) (e.g., ["en", "de"] would remove these translations).
entailment
public function upload() { $response = parent::upload(); return count($this->errors) > 0 ? $this->errorResponse() : $response; }
Upload files @param void @return string
entailment
public function render() { return Html::div( [ $this->getPreviousPageButton(), $this->getPagesSelect(), $this->getNextPageButton(), ] )->addClass( 'pagination' ); }
Get the evaluated contents of the object. @return string|Element
entailment
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new RoutingConfigPass()); $container->addCompilerPass(new ServiceProvidersPass()); $container->addCompilerPass(new ResolveSecretPass()); }
{@inheritDoc}
entailment
public static function filter($html, array $config = null, $spec = null) { require_once __DIR__.'/htmLawed/htmLawed.php'; if ($config === null) { $config = self::$defaultConfig; } if (isset($config['spec']) && !$spec) { $spec = $config['spec']; } if ($spec === null) { $spec = static::$defaultSpec; } return htmLawed($html, $config, $spec); }
Filters a string of html with the htmLawed library. @param string $html The text to filter. @param array|null $config Config settings for the array. @param string|array|null $spec A specification to further limit the allowed attribute values in the html. @return string Returns the filtered html. @see http://www.bioinformatics.org/phplabware/internal_utilities/htmLawed/htmLawed_README.htm
entailment
public static function filterRSS($html) { $config = array( 'anti_link_spam' => ['`.`', ''], 'comment' => 1, 'cdata' => 3, 'css_expression' => 1, 'deny_attribute' => 'on*,style,class', 'elements' => '*-applet-form-input-textarea-iframe-script-style-object-embed-comment-link-listing-meta-noscript-plaintext-xmp', 'keep_bad' => 0, 'schemes' => 'classid:clsid; href: aim, feed, file, ftp, gopher, http, https, irc, mailto, news, nntp, sftp, ssh, telnet; style: nil; *:file, http, https', // clsid allowed in class 'valid_xhtml' => 1, 'balance' => 1 ); $spec = static::$defaultSpec; $result = static::filter($html, $config, $spec); return $result; }
Filter a string of html so that it can be put into an rss feed. @param $html The html text to fitlter. @return string Returns the filtered html. @see Htmlawed::filter().
entailment
public function clear() { $this->session->remove($this->getSessionKey()); $this->session->remove($this->getSessionExtraKey()); $this->session->remove($this->getSessionTargetPathKey()); }
Clear services management session variables.
entailment
public function register() { AliasLoader::getInstance()->alias( 'ArboryRouter', ArboryRouter::class ); AliasLoader::getInstance()->alias( 'Admin', Admin::class ); AliasLoader::getInstance()->alias( 'Page', Page::class ); AliasLoader::getInstance()->alias( 'Settings', Settings::class ); $this->app->singleton( NodesRepository::class, function() { $repository = new NodesRepository(); $repository->setQueryOnlyActiveNodes( true ); return $repository; } ); $this->app->singleton( ContentTypeRegister::class, function () { return new ContentTypeRegister(); } ); $this->app->singleton( 'arbory_router', function () { return $this->app->make( ContentTypeRoutesRegister::class ); } ); $this->app->singleton( 'arbory_page_builder', function() { return new PageBuilder( $this->app->make( ContentTypeRegister::class ), $this->app->make( 'arbory_router' ) ); } ); $this->routes = $this->app->make( 'arbory_router' ); }
Register the service provider. @return void
entailment
public function createDynamicallyObjects($struct, $keypath_array) { if (!$this->studyType($struct, $problem)) { return $problem; } $path_string = ""; for ($i = 0; $i < count($keypath_array); $i++) { $key = $keypath_array[$i]; $path_string .= $key . "/"; } $this->accessDynamically($path_string, $struct); // cria return $this->returnTypeConvert($struct); }
[Create nested obj Dynamically if(key exist || key !exist), by $path_string @param [array|string|\stdClass] $struct1 [Structure] @param [array] $keypath_array [Array with the keys that will be created] @return [array|string|\stdClass] New structure
entailment
private function accessDynamically($path_string, &$array) { $keys = explode('/', substr_replace($path_string, "", -1)); $ref = &$array; foreach ($keys as $key => $value) { $ref = &$ref[$value]; } $ref = array(); }
[This function enables you to dynamically access the value of a structure] @param [string] $path_string [path] @param [array] $array current [array]
entailment
public function walker(&$struct, $callback) { if (!$this->studyType($struct, $problem)) { return $problem; } $this->clockStart(); $replaceWalker = function(&$struct, $callback) use (&$replaceWalker) { if (is_array($struct)) { foreach ($struct as $key => &$value) { $callback($struct, $key, $value); if (isset($struct[$key])) { if (is_array($struct[$key])) { $replaceWalker($value, $callback); } else { } } } } return $struct; }; // Call the recursive method to walk in the struct $replaced_array = $replaceWalker($struct, $callback); if ($this->config["debug"]) { $replaced_array["time"] = $this->clockMark(); } return $this->returnTypeConvert($replaced_array); }
[walk throughout the structure] @param [array|string|\stdClass] $struct [Structure] @param [function] $callback [The function will always be called when walking through the nodes] @return [array|string|\stdClass] Input structure
entailment
public function getdiff($struct1, $struct2, $slashtoobject = false) { if (!$this->studyType($struct1, $problem) || !$this->studyType($struct2, $problem)) { return $problem; } $this->clockStart(); $structpath1_array = array(); $structpath2_array = array(); $this->structPathArray($struct1, $structpath1_array, ""); $this->structPathArray($struct2, $structpath2_array, ""); $deltadiff_array = $this->structPathArrayDiff($structpath1_array, $structpath2_array, $slashtoobject); if ($this->config["debug"]) { $deltadiff_array["time"] = $this->clockMark(); } return $this->returnTypeConvert($deltadiff_array); }
Returns the difference between two structures @param [array|string|\stdClass] $struct1 [struct1] @param [array|string|\stdClass] $struct2 [struct2] @return [array|string|\stdClass] struct diff
entailment
private function structPathArray($assocarray, &$array, $currentpath) { if (is_array($assocarray)) { foreach ($assocarray as $key => $value) { if (array_key_exists($key, $assocarray)) { $path = $currentpath !== '' ? $currentpath . "/" . $key : sprintf($key); if (gettype($assocarray[$key]) == "array" && !empty($assocarray[$key])) { $this->structPathArray($assocarray[$key], $array, $path); } elseif (gettype($assocarray[$key]) == "object") { if (!empty((array)$assocarray[$key]) ) { // Force Casting (array)Obj $this->structPathArray((array)$assocarray[$key], $array, $path); } else { $array[$path] = array(); } } else { if ($path != "") { $array[$path] = $value; } } } } } }
[Returns a array with all the possible paths of the structure -> &$array. There is several ways to do this and i believe it's not the best way, but I chose this way, separately(structPathArray() + structPathArrayDiff()), to be more didactic. In the middle of recursion I could already make comparisons could be faster.] @param [array] $assocarray [Structure already standardized as associative array to get performance*] @param [array] &$array [Array paths created from the structure] @param [string] $currentpath [Current path]
entailment
public function structMerge($struct1, $struct2, $slashtoobject = false) { if (!$this->studyType($struct1, $problem) || !$this->studyType($struct2, $problem)) { return $problem; } $this->clockStart(); $structpath1_array = array(); $structpath2_array = array(); $this->structPathArray($struct1, $structpath1_array, ""); $this->structPathArray($struct2, $structpath2_array, ""); $merged_array = array_merge($structpath2_array, $structpath1_array); if ($this->config["debug"]) { $merged_array["time"] = $this->clockMark(); } if ($slashtoobject) { $merged_array = $this->pathSlashToStruct($merged_array); } return $this->returnTypeConvert($merged_array); }
[Join two structures] @param [array|string|\stdClass] $struct1 [Structure] @param [array|string|\stdClass] $struct2 [Structure] @return [array|string|\stdClass] [The union of structures]
entailment
private function pathSlashToStruct($assocarray) { $new_assocarray = []; $this->switchType(); if (is_array($assocarray)) { foreach ($assocarray as $key => $value) { if (strpos($key, '/') !== false) { $aux = explode("/", $key); $newkey = $aux[0]; array_shift($aux); if (isset($new_assocarray[$newkey])) { $new_assocarray[$newkey] = $this->createDynamicallyObjects($new_assocarray[$newkey], $aux); $new_assocarray[$newkey] = $this->setDynamicallyValue($new_assocarray[$newkey], $aux, $value); } else { $new_assocarray[$newkey] = $this->createDynamicallyObjects(array(), $aux); $new_assocarray[$newkey] = $this->setDynamicallyValue($new_assocarray[$newkey], $aux, $value); } } else { $new_assocarray[$key] = $value; } } } $this->switchType(); return $new_assocarray; }
[Convert the slashs to nested structures] @param [type] $assocarray [Associative array to convert the keys] @return [array] [No slashs on key]
entailment
private function structPathArrayDiff($structpath1_array, $structpath2_array, $slashtoobject) { $deltadiff_array = array( "new" => array(), "removed" => array(), "edited" => array() ); foreach ($structpath1_array as $key1 => $value1) { if (array_key_exists($key1, $structpath2_array)) { if ($value1 !== $structpath2_array[$key1]) { $edited = array( "oldvalue" => $structpath2_array[$key1], "newvalue" => $value1 ); $deltadiff_array["edited"][$key1] = $edited; } } else { $deltadiff_array["new"][$key1] = $value1; } } $removido = array_diff_key($structpath2_array, $structpath1_array); if (!empty($removido)) { foreach ($removido as $key => $value) { $deltadiff_array["removed"][$key] = $value; } } if ($slashtoobject) { foreach ($deltadiff_array as $key => &$value) { //the length will be always 3, [new, removed, edited] $value = $this->pathSlashToStruct($value); } } return $deltadiff_array; }
[Returns a structure with the news] @param [array] $structpath1_array [Vector paths of structure 1] @param [array] $structpath2_array [Vector paths of structure 2] @param [boolean] $slashtoobject [Simple path with slashs or nested structures] @return [array] [Delta array]
entailment
private function returnTypeConvert($struct) { switch ($this->config["returntype"]) { case 'jsonstring': if (!($this->isJsonString($struct))) { return json_encode($struct); } return $struct; break; case 'object': return json_decode(json_encode($struct), false); break; case 'array': return $struct; break; default: return "returntype não é valido!"; break; } }
[Returns a converted structure] @param [array|string|\stdClass] $struct [Structure for converting] @return [array|string|\stdClass] [Converted structure]
entailment
private function studyType(&$struct, &$problem) { if ($this->isJsonString($struct)) { $struct = json_decode($struct, true); return true; } else if(is_array($struct)) { return true; } else if(is_object($struct)) { $struct = (array)$struct; return true; } else { $problem = "the parameter is not a valid structure"; return false; } }
[analyzes the structure] @param [array|string|\stdClass] &$struct [Structure] @param [string] &$problem [If there is a problem with the structure , it will be returned] @return [type] [true->Everything is ok, false->Error]
entailment
private function switchType() { $aux = $this->config["returntype"]; $this->config["returntype"] = $this->typetowork; $this->typetowork = $aux; }
[switch the type]
entailment
public function indexAction(string $slugs = '', Request $request): Response { if (preg_match('#/$#', $slugs)) { return $this->redirect($this->generateUrl('orbitale_cms_category', ['slugs' => rtrim($slugs, '/')])); } $slugsArray = preg_split('~/~', $slugs, -1, PREG_SPLIT_NO_EMPTY); $categories = $this->get('orbitale_cms.category_repository')->findFrontCategories($slugsArray); $category = $this->getFinalTreeElement($slugsArray, $categories); $validOrderFields = ['createdAt', 'id', 'title', 'content']; $limit = $request->query->get('limit', 10); $page = $request->query->get('page', 1); $order = $request->query->get('order', 'asc'); $orderBy = $request->query->get('order_by', current($validOrderFields)); if (!in_array($orderBy, $validOrderFields, true)) { $orderBy = current($validOrderFields); } $pages = $this->get('orbitale_cms.page_repository')->findByCategory( $category, $order, $orderBy, $page, $limit ); return $this->render('@OrbitaleCms/Front/category.html.twig', [ 'category' => $category, 'categories' => $categories, 'pages' => $pages, 'pagesCount' => count($pages), 'filters' => [ 'page' => $page, 'limit' => $limit, 'orderBy' => $orderBy, 'order' => $order, ], ]); }
@param string $slugs @param Request $request @return Response
entailment
public function load(array $configs, ContainerBuilder $container) { $configuration = new Configuration(); $config = $this->processConfiguration($configuration, $configs); foreach ($config['layouts'] as $name => $layout) { $config['layouts'][$name] = array_merge([ 'name' => $name, 'assets_css' => [], 'assets_js' => [], 'host' => '', 'pattern' => '', ], $layout); ksort($config['layouts'][$name]); } foreach ($config as $key => $value) { $container->setParameter('orbitale_cms.'.$key, $value); } $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('services.yaml'); }
{@inheritdoc}
entailment
public function addChild(Page $page): Page { $this->children->add($page); if ($page->getParent() !== $this) { $page->setParent($this); } return $this; }
@param Page $page @return Page
entailment
public function getTree(string $separator = '/') { $tree = ''; $current = $this; do { $tree = $current->getSlug().$separator.$tree; $current = $current->getParent(); } while ($current); return trim($tree, $separator); }
@param string $separator @return string
entailment