_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q260800
PipelineBuilder.setKeys
test
public function setKeys(iterable $keys) { $combine = function ($values, $keys) { return new CombineIterator($keys, $values); }; return $this->then($combine, i\iterable_to_array($keys)); }
php
{ "resource": "" }
q260801
FilteringTrait.slice
test
public function slice(int $offset, ?int $size = null) { return $this->then(i\iterable_slice, $offset, $size); }
php
{ "resource": "" }
q260802
SortingTrait.sort
test
public function sort($compare, bool $preserveKeys = true) { return $this->then(i\iterable_sort, $compare, $preserveKeys); }
php
{ "resource": "" }
q260803
VariableTrait.setVariables
test
public function setVariables($variables) { if (!is_array($variables)) { return $this; } foreach ($variables as $key => $value) { $this->setVariable($key, $value); } return $this; }
php
{ "resource": "" }
q260804
VariableTrait.setVariable
test
public function setVariable($name, $value) { switch ($name) { case 'date': try { if ($value instanceof \DateTime) { $this->offsetSet('date', $value); } else { if (is_numeric($value)) { $this->offsetSet('date', (new \DateTime())->setTimestamp($value)); } else { if (is_string($value)) { $this->offsetSet('date', new \DateTime($value)); } } } } catch (Exception $e) { throw new Exception(sprintf("Expected date string in page ID: '%s'", $this->getId())); } break; case 'draft': if ($value === true) { $this->offsetSet('published', false); } break; default: $this->offsetSet($name, $value); } return $this; }
php
{ "resource": "" }
q260805
SavePages.getPathname
test
protected function getPathname(Page $page) { // force pathname of a file node page (ie: "section/index.md") if ($page->getName() == 'index') { return $page->getPath().'/'.$this->config->get('output.filename'); } else { // custom extension, ex: 'manifest.json' if (!empty(pathinfo($page->getPermalink(), PATHINFO_EXTENSION))) { return $page->getPermalink(); } // underscore prefix, ex: '_redirects' if (strpos($page->getPermalink(), '_') === 0) { return $page->getPermalink(); } return $page->getPermalink().'/'.$this->config->get('output.filename'); } }
php
{ "resource": "" }
q260806
AntiSpoof.getScriptTag
test
private static function getScriptTag( $name ) { $name = "SCRIPT_" . strtoupper( trim( $name ) ); // Linear search foreach ( self::$script_ranges as $range ) { if ( $name == $range[2] ) { return $range[2]; } } // Otherwise... return null; }
php
{ "resource": "" }
q260807
AntiSpoof.isAllowedScriptCombination
test
private static function isAllowedScriptCombination( $scriptList ) { $allowedScriptCombinations = [ [ "SCRIPT_COPTIC", "SCRIPT_COPTIC_EXTRAS" ], # Coptic, using old Greek chars [ "SCRIPT_GREEK", "SCRIPT_COPTIC_EXTRAS" ], # Coptic, using new Coptic chars [ "SCRIPT_HAN", "SCRIPT_BOPOMOFO" ], # Chinese [ "SCRIPT_HAN", "SCRIPT_HANGUL" ], # Korean [ "SCRIPT_HAN", "SCRIPT_KATAKANA", "SCRIPT_HIRAGANA" ] # Japanese ]; foreach ( $allowedScriptCombinations as $allowedCombo ) { if ( self::isSubsetOf( $scriptList, $allowedCombo ) ) { return true; } } return false; }
php
{ "resource": "" }
q260808
AntiSpoof.stringToList
test
public static function stringToList( $str ) { $ar = []; if ( !preg_match_all( '/./us', $str, $ar ) ) { return []; } $out = []; foreach ( $ar[0] as $char ) { $out[] = Utils::utf8ToCodepoint( $char ); } return $out; }
php
{ "resource": "" }
q260809
BatchAntiSpoof.execute
test
public function execute() { $this->output( "Creating username spoofs...\n" ); $userCol = $this->getUserColumn(); $iterator = new BatchRowIterator( $this->getDB( DB_MASTER ), $this->getTableName(), $this->getPrimaryKey(), $this->getBatchSize() ); $iterator->setFetchColumns( [ $userCol ] ); $n = 0; foreach ( $iterator as $batch ) { $items = []; foreach ( $batch as $row ) { $items[] = $this->makeSpoofUser( $row->$userCol ); } $n += count( $items ); $this->output( "...$n\n" ); $this->batchRecord( $items ); $this->waitForSlaves(); } $this->output( "$n user(s) done.\n" ); }
php
{ "resource": "" }
q260810
RenderPages.getAllLayoutsPaths
test
protected function getAllLayoutsPaths() { $paths = []; // layouts/ if (is_dir($this->config->getLayoutsPath())) { $paths[] = $this->config->getLayoutsPath(); } // <theme>/layouts/ if ($this->config->hasTheme()) { $themes = $this->config->getTheme(); foreach ($themes as $theme) { $paths[] = $this->config->getThemeDirPath($theme); } } // res/layouts/ if (is_dir($this->config->getInternalLayoutsPath())) { $paths[] = $this->config->getInternalLayoutsPath(); } return $paths; }
php
{ "resource": "" }
q260811
RenderPages.addGlobals
test
protected function addGlobals() { // adds global variables $this->phpoole->getRenderer()->addGlobal('site', array_merge( $this->config->get('site'), ['menus' => $this->phpoole->getMenus()], ['pages' => $this->phpoole->getPages()->filter(function (Page $page) { return $page->getVariable('published'); })], ['time' => time()] )); $this->phpoole->getRenderer()->addGlobal('cecil', [ 'url' => sprintf('https://cecil.app/#%s', $this->phpoole->getVersion()), 'version' => $this->phpoole->getVersion(), 'poweredby' => sprintf('Cecil/PHPoole v%s', $this->phpoole->getVersion()), ]); }
php
{ "resource": "" }
q260812
GeneratorManager.process
test
public function process(PageCollection $pageCollection, \Closure $messageCallback) { $max = $this->count(); if ($max > 0) { $this->top(); while ($this->valid()) { /* @var GeneratorInterface $generator */ $generator = $this->current(); /* @var $generatedPages PageCollection */ $generatedPages = $generator->generate($pageCollection, $messageCallback); foreach ($generatedPages as $page) { /* @var $page \PHPoole\Collection\Page\Page */ if ($pageCollection->has($page->getId())) { $pageCollection->replace($page->getId(), $page); } else { $pageCollection->add($page); } } $message = substr(strrchr(get_class($generator), '\\'), 1).': '.count($generatedPages); $count = ($max - $this->key()); call_user_func_array($messageCallback, ['GENERATE_PROGRESS', $message, $count, $max]); $this->next(); } } return $pageCollection; }
php
{ "resource": "" }
q260813
AtomLoader.setParam
test
protected function setParam(\SimpleXMLElement $element, Feed $feed) { if (count($element) === 0) { $feed->set($element->getName(), (string)$element); } else { $feed->set($element->getName(), $this->extractParam($element)); } }
php
{ "resource": "" }
q260814
AtomLoader.extractParam
test
protected function extractParam(\SimpleXMLElement $element) { $param = array(); foreach ($element as $subElement) { if (count($subElement) === 0) { $param[$subElement->getName()] = (string)$subElement; } else { $param[$subElement->getName()] = $this->extractParam($subElement); } } return $param; }
php
{ "resource": "" }
q260815
Util.runGitCommand
test
public static function runGitCommand($command) { try { $process = new Process($command, __DIR__); if (0 === $process->run()) { return trim($process->getOutput()); } throw new \RuntimeException( sprintf( 'The tag or commit hash could not be retrieved from "%s": %s', __DIR__, $process->getErrorOutput() ) ); } catch (\RuntimeException $exception) { throw new \RuntimeException('Process error'); } }
php
{ "resource": "" }
q260816
Util.sortByDate
test
public static function sortByDate($a, $b) { if (!isset($a['date'])) { return -1; } if (!isset($b['date'])) { return 1; } if ($a['date'] == $b['date']) { return 0; } return ($a['date'] > $b['date']) ? -1 : 1; }
php
{ "resource": "" }
q260817
Feed.remove
test
public function remove($id) { $success = false; foreach ($this->items as $i => $item) { if ($item->getFeedId() === $id) { unset($this->items[$i]); $success = true; break; } } if (false === $success) { throw new \InvalidArgumentException('Unknown item'); } return $this; }
php
{ "resource": "" }
q260818
Feed.replace
test
public function replace($id, ItemInterface $newItem) { $success = false; foreach ($this->items as $i => $item) { if ($item->getFeedId() == $id) { $this->items[$i] = $newItem; $success = true; break; } } if (false === $success) { throw new \InvalidArgumentException('Unknown item'); } return $this; }
php
{ "resource": "" }
q260819
Feed.merge
test
public function merge(Feed $feed) { $this->items = array(); foreach ($feed as $item) { $this->add($item); } return $this; }
php
{ "resource": "" }
q260820
Feed.autoSlice
test
protected function autoSlice() { $maxItems = $this->get('max_items', 10); if (count($this) > $maxItems) { $this->items = array_slice( $this->items, count($this) - $maxItems, $maxItems ); } return $this; }
php
{ "resource": "" }
q260821
SpoofUser.getConflicts
test
public function getConflicts() { $dbr = $this->getDBSlave(); // Join against the user table to ensure that we skip stray // entries left after an account is renamed or otherwise munged. $spoofedUsers = $dbr->select( [ 'spoofuser', $this->getTableName() ], [ 'su_name' ], // Same thing due to the join. Saves extra variableness [ 'su_normalized' => $this->normalized, 'su_name = ' . $this->getUserColumn(), ], __METHOD__, [ 'LIMIT' => 5 ] ); $spoofs = []; foreach ( $spoofedUsers as $row ) { array_push( $spoofs, $row->su_name ); } return $spoofs; }
php
{ "resource": "" }
q260822
SpoofUser.batchRecord
test
public static function batchRecord( IDatabase $dbw, $items ) { if ( !count( $items ) ) { return false; } $fields = []; /** * @var $item SpoofUser */ foreach ( $items as $item ) { $fields[] = $item->insertFields(); } $dbw->replace( 'spoofuser', [ 'su_name' ], $fields, __METHOD__ ); return true; }
php
{ "resource": "" }
q260823
AtomRenderer.writeItems
test
private function writeItems(XMLManager $xml, Feed $feed) { foreach ($feed as $item) { $this->writeItem($xml, $item); } }
php
{ "resource": "" }
q260824
ScheduleManagerScheduleIterator.setCurrent
test
protected function setCurrent() { if(count($this->buffer) === 0) { $this->buffer(); } $this->current = count($this->buffer) > 0 ? array_pop($this->buffer) : null; }
php
{ "resource": "" }
q260825
ScheduleManagerScheduleIterator.buffer
test
protected function buffer() { $this->buffer = $this->scheduleManager->findSchedules($this->limit, $this->offset); $this->offset += count($this->buffer); }
php
{ "resource": "" }
q260826
Collection.sortByDate
test
public function sortByDate() { return $this->usort(function ($a, $b) { if (!isset($a['date'])) { return -1; } if (!isset($b['date'])) { return 1; } if ($a['date'] == $b['date']) { return 0; } return ($a['date'] > $b['date']) ? -1 : 1; }); }
php
{ "resource": "" }
q260827
Config.import
test
public function import($config) { if (is_array($config)) { $data = $this->getAll(); $origin = $data->export(); $data->import($config); $data->import($origin); $this->setFromData($data); } }
php
{ "resource": "" }
q260828
Config.setFromData
test
protected function setFromData(Data $data) { if ($this->data !== $data) { $this->data = $data; } return $this; }
php
{ "resource": "" }
q260829
Config.setSourceDir
test
public function setSourceDir($sourceDir = null) { if ($sourceDir === null) { $sourceDir = getcwd(); } if (!is_dir($sourceDir)) { throw new \InvalidArgumentException(sprintf("'%s' is not a valid source directory.", $sourceDir)); } $this->sourceDir = $sourceDir; return $this; }
php
{ "resource": "" }
q260830
Config.setDestinationDir
test
public function setDestinationDir($destinationDir = null) { if ($destinationDir === null) { $destinationDir = $this->sourceDir; } if (!is_dir($destinationDir)) { throw new \InvalidArgumentException(sprintf("'%s' is not a valid destination directory.", $destinationDir)); } $this->destinationDir = $destinationDir; return $this; }
php
{ "resource": "" }
q260831
Layout.finder
test
public function finder(Page $page, Config $config) { $layout = 'unknown'; // what layouts could be use for the page? $layouts = self::fallback($page); // take the first available layout foreach ($layouts as $layout) { // is it in layouts/ dir? if (Util::getFS()->exists($config->getLayoutsPath().'/'.$layout)) { return $layout; } // is it in <theme>/layouts/ dir? if ($config->hasTheme()) { $themes = $config->getTheme(); foreach ($themes as $theme) { if (Util::getFS()->exists($config->getThemeDirPath($theme, 'layouts').'/'.$layout)) { return $layout; } } } // is it in res/layouts/ dir? if (Util::getFS()->exists($config->getInternalLayoutsPath().'/'.$layout)) { return $layout; } } throw new Exception(sprintf("Layout '%s' not found for page '%s'!", $layout, $page->getId())); }
php
{ "resource": "" }
q260832
Layout.fallback
test
protected static function fallback(Page $page) { // remove redundant '.twig' extension $layout = str_replace('.twig', '', $page->getLayout()); switch ($page->getNodeType()) { case NodeType::HOMEPAGE: $layouts = [ 'index.html.twig', '_default/list.html.twig', '_default/page.html.twig', ]; break; case NodeType::SECTION: $layouts = [ // 'section/$section.html.twig', '_default/section.html.twig', '_default/list.html.twig', ]; if ($page->getPathname()) { $section = explode('/', $page->getPathname())[0]; $layouts = array_merge( [sprintf('section/%s.html.twig', $section)], $layouts ); } break; case NodeType::TAXONOMY: $layouts = [ // 'taxonomy/$singular.html.twig', '_default/taxonomy.html.twig', '_default/list.html.twig', ]; if ($page->getVariable('singular')) { $layouts = array_merge( [sprintf('taxonomy/%s.html.twig', $page->getVariable('singular'))], $layouts ); } break; case NodeType::TERMS: $layouts = [ // 'taxonomy/$singular.terms.html.twig', '_default/terms.html.twig', ]; if ($page->getVariable('singular')) { $layouts = array_merge( [sprintf('taxonomy/%s.terms.html.twig', $page->getVariable('singular'))], $layouts ); } break; default: $layouts = [ // '$section/$layout.twig', // '$layout.twig', // '$section/page.html.twig', // 'page.html.twig', '_default/page.html.twig', ]; $layouts = array_merge( ['page.html.twig'], $layouts ); if ($page->getSection()) { $layouts = array_merge( [sprintf('%s/page.html.twig', $page->getSection())], $layouts ); } if ($page->getLayout()) { $layouts = array_merge( [sprintf('%s.twig', $layout)], $layouts ); if ($page->getSection()) { $layouts = array_merge( [sprintf('%s/%s.twig', $page->getSection(), $layout)], $layouts ); } } } return $layouts; }
php
{ "resource": "" }
q260833
Page.parse
test
public function parse() { $parser = new Parser($this->file); $parsed = $parser->parse(); $this->frontmatter = $parsed->getFrontmatter(); $this->body = $parsed->getBody(); return $this; }
php
{ "resource": "" }
q260834
Page.getSection
test
public function getSection() { if (empty($this->getVariable('section')) && !empty($this->path)) { $this->setSection(explode('/', $this->path)[0]); } return $this->getVariable('section'); }
php
{ "resource": "" }
q260835
Page.getPermalink
test
public function getPermalink() { if (empty($this->getVariable('permalink'))) { $this->setPermalink($this->getPathname()); } return $this->getVariable('permalink'); }
php
{ "resource": "" }
q260836
Builder.setConfig
test
public function setConfig($config) { if (!$config instanceof Config) { $config = new Config($config); } if ($this->config !== $config) { $this->config = $config; } return $this; }
php
{ "resource": "" }
q260837
Builder.build
test
public function build($options) { // backward compatibility if ($options === true) { $options['verbosity'] = self::VERBOSITY_VERBOSE; } $this->options = array_merge([ 'verbosity' => self::VERBOSITY_NORMAL, // -1: quiet, 0: normal, 1: verbose, 2: debug 'drafts' => false, // build drafts or not 'dry-run' => false, // if dry-run is true, generated files are not saved ], $options); $steps = []; // init... foreach ($this->steps as $step) { /* @var $stepClass Step\StepInterface */ $stepClass = new $step($this); $stepClass->init($this->options); $steps[] = $stepClass; } $this->steps = $steps; // ... and process! foreach ($this->steps as $step) { /* @var $step Step\StepInterface */ $step->runProcess(); } // show process time call_user_func_array($this->messageCallback, [ 'TIME', sprintf('Built in %ss', round(microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'], 2)), ]); // show log $this->showLog($this->options['verbosity']); return $this; }
php
{ "resource": "" }
q260838
Builder.getVersion
test
public function getVersion() { if (!isset($this->version)) { try { $this->version = @file_get_contents(__DIR__.'/../VERSION'); if ($this->version === false) { throw new \Exception('Can\'t get version file!'); } } catch (\Exception $e) { $this->version = self::VERSION; } } return $this->version; }
php
{ "resource": "" }
q260839
Extension.filterBy
test
public function filterBy($pages, $variable, $value) { $filteredPages = $pages->filter(function (Page $page) use ($variable, $value) { // filter virtual pages in section if ($variable == 'section' && $page->getVariable('virtual')) { return false; } // dedicated getter? $method = 'get'.ucfirst($variable); if (method_exists($page, $method) && $page->$method() == $value) { return true; } if ($page->getVariable($variable) == $value) { return true; } }); return $filteredPages; }
php
{ "resource": "" }
q260840
Extension.sortByDate
test
public function sortByDate($array) { $callback = function ($a, $b) { if (!isset($a['date'])) { return -1; } if (!isset($b['date'])) { return 1; } if ($a['date'] == $b['date']) { return 0; } return ($a['date'] > $b['date']) ? -1 : 1; }; if ($array instanceof Collection) { $array = $array->toArray(); } if (is_array($array)) { usort($array, $callback); } return $array; }
php
{ "resource": "" }
q260841
Extension.createUrl
test
public function createUrl(\Twig_Environment $env, $value = null, $options = null) { $base = ''; $baseurl = $env->getGlobals()['site']['baseurl']; $hash = md5($env->getGlobals()['site']['time']); $canonical = null; $addhash = true; if (isset($options['canonical'])) { $canonical = $options['canonical']; } if (is_bool($options)) { // backward compatibility $canonical = $options; } if (isset($options['addhash'])) { $addhash = $options['addhash']; } if ($env->getGlobals()['site']['canonicalurl'] === true || $canonical === true) { $base = rtrim($baseurl, '/'); } if ($canonical === false) { $base = ''; } if ($value instanceof Page) { $value = $value->getPermalink(); if (false !== strpos($value, '.')) { // file URL (with a dot for extension) $url = $base.'/'.ltrim($value, '/'); } else { $url = $base.'/'.ltrim(rtrim($value, '/').'/', '/'); } } else { if (preg_match('~^(?:f|ht)tps?://~i', $value)) { // external URL $url = $value; } elseif (false !== strpos($value, '.')) { // file URL (with a dot for extension) $url = $base.'/'.ltrim($value, '/'); if ($addhash) { $url .= '?'.$hash; } } else { $value = $this->slugifyFilter($value); $url = $base.'/'.ltrim(rtrim($value, '/').'/', '/'); } } return $url; }
php
{ "resource": "" }
q260842
Extension.minify
test
public function minify($path) { $filePath = $this->destPath.'/'.$path; if (is_file($filePath)) { $extension = (new \SplFileInfo($filePath))->getExtension(); switch ($extension) { case 'css': $minifier = new Minify\CSS($filePath); break; case 'js': $minifier = new Minify\JS($filePath); break; default: throw new Exception(sprintf("File '%s' should be a '.css' or a '.js'!", $path)); } $minifier->minify($filePath); return $path; } throw new Exception(sprintf("File '%s' doesn't exist!", $path)); }
php
{ "resource": "" }
q260843
Extension.toCss
test
public function toCss($path) { $filePath = $this->destPath.'/'.$path; $subPath = substr($path, 0, strrpos($path, '/')); if (is_file($filePath)) { $extension = (new \SplFileInfo($filePath))->getExtension(); switch ($extension) { case 'scss': $scssPhp = new Compiler(); $scssPhp->setImportPaths($this->destPath.'/'.$subPath); $targetPath = preg_replace('/scss/m', 'css', $path); // compile if target file doesn't exists if (!$this->fileSystem->exists($this->destPath.'/'.$targetPath)) { $scss = file_get_contents($filePath); $css = $scssPhp->compile($scss); $this->fileSystem->dumpFile($this->destPath.'/'.$targetPath, $css); } return $targetPath; break; default: throw new Exception(sprintf("File '%s' should be a '.scss'!", $path)); } } throw new Exception(sprintf("File '%s' doesn't exist!", $path)); }
php
{ "resource": "" }
q260844
Extension.readtime
test
public function readtime($text) { $words = str_word_count(strip_tags($text)); $min = floor($words / 200); if ($min === 0) { return '1'; } return $min; }
php
{ "resource": "" }
q260845
Extension.hashFile
test
public function hashFile($path) { if (is_file($filePath = $this->destPath.'/'.$path)) { return sprintf('sha384-%s', base64_encode(hash_file('sha384', $filePath, true))); } }
php
{ "resource": "" }
q260846
GenerateMenus.collectPages
test
protected function collectPages() { foreach ($this->phpoole->getPages() as $page) { /* @var $page \PHPoole\Collection\Page\Page */ if (!empty($page['menu'])) { /* * Single case * ie: * menu: main */ if (is_string($page['menu'])) { $item = (new Entry($page->getId())) ->setName($page->getTitle()) ->setUrl($page->getPermalink()); /* @var $menu \PHPoole\Collection\Menu\Menu */ $menu = $this->phpoole->getMenus()->get($page['menu']); $menu->add($item); } else { /* * Multiple case * ie: * menu: * main: * weight: 1000 * other */ if (is_array($page['menu'])) { foreach ($page['menu'] as $name => $value) { $item = (new Entry($page->getId())) ->setName($page->getTitle()) ->setUrl($page->getPermalink()) ->setWeight($value['weight']); /* @var $menu \PHPoole\Collection\Menu\Menu */ $menu = $this->phpoole->getMenus()->get($name); $menu->add($item); } } } } } }
php
{ "resource": "" }
q260847
FeedFactory.render
test
public function render($feed, $rendererName='rss') { $renderer = $this->getRenderer($rendererName); return $renderer->render($this->get($feed)); }
php
{ "resource": "" }
q260848
FeedFactory.load
test
public function load($feedName, $loaderName = 'rss_file') { $loader = $this->getLoader($loaderName); $feed = $this->get($feedName); $loadedFeed = $loader->load($feed->getFilename($loader->getFormat())); return $this->feeds[$feedName] = $feed->merge($loadedFeed); }
php
{ "resource": "" }
q260849
Sniffer.sniff
test
public function sniff($input) { if (is_array($input)) { return $this->sniffAll($input); } return $this->run($input); }
php
{ "resource": "" }
q260850
Sniffer.is
test
public function is($input, $type) { if (!isset($this->types[$type])) { throw new \Exception('Type Not found use one of supported types ( '.implode(' , ', array_keys($this->types)).' )'); } $typeClass = $this->types[$type]; return (new $typeClass())->sniff($input); }
php
{ "resource": "" }
q260851
Sniffer.sniffAll
test
private function sniffAll(array $inputs) { $result = []; foreach ($inputs as $key => $input): $result[$key] = $this->run($input); endforeach; return $result; }
php
{ "resource": "" }
q260852
Sniffer.run
test
private function run($input) { foreach ($this->types as $name => $typeClass): //check if it custom type closure if (is_object($typeClass) && $typeClass instanceof Closure) { if ($typeClass($input) === true) { return $name; } continue; } if ((new $typeClass())->sniff($input) === true) { return $name; } endforeach; //nothing captuared return 'unknown'; }
php
{ "resource": "" }
q260853
ScheduleManager.save
test
public function save(ScheduleInterface $schedule, $andFlush = true) { $this->objectManager->persist($schedule); if ($andFlush) { $this->objectManager->flush(); } }
php
{ "resource": "" }
q260854
RssRenderer.render
test
public function render(Feed $feed) { $filename = sprintf('%s/%s', $this->basePath, $feed->getFilename('rss')); if (is_file($filename)) { unlink($filename); } $xml = new XMLManager($filename); $this->init($xml, $feed); $this->writeItems($xml, $feed); $xml->save(); }
php
{ "resource": "" }
q260855
RssRenderer.createItem
test
private function createItem(XMLManager $xml) { $itemNode = $xml->getXml()->createElement('item'); $channelNode = $xml->getXml()->getElementsByTagName('channel')->item(0); $channelNode->appendChild($itemNode); return $itemNode; }
php
{ "resource": "" }
q260856
RssRenderer.getAuthor
test
private function getAuthor(ItemInterface $item) { $authorData = $item->getFeedAuthor(); $author = ''; if(isset($authorData['name'])) { $author .= $authorData['name']; } if (isset($authorData['email'])) { $author .= empty($author) ? $authorData['email'] : ' ' . $authorData['email']; } if(!empty($author)) { return $author; } return null; }
php
{ "resource": "" }
q260857
RssRenderer.getComments
test
private function getComments(ItemInterface $item) { $commentRoute = $item->getFeedCommentRoute(); if (!$commentRoute) { return null; } elseif (is_array($commentRoute)) { return $this->router->generate($commentRoute[0], $commentRoute[1]); } else { return $this->router->generate($commentRoute); } }
php
{ "resource": "" }
q260858
XMLManager.hasXMLSyntaxMarkers
test
protected function hasXMLSyntaxMarkers($content) { foreach (array('<', '&') as $char) { if (strpos($content, $char) !== false) { return true; } } return false; }
php
{ "resource": "" }
q260859
Taxonomy.collectTaxonomiesFromPages
test
protected function collectTaxonomiesFromPages() { /* @var $page Page */ foreach ($this->pageCollection as $page) { foreach (array_keys($this->config->get('site.taxonomies')) as $plural) { if (isset($page[$plural])) { // converts a list to an array if necessary if (!is_array($page[$plural])) { $page->setVariable($plural, [$page[$plural]]); } foreach ($page[$plural] as $term) { // adds each terms to the vocabulary collection $this->taxonomies->get($plural) ->add(new Term($term)); // adds each pages to the term collection $this->taxonomies ->get($plural) ->get($term) ->add($page); } } } } }
php
{ "resource": "" }
q260860
Taxonomy.createNodePages
test
protected function createNodePages() { /* @var $terms Vocabulary */ foreach ($this->taxonomies as $plural => $terms) { if (count($terms) > 0) { /* * Creates $plural/$term pages (list of pages) * ex: /tags/tag-1/ */ /* @var $pages PageCollection */ foreach ($terms as $term => $pages) { if (!$this->pageCollection->has($term)) { $pages = $pages->sortByDate()->toArray(); $page = (new Page()) ->setId(Page::urlize(sprintf('%s/%s/', $plural, $term))) ->setPathname(Page::urlize(sprintf('%s/%s', $plural, $term))) ->setTitle(ucfirst($term)) ->setNodeType(NodeType::TAXONOMY) ->setVariable('pages', $pages) ->setVariable('date', $date = reset($pages)->getDate()) ->setVariable('singular', $this->config->get('site.taxonomies')[$plural]) ->setVariable('pagination', ['pages' => $pages]); $this->generatedPages->add($page); } } /* * Creates $plural pages (list of terms) * ex: /tags/ */ $page = (new Page()) ->setId(Page::urlize($plural)) ->setPathname(strtolower($plural)) ->setTitle($plural) ->setNodeType(NodeType::TERMS) ->setVariable('plural', $plural) ->setVariable('singular', $this->config->get('site.taxonomies')[$plural]) ->setVariable('terms', $terms) ->setVariable('date', $date); // add page only if a template exist try { $this->generatedPages->add($page); } catch (Exception $e) { echo $e->getMessage()."\n"; // do not add page unset($page); } } } }
php
{ "resource": "" }
q260861
OptimizeCommand.compileViews
test
protected function compileViews(): void { foreach ($this->laravel['view']->getFinder()->getPaths() as $path) { $this->compileViewsInPath($path); } }
php
{ "resource": "" }
q260862
OptimizeCommand.compileViewsInPath
test
protected function compileViewsInPath(string $path): void { foreach ($this->laravel['files']->allFiles($path) as $file) { try { $engine = $this->laravel['view']->getEngineFromPath($file); } catch (InvalidArgumentException $e) { continue; } $this->compileSingleViewFile($engine, $file); } }
php
{ "resource": "" }
q260863
OptimizeCommand.compileSingleViewFile
test
protected function compileSingleViewFile($engine, string $file): void { if ($engine instanceof CompilerEngine) { $engine->getCompiler()->compile($file); } }
php
{ "resource": "" }
q260864
DiffUtils.generate
test
public static function generate($before, $after) { if ($before === $after) { return ''; } if (strlen($before) > self::MAX_SIZE || strlen($after) > self::MAX_SIZE) { return ''; } $beforeTmpFile = tempnam(sys_get_temp_dir(), 'diff'); file_put_contents($beforeTmpFile, $before); $afterTmpFile = tempnam(sys_get_temp_dir(), 'diff'); file_put_contents($afterTmpFile, $after); $proc = new Process('git diff --no-index --exit-code -- '.escapeshellarg($beforeTmpFile).' '.escapeshellarg($afterTmpFile)); $proc->run(); @unlink($beforeTmpFile); @unlink($afterTmpFile); switch ($proc->getExitCode()) { // $before and $after were deemed identical. Should normally never // be reached as we already check for this above. case 0: return ''; // The first four lines contain information about the files which were being compared. // We can savely trim them as we only generate the diff for one file. case 1: $output = explode("\n", $proc->getOutput()); return implode("\n", array_slice($output, 4)); default: throw new ProcessFailedException($proc); } }
php
{ "resource": "" }
q260865
DiffUtils.parse
test
public static function parse($diff) { if ('' === $diff) { return array(); } $lines = explode("\n", $diff); $nbLines = count($lines); $curLine = 0; $chunks = array(); while ($curLine < $nbLines) { $chunks[] = self::parseChunk($lines, $nbLines, $curLine); } return $chunks; }
php
{ "resource": "" }
q260866
Dispatchable.boot
test
public function boot() { // Extension should be activated only if we're not running under // safe mode (or debug mode). This is to ensure that developer have // a way to disable broken extension without tempering the database. if (! ($this->booted() || $this->status->is('safe'))) { // Avoid extension booting being called more than once. $this->booted = true; $this->registerActiveExtensions(); // Boot are executed once all extension has been registered. This // would allow extension to communicate with other extension // without having to known the registration dependencies. $this->dispatcher->boot(); $this->events->dispatch('orchestra.extension: booted'); } return $this; }
php
{ "resource": "" }
q260867
Dispatchable.finish
test
public function finish() { $this->extensions->each(function ($options, $name) { $this->dispatcher->finish($name, $options); }); $this->extensions = new Collection(); $this->booted = false; return $this; }
php
{ "resource": "" }
q260868
Dispatchable.registerActiveExtensions
test
protected function registerActiveExtensions(): void { $available = $this->memory->get('extensions.available', []); $active = $this->memory->get('extensions.active', []); // Loop all active extension and merge the configuration with // available config. Extension registration is handled by dispatcher // process due to complexity of extension boot process. Collection::make($active)->filter(function ($options, $name) use ($available) { return isset($available[$name]); })->map(function ($options, $name) use ($available) { $options['config'] = \array_merge( (array) $available[$name]['config'] ?? [], (array) $options['config'] ?? [] ); return $options; })->each(function ($options, $name) { $this->extensions->put($name, $options); $this->dispatcher->register($name, $options); }); }
php
{ "resource": "" }
q260869
Dispatchable.after
test
public function after(Closure $callback = null): void { if ($this->booted() || $this->status->is('safe')) { $this->app->call($callback); return; } $this->events->listen('orchestra.extension: booted', $callback); }
php
{ "resource": "" }
q260870
ProviderRepository.provides
test
public function provides(array $provides) { $this->compiled = Collection::make($provides)->mapWithKeys(function ($provider) { $options = $this->manifest[$provider] ?? $this->recompileProvider($provider); $this->loadDeferredServiceProvider($provider, $options); $this->loadEagerServiceProvider($provider, $options); $this->loadQueuedServiceProvider($provider, $options); return [$provider => Arr::except($options, ['instance'])]; })->all(); }
php
{ "resource": "" }
q260871
ProviderRepository.writeManifestFile
test
protected function writeManifestFile(array $manifest = []) { $this->files->put($this->manifestPath, '<?php return '.\var_export($manifest, true).';'); }
php
{ "resource": "" }
q260872
ProviderRepository.registerDeferredServiceProvider
test
protected function registerDeferredServiceProvider($provider, ServiceProvider $instance) { return [ 'instance' => $instance, 'eager' => false, 'when' => $instance->when(), 'deferred' => \array_fill_keys($instance->provides(), $provider), ]; }
php
{ "resource": "" }
q260873
ProviderRepository.loadQueuedServiceProvider
test
protected function loadQueuedServiceProvider($provider, array $options) { foreach ($options['when'] as $listen) { $this->events->listen($listen, function () use ($provider, $options) { $this->app->register($options['instance'] ?? $provider); }); } }
php
{ "resource": "" }
q260874
Activator.activate
test
public function activate(Listener $listener, Fluent $extension) { if ($this->factory->started($extension->get('name'))) { return $listener->abortWhenRequirementMismatched(); } return $this->execute($listener, 'activation', $extension, function (Factory $factory, $name) { $factory->activate($name); }); }
php
{ "resource": "" }
q260875
Repository.map
test
public function map(string $name, array $aliases): bool { $memory = $this->memory->make(); $meta = $memory->get("extension_{$name}", []); foreach ($aliases as $current => $default) { isset($meta[$current]) && $this->config->set($default, $meta[$current]); $meta[$current] = $this->config->get($default); } $memory->put("extension_{$name}", $meta); return true; }
php
{ "resource": "" }
q260876
DomainAware.registerDomainAwareness
test
public function registerDomainAwareness() { $this->app->resolving(RouteGenerator::class, function (RouteGenerator $generator, Application $app) { $generator->setBaseUrl($app->make('config')->get('app.url')); }); }
php
{ "resource": "" }
q260877
Factory.detect
test
public function detect(): Collection { $this->events->dispatch('orchestra.extension: detecting'); return \tap($this->finder()->detect(), function ($extensions) { $this->memory->put('extensions.available', $extensions->map(function ($item) { return Arr::except($item, ['description', 'author', 'url', 'version']); })->all()); }); }
php
{ "resource": "" }
q260878
Factory.option
test
public function option(string $name, string $option, $default = null) { if (! $this->extensions->has($name)) { return \value($default); } return Arr::get($this->extensions->get($name), $option, $default); }
php
{ "resource": "" }
q260879
Factory.publish
test
public function publish(string $name): void { $this->app->make('orchestra.publisher.migrate')->extension($name); $this->app->make('orchestra.publisher.asset')->extension($name); $this->events->dispatch('orchestra.publishing', [$name]); $this->events->dispatch("orchestra.publishing: {$name}"); }
php
{ "resource": "" }
q260880
Factory.register
test
public function register(string $name, string $path): bool { return $this->finder()->registerExtension($name, $path); }
php
{ "resource": "" }
q260881
Factory.route
test
public function route(string $name, string $default = '/'): UrlGeneratorContract { // Boot the extension. ! $this->booted() && $this->app->make(LoadExtension::class)->bootstrap($this->app); if (! isset($this->routes[$name])) { // All route should be manage via `orchestra/extension::handles.{name}` // config key, except for orchestra/foundation. $key = "orchestra/extension::handles.{$name}"; $prefix = $this->app->make('config')->get($key, $default); $this->routes[$name] = $this->app->make('orchestra.extension.url')->handle($prefix); } return $this->routes[$name]; }
php
{ "resource": "" }
q260882
Operation.activating
test
protected function activating(string $name): bool { if (\is_null($active = $this->refresh($name))) { return false; } $this->extensions->put($name, $active[$name]); $this->publish($name); $this->dispatcher->activating($name, $active[$name]); return true; }
php
{ "resource": "" }
q260883
Operation.refresh
test
public function refresh(string $name): ?array { $memory = $this->memory; $available = $memory->get('extensions.available', []); $active = $memory->get('extensions.active', []); if (! isset($available[$name])) { return null; } // Append the activated extension to active extensions, and also // publish the extension (migrate the database and publish the // asset). if (! \is_null($handles = $active[$name]['config']['handles'] ?? null)) { Arr::set($available, "{$name}.config.handles", $handles); } $active[$name] = $available[$name]; $memory->put('extensions.active', $active); return $active; }
php
{ "resource": "" }
q260884
Operation.reset
test
public function reset(string $name): bool { $memory = $this->memory; $default = $memory->get("extensions.available.{$name}", []); $memory->put("extensions.active.{$name}", $default); if ($memory->has("extension_{$name}")) { $memory->put("extension_{$name}", []); } return true; }
php
{ "resource": "" }
q260885
ElementAnnotationsListener.handleExcludeField
test
public function handleExcludeField(EventInterface $event) { /** @var \Doctrine\ORM\Mapping\ClassMetadataInfo $metadata */ $metadata = $event->getParam('metadata'); $identifiers = $metadata->getIdentifierFieldNames(); return in_array($event->getParam('name'), $identifiers) && ($metadata->generatorType === ClassMetadata::GENERATOR_TYPE_IDENTITY || $metadata->generatorType === ClassMetadata::GENERATOR_TYPE_CUSTOM); }
php
{ "resource": "" }
q260886
ThemeManager.createOrchestraDriver
test
protected function createOrchestraDriver(): ThemeContract { $theme = new Theme( $this->app, $this->app->make('events'), $this->app->make('files') ); return $theme->initiate(); }
php
{ "resource": "" }
q260887
Plugin.bootstrap
test
public function bootstrap(Application $app) { $this->bootstrapConfiguration($app); $this->bootstrapForm($app); $this->bootstrapMenuHandler($app); $this->bootstrapSidebarPlaceholders($app); $this->bootstrapValidationRules($app); }
php
{ "resource": "" }
q260888
Plugin.bootstrapConfiguration
test
protected function bootstrapConfiguration(Application $app) { if (empty($this->extension) || empty($this->config)) { return; } $app->make('orchestra.extension.config')->map($this->extension, $this->config); }
php
{ "resource": "" }
q260889
Plugin.bootstrapForm
test
protected function bootstrapForm(Application $app) { $this->attachListenerOn($app, 'form', function (Fluent $model, FormBuilder $form) { $this->form($model, $form); }); }
php
{ "resource": "" }
q260890
Plugin.bootstrapMenuHandler
test
protected function bootstrapMenuHandler(Application $app) { if (\is_null($this->menu)) { return; } $app->make('events')->listen('orchestra.ready: admin', $this->menu); }
php
{ "resource": "" }
q260891
Plugin.bootstrapSidebarPlaceholders
test
protected function bootstrapSidebarPlaceholders(Application $app) { $widget = $app->make('orchestra.widget'); $placeholder = $widget->make('placeholder.orchestra.extensions'); $this->attachListenerOn($app, 'form', function () use ($placeholder) { foreach ($this->sidebar as $name => $view) { $placeholder->add($name)->value(\view($view)); } }); }
php
{ "resource": "" }
q260892
Plugin.bootstrapValidationRules
test
protected function bootstrapValidationRules(Application $app) { $this->attachListenerOn($app, 'validate', function (Fluent $rules) { foreach ($this->rules as $name => $validation) { $rules[$name] = $validation; } }); }
php
{ "resource": "" }
q260893
Plugin.attachListenerOn
test
protected function attachListenerOn(Application $app, $event, Closure $callback) { $app->make('events')->listen("orchestra.{$event}: extension.{$this->extension}", $callback); }
php
{ "resource": "" }
q260894
Theme.initiate
test
public function initiate() { $baseUrl = $this->app->make('request')->root(); // Register relative and absolute URL for theme usage. $this->absoluteUrl = \rtrim($baseUrl, '/').'/themes'; $this->relativeUrl = \trim(\str_replace($baseUrl, '/', $this->absoluteUrl), '/'); return $this; }
php
{ "resource": "" }
q260895
Theme.setTheme
test
public function setTheme(?string $theme): void { if (! \is_null($this->theme)) { $this->resolved && $this->resetViewPaths(); $this->dispatcher->dispatch("orchestra.theme.unset: {$this->theme}"); } $this->theme = $theme; $this->dispatcher->dispatch("orchestra.theme.set: {$this->theme}"); if ($this->resolved) { $this->resolved = false; $this->resolving(); } }
php
{ "resource": "" }
q260896
Theme.boot
test
public function boot(): bool { if ($this->booted) { return false; } $this->booted = true; $themePath = $this->getThemePath(); $autoload = $this->getThemeAutoloadFiles($themePath); foreach ($autoload as $file) { $file = \ltrim($file, '/'); $this->files->requireOnce("{$themePath}/{$file}"); } $this->dispatcher->dispatch("orchestra.theme.boot: {$this->theme}"); return true; }
php
{ "resource": "" }
q260897
Theme.resolving
test
public function resolving(): bool { if ($this->resolved) { return false; } $this->resolved = true; $this->dispatcher->dispatch('orchestra.theme.resolving', [$this, $this->app]); $this->setViewPaths(); return true; }
php
{ "resource": "" }
q260898
Theme.getAvailableThemePaths
test
public function getAvailableThemePaths(): array { return Collection::make($this->getThemePaths())->filter(function ($path) { return $this->files->isDirectory($path); })->values()->all(); }
php
{ "resource": "" }
q260899
Theme.getThemeAutoloadFiles
test
protected function getThemeAutoloadFiles(string $themePath): array { $manifest = new Manifest($this->files, $themePath); return $manifest->autoload ?? []; }
php
{ "resource": "" }