_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q262400
PluginInstaller.getRootPackage
test
protected static function getRootPackage(\Composer\Composer $composer) { $rootPackage = $composer->getPackage(); if ($rootPackage) { while ($rootPackage instanceof \Composer\Package\AliasPackage) { $rootPackage = $rootPackage->getAliasOf(); } } return $rootPackage; }
php
{ "resource": "" }
q262401
PluginInstaller.getInstallPath
test
public function getInstallPath(\Composer\Package\PackageInterface $package) { $packageType = $package->getType(); $installDir = $this->initializeInstallDir($packageType); $installName = static::getInstallName($package, $this->rootPackage); return $installDir . '/' . $installName; }
php
{ "resource": "" }
q262402
PluginInstaller.initializeInstallDir
test
protected function initializeInstallDir($packageType) { $installDir = ''; $rootPackageExtra = $this->rootPackage ? $this->rootPackage->getExtra() : null; if (!empty($rootPackageExtra[$packageType . '-dir'])) { $installDir = rtrim($rootPackageExtra[$packageType . '-dir'], '/\\'); } if (!$installDir) { if (empty($this->installDirs[$packageType])) { throw new \InvalidArgumentException( "The package type '" . $packageType . "' is not supported" ); } $installDir = $this->installDirs[$packageType]; } if (!$this->filesystem->isAbsolutePath($installDir)) { $installDir = dirname($this->vendorDir) . '/' . $installDir; } $this->filesystem->ensureDirectoryExists($installDir); return realpath($installDir); }
php
{ "resource": "" }
q262403
LayoutDcaListener.generatePalette
test
public function generatePalette(): void { // @codingStandardsIgnoreStart // TODO: How to handle editAll actions? // @codingStandardsIgnoreEnd if (Input::get('table') != 'tl_layout' || Input::get('act') != 'edit') { return; } $layout = LayoutModel::findByPk(Input::get('id')); // dynamically render palette so that extensions can plug into default palette if ($layout->layoutType == 'bootstrap') { $metaPalettes = & $GLOBALS['TL_DCA']['tl_layout']['metapalettes']; $metaPalettes['__base__'] = $this->getMetaPaletteOfPalette('tl_layout'); $metaPalettes['default extends __base__'] = $this->environment ->getConfig() ->get('layout.metapalette', array()); // unset default palette. otherwise metapalettes will not render this palette unset($GLOBALS['TL_DCA']['tl_layout']['palettes']['default']); $subSelectPalettes = $this->environment->getConfig()->get('layout.metasubselectpalettes', array()); foreach ($subSelectPalettes as $field => $meta) { foreach ($meta as $value => $definition) { unset($GLOBALS['TL_DCA']['tl_layout']['subpalettes'][$field . '_' . $value]); $GLOBALS['TL_DCA']['tl_layout']['metasubselectpalettes'][$field][$value] = $definition; } } } else { MetaPalettes::appendFields('tl_layout', 'title', array('layoutType')); } }
php
{ "resource": "" }
q262404
LayoutDcaListener.getMetaPaletteOfPalette
test
protected function getMetaPaletteOfPalette(string $table, string $name = 'default'): array { $palette = $GLOBALS['TL_DCA'][$table]['palettes'][$name]; $metaPalette = array(); $legends = explode(';', $palette); foreach ($legends as $legend) { $fields = explode(',', $legend); preg_match('/\{(.*)_legend(:hide)?\}/', $fields[0], $matches); if (isset($matches[2])) { $fields[0] = $matches[2]; } else { array_shift($fields); } $metaPalette[$matches[1]] = $fields; } return $metaPalette; }
php
{ "resource": "" }
q262405
LeavingContextFailed.inContext
test
public static function inContext(Context $context, $code = 0, Throwable $previous = null): self { return new static( sprintf('Leaving context "%s" failed. Context stack is empty', $context->__toString()), $code, $previous ); }
php
{ "resource": "" }
q262406
ConfigSubscriber.enterThemeContext
test
public function enterThemeContext(InitializeLayout $event): void { $event->getEnvironment()->enterContext(ThemeContext::forTheme((int) $event->getLayoutModel()->pid)); }
php
{ "resource": "" }
q262407
ConfigSubscriber.buildContextConfig
test
public function buildContextConfig(BuildContextConfig $command): void { $context = $command->getContext(); if ($context instanceof ApplicationContext) { $command->setConfig($this->config); } }
php
{ "resource": "" }
q262408
ColorRotate.getColor
test
public function getColor(string $identifier): string { if (!isset($this->cache[$identifier])) { $this->cache[$identifier] = $this->rotateColor(); } return $this->cache[$identifier]; }
php
{ "resource": "" }
q262409
ColorRotate.rotateColor
test
private function rotateColor(): string { $color = $this->convertHSVtoRGB($this->rotatingColor, $this->saturation, $this->value); $this->rotatingColor += .3; if ($this->rotatingColor > 1) { $this->rotatingColor -= 1; } return $color; }
php
{ "resource": "" }
q262410
ColorRotate.convertHSVtoRGB
test
private function convertHSVtoRGB(float $hue, float $saturation, float $value): string { // First $hue *= 6; // Second $i = floor($hue); $f = ($hue - $i); // Third $m = ($value * (1 - $saturation)); $n = ($value * (1 - $saturation * $f)); $k = ($value * (1 - $saturation * (1 - $f))); // Forth switch ($i) { case 0: list($red, $green, $blue) = array($value, $k, $m); break; case 1: list($red, $green, $blue) = array($n, $value, $m); break; case 2: list($red, $green, $blue) = array($m, $value, $k); break; case 3: list($red, $green, $blue) = array($m, $n, $value); break; case 4: list($red, $green, $blue) = array($k, $m, $value); break; case 5: case 6: // for when $H=1 is given default: list($red, $green, $blue) = array($value, $m, $n); break; } return sprintf('#%02x%02x%02x', ($red * 255), ($green * 255), ($blue * 255)); }
php
{ "resource": "" }
q262411
Environment.enterContext
test
public function enterContext(Context $context): void { // Already in the context. if ($this->context && $this->context->match($context)) { return; } $this->switchContext($context, true); }
php
{ "resource": "" }
q262412
Environment.leaveContext
test
public function leaveContext(?Context $currentContext = null): void { if (!$this->context) { throw LeavingContextFailed::noContext(); } // Not in expected context. Just quit. if ($currentContext && !$currentContext->match($this->context)) { return; } // Get last know context which was used before current context. $context = array_pop($this->contextStack); if ($context === null) { throw LeavingContextFailed::inContext($this->context); } $this->switchContext($context); }
php
{ "resource": "" }
q262413
Environment.switchContext
test
private function switchContext(Context $context, bool $keepCurrentInStack = false): void { $command = new BuildContextConfig($this, $context, $this->config); $this->messageBus->dispatch($command::NAME, $command); if ($command->getConfig()) { $this->config = $command->getConfig(); } if ($keepCurrentInStack && $this->context) { $this->contextStack[] = $this->context; } $this->context = $context; $event = new ContextEntered($this, $context); $this->messageBus->dispatch($event::NAME, $event); }
php
{ "resource": "" }
q262414
ConfigPass.loadConfigFromBundles
test
private function loadConfigFromBundles(ContainerBuilder $container) { $config = []; foreach ($container->getParameter('kernel.bundles') as $bundleClass) { $refClass = new \ReflectionClass($bundleClass); $bundleDir = dirname($refClass->getFileName()); $configFile = $bundleDir . '/Resources/config/contao_bootstrap.yml'; if (file_exists($configFile)) { $config = ArrayUtil::merge($config, Yaml::parse(file_get_contents($configFile))); } } $container->setParameter('contao_bootstrap.config', $config); }
php
{ "resource": "" }
q262415
ConfigPass.setConfigTypesArgument
test
private function setConfigTypesArgument(ContainerBuilder $container): void { if (!$container->has('contao_bootstrap.config.type_manager')) { return; } $definition = $container->findDefinition('contao_bootstrap.config.type_manager'); $taggedServiceIds = $container->findTaggedServiceIds('contao_bootstrap.config.type'); $services = (array) $definition->getArgument(1); foreach (array_keys($taggedServiceIds) as $serviceId) { $services[] = new Reference($serviceId); } $definition->replaceArgument(1, $services); }
php
{ "resource": "" }
q262416
ModuleDcaListener.getTemplates
test
public function getTemplates(DataContainer $dataContainer): array { $config = array(); $prefix = ''; // MCW compatibility if ($dataContainer instanceof MultiColumnWizard) { $field = $dataContainer->strField; $table = $dataContainer->strTable; } else { $field = $dataContainer->field; $table = $dataContainer->table; } if (array_key_exists('eval', $GLOBALS['TL_DCA'][$table]['fields'][$field])) { $config = $GLOBALS['TL_DCA'][$table]['fields'][$field]['eval']; } if (array_key_exists('templatePrefix', $config)) { $prefix = $config['templatePrefix']; } return \Controller::getTemplateGroup($prefix); }
php
{ "resource": "" }
q262417
ModuleDcaListener.pagePicker
test
public function pagePicker(DataContainer $dataContainer): string { $template = ' <a href="contao/page.php?do=%s&amp;table=%s&amp;field=%s&amp;value=%s" title="%s"'; $template .= ' onclick="Backend.getScrollOffset();Backend.openModalSelector({\'width\':765,\'title\':\'%s\''; $template .= ',\'url\':this.href,\'id\':\'%s\',\'tag\':\'ctrl_%s\',\'self\':this});return false">%s</a>'; return sprintf( $template, Input::get('do'), $dataContainer->table, $dataContainer->field, str_replace(array('{{link_url::', '}}'), '', $dataContainer->value), specialchars($GLOBALS['TL_LANG']['MSC']['pagepicker']), specialchars(str_replace("'", "\\'", $GLOBALS['TL_LANG']['MOD']['page'][0])), $dataContainer->field, $dataContainer->field . ((\Input::get('act') == 'editAll') ? '_' . $dataContainer->id : ''), Image::getHtml( 'pickpage.gif', $GLOBALS['TL_LANG']['MSC']['pagepicker'], 'style="vertical-align:top;cursor:pointer"' ) ); }
php
{ "resource": "" }
q262418
ModuleDcaListener.getAllArticles
test
public function getAllArticles(): array { $user = BackendUser::getInstance(); $pids = array(); $articles = array(); // Limit pages to the user's pagemounts if ($user->isAdmin) { $objArticle = Database::getInstance()->execute( 'SELECT a.id, a.pid, a.title, a.inColumn, p.title AS parent FROM tl_article a LEFT JOIN tl_page p ON p.id=a.pid ORDER BY parent, a.sorting' ); } else { foreach ($user->pagemounts as $id) { $pids[] = $id; $pids = array_merge($pids, Database::getInstance()->getChildRecords($id, 'tl_page')); } if (empty($pids)) { return $articles; } $pids = implode(',', array_map('intval', array_unique($pids))); $objArticle = Database::getInstance()->execute( 'SELECT a.id, a.pid, a.title, a.inColumn, p.title AS parent FROM tl_article a LEFT JOIN tl_page p ON p.id=a.pid WHERE a.pid IN(' . $pids . ') ORDER BY parent, a.sorting' ); } // Edit the result if ($objArticle->numRows) { Controller::loadLanguageFile('tl_article'); while ($objArticle->next()) { $key = $objArticle->parent . ' (ID ' . $objArticle->pid . ')'; $articles[$key][$objArticle->id] = $objArticle->title . ' (' . ($GLOBALS['TL_LANG']['tl_article'][$objArticle->inColumn] ?: $objArticle->inColumn) . ', ID ' . $objArticle->id . ')'; } } return $articles; }
php
{ "resource": "" }
q262419
ModuleDcaListener.getAllModules
test
public function getAllModules(): array { $modules = array(); $query = 'SELECT m.id, m.name, t.name AS theme FROM tl_module m LEFT JOIN tl_theme t ON m.pid=t.id'; if (Input::get('table') == 'tl_module' && \Input::get('act') == 'edit') { $query .= ' WHERE m.id != ?'; } $query .= ' ORDER BY t.name, m.name'; $result = Database::getInstance() ->prepare($query) ->execute(Input::get('id')); while ($result->next()) { $modules[$result->theme][$result->id] = $result->name . ' (ID ' . $result->id . ')'; } return $modules; }
php
{ "resource": "" }
q262420
TemplateParseListener.prepare
test
public function prepare(Template $template): void { if ($this->preRenderFilter->supports($template)) { $this->preRenderFilter->filter($template); } }
php
{ "resource": "" }
q262421
TemplateParseListener.parse
test
public function parse(string $buffer, string $templateName): string { if ($this->postRenderFilter->supports($templateName)) { $buffer = $this->postRenderFilter->filter($buffer, $templateName); } return $buffer; }
php
{ "resource": "" }
q262422
TemplateFilterPass.registerTaggedServices
test
private function registerTaggedServices( ContainerBuilder $container, string $definitionId, string $tagName, $argumentIndex = 0 ): bool { if (!$container->has($definitionId)) { return false; } $definition = $container->findDefinition($definitionId); $taggedServiceIds = $container->findTaggedServiceIds($tagName); $services = (array) $definition->getArgument($argumentIndex); foreach (array_keys($taggedServiceIds) as $serviceId) { $services[] = new Reference($serviceId); } $definition->replaceArgument(0, $services); return true; }
php
{ "resource": "" }
q262423
HookListener.initializeEnvironment
test
protected function initializeEnvironment(): void { $event = new InitializeEnvironment($this->environment); $this->eventDispatcher->dispatch($event::NAME, $event); }
php
{ "resource": "" }
q262424
HookListener.initializeLayout
test
public function initializeLayout(\PageModel $page, \LayoutModel $layout): void { $environment = $this->environment; $environment->setLayout($layout); $environment->setEnabled($layout->layoutType == 'bootstrap'); $event = new InitializeLayout($environment, $layout, $page); $this->eventDispatcher->dispatch($event::NAME, $event); }
php
{ "resource": "" }
q262425
PhpInterface.addChild
test
public function addChild($child): AbstractElement { if ($child instanceof PhpMethod) { $child->setHasBody(false); } return parent::addChild($child); }
php
{ "resource": "" }
q262426
Compiler.compile
test
public function compile($input, $path = null) { //Compiler reset $this->files = $path ? [$path] : []; $this->mixins = []; $this->calledMixins = []; $this->blocks = []; $this->level = 0; $this->iteratorId = 0; $this->forceInline = false; //Parse the input into an AST $node = null; try { $node = $this->parser->parse($input); } catch(\Exception $e) { //This is needed to be able to keep track of the //file path that is erroring if (!($e instanceof Exception)) $this->throwException($e->getMessage()); else throw $e; } //There are some things we need to take care of before compilation $this->handleImports($node); $this->handleBlocks($node); $this->handleMixins($node); //The actual compilation process ($node is the very root \Tale\Pug\Parser\Node of everything) $phtml = $this->compileNode($node); //Reset the level again for our next operations $this->level = 0; //Now we append/prepend specific stuff (like mixin functions and helpers) $mixins = $this->compileMixins(); $helpers = ''; if ($this->options['stand_alone']) { $helpers = file_get_contents(__DIR__.'/Compiler/functions.php')."\n?>\n"; $helpers .= $this->createCode('namespace {'); } //Put everything together $phtml = implode('', [$helpers, $mixins, $phtml]); if ($this->options['stand_alone']) $phtml .= $this->createCode('}'); //Reset the files after compilation so that compileFile may resolve correctly //Happens when you call compileFile twice on different files //Note that Compiler only uses the include-path, when there is no file in the //file name storage $_files $this->files = []; //Return the compiled PHTML return trim($phtml); }
php
{ "resource": "" }
q262427
Compiler.compileNode
test
protected function compileNode(Node $node) { $method = 'compile'.ucfirst($node->type); if (!method_exists($this, $method)) $this->throwException( "No handler $method found for $node->type found. It seems you have customized nodes. You need to ". "extend the Tale Pug Compiler and add own $method-method for the respective node type.", $node ); //resolve expansions if (isset($node->expands)) { $current = $node; while (isset($current->expands)) { $expandedNode = $current->expands; unset($current->expands); $current->parent->insertBefore($current, $expandedNode); $current->parent->remove($current); $expandedNode->append($current); $current = $expandedNode; } return $this->compileNode($current); } return call_user_func([$this, $method], $node); }
php
{ "resource": "" }
q262428
Compiler.throwException
test
protected function throwException($message, Node $relatedNode = null) { if ($relatedNode) $message .= "\n(".$relatedNode->type .' at '.$relatedNode->line .':'.$relatedNode->offset.')'; if (!empty($this->files)) $message .= "\nError occured in: [".end($this->files).']'; throw new Exception( "Failed to compile Pug: $message" ); }
php
{ "resource": "" }
q262429
DoctrineExtractor.getPhpType
test
private function getPhpType($doctrineType) { switch ($doctrineType) { case 'smallint': // No break case 'bigint': // No break case 'integer': return Type::BUILTIN_TYPE_INT; case 'decimal': return Type::BUILTIN_TYPE_FLOAT; case 'text': // No break case 'guid': return Type::BUILTIN_TYPE_STRING; case 'boolean': return Type::BUILTIN_TYPE_BOOL; case 'blob': // No break case 'binary': return Type::BUILTIN_TYPE_RESOURCE; default: return $doctrineType; } }
php
{ "resource": "" }
q262430
PhpDocExtractor.getFileReflector
test
private function getFileReflector(\ReflectionClass $reflectionClass) { if (!($fileName = $reflectionClass->getFileName()) || 'hh' === pathinfo($fileName, PATHINFO_EXTENSION)) { return; } if (isset(self::$fileReflectors[$fileName])) { return self::$fileReflectors[$fileName]; } self::$fileReflectors[$fileName] = new FileReflector($fileName); self::$fileReflectors[$fileName]->process(); return self::$fileReflectors[$fileName]; }
php
{ "resource": "" }
q262431
PhpDocExtractor.getDocBlock
test
private function getDocBlock($class, $property) { $propertyHash = sprintf('%s::%s', $class, $property); if (isset(self::$docBlocks[$propertyHash])) { return self::$docBlocks[$propertyHash]; } $ucFirstProperty = ucfirst($property); switch (true) { case $docBlock = $this->getDocBlockFromProperty($class, $property): $data = array($docBlock, self::PROPERTY, null); break; case list($docBlock) = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::ACCESSOR): $data = array($docBlock, self::ACCESSOR, null); break; case list($docBlock, $prefix) = $this->getDocBlockFromMethod($class, $ucFirstProperty, self::MUTATOR): $data = array($docBlock, self::MUTATOR, $prefix); break; default: $data = array(null, null); } return self::$docBlocks[$propertyHash] = $data; }
php
{ "resource": "" }
q262432
PhpDocExtractor.getDocBlockFromProperty
test
private function getDocBlockFromProperty($class, $property) { // Use a ReflectionProperty instead of $class to get the parent class if applicable try { $reflectionProperty = new \ReflectionProperty($class, $property); } catch (\ReflectionException $reflectionException) { return; } $reflectionCLass = $reflectionProperty->getDeclaringClass(); $fileReflector = $this->getFileReflector($reflectionCLass); if (!$fileReflector) { return; } foreach ($fileReflector->getClasses() as $classReflector) { $className = $this->getClassName($classReflector); if ($className === $reflectionCLass->name) { foreach ($classReflector->getProperties() as $propertyReflector) { // strip the $ prefix $propertyName = substr($propertyReflector->getName(), 1); if ($propertyName === $property) { return $propertyReflector->getDocBlock(); } } } } }
php
{ "resource": "" }
q262433
PhpDocExtractor.getDocBlockFromMethod
test
private function getDocBlockFromMethod($class, $ucFirstProperty, $type) { $prefixes = $type === self::ACCESSOR ? ReflectionExtractor::$accessorPrefixes : ReflectionExtractor::$mutatorPrefixes; foreach ($prefixes as $prefix) { $methodName = $prefix.$ucFirstProperty; try { $reflectionMethod = new \ReflectionMethod($class, $methodName); if ( (self::ACCESSOR === $type && 0 === $reflectionMethod->getNumberOfRequiredParameters()) || (self::MUTATOR === $type && $reflectionMethod->getNumberOfParameters() >= 1) ) { break; } } catch (\ReflectionException $reflectionException) { // Try the next prefix if the method doesn't exist } } if (!isset($reflectionMethod)) { return; } $reflectionClass = $reflectionMethod->getDeclaringClass(); $fileReflector = $this->getFileReflector($reflectionClass); if (!$fileReflector) { return; } foreach ($fileReflector->getClasses() as $classReflector) { $className = $this->getClassName($classReflector); if ($className === $reflectionClass->name) { if ($methodReflector = $classReflector->getMethod($methodName)) { return array($methodReflector->getDocBlock(), $prefix); } } } }
php
{ "resource": "" }
q262434
PhpDocExtractor.getPhpTypeAndClass
test
private function getPhpTypeAndClass($docType) { if (in_array($docType, Type::$builtinTypes)) { return array($docType, null); } return array('object', substr($docType, 1)); }
php
{ "resource": "" }
q262435
Wallhaven.login
test
public function login($username, $password) { if (empty($username) || empty($password)) { throw new LoginException("Incorrect username or password."); } $this->initClient(true); $login = $this->client->post(self::URL_LOGIN, [ 'form_params' => [ '_token' => $this->getToken(), 'username' => $username, 'password' => $password ], 'on_stats' => function (TransferStats $stats) use (&$url) { $url = $stats->getEffectiveUri(); } ]); if ($url == self::URL_HOME . self::URL_LOGIN) { throw new LoginException("Incorrect username or password."); } $this->username = $username; }
php
{ "resource": "" }
q262436
Wallhaven.initClient
test
private function initClient($withCookies = false) { if ($withCookies) { $jar = new CookieJar(); $this->client = new Client( [ 'base_uri' => self::URL_HOME, 'cookies' => $jar ]); } else { $this->client = new Client(['base_uri' => self::URL_HOME]); } }
php
{ "resource": "" }
q262437
Wallhaven.getToken
test
private function getToken() { $body = $this->client->get('/')->getBody()->getContents(); $dom = new Dom(); $dom->load($body); $token = $dom->find('input[name="_token"]')[0]->value; if (empty($token)) { throw new LoginException("Cannot find login token on Wallhaven's homepage."); } return $token; }
php
{ "resource": "" }
q262438
Wallhaven.search
test
public function search( $query, $categories = Category::ALL, $purity = Purity::SFW, $sorting = Sorting::RELEVANCE, $order = Order::DESC, $resolutions = [], $ratios = [], $page = 1 ) { $result = $this->client->get(self::URL_SEARCH, [ 'query' => [ 'q' => $query, 'categories' => self::getBinary($categories), 'purity' => self::getBinary($purity), 'sorting' => $sorting, 'order' => $order, 'resolutions' => implode(',', $resolutions), 'ratios' => implode(',', $ratios), 'page' => $page ], 'headers' => [ 'X-Requested-With' => 'XMLHttpRequest' ] ]); $body = $result->getBody()->getContents(); $dom = new Dom(); $dom->load($body); $figures = $dom->find('figure.thumb'); $wallpapers = new WallpaperList(); foreach ($figures as $figure) { $id = preg_split('#' . self::URL_HOME . self::URL_WALLPAPER . '/#', $figure->find('a.preview')->getAttribute('href'))[1]; $classText = $figure->getAttribute('class'); preg_match("/thumb thumb-(sfw|sketchy|nsfw) thumb-(general|anime|people)/", $classText, $classMatches); $purity = constant('Wallhaven\Purity::' . strtoupper($classMatches[1])); $category = constant('Wallhaven\Category::' . strtoupper($classMatches[2])); $resolution = str_replace(' ', '', trim($figure->find('span.wall-res')->text)); $favorites = (int)$figure->find('.wall-favs')->text; $w = new Wallpaper($id, $this->client); $w->setProperties([ 'purity' => $purity, 'category' => $category, 'resolution' => $resolution, 'favorites' => $favorites ]); $wallpapers[] = $w; } return $wallpapers; }
php
{ "resource": "" }
q262439
PropertyInfo.extract
test
private function extract(array $extractors, $method, array $arguments) { foreach ($extractors as $extractor) { $value = call_user_func_array(array($extractor, $method), $arguments); if (null !== $value) { return $value; } } }
php
{ "resource": "" }
q262440
Wallpaper.getTags
test
public function getTags() { if ($this->cacheEnabled && $this->tags !== null) { return $this->tags; } $dom = $this->getDom(); $this->tags = []; foreach ($dom->find('a.tagname') as $e) { $this->tags[] = $e->text; } return $this->tags; }
php
{ "resource": "" }
q262441
Wallpaper.download
test
public function download($directory) { if (!file_exists($directory)) { if (!@mkdir($directory, null, true)) { throw new DownloadException("The download directory cannot be created."); } } $url = $this->getImageUrl(); $this->client->get($url, [ 'save_to' => $directory . '/' . basename($url), ]); }
php
{ "resource": "" }
q262442
Filter.getWallpapers
test
public function getWallpapers() { $wallpapers = new WallpaperList(); for ($i = 1; $i <= $this->pages; ++$i) { $wallpapers->addAll($this->wallhaven->search( $this->keywords, $this->categories, $this->purity, $this->sorting, $this->order, $this->resolutions, $this->ratios, $i )); } return $wallpapers; }
php
{ "resource": "" }
q262443
WallpaperList.downloadAll
test
public function downloadAll($directory) { if (!file_exists($directory)) { if (!@mkdir($directory, null, true)) { throw new DownloadException("The download directory cannot be created."); } } $client = new Client(); $requests = []; foreach ($this->wallpapers as $w) { $url = $w->getImageUrl(true); $requests[] = $client->createRequest('GET', $url, [ 'save_to' => $directory . '/' . basename($url) ]); } $results = Pool::batch($client, $requests); // Retry with PNG $retryRequests = []; foreach ($results->getFailures() as $e) { // Delete failed files unlink($directory . '/' . basename($e->getRequest()->getUrl())); $urlPng = str_replace('.jpg', '.png', $e->getRequest()->getUrl()); $statusCode = $e->getResponse()->getStatusCode(); if ($statusCode == 404) { $retryRequests[] = $client->createRequest('GET', $urlPng, [ 'save_to' => $directory . '/' . basename($urlPng) ]); } } Pool::batch($client, $retryRequests); }
php
{ "resource": "" }
q262444
ReflectionExtractor.extractFromMutator
test
private function extractFromMutator($class, $property) { list($reflectionMethod, $prefix) = $this->getMutatorMethod($class, $property); if (null === $reflectionMethod) { return; } $reflectionParameters = $reflectionMethod->getParameters(); $reflectionParameter = $reflectionParameters[0]; $arrayMutator = in_array($prefix, self::$arrayMutatorPrefixes); if (method_exists($reflectionParameter, 'getType') && $reflectionType = $reflectionParameter->getType()) { $fromReflectionType = $this->extractFromReflectionType($reflectionType); if (!$arrayMutator) { return array($fromReflectionType); } $phpType = Type::BUILTIN_TYPE_ARRAY; $collectionKeyType = new Type(Type::BUILTIN_TYPE_INT); $collectionValueType = $fromReflectionType; } if ($reflectionParameter->isArray()) { $phpType = Type::BUILTIN_TYPE_ARRAY; $collection = true; } if ($arrayMutator) { $collection = true; $nullable = false; $collectionNullable = $reflectionParameter->allowsNull(); } else { $nullable = $reflectionParameter->allowsNull(); $collectionNullable = false; } if (!isset($collection)) { $collection = false; } if (method_exists($reflectionParameter, 'isCallable') && $reflectionParameter->isCallable()) { $phpType = Type::BUILTIN_TYPE_CALLABLE; } if ($typeHint = $reflectionParameter->getClass()) { if ($collection) { $phpType = Type::BUILTIN_TYPE_ARRAY; $collectionKeyType = new Type(Type::BUILTIN_TYPE_INT); $collectionValueType = new Type(Type::BUILTIN_TYPE_OBJECT, $collectionNullable, $typeHint->name); } else { $phpType = Type::BUILTIN_TYPE_OBJECT; $typeClass = $typeHint->name; } } // Nothing useful extracted if (!isset($phpType)) { return; } return array( new Type( $phpType, $nullable, isset($typeClass) ? $typeClass : null, $collection, isset($collectionKeyType) ? $collectionKeyType : null, isset($collectionValueType) ? $collectionValueType : null ), ); }
php
{ "resource": "" }
q262445
ReflectionExtractor.extractFromAccessor
test
private function extractFromAccessor($class, $property) { list($reflectionMethod, $prefix) = $this->getAccessorMethod($class, $property); if (null === $reflectionMethod) { return; } if (method_exists($reflectionMethod, 'getReturnType') && $reflectionType = $reflectionMethod->getReturnType()) { return array($this->extractFromReflectionType($reflectionType)); } if (in_array($prefix, array('is', 'can'))) { return array(new Type(Type::BUILTIN_TYPE_BOOL)); } }
php
{ "resource": "" }
q262446
ReflectionExtractor.extractFromReflectionType
test
private function extractFromReflectionType(\ReflectionType $reflectionType) { $phpTypeOrClass = (string) $reflectionType; $nullable = $reflectionType->allowsNull(); if ($reflectionType->isBuiltin()) { if (Type::BUILTIN_TYPE_ARRAY === $phpTypeOrClass) { $type = new Type(Type::BUILTIN_TYPE_ARRAY, $nullable, null, true); } else { $type = new Type($phpTypeOrClass, $nullable); } } else { $type = new Type(Type::BUILTIN_TYPE_OBJECT, $nullable, $phpTypeOrClass); } return $type; }
php
{ "resource": "" }
q262447
ReflectionExtractor.isPublicProperty
test
private function isPublicProperty($class, $property) { try { $reflectionProperty = new \ReflectionProperty($class, $property); return $reflectionProperty->isPublic(); } catch (\ReflectionException $reflectionExcetion) { // Return false if the property doesn't exist } return false; }
php
{ "resource": "" }
q262448
ReflectionExtractor.getAccessorMethod
test
private function getAccessorMethod($class, $property) { $ucProperty = ucfirst($property); foreach (self::$accessorPrefixes as $prefix) { try { $reflectionMethod = new \ReflectionMethod($class, $prefix.$ucProperty); if (0 === $reflectionMethod->getNumberOfRequiredParameters()) { return array($reflectionMethod, $prefix); } } catch (\ReflectionException $reflectionException) { // Return null if the property doesn't exist } } return; }
php
{ "resource": "" }
q262449
ReflectionExtractor.getMutatorMethod
test
private function getMutatorMethod($class, $property) { $ucProperty = ucfirst($property); foreach (self::$mutatorPrefixes as $prefix) { try { $reflectionMethod = new \ReflectionMethod($class, $prefix.$ucProperty); // Parameter can be optional to allow things like: method(array $foo = null) if ($reflectionMethod->getNumberOfParameters() >= 1) { return array($reflectionMethod, $prefix); } } catch (\ReflectionException $reflectionException) { // Try the next prefix if the method doesn't exist } } }
php
{ "resource": "" }
q262450
ReflectionExtractor.getPropertyName
test
private function getPropertyName($methodName) { $pattern = implode('|', array_merge(self::$accessorPrefixes, self::$mutatorPrefixes)); if (preg_match('/^('.$pattern.')(.+)$/i', $methodName, $matches)) { return $matches[2]; } }
php
{ "resource": "" }
q262451
LaravelExtension.load
test
public function load(ServiceContainer $container) { // Create & store Laravel wrapper $container->setShared( 'laravel', function (ServiceContainer $c) { $config = $c->getParam('laravel_extension'); $laravel = new Laravel( isset($config['testing_environment']) ? $config['testing_environment'] : null, isset($config['app_classname']) ? $config['app_classname'] : null ); return $laravel; } ); // Bootstrap maintainer to bind Laravel wrapper to specs $container->setShared( 'runner.maintainers.laravel', function (ServiceContainer $c) { return new LaravelMaintainer( $c->get('laravel') ); } ); // Bootstrap maintainer to bind app Presenter to specs, so it // can be passed to custom matchers $container->setShared( 'runner.maintainers.presenter', function (ServiceContainer $c) { return new PresenterMaintainer( $c->get('formatter.presenter') ); } ); // Bootstrap listener to setup Laravel application for specs $container->setShared( 'event_dispatcher.listeners.laravel', function (ServiceContainer $c) { return new LaravelListener($c->get('laravel')); } ); }
php
{ "resource": "" }
q262452
Laravel.createApplication
test
protected function createApplication() { putenv('APP_ENV=' . $this->getEnv()); if (!is_a($this->appClassName, App::class, true)) { throw new Exception("Instance of Pixelindustries\\PhpspecTestbench\\App expected, got {$this->appClassName}."); } return (new $this->appClassName)->createApplication(); }
php
{ "resource": "" }
q262453
IniModifier.setValue
test
public function setValue($name, $value, $section = 0, $key = null) { if (!preg_match('/^[^\\[\\]]*$/', $name)) { throw new IniInvalidArgumentException("Invalid value name $name"); } if (is_array($value)) { if ($key !== null) { throw new IniInvalidArgumentException('You cannot indicate a key for an array value'); } $this->_setArrayValue($name, $value, $section); } else { $this->_setValue($name, $value, $section, $key); } }
php
{ "resource": "" }
q262454
IniModifier.setValues
test
public function setValues($values, $section = 0) { foreach ($values as $name => $val) { $this->setValue($name, $val, $section); } }
php
{ "resource": "" }
q262455
IniModifier.removeSection
test
public function removeSection($section = 0, $removePreviousComment = true) { if ($section === 0 || !isset($this->content[$section])) { return; } if ($removePreviousComment) { // retrieve the previous section $previousSection = -1; foreach ($this->content as $s => $c) { if ($s === $section) { break; } else { $previousSection = $s; } } if ($previousSection != -1) { //retrieve the last comment $s = $this->content[$previousSection]; end($s); $tok = current($s); while ($tok !== false) { if ($tok[0] != self::TK_WS && $tok[0] != self::TK_COMMENT) { break; } if ($tok[0] == self::TK_COMMENT && strpos($tok[1], '<?') === false) { $this->content[$previousSection][key($s)] = array(self::TK_WS, '--'); } $tok = prev($s); } } } unset($this->content[$section]); $this->modified = true; }
php
{ "resource": "" }
q262456
IniModifier.mergeSection
test
public function mergeSection($sectionSource, $sectionTarget) { if (!isset($this->content[$sectionTarget])) { return $this->renameSection($sectionSource, $sectionTarget); } if (!isset($this->content[$sectionSource])) { return false; } $this->mergeValues($this->content[$sectionSource], $sectionTarget); if ($sectionSource == '0') { $this->content[$sectionSource] = array(); } else { unset($this->content[$sectionSource]); } $this->modified = true; return true; }
php
{ "resource": "" }
q262457
IniModifier.renameValue
test
public function renameValue($name, $newName, $section = 0) { if (!isset($this->content[$section])) { return false; } foreach ($this->content[$section] as $k => $item) { if ($item[0] != self::TK_VALUE && $item[0] != self::TK_ARR_VALUE) { continue; } if ($item[1] != $name) { continue; } $this->content[$section][$k][1] = $newName; $this->modified = true; if ($item[0] == self::TK_VALUE) { break; } } return true; }
php
{ "resource": "" }
q262458
IniModifier.renameSection
test
public function renameSection($oldName, $newName) { if (!isset($this->content[$oldName])) { return false; } if (isset($this->content[$newName])) { return $this->mergeSection($oldName, $newName); } $newcontent = array(); foreach ($this->content as $section => $values) { if ((string) $oldName == (string) $section) { if ($section == '0') { $newcontent[0] = array(); } if ($values[0][0] == self::TK_SECTION) { $values[0][1] = '['.$newName.']'; } else { array_unshift($values, array(self::TK_SECTION, '['.$newName.']')); } $newcontent[$newName] = $values; } else { $newcontent [$section] = $values; } } $this->content = $newcontent; $this->modified = true; return true; }
php
{ "resource": "" }
q262459
Util.read
test
public static function read($filename, $asObject = false) { if (file_exists($filename)) { if ($asObject) { return (object) parse_ini_file($filename, true, INI_SCANNER_TYPED); } else { return parse_ini_file($filename, true, INI_SCANNER_TYPED); } } else { return false; } }
php
{ "resource": "" }
q262460
Util.readAndMergeObject
test
public static function readAndMergeObject($filename, $content, $flags = 0, $ignoredSection = array()) { if (!file_exists($filename)) { return false; } $newContent = @parse_ini_file($filename, true, INI_SCANNER_TYPED); if ($newContent === false) { return false; } return self::mergeIniObjectContents($content, $newContent, $flags, $ignoredSection); }
php
{ "resource": "" }
q262461
Util.mergeIniObjectContents
test
public static function mergeIniObjectContents( $baseContent, $contentToImport, $flags = 0, $ignoredSection = array() ) { $contentToImport = (array) $contentToImport; foreach ($contentToImport as $k => $v) { if (!isset($baseContent->$k)) { $baseContent->$k = $v; continue; } if (($flags & self::NOT_MERGE_PROTECTED_DIRECTIVE) && $k[0] == '_') { continue; } if (in_array($k, $ignoredSection)) { continue; } if (is_array($v)) { // this is a section or a array value if (!is_array($baseContent->$k)) { $baseContent->$k = $v; } else { if ($flags & self::NORMAL_MERGE_ARRAY_VALUES_WITH_INTEGER_KEYS) { if (self::hasOnlyIntegerKeys($v) && self::hasOnlyIntegerKeys($baseContent->$k)) { $baseContent->$k = array_merge($baseContent->$k, $v); continue; } $newbase = $baseContent->$k; } else { // first, in the case of an array value, clean the $base value, by removing all values with numerical keys // as it does not make sens to merge two simple arrays here. $newbase = array(); foreach ($baseContent->$k as $k2 => $v2) { if (is_string($k2)) { $newbase[$k2] = $v2; } } } $baseContent->$k = self::mergeSectionContent($newbase, $v, $flags); } } else { $baseContent->$k = $v; } } return $baseContent; }
php
{ "resource": "" }
q262462
Util._iniValue
test
private static function _iniValue($key, $value) { if (is_array($value)) { $res = ''; foreach ($value as $v) { $res .= self::_iniValue($key.'[]', $v); } return $res; } elseif ($value == '' || is_numeric($value) || (is_string($value) && preg_match("/^[\w\\-\\.]*$/", $value) && strpos("\n", $value) === false) ) { return $key.'='.$value."\n"; } elseif ($value === false) { return $key."=off\n"; } elseif ($value === true) { return $key."=on\n"; } else { return $key.'="'.$value."\"\n"; } }
php
{ "resource": "" }
q262463
IniModifierArray.setValue
test
public function setValue($name, $value, $section = 0, $key = null) { if ($this->lastModifier instanceof IniModifierInterface) { $this->lastModifier->setValue($name, $value, $section, $key); } else { trigger_error('The top ini content is not alterable', E_USER_WARNING); } }
php
{ "resource": "" }
q262464
IniModifierArray.setValues
test
public function setValues($values, $section = 0) { if ($this->lastModifier instanceof IniModifierInterface) { $this->lastModifier->setValues($values, $section); } else { trigger_error('The top ini content is not alterable', E_USER_WARNING); } }
php
{ "resource": "" }
q262465
IniModifierArray.getValues
test
public function getValues($section = 0) { $finalValues = array(); foreach ($this->modifiers as $mod) { $values = $mod->getValues($section); if (!count($values)) { continue; } if (!count($finalValues)) { $finalValues = $values; continue; } foreach ($values as $key => &$value) { if (!isset($finalValues[$key])) { $finalValues[$key] = $value; continue; } if (is_array($value) && is_array($finalValues[$key])) { $finalValues[$key] = array_merge($finalValues[$key], $value); } else { $finalValues[$key] = $value; } } } return $finalValues; }
php
{ "resource": "" }
q262466
IniModifierArray.removeValue
test
public function removeValue($name, $section = 0, $key = null, $removePreviousComment = true) { foreach ($this->modifiers as $mod) { if ($mod instanceof IniModifierInterface) { $mod->removeValue($name, $section, $key, $removePreviousComment); } } }
php
{ "resource": "" }
q262467
IniModifierArray.removeSection
test
public function removeSection($section = 0, $removePreviousComment = true) { foreach ($this->modifiers as $mod) { if ($mod instanceof IniModifierInterface) { $mod->removeSection($section, $removePreviousComment); } } }
php
{ "resource": "" }
q262468
MultiIniModifier.setValue
test
public function setValue($name, $value, $section = 0, $key = null) { $this->overrider->setValue($name, $value, $section, $key); }
php
{ "resource": "" }
q262469
MultiIniModifier.setValueOnMaster
test
public function setValueOnMaster($name, $value, $section = 0, $key = null) { if (!$this->master instanceof IniModifierInterface) { throw new IniException('Cannot set value on master which is only an ini reader'); } $this->master->setValue($name, $value, $section, $key); }
php
{ "resource": "" }
q262470
MultiIniModifier.setValuesOnMaster
test
public function setValuesOnMaster($values, $section = 0) { if (!$this->master instanceof IniModifierInterface) { throw new IniException('Cannot set value on master which is only an ini reader'); } $this->master->setValues($values, $section); }
php
{ "resource": "" }
q262471
MultiIniModifier.getValueOnMaster
test
public function getValueOnMaster($name, $section = 0, $key = null) { return $this->master->getValue($name, $section, $key); }
php
{ "resource": "" }
q262472
MultiIniModifier.getValues
test
public function getValues($section = 0) { $masterValues = $this->master->getValues($section); $overValues = $this->overrider->getValues($section); foreach ($overValues as $key => &$value) { if (!isset($masterValues[$key])) { $masterValues[$key] = $value; continue; } if (is_array($value) && is_array($masterValues[$key])) { $masterValues[$key] = array_merge($masterValues[$key], $value); } else { $masterValues[$key] = $value; } } return $masterValues; }
php
{ "resource": "" }
q262473
MultiIniModifier.removeValue
test
public function removeValue($name, $section = 0, $key = null, $removePreviousComment = true) { if ($this->master instanceof IniModifierInterface) { $this->master->removeValue($name, $section, $key, $removePreviousComment); } $this->overrider->removeValue($name, $section, $key, $removePreviousComment); }
php
{ "resource": "" }
q262474
MultiIniModifier.removeValueOnMaster
test
public function removeValueOnMaster($name, $section = 0, $key = null, $removePreviousComment = true) { if (!$this->master instanceof IniModifierInterface) { throw new IniException('Cannot remove value on master which is only an ini reader'); } $this->master->removeValue($name, $section, $key, $removePreviousComment); }
php
{ "resource": "" }
q262475
MultiIniModifier.isSection
test
public function isSection($name) { return $this->overrider->isSection($name) || $this->master->isSection($name); }
php
{ "resource": "" }
q262476
IniReader.getValues
test
public function getValues($section = 0) { if (!isset($this->content[$section])) { return array(); } $values = array(); foreach ($this->content[$section] as $k => $item) { if ($item[0] != self::TK_VALUE && $item[0] != self::TK_ARR_VALUE) { continue; } $val = $this->convertValue($item[2]); if ($item[0] == self::TK_VALUE) { $values[$item[1]] = $val; } else { $values[$item[1]][$item[3]] = $val; } } return $values; }
php
{ "resource": "" }
q262477
StandardLoaderFactory.createFileLoader
test
public function createFileLoader($type, ContainerBuilder $container, $path) { $className = $this->getClassNameByShortType($type); return new $className($container, new FileLocator($path)); }
php
{ "resource": "" }
q262478
StandardLoaderFactory.getClassNameByShortType
test
protected function getClassNameByShortType($type) { if (!isset($this->shortTypeToClassMapping[$type])) { throw UnknownFormatException::create($type); } return $this->shortTypeToClassMapping[$type]; }
php
{ "resource": "" }
q262479
SecureCookie.make
test
public function make($name, $value, $minutes = null, $path = null, $domain = null, $secure = false, $httponly = true) { // Calculate a hash for the data and append it to the end of the data string $hash = hash_hmac($this->hash_algo, $value, $this->hash_secret); $value .= $hash; $minutes = $minutes ? $minutes : self::DEFAULT_EXPIRATION_DATE; // Set a cookie with the data $ttl = $minutes === null ? 0 : time() + ($minutes * 60); return setcookie($name, base64_encode($value), $ttl, $path, $domain, $secure, $httponly); }
php
{ "resource": "" }
q262480
ConvertCommand.execute
test
protected function execute(InputInterface $input, OutputInterface $output) { $fileToConvert = $this->determineFile($output, $input->getArgument('file')); $newFormat = $input->getArgument('format'); $newConfig = $this ->getContainer() ->get('tuck_converter.config_format_converter') ->convertFile($fileToConvert, $newFormat); if ($input->getOption('output')) { $output->write($newConfig); } else { $this->writeToFile($output, $fileToConvert, $newConfig, $newFormat); } }
php
{ "resource": "" }
q262481
ConvertCommand.determineFile
test
protected function determineFile(OutputInterface $output, $givenFileName) { if (is_file($givenFileName)) { return new \SplFileInfo($givenFileName); } return $this->chooseFileInDirectory( $output, $this->chooseBundle($output)->getPath().'/Resources/config/' ); }
php
{ "resource": "" }
q262482
ConvertCommand.chooseBundle
test
protected function chooseBundle(OutputInterface $output) { $bundles = $this->getContainer()->get('kernel')->getBundles(); $selectedBundle = $this->getHelperSet()->get('dialog')->ask( $output, '<info>Which bundle\'s config would you like to convert? </info>', null, array_keys($bundles) ); if (!isset($bundles[$selectedBundle])) { throw UnknownBundleException::create($selectedBundle); } return $bundles[$selectedBundle]; }
php
{ "resource": "" }
q262483
ConvertCommand.writeToFile
test
protected function writeToFile(OutputInterface $output, SplFileInfo $originalFile, $newConfig, $newFormat) { $proposedLocation = $originalFile->getPath().'/services.'.$newFormat; $location = $this->getHelperSet()->get('dialog')->ask( $output, "<info>Where should the new config be written?</info> [{$proposedLocation}] ", $proposedLocation ); if (file_exists($location) && !$this->getHelperSet()->get('dialog')->askConfirmation($output, 'File exists. Overwrite? ') ) { $output->writeln('Aborting...'); return; } file_put_contents($location, $newConfig); $output->writeln( "Written! Don't forget to update the DependencyInjection/*Extension class in your bundle to use the new ". "loader class and delete the old config file." ); }
php
{ "resource": "" }
q262484
StandardDumperFactory.createDumper
test
public function createDumper($type, ContainerBuilder $container) { $className = $this->getClassNameByShortType($type); return new $className($container); }
php
{ "resource": "" }
q262485
ConfigFormatConverter.convertString
test
public function convertString($content, $oldFormat, $newFormat) { $tempFile = $this->tempFileFactory->createFile($content, $oldFormat); try { $output = $this->convertFile($tempFile, $newFormat); } catch (\Exception $e) { // Cleanup the temp file, even with a failure unlink($tempFile->getRealPath()); throw $e; } unlink($tempFile->getRealPath()); return $output; }
php
{ "resource": "" }
q262486
Cookie.read
test
public function read($session_id) { // Check for the existance of a cookie with the name of the session id // Make sure that the cookie is atleast the size of our hash, otherwise it's invalid // Return an empty string if it's invalid. if (! $this->storage->has($session_id)) return ''; try { $data = $this->storage->get($session_id); } catch (HashMismatchException $ex) { $data = ''; } // Return the data, now that it's been verified. return $data; }
php
{ "resource": "" }
q262487
RouteListCommand.getRoutes
test
protected function getRoutes(): array { $routes = []; foreach ($this->routes as $route) { if (($routeInfo = $this->getRouteInformation($route)) !== null) { $routes[] = $routeInfo; } } if ($sort = $this->option('sort')) { $routes = self::sort($routes, static function ($route) use ($sort) { return $route[$sort]; }); } if ($this->option('reverse')) { $routes = \array_reverse($routes); } return \array_filter($routes); }
php
{ "resource": "" }
q262488
RouteListCommand.sort
test
protected static function sort(array $array, callable $callback): array { $results = []; foreach ($array as $key => $value) { $results[$key] = $callback($value, $key); } \asort($results, \SORT_REGULAR); foreach (\array_keys($results) as $key) { $results[$key] = $array[$key]; } return $results; }
php
{ "resource": "" }
q262489
LimitStream.setOffset
test
public function setOffset(int $offset): void { $current = $this->stream->tell(); if ($current !== $offset) { // If the stream cannot seek to the offset position, then read to it if ($this->stream->isSeekable()) { $this->stream->seek($offset); } elseif ($current > $offset) { throw new RuntimeException(\sprintf('Could not seek to stream offset %s', $offset)); } else { $this->stream->read($offset - $current); } } $this->offset = $offset; }
php
{ "resource": "" }
q262490
View.gatherData
test
protected function gatherData(): array { $data = \array_merge($this->factory->getShared(), $this->data); foreach ($data as $key => $value) { if ($value instanceof Renderable) { $data[$key] = $value->render(); } elseif ($value instanceof Closure) { $data[$key] = $value(); } } return $data; }
php
{ "resource": "" }
q262491
OptionDumpCommand.putContentToFile
test
private function putContentToFile(string $file, string $content, string $key): void { if ($this->hasOption('overwrite') || ! \file_exists($file)) { \file_put_contents($file, $content); } else { if ($this->hasOption('merge')) { $confirmed = true; } else { $confirmed = $this->confirm(\sprintf('Do you really wish to overwrite %s', $key)); } if ($confirmed) { \file_put_contents($file, $content); } } }
php
{ "resource": "" }
q262492
OptionDumpCommand.getConfigReader
test
private function getConfigReader(): OptionsReader { $command = $this; return new class($command) extends OptionsReader { /** * A OptionDumpCommand instance. * * @var \Viserio\Component\OptionsResolver\Command\OptionDumpCommand */ private $command; /** * @param \Viserio\Component\OptionsResolver\Command\OptionDumpCommand $command */ public function __construct(OptionDumpCommand $command) { $this->command = $command; } /** * Read the mandatory options and ask for the value. * * @param string $className * @param array $dimensions * @param array $mandatoryOptions * * @return array */ protected function readMandatoryOption(string $className, array $dimensions, array $mandatoryOptions): array { $options = []; foreach ($mandatoryOptions as $key => $mandatoryOption) { if (! \is_scalar($mandatoryOption)) { $options[$key] = $this->readMandatoryOption($className, $dimensions, $mandatoryOptions[$key]); continue; } $options[$mandatoryOption] = $this->command->ask( \sprintf( '%s: Please enter the following mandatory value for [%s]', $className, \implode('.', $dimensions) . '.' . $mandatoryOption ) ); } return $options; } }; }
php
{ "resource": "" }
q262493
MiddlewareBasedDispatcher.runRoute
test
protected function runRoute(RouteContract $route, ServerRequestInterface $request): ResponseInterface { $pipeline = new Pipeline(); if ($this->container !== null) { $pipeline->setContainer($this->container); } return $pipeline->send($request) ->through($this->gatherRouteMiddleware($route)) ->then(static function ($request) use ($route) { return $route->run($request); }); }
php
{ "resource": "" }
q262494
MiddlewareBasedDispatcher.gatherRouteMiddleware
test
protected function gatherRouteMiddleware(RouteContract $route): array { $middleware = []; self::map($route->gatherMiddleware(), function ($nameOrObject) use (&$middleware, $route): void { $bypass = $route->gatherDisabledMiddleware(); if (\is_object($nameOrObject) && ! isset($bypass[\get_class($nameOrObject)])) { $middleware[] = $nameOrObject; } else { $middleware[] = MiddlewareNameResolver::resolve( $nameOrObject, $this->middleware, $this->middlewareGroups, $bypass ); } }); return (new SortedMiddleware( $this->middlewarePriority, self::flatten($middleware) ))->getAll(); }
php
{ "resource": "" }
q262495
MiddlewareBasedDispatcher.flatten
test
protected static function flatten(array $array): array { $flattened = []; foreach ($array as $key => $value) { if (\is_array($value)) { $flattened = \array_merge($flattened, static::flatten($value)); } else { $flattened[] = $value; } } return $flattened; }
php
{ "resource": "" }
q262496
LoadConfiguration.loadConfigurationFiles
test
protected static function loadConfigurationFiles(KernelContract $kernel, RepositoryContract $config): void { foreach (static::getFiles($kernel->getConfigPath('packages'), self::CONFIG_EXTS) as $path) { $config->import($path); } foreach (static::getFiles($kernel->getConfigPath(), self::CONFIG_EXTS) as $path) { $config->import($path); } foreach (static::getFiles($kernel->getConfigPath($kernel->getEnvironment()), self::CONFIG_EXTS) as $path) { $config->import($path); } foreach (static::getFiles($kernel->getConfigPath('packages' . \DIRECTORY_SEPARATOR . $kernel->getEnvironment()), self::CONFIG_EXTS) as $path) { $config->import($path); } }
php
{ "resource": "" }
q262497
Pipeline.getSlice
test
protected function getSlice(): Closure { return function ($stack, $stage) { return function ($traveler) use ($stack, $stage) { // If the $stage is an instance of a Closure, we will just call it directly. if ($stage instanceof Closure) { return $stage($traveler, $stack); } // Otherwise we'll resolve the stages out of the container and call it with // the appropriate method and arguments, returning the results back out. if ($this->container && ! \is_object($stage) && \is_string($stage)) { return $this->sliceThroughContainer($traveler, $stack, $stage); } if (\is_array($stage)) { $parameters = [$traveler, $stack]; $class = \array_shift($stage); if (\is_object($class) && (\is_string($class) && \class_exists($class))) { throw new \InvalidArgumentException(\sprintf( 'The first entry in the array must be a class, [%s] given.', \is_object($class) ? \get_class($class) : \gettype($class) )); } /** @var \Closure $object */ $object = (new ReflectionClass($class))->newInstanceArgs($stage); return $object(...$parameters); } // If the pipe is already an object we'll just make a callable and pass it to // the pipe as-is. There is no need to do any extra parsing and formatting // since the object we're given was already a fully instantiated object. $parameters = [$traveler, $stack]; return $stage->{$this->method}(...$parameters); }; }; }
php
{ "resource": "" }
q262498
Pipeline.parseStageString
test
protected function parseStageString(string $stage): array { [$name, $parameters] = \array_pad(\explode(':', $stage, 2), 2, []); if (\is_string($parameters)) { $parameters = \explode(',', $parameters); } return [$name, $parameters]; }
php
{ "resource": "" }
q262499
Application.call
test
public function call(string $command, array $parameters = [], ?OutputInterface $outputBuffer = null): int { if (\is_subclass_of($command, SymfonyCommand::class)) { /** @var \Symfony\Component\Console\Command\Command $symfonyCommand */ $symfonyCommand = $command; if (($commandName = $symfonyCommand::getDefaultName()) !== null) { $command = $commandName; } } if (! $this->has($command)) { throw new CommandNotFoundException(\sprintf('The command [%s] does not exist.', $command)); } $this->lastOutput = $outputBuffer ?: new BufferedOutput(); $this->setCatchExceptions(false); \array_unshift($parameters, $command); $input = new ArrayInput($parameters); if ($input->hasParameterOption(['--no-interaction'], true)) { $input->setInteractive(false); } $result = $this->run($input, $this->lastOutput); $this->setCatchExceptions(true); return $result; }
php
{ "resource": "" }