_id
stringlengths
2
7
title
stringlengths
3
151
partition
stringclasses
3 values
text
stringlengths
83
13k
language
stringclasses
1 value
meta_information
dict
q262800
Translator.log
test
protected function log(string $id, string $domain): void { $catalogue = $this->catalogue; if ($catalogue->defines($id, $domain)) { return; } if ($catalogue->has($id, $domain)) { $this->logger->debug( 'Translation use fallback catalogue.', ['id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale()] ); } else { $this->logger->warning( 'Translation not found.', ['id' => $id, 'domain' => $domain, 'locale' => $catalogue->getLocale()] ); } }
php
{ "resource": "" }
q262801
Translator.collectMessage
test
protected function collectMessage( ?string $locale, string $domain, string $id, string $translation, array $parameters = [] ): void { $catalogue = $this->catalogue; if ($catalogue->defines($id, $domain)) { $state = self::MESSAGE_DEFINED; } elseif ($catalogue->has($id, $domain)) { $state = self::MESSAGE_EQUALS_FALLBACK; $fallbackCatalogue = $catalogue->getFallbackCatalogue(); while ($fallbackCatalogue) { if ($fallbackCatalogue->defines($id, $domain)) { $locale = $fallbackCatalogue->getLocale(); break; } $fallbackCatalogue = $fallbackCatalogue->getFallbackCatalogue(); } } else { $state = self::MESSAGE_MISSING; } $this->messages[] = [ 'locale' => $locale, 'domain' => $domain, 'id' => $id, 'translation' => $translation, 'parameters' => $parameters, 'state' => $state, ]; }
php
{ "resource": "" }
q262802
AbstractLintCommand.display
test
protected function display(array $files, string $format, bool $displayCorrectFiles): int { switch ($format) { case 'txt': return $this->displayTxt($files, $displayCorrectFiles); case 'json': return $this->displayJson($files); default: throw new InvalidArgumentException(\sprintf('The format [%s] is not supported.', $format)); } }
php
{ "resource": "" }
q262803
AbstractLintCommand.displayJson
test
protected function displayJson(array $filesInfo): int { $errors = 0; \array_walk($filesInfo, static function (&$v) use (&$errors): void { $v['file'] = (string) $v['file']; if (! $v['valid']) { $errors++; } }); $this->getOutput()->writeln(\json_encode($filesInfo, \JSON_PRETTY_PRINT | \JSON_UNESCAPED_SLASHES)); return \min($errors, 1); }
php
{ "resource": "" }
q262804
AbstractLintCommand.getFiles
test
protected function getFiles(string $fileOrDirectory): Generator { if (\is_file($fileOrDirectory)) { yield $fileOrDirectory; return; } foreach (self::getDirectoryIterator($fileOrDirectory) as $file) { if (! \in_array($file->getExtension(), ['xlf', 'xliff'], true)) { continue; } yield (string) $file; } }
php
{ "resource": "" }
q262805
AbstractLintCommand.getStdin
test
protected function getStdin(): ?string { if (\ftell(\STDIN) !== 0) { return null; } $inputs = ''; while (! \feof(\STDIN)) { $inputs .= \fread(\STDIN, 1024); } return $inputs; }
php
{ "resource": "" }
q262806
AbstractLintCommand.getDirectoryIterator
test
protected static function getDirectoryIterator(string $directory): RecursiveIteratorIterator { return new RecursiveIteratorIterator( new RecursiveDirectoryIterator($directory, FilesystemIterator::SKIP_DOTS | FilesystemIterator::FOLLOW_SYMLINKS), RecursiveIteratorIterator::LEAVES_ONLY ); }
php
{ "resource": "" }
q262807
ValidateNameTrait.validateEventName
test
protected function validateEventName(string $eventName): void { \preg_match_all('/([a-zA-Z0-9_\\.]+)/', $eventName, $matches); if (\count($matches[0]) >= 2) { throw new InvalidArgumentException( 'The event name must only contain the characters A-Z, a-z, 0-9, _, and \'.\'.' ); } }
php
{ "resource": "" }
q262808
BytesFormatTrait.convertToBytes
test
protected static function convertToBytes(string $number): int { /** * Prefixes to specify unit of measure for memory amount. * * Warning: it is important to maintain the exact order of letters in this literal, * as it is used to convert string with units to bytes */ $memoryUnits = 'BKMGTPE'; if (\preg_match('/^(.*\d)\h*(\D)$/', $number, $matches) !== 1) { throw new InvalidArgumentException("Number format '{$number}' is not recognized."); } $unitSymbol = \mb_strtoupper($matches[2]); if (\mb_strpos($memoryUnits, $unitSymbol) === false) { throw new InvalidArgumentException("The number '{$number}' has an unrecognized unit: '{$unitSymbol}'."); } $result = self::convertToNumber($matches[1]); $pow = $unitSymbol ? \mb_strpos($memoryUnits, $unitSymbol) : 0; if (\PHP_INT_SIZE <= 4 && $pow >= 4) { throw new OutOfBoundsException('A 32-bit system is unable to process such a number.'); } if ($unitSymbol) { $result *= 1024 ** $pow; } return (int) $result; }
php
{ "resource": "" }
q262809
BytesFormatTrait.convertToNumber
test
private static function convertToNumber(string $number): string { \preg_match_all('/(\D+)/', $number, $matches); if (\count(\array_unique($matches[0])) > 1) { throw new InvalidArgumentException( "The number '{$number}' seems to have decimal part. Only integer numbers are supported." ); } return \preg_replace('/\D+/', '', $number); }
php
{ "resource": "" }
q262810
ManagerTrait.getConfigFromName
test
protected function getConfigFromName(string $name): array { $adapter = $this->resolvedOptions[static::CONFIG_LIST_NAME] ?? []; if (isset($adapter[$name]) && \is_array($adapter[$name])) { $config = $adapter[$name]; $config['name'] = $name; return $config; } return ['name' => $name]; }
php
{ "resource": "" }
q262811
ManagerTrait.create
test
protected function create(array $config, string $method, string $errorMessage) { if (isset($this->extensions[$config['name']])) { return $this->callCustomCreator($config['name'], $config); } if (\method_exists($this, $method)) { return $this->{$method}($config); } throw new InvalidArgumentException(\sprintf($errorMessage, $config['name'])); }
php
{ "resource": "" }
q262812
ChainExtractor.addExtractor
test
public function addExtractor(string $format, ExtractorContract $extractor): void { $this->extractors[$format] = $extractor; }
php
{ "resource": "" }
q262813
AliasLoaderServiceProvider.createAliasLoader
test
public static function createAliasLoader(ContainerInterface $container): AliasLoaderContract { $options = self::resolveOptions($container->get('config')); $loader = new AliasLoader($options['aliases']); $cachePath = self::getCachePath($container, $options); if ($cachePath !== null) { $loader->setCachePath($cachePath); if ($options['real_time_proxy'] === true) { $loader->enableRealTimeStaticalProxy(); } } return $loader; }
php
{ "resource": "" }
q262814
AliasLoaderServiceProvider.getCachePath
test
private static function getCachePath(ContainerInterface $container, array $options): ?string { $cachePath = $options['cache_path']; if ($cachePath === null && $container->has(KernelContract::class)) { $cachePath = $container->get(KernelContract::class)->getStoragePath('staticalproxy'); } return $cachePath; }
php
{ "resource": "" }
q262815
QueueingDispatcher.pushCommandToQueue
test
protected function pushCommandToQueue(QueueContract $queue, $command) { if (isset($command->queue, $command->delay)) { return $queue->laterOn($command->queue, $command->delay, $command); } if (isset($command->queue)) { return $queue->pushOn($command->queue, $command); } if (isset($command->delay)) { return $queue->later($command->delay, $command); } return $queue->push($command); }
php
{ "resource": "" }
q262816
QueueingDispatcher.commandShouldBeQueued
test
protected function commandShouldBeQueued($command): bool { if ($command instanceof ShouldQueueContract) { return true; } $reflection = new ReflectionClass($this->getHandlerClass($command)); return $reflection->implementsInterface(ShouldQueueContract::class); }
php
{ "resource": "" }
q262817
SessionManager.createCookieDriver
test
protected function createCookieDriver(): StoreContract { if ($this->cookieJar === null) { throw new RuntimeException(\sprintf('No instance of [%s] found.', JarContract::class)); } return $this->buildSession( new CookieSessionHandler( $this->cookieJar, $this->resolvedOptions['lifetime'] ) ); }
php
{ "resource": "" }
q262818
SessionManager.createMigratingDriver
test
protected function createMigratingDriver(array $config): StoreContract { if (! isset($config['current'], $config['write_only'])) { throw new RuntimeException('The MigratingSessionHandler needs a current and write only handler.'); } $currentHandler = $this->getDriver($config['current']); $writeOnlyHandler = $this->getDriver($config['write_only']); return $this->buildSession( new MigratingSessionHandler($currentHandler->getHandler(), $writeOnlyHandler->getHandler()) ); }
php
{ "resource": "" }
q262819
SessionManager.createCacheBased
test
protected function createCacheBased($driver): StoreContract { if ($this->cacheManager === null) { throw new RuntimeException(\sprintf('No instance of [%s] found.', CacheManagerContract::class)); } return $this->buildSession( new Psr6SessionHandler( clone $this->cacheManager->getDriver($driver), ['ttl' => $this->resolvedOptions['lifetime'], 'prefix' => 'ns_ses_'] ) ); }
php
{ "resource": "" }
q262820
SessionManager.buildSession
test
protected function buildSession(SessionHandlerInterface $handler): StoreContract { if ($this->resolvedOptions['encrypt'] === true) { return $this->buildEncryptedSession($handler); } return new Store($this->resolvedOptions['cookie']['name'], $handler); }
php
{ "resource": "" }
q262821
SessionManager.buildEncryptedSession
test
protected function buildEncryptedSession(SessionHandlerInterface $handler): StoreContract { return new EncryptedStore( $this->resolvedOptions['cookie']['name'], $handler, $this->key ); }
php
{ "resource": "" }
q262822
Action.parse
test
public static function parse(string $uri, $action): array { // If no action is passed in right away, we assume the user will make use of // fluent routing. In that case, we set a default closure, to be executed // if the user never explicitly sets an action to handle the given uri. if ($action === null) { return static::missingAction($uri); } // If the action is already a Closure instance, we will just set that instance // as the "uses" property. if (\is_callable($action)) { return ['uses' => $action]; } // If no "uses" property has been set, we will dig through the array to find a // Closure instance within this list. We will set the first Closure we come across. if (! isset($action['uses'])) { $callback = static function ($key, $value) { return \is_callable($value) && \is_numeric($key); }; $action['uses'] = self::getFirst($action, $callback); } if (\is_string($action['uses']) && \strpos($action['uses'], '@') === false) { if (! \method_exists($action['uses'], '__invoke')) { throw new UnexpectedValueException(\sprintf( 'Invalid route action: [%s].', $action['uses'] )); } $action['uses'] = $action['uses'] . '@__invoke'; } return $action; }
php
{ "resource": "" }
q262823
Action.getFirst
test
protected static function getFirst(array $array, callable $callback) { foreach ($array as $key => $value) { if ($callback($key, $value)) { return $value; } } return null; }
php
{ "resource": "" }
q262824
XliffParser.parseNotes
test
private static function parseNotes(SimpleXMLElement $noteElement, ?string $encoding = null): array { $notes = []; /** @var \SimpleXMLElement $xmlNote */ foreach ($noteElement as $xmlNote) { $noteAttributes = $xmlNote->attributes(); $note = ['content' => self::utf8ToCharset((string) $xmlNote, $encoding)]; if (isset($noteAttributes['priority'])) { $note['priority'] = (int) $noteAttributes['priority']; } if (isset($noteAttributes['from'])) { $note['from'] = (string) $noteAttributes['from']; } $notes[] = $note; } return $notes; }
php
{ "resource": "" }
q262825
XliffParser.utf8ToCharset
test
private static function utf8ToCharset(string $content, string $encoding = null): string { if ($encoding !== 'UTF-8' && $encoding !== null) { return \mb_convert_encoding($content, $encoding, 'UTF-8'); } return $content; }
php
{ "resource": "" }
q262826
TaggableParser.tag
test
protected function tag(string $tag, array $data): array { $taggedData = []; foreach ($data as $key => $value) { $name = \sprintf( '%s' . self::TAG_DELIMITER . '%s', $tag, $key ); $taggedData[$name] = $value; } return $taggedData; }
php
{ "resource": "" }
q262827
LoggerServiceProvider.createLogManger
test
public static function createLogManger(ContainerInterface $container): LogManager { $manager = new LogManager($container->get('config')); if ($container->has(EventManagerContract::class)) { $manager->setEventManager($container->get(EventManagerContract::class)); } return $manager; }
php
{ "resource": "" }
q262828
ConfirmableTrait.confirmToProceed
test
public function confirmToProceed(string $warning = 'Application is in Production mode!', $callback = null): bool { $callback = $callback ?? $this->getDefaultConfirmCallback(); $shouldConfirm = $callback instanceof Closure ? $callback() : $callback; if ($shouldConfirm) { if ($this->option('force')) { return true; } $this->comment(\str_repeat('*', \mb_strlen($warning) + 12)); $this->comment('* ' . $warning . ' *'); $this->comment(\str_repeat('*', \mb_strlen($warning) + 12)); $this->line(''); $confirmed = $this->confirm('Do you really wish to run this command?'); if (! $confirmed) { $this->comment('Command Cancelled!'); return false; } } return true; }
php
{ "resource": "" }
q262829
ConfirmableTrait.getDefaultConfirmCallback
test
protected function getDefaultConfirmCallback(): Closure { return function () { if ($this->container !== null && $this->container->has('env')) { return $this->container->get('env') === 'prod'; } if (($env = \getenv('APP_ENV')) !== false) { return $env === 'prod'; } return true; }; }
php
{ "resource": "" }
q262830
Profiler.injectProfiler
test
protected function injectProfiler(ResponseInterface $response, string $token): ResponseInterface { $content = (string) $response->getBody(); $renderedContent = $this->createTemplate($token); $pos = \mb_strripos($content, '</body>'); if ($pos !== false) { $stream = $this->streamFactory->createStream( \mb_substr($content, 0, $pos) . $renderedContent . \mb_substr($content, $pos) ); // Update the new content and reset the content length $response = $response->withoutHeader('content-length'); return $response->withBody($stream); } $response->getBody()->write($renderedContent); return $response; }
php
{ "resource": "" }
q262831
Profiler.collectData
test
private function collectData( string $token, ServerRequestInterface $serverRequest, ResponseInterface $response ): void { // sort on priority \usort($this->collectors, static function ($a, $b) { return $a['priority'] <=> $b['priority']; }); foreach ($this->collectors as $name => $collector) { $collector['collector']->collect($serverRequest, $response); $this->collectors[$name]['collector'] = $collector['collector']; } $ip = (new ClientIp($serverRequest))->getIpAddress(); if ($this->cachePool !== null) { $this->createProfile( $token, $ip ?? 'Unknown', $serverRequest->getMethod(), (string) $serverRequest->getUri(), $response->getStatusCode(), \microtime(true), \date('Y-m-d H:i:s'), $this->collectors ); } }
php
{ "resource": "" }
q262832
Profiler.createTemplate
test
private function createTemplate(string $token): string { $assets = $this->getAssetsRenderer(); $template = new TemplateManager( $this->collectors, $this->template, $token, $assets->getIcons() ); return $assets->render() . $template->render(); }
php
{ "resource": "" }
q262833
Profiler.createProfile
test
private function createProfile( string $token, string $ip, string $method, string $url, int $statusCode, float $time, string $date, array $collectors ): void { $profile = new Profile($token); $profile->setIp($ip); $profile->setMethod($method); $profile->setUrl($url); $profile->setTime($time); $profile->setDate($date); $profile->setStatusCode($statusCode); $profile->setCollectors($collectors); $item = $this->cachePool->getItem($token); $item->set($profile); $item->expiresAfter(60); $this->cachePool->save($item); }
php
{ "resource": "" }
q262834
ParseLevelTrait.parseLevel
test
public static function parseLevel(string $level): int { if (isset(self::$levels[$level])) { return self::$levels[$level]; } throw new InvalidArgumentException('Invalid log level.'); }
php
{ "resource": "" }
q262835
StartSessionMiddleware.startSession
test
protected function startSession(ServerRequestInterface $request): StoreContract { $session = $this->manager->getDriver(); $cookies = RequestCookies::fromRequest($request); $session->setId($cookies->has($session->getName()) ? $cookies->get($session->getName())->getValue() : ''); foreach ($this->fingerprintGenerators as $fingerprintGenerator) { $session->addFingerprintGenerator(new $fingerprintGenerator($request)); } if ($session->handlerNeedsRequest()) { $session->setRequestOnHandler($request); } if (! $session->open()) { $session->start(); } return $session; }
php
{ "resource": "" }
q262836
StartSessionMiddleware.storeCurrentUrl
test
protected function storeCurrentUrl(ServerRequestInterface $request, StoreContract $session): StoreContract { if ($request->getMethod() === 'GET' && $request->getHeaderLine('x-requested-with') !== 'XMLHttpRequest' ) { $session->setPreviousUrl((string) $request->getUri()); } return $session; }
php
{ "resource": "" }
q262837
StartSessionMiddleware.collectGarbage
test
protected function collectGarbage(StoreContract $session): void { $lottery = $this->cookieConfig['lottery']; $hitsLottery = \random_int(1, $lottery[1]) <= $lottery[0]; // Here we will see if this request hits the garbage collection lottery by hitting // the odds needed to perform garbage collection on any given request. If we do // hit it, we'll call this handler to let it delete all the expired sessions. if ($hitsLottery) { $session->getHandler()->gc($this->lifetime); } }
php
{ "resource": "" }
q262838
StartSessionMiddleware.addCookieToResponse
test
protected function addCookieToResponse( ServerRequestInterface $request, ResponseInterface $response, StoreContract $session ): ResponseInterface { if ($session->getHandler() instanceof CookieSessionHandler) { $session->save(); } $uri = $request->getUri(); $setCookie = new SetCookie( $session->getName(), $session->getId(), $this->cookieConfig['expire_on_close'] === true ? 0 : Chronos::now()->addSeconds($this->lifetime), $this->cookieConfig['path'] ?? '/', $this->cookieConfig['domain'] ?? $uri->getHost(), $this->cookieConfig['secure'] ?? ($uri->getScheme() === 'https'), $this->cookieConfig['http_only'] ?? true, $this->cookieConfig['samesite'] ?? false ); return $response->withAddedHeader('set-cookie', (string) $setCookie); }
php
{ "resource": "" }
q262839
View.createResponseView
test
public static function createResponseView(string $template, array $args = []): ResponseInterface { $response = self::$container->get(ResponseFactoryInterface::class)->createResponse(); $response = $response->withAddedHeader('Content-Type', 'text/html'); $stream = self::$container->get(StreamFactoryInterface::class)->createStream(); $stream->write((string) self::$container->get(ViewFactory::class)->create($template, $args)); return $response->withBody($stream); }
php
{ "resource": "" }
q262840
Loader.findTemplate
test
public function findTemplate(string $name): string { if ($this->files->has($name)) { return $name; } $name = $this->normalizeName($name); if (isset($this->cache[$name])) { return $this->cache[$name]; } try { $found = $this->finder->find($name); $this->cache[$name] = $found['path']; } catch (InvalidArgumentException $exception) { throw new LoaderError($exception->getMessage()); } return $this->cache[$name]; }
php
{ "resource": "" }
q262841
Loader.normalizeName
test
protected function normalizeName(string $name): string { if ($this->files->getExtension($name) === $this->extension) { $name = \mb_substr($name, 0, -(\mb_strlen($this->extension) + 1)); } return $name; }
php
{ "resource": "" }
q262842
Mailer.parseView
test
protected function parseView($view): array { if (\is_string($view)) { return [$view, null, null]; } // If the given view is an array with numeric keys, we will just assume that // both a "pretty" and "plain" view were provided, so we will return this // array as is, since must should contain both views with numeric keys. if (\is_array($view) && isset($view[0])) { return [$view[0], $view[1], null]; } // If the view is an array, but doesn't contain numeric keys, we will assume // the the views are being explicitly specified and will extract them via // named keys instead, allowing the developers to use one or the other. if (\is_array($view)) { return [ $view['html'] ?? null, $view['text'] ?? null, $view['raw'] ?? null, ]; } throw new UnexpectedValueException('Invalid view.'); }
php
{ "resource": "" }
q262843
Mailer.addContent
test
protected function addContent( MessageContract $message, ?string $view, ?string $plain, ?string $raw, array $data ): void { if ($view !== null) { $message->setBody($this->createView($view, $data), 'text/html'); } if ($plain !== null) { $method = $view !== null ? 'addPart' : 'setBody'; $message->{$method}($this->createView($plain, $data), 'text/plain'); } if ($raw !== null) { $method = ($view !== null || $plain !== null) ? 'addPart' : 'setBody'; $message->{$method}($raw, 'text/plain'); } }
php
{ "resource": "" }
q262844
Mailer.sendSwiftMessage
test
protected function sendSwiftMessage(Swift_Mime_SimpleMessage $message): int { if (! $this->shouldSendMessage($message)) { return 0; } try { return $this->swift->send($message, $this->failedRecipients); } finally { $this->forceReconnecting(); } }
php
{ "resource": "" }
q262845
Mailer.shouldSendMessage
test
protected function shouldSendMessage(Swift_Mime_SimpleMessage $message): bool { if (! $this->eventManager) { return true; } return $this->eventManager->trigger(new MessageSendingEvent($this, $message)) !== false; }
php
{ "resource": "" }
q262846
Mailer.createMessage
test
protected function createMessage(): MessageContract { $message = new Message($this->swift->createMessage()); // If a global from address has been specified we will set it on every message // instances so the developer does not have to repeat themselves every time // they create a new message. We will just go ahead and push the address. if (isset($this->from['address'])) { $message->from($this->from['address'], $this->from['name']); } // When a global reply address was specified we will set this on every message // instance so the developer does not have to repeat themselves every time // they create a new message. We will just go ahead and push this address. if (! empty($this->replyTo['address'])) { $message->replyTo($this->replyTo['address'], $this->replyTo['name']); } return $message; }
php
{ "resource": "" }
q262847
Mailer.callMessageBuilder
test
protected function callMessageBuilder($callback, MessageContract $message) { if ($callback instanceof Closure) { return $callback($message); } if ($this->container !== null) { return $this->getInvoker()->call($callback)->mail($message); } throw new InvalidArgumentException('Callback is not valid.'); }
php
{ "resource": "" }
q262848
Mailer.createView
test
protected function createView(string $view, array $data): string { if ($this->viewFactory !== null) { return $this->viewFactory->create($view, $data)->render(); } return \vsprintf($view, $data); }
php
{ "resource": "" }
q262849
SimpleDispatcher.handleFound
test
protected function handleFound( RouteCollectionContract $routes, ServerRequestInterface $request, string $identifier, array $segments ): ResponseInterface { $route = $routes->match($identifier); foreach ($segments as $key => $value) { $route->addParameter($key, \rawurldecode($value)); } // Add route to the request's attributes in case a middleware or handler needs access to the route. $request = $request->withAttribute('_route', $route); $this->current = $route; if ($this->eventManager !== null) { $this->eventManager->trigger(new RouteMatchedEvent($this, $route, $request)); } return $this->runRoute($route, $request); }
php
{ "resource": "" }
q262850
SimpleDispatcher.prepareUriPath
test
protected function prepareUriPath(string $path): string { $path = '/' . \ltrim($path, '/'); if (\strlen($path) !== 1 && \substr($path, -1) === '/') { $path = \substr_replace($path, '', -1); } return $path; }
php
{ "resource": "" }
q262851
SimpleDispatcher.generateRouterFile
test
protected function generateRouterFile(RouteCollectionContract $routes): void { $routerCompiler = new RouteTreeCompiler(new RouteTreeBuilder(), new RouteTreeOptimizer()); $closure = $routerCompiler->compile($routes->getRoutes()); \file_put_contents($this->path, $closure, \LOCK_EX); }
php
{ "resource": "" }
q262852
SimpleDispatcher.generateDirectory
test
private static function generateDirectory(string $dir): void { if (\is_dir($dir) && \is_writable($dir)) { return; } if (! @\mkdir($dir, 0777, true) || ! \is_writable($dir)) { throw new RuntimeException(\sprintf( 'Route cache directory [%s] cannot be created or is write protected.', $dir )); } }
php
{ "resource": "" }
q262853
FileLoader.getPath
test
protected function getPath(string $file): string { foreach ($this->directories as $directory) { $dirFile = $directory . \DIRECTORY_SEPARATOR . $file; if (\file_exists($dirFile)) { return $directory . \DIRECTORY_SEPARATOR; } } return ''; }
php
{ "resource": "" }
q262854
FileLoader.checkOption
test
protected function checkOption(?array $options): void { if (isset($options['tag'])) { return; } if (isset($options['group'])) { return; } if ($options !== null) { throw new NotSupportedException('Only the options "tag" and "group" are supported.'); } }
php
{ "resource": "" }
q262855
FileLoader.getParser
test
protected function getParser(?array $options): Parser { if (($tag = $options['tag'] ?? null) !== null) { $class = self::TAG_PARSER; return (new $class())->setTag($tag); } if (($group = $options['group'] ?? null) !== null) { $class = self::GROUP_PARSER; return (new $class())->setGroup($group); } return new Parser(); }
php
{ "resource": "" }
q262856
FilesystemHelperTrait.getRequire
test
public function getRequire(string $path) { $path = $this->getTransformedPath($path); if ($this->isFile($path) && $this->has($path)) { return require $path; } throw new FileNotFoundException($path); }
php
{ "resource": "" }
q262857
FilesystemHelperTrait.requireOnce
test
public function requireOnce(string $path) { $path = $this->getTransformedPath($path); if ($this->isFile($path) && $this->has($path)) { require_once $path; } throw new FileNotFoundException($path); }
php
{ "resource": "" }
q262858
FilesystemHelperTrait.link
test
public function link(string $target, string $link): ?bool { $target = $this->getTransformedPath($target); $link = $this->getTransformedPath($link); if (! $this->isWindows()) { return \symlink($target, $link); } $mode = $this->isDirectory($target) ? 'J' : 'H'; $output = $return = false; \exec("mklink /{$mode} \"{$link}\" \"{$target}\"", $output, $return); return $return; }
php
{ "resource": "" }
q262859
TranslationManager.setDirectories
test
public function setDirectories(array $directories): self { foreach ($directories as $directory) { $this->addDirectory($directory); } return $this; }
php
{ "resource": "" }
q262860
TranslationManager.addDirectory
test
public function addDirectory(string $directory): self { if (! \in_array($directory, $this->directories, true)) { $this->directories[] = $directory; } return $this; }
php
{ "resource": "" }
q262861
TranslationManager.import
test
public function import(string $file): self { $loader = $this->getLoader(); $loader->setDirectories($this->directories); $langFile = $loader->load($file); if (! isset($langFile['lang'])) { throw new InvalidArgumentException(\sprintf('File [%s] cant be imported. Key for language is missing.', $file)); } $this->addMessageCatalogue(new MessageCatalogue($langFile['lang'], $langFile)); return $this; }
php
{ "resource": "" }
q262862
TranslationManager.addMessageCatalogue
test
public function addMessageCatalogue(MessageCatalogueContract $messageCatalogue): self { $locale = $messageCatalogue->getLocale(); if ($fallback = $this->getLanguageFallback($messageCatalogue->getLocale())) { $messageCatalogue->addFallbackCatalogue($fallback); } elseif ($this->defaultFallback !== null) { $messageCatalogue->addFallbackCatalogue($this->defaultFallback); } $translation = new Translator($messageCatalogue, $this->formatter); $translation->setLogger($this->logger); $this->translations[$locale] = $translation; return $this; }
php
{ "resource": "" }
q262863
TranslationManager.setLanguageFallback
test
public function setLanguageFallback(string $lang, MessageCatalogueContract $fallback): self { $this->langFallback[$lang] = $fallback; return $this; }
php
{ "resource": "" }
q262864
TranslationManager.getLanguageFallback
test
public function getLanguageFallback(string $lang): ?MessageCatalogueContract { if (isset($this->langFallback[$lang])) { return $this->langFallback[$lang]; } return null; }
php
{ "resource": "" }
q262865
Paginator.addPresenter
test
public function addPresenter(string $key, PresenterContract $presenter): self { $this->presenter[$key] = $presenter; return $this; }
php
{ "resource": "" }
q262866
Paginator.checkForMorePages
test
protected function checkForMorePages(): void { $this->hasMore = \count($this->items) > $this->itemCountPerPage; $this->items = $this->items->slice(0, $this->itemCountPerPage); }
php
{ "resource": "" }
q262867
WebServerConfig.getDisplayAddress
test
public function getDisplayAddress(): ?string { if ('0.0.0.0' !== $this->getHostname()) { return null; } if (false === $localHostname = \gethostname()) { return null; } return \gethostbyname($localHostname) . ':' . $this->getPort(); }
php
{ "resource": "" }
q262868
WebServerConfig.findFrontController
test
private static function findFrontController(string $documentRoot, string $env): string { $fileNames = ['index_' . $env . '.php', 'index.php']; foreach ($fileNames as $fileName) { if (\file_exists($documentRoot . \DIRECTORY_SEPARATOR . $fileName)) { return $fileName; } } throw new InvalidArgumentException( \sprintf( 'Unable to find the front controller under [%s] (none of these files exist: [%s]).', $documentRoot, \implode(', ', $fileNames) ) ); }
php
{ "resource": "" }
q262869
WebServerConfig.findHostnameAndPort
test
private static function findHostnameAndPort(array $config): array { if ($config['host'] === null) { $config['host'] = '127.0.0.1'; $config['port'] = self::findBestPort($config['host']); } elseif (isset($config['host'], $config['port']) && $config['port'] !== null && $config['host'] === '*') { $config['host'] = '0.0.0.0'; } elseif ($config['port'] === null) { $config['port'] = self::findBestPort($config['host']); } if (! \ctype_digit((string) $config['port'])) { throw new InvalidArgumentException(\sprintf('Port [%s] is not valid.', (string) $config['port'])); } $config['address'] = $config['host'] . ':' . $config['port']; return $config; }
php
{ "resource": "" }
q262870
WebServerConfig.findBestPort
test
private static function findBestPort(string $host): string { $port = 8000; while (false !== $fp = @\fsockopen($host, $port, $errno, $errstr, 1)) { \fclose($fp); if ($port++ >= 8100) { throw new RuntimeException('Unable to find a port available to run the web server.'); } } return (string) $port; }
php
{ "resource": "" }
q262871
TemplateManager.escape
test
public static function escape(string $raw): string { $flags = \ENT_QUOTES; if (\defined('ENT_SUBSTITUTE')) { $flags |= \ENT_SUBSTITUTE; } $raw = \str_replace(\chr(9), ' ', $raw); return \htmlspecialchars($raw, $flags); }
php
{ "resource": "" }
q262872
TemplateManager.getSortedData
test
public function getSortedData(): array { $data = [ 'menus' => [], 'panels' => [], 'icons' => $this->icons, ]; foreach ($this->collectors as $name => $collector) { $collector = $collector['collector']; if ($collector instanceof TooltipAwareContract) { $data['menus'][$collector->getName()] = [ 'menu' => $collector->getMenu(), 'tooltip' => $collector->getTooltip(), 'position' => $collector->getMenuPosition(), ]; } else { $data['menus'][$collector->getName()] = [ 'menu' => $collector->getMenu(), 'position' => $collector->getMenuPosition(), ]; } if ($collector instanceof PanelAwareContract) { $class = ''; $panel = $collector->getPanel(); // @codeCoverageIgnoreStart if (\mb_strpos($panel, '<div class="profiler-tabs') !== false) { $class = ' profiler-body-has-tabs'; } elseif (\mb_strpos($panel, '<select class="content-selector"') !== false) { $class = ' profiler-body-has-selector'; } elseif (\mb_strpos($panel, '<ul class="metrics"') !== false) { $class = ' profiler-body-has-metrics'; } elseif (\mb_strpos($panel, '<table>') !== false) { $class = ' profiler-body-has-table'; } // @codeCoverageIgnoreEnd $data['panels'][$collector->getName()] = [ 'content' => $panel, 'class' => $class, ]; } } return $data; }
php
{ "resource": "" }
q262873
MultipartStream.createAppendStream
test
private function createAppendStream(array $elements): StreamInterface { $stream = new AppendStream(); foreach ($elements as $element) { $this->addElement($stream, $element); } // Add the trailing boundary with CRLF $stream->addStream(Util::createStreamFor("--{$this->boundary}--\r\n")); return $stream; }
php
{ "resource": "" }
q262874
PhpExtractor.parseTokens
test
protected function parseTokens(array $tokens): array { $tokenIterator = new ArrayIterator($tokens); $messages = []; for ($key = 0; $key < $tokenIterator->count(); $key++) { foreach ($this->sequences as $sequence) { $message = ''; $domain = $this->defaultDomain; $tokenIterator->seek($key); foreach ($sequence as $sequenceKey => $item) { $this->seekToNextRelevantToken($tokenIterator); if ($this->normalizeToken($tokenIterator->current()) === $item) { $tokenIterator->next(); continue; } if (self::MESSAGE_TOKEN === $item) { $message = $this->getValue($tokenIterator); if (\count($sequence) === ($sequenceKey + 1)) { break; } } elseif (self::METHOD_ARGUMENTS_TOKEN === $item) { $this->skipMethodArgument($tokenIterator); } elseif (self::DOMAIN_TOKEN === $item) { $domain = $this->getValue($tokenIterator); break; } else { break; } } if ($message) { $messages[$domain][\trim($message)] = $this->prefix . \trim($message); break; } } } return $messages; }
php
{ "resource": "" }
q262875
PhpExtractor.seekToNextRelevantToken
test
private function seekToNextRelevantToken(Iterator $tokenIterator): void { for (; $tokenIterator->valid(); $tokenIterator->next()) { $token = $tokenIterator->current(); if ($token[0] !== \T_WHITESPACE) { break; } } }
php
{ "resource": "" }
q262876
PhpExtractor.getValue
test
private function getValue(Iterator $tokenIterator): string { $message = ''; $docToken = ''; for (; $tokenIterator->valid(); $tokenIterator->next()) { $t = $tokenIterator->current(); if (! isset($t[1])) { break; } switch ($t[0]) { case \T_START_HEREDOC: $docToken = $t[1]; break; case \T_ENCAPSED_AND_WHITESPACE: case \T_CONSTANT_ENCAPSED_STRING: $message .= $t[1]; break; case \T_END_HEREDOC: return ScalarString::parseDocString($docToken, $message); default: break 2; } } if ($message) { $message = ScalarString::parse($message); } return $message; }
php
{ "resource": "" }
q262877
ProfilerPDOBridgeServiceProvider.createTraceablePDODecorator
test
public static function createTraceablePDODecorator( ContainerInterface $container, ?PDO $pdo = null ): ?TraceablePDODecorater { if ($pdo === null) { return null; } return new TraceablePDODecorater($pdo); }
php
{ "resource": "" }
q262878
EncryptedCookiesMiddleware.decrypt
test
protected function decrypt(ServerRequestInterface $request): ServerRequestInterface { $cookies = RequestCookies::fromRequest($request); /** @var Cookie $cookie */ foreach ($cookies->getAll() as $cookie) { $name = $cookie->getName(); if ($this->isDisabled($name)) { continue; } try { $decryptedValue = Crypto::decrypt($cookie->getValue(), $this->key); $cookies = $cookies->forget($name); $cookie = $cookie->withValue($decryptedValue->getString()); $cookies = $cookies->add($cookie); } catch (InvalidMessage $exception) { $cookies = $cookies->add(new Cookie($name, null)); } } return $cookies->renderIntoCookieHeader($request); }
php
{ "resource": "" }
q262879
EncryptedCookiesMiddleware.encrypt
test
protected function encrypt(ResponseInterface $response): ResponseInterface { $cookies = ResponseCookies::fromResponse($response); /** @var SetCookie $cookie */ foreach ($cookies->getAll() as $cookie) { $name = $cookie->getName(); if ($this->isDisabled($name)) { continue; } $cookies = $cookies->forget($name); $encryptedValue = Crypto::encrypt( new HiddenString($cookie->getValue()), $this->key ); $cookies = $cookies->add( $this->duplicate( $cookie, $encryptedValue ) ); } return $cookies->renderIntoSetCookieHeader($response); }
php
{ "resource": "" }
q262880
EncryptedCookiesMiddleware.duplicate
test
protected function duplicate(CookieContract $cookie, string $value): CookieContract { return new SetCookie( $cookie->getName(), $value, $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly() ); }
php
{ "resource": "" }
q262881
Kernel.registerCommand
test
public function registerCommand(SymfonyCommand $command): void { $this->bootstrap(); $this->getConsole()->add($command); }
php
{ "resource": "" }
q262882
Kernel.getConsole
test
protected function getConsole(): Cerebro { if ($this->console === null) { $console = $this->getContainer()->get(Cerebro::class); $console->setVersion($this->resolvedOptions['version']); $console->setName($this->resolvedOptions['console_name']); return $this->console = $console; } return $this->console; }
php
{ "resource": "" }
q262883
AbstractKernel.initProjectDirs
test
protected function initProjectDirs(): array { if ($this->projectDirs === null) { $jsonFile = $this->rootDir . \DIRECTORY_SEPARATOR . 'composer.json'; $dirs = [ 'app-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'app', 'config-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'config', 'database-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'database', 'public-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'public', 'resources-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'resources', 'routes-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'routes', 'tests-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'tests', 'storage-dir' => $this->rootDir . \DIRECTORY_SEPARATOR . 'storage', ]; if (\file_exists($jsonFile)) { $jsonData = \json_decode(\file_get_contents($jsonFile), true); $extra = $jsonData['extra'] ?? []; foreach ($extra as $key => $value) { if (\array_key_exists($key, $dirs)) { $dirs[$key] = $this->rootDir . \DIRECTORY_SEPARATOR . \ltrim($value, '/\\'); } } } $this->projectDirs = $dirs; } return $this->projectDirs; }
php
{ "resource": "" }
q262884
ViewFinder.findNamedPathView
test
protected function findNamedPathView(string $name): array { [$namespace, $view] = $this->getNamespaceSegments($name); return $this->findInPaths($view, $this->hints[$namespace]); }
php
{ "resource": "" }
q262885
ViewFinder.getNamespaceSegments
test
protected function getNamespaceSegments(string $name): array { $segments = \explode(FinderContract::HINT_PATH_DELIMITER, $name); if (\count($segments) !== 2) { throw new InvalidArgumentException(\sprintf('View [%s] has an invalid name.', $name)); } if (! isset($this->hints[$segments[0]])) { throw new InvalidArgumentException(\sprintf('No hint path defined for [%s].', $segments[0])); } return $segments; }
php
{ "resource": "" }
q262886
ViewFinder.findInPaths
test
protected function findInPaths(string $name, array $paths): array { foreach ($paths as $path) { foreach ($this->getPossibleViewFiles($name) as $fileInfos) { $viewPath = $path . \DIRECTORY_SEPARATOR . $fileInfos['file']; if ($this->files->has($viewPath)) { return [ 'path' => $viewPath, 'name' => $fileInfos['file'], 'extension' => $fileInfos['extension'], ]; } } } throw new InvalidArgumentException(\sprintf('View [%s] not found.', $name)); }
php
{ "resource": "" }
q262887
ViewFinder.getPossibleViewFiles
test
protected function getPossibleViewFiles(string $name): array { return \array_map(static function ($extension) use ($name) { return [ 'extension' => $extension, 'file' => \str_replace('.', \DIRECTORY_SEPARATOR, $name) . '.' . $extension, ]; }, self::$extensions); }
php
{ "resource": "" }
q262888
WrappedListener.getInfo
test
public function getInfo(string $eventName): array { if ($this->stub === null) { $this->stub = self::$hasClassStub ? new ClassStub($this->pretty . '()', $this->listener) : $this->pretty . '()'; } return [ 'priority' => $this->eventManager !== null ? $this->eventManager->getListenerPriority($eventName, $this->listener) : null, 'pretty' => $this->pretty, 'stub' => $this->stub, ]; }
php
{ "resource": "" }
q262889
ResponseCookies.renderIntoSetCookieHeader
test
public function renderIntoSetCookieHeader(ResponseInterface $response): ResponseInterface { $response = $response->withoutHeader('set-cookie'); foreach ($this->cookies as $cookies) { $response = $response->withAddedHeader('set-cookie', (string) $cookies); } return $response; }
php
{ "resource": "" }
q262890
TwigBridgeDataCollectorsServiceProvider.extendTwigEnvironment
test
public static function extendTwigEnvironment( ContainerInterface $container, ?TwigEnvironment $twig = null ): ?TwigEnvironment { if ($twig !== null) { $options = self::resolveOptions($container->get('config')); if ($options['collector']['twig'] === true) { $twig->addExtension(new ProfilerExtension( $container->get(Profile::class) )); } } return $twig; }
php
{ "resource": "" }
q262891
MessagesDataCollector.getMessages
test
public function getMessages(): array { $messages = $this->messages; // sort messages by their timestamp \usort($messages, static function ($a, $b) { if ($a['time'] === $b['time']) { return 0; } return $a['time'] < $b['time'] ? -1 : 1; }); return $messages; }
php
{ "resource": "" }
q262892
MessagesDataCollector.addMessage
test
public function addMessage($message, string $label = 'info'): void { if (! \is_string($message)) { $message = $this->cloneVar($message); } $this->messages[] = [ 'message' => \is_string($message) ? $message : $this->cloneVar($message), 'label' => $label, 'time' => \microtime(true), ]; }
php
{ "resource": "" }
q262893
MiddlewareAwareTrait.aliasMiddleware
test
public function aliasMiddleware(string $name, $middleware) { if (isset($this->middleware[$name])) { throw new RuntimeException(\sprintf('Alias [%s] already exists.', $name)); } if (\is_string($middleware) || \is_object($middleware)) { $className = $this->getMiddlewareClassName($middleware); if (\class_exists($className)) { $this->validateMiddleware($className); } $this->middleware[$name] = $middleware; return $this; } throw new UnexpectedValueException(\sprintf('Expected string or object; received [%s].', \gettype($middleware))); }
php
{ "resource": "" }
q262894
ServerLogCommand.getLogs
test
private function getLogs($socket): ?\Generator { $sockets = [\fstat($socket)['size'] => $socket]; $write = []; while (true) { $read = $sockets; \stream_select($read, $write, $write, null); foreach ($read as $stream) { $size = \fstat($stream)['size']; if ($socket === $stream) { $stream = \stream_socket_accept($socket); $sockets[$size] = $stream; } elseif (\feof($stream)) { unset($sockets[$size]); \fclose($stream); } else { yield $size => \fgets($stream); } } } }
php
{ "resource": "" }
q262895
PhpEngine.handleViewException
test
protected function handleViewException(Throwable $exception, int $obLevel): void { while (\ob_get_level() > $obLevel) { \ob_end_clean(); } throw $exception; }
php
{ "resource": "" }
q262896
PhpEngine.getErrorException
test
private function getErrorException($exception): ErrorException { // @codeCoverageIgnoreStart if ($exception instanceof ParseError) { $message = 'Parse error: ' . $exception->getMessage(); $severity = \E_PARSE; } elseif ($exception instanceof TypeError) { $message = 'Type error: ' . $exception->getMessage(); $severity = \E_RECOVERABLE_ERROR; } else { $message = $exception->getMessage(); $severity = \E_ERROR; } // @codeCoverageIgnoreEnd return new ErrorException( $message, $exception->getCode(), $severity, $exception->getFile(), $exception->getLine() ); }
php
{ "resource": "" }
q262897
AliasLoader.getCachePath
test
public function getCachePath(): ?string { if ($this->realTimeStaticalProxyActivated === true && $this->cachePath === null) { throw new RuntimeException('Please provide a valid cache path.'); } return $this->cachePath; }
php
{ "resource": "" }
q262898
AliasLoader.ensureStaticalProxyExists
test
protected function ensureStaticalProxyExists(string $alias): string { $path = $this->getCachePath() . \DIRECTORY_SEPARATOR . 'staticalproxy-' . \sha1($alias) . '.php'; if (\file_exists($path)) { return $path; } \file_put_contents( $path, $this->formatStaticalProxyStub( $alias, \file_get_contents(__DIR__ . \DIRECTORY_SEPARATOR . 'Stubs' . \DIRECTORY_SEPARATOR . 'StaticalProxy.stub') ) ); return $path; }
php
{ "resource": "" }
q262899
AliasLoader.formatStaticalProxyStub
test
protected function formatStaticalProxyStub(string $alias, string $stub): string { $replacements = [ \str_replace('/', '\\', \dirname(\str_replace('\\', '/', $alias))), self::getClassBasename($alias), \mb_substr($alias, \mb_strlen($this->staticalProxyNamespace)), ]; return \str_replace( ['DummyNamespace', 'DummyClass', 'DummyTarget'], $replacements, $stub ); }
php
{ "resource": "" }