_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q262700 | PoParser.addReferences | test | private static function addReferences(string $data, array $entry): array
{
foreach (\preg_split('/#:\s+/', \trim($data)) as $value) {
if (\count(\preg_split('/\s+/', $value)) >= 2) {
if (\preg_match_all('/([.\/a-zA-Z]+)(:(\d*))/', ' ' . $value, $matches, \PREG_SET_ORDER, 1)) {
$key = '';
$values = [];
foreach ($matches as $match) {
$filename = $match[1];
$line = $match[3] ?? null;
$key .= \sprintf('{%s}:{%s} ', $filename, $line);
$values[] = [$filename, $line];
}
$entry['references'][\trim($key)] = $values;
}
} else {
if (\preg_match('/^(.+)(:(\d*))?$/U', $value, $matches)) {
$filename = $matches[1];
$line = $matches[3] ?? null;
$key = \sprintf('{%s}:{%s}', $filename, $line);
$entry['references'][$key] = [$filename, $line];
}
}
}
return $entry;
} | php | {
"resource": ""
} |
q262701 | PoParser.processObsoleteEntry | test | private static function processObsoleteEntry(
?string $lastPreviousKey,
?string $tmpKey,
string $str,
array $entry
): array {
$entry['obsolete'] = true;
switch ($tmpKey) {
case 'msgid':
$entry['msgid'][] = self::convertString($str);
$lastPreviousKey = $tmpKey;
break;
case 'msgstr':
$entry['msgstr'][] = self::convertString($str);
$lastPreviousKey = $tmpKey;
break;
default:
break;
}
return [$entry, $lastPreviousKey];
} | php | {
"resource": ""
} |
q262702 | PoParser.processPreviousEntry | test | private static function processPreviousEntry(
?string $lastPreviousKey,
?string $tmpKey,
string $str,
array $entry,
string $key
): array {
switch ($tmpKey) {
case 'msgid':
case 'msgid_plural':
case 'msgstr':
$entry[$key][$tmpKey][] = self::convertString($str);
$lastPreviousKey = $tmpKey;
break;
default:
$entry[$key][$tmpKey] = self::convertString($str);
break;
}
return [$entry, $lastPreviousKey];
} | php | {
"resource": ""
} |
q262703 | PoParser.extractMultiLines | test | private static function extractMultiLines(
?string $state,
array $entry,
string $line,
string $key,
int $i
): array {
$addEntry = static function (array $entry, ?string $state, string $line): array {
if (! isset($entry[$state])) {
throw new ParseException([
'message' => \sprintf('Parse error! Missing state: [%s].', $state),
]);
}
// Convert it to array
if (\is_string($entry[$state])) {
$entry[$state] = [$entry[$state]];
}
$entry[$state][] = self::convertString($line);
return $entry;
};
switch ($state) {
case 'msgctxt':
case 'msgid':
case 'msgid_plural':
$entry = $addEntry($entry, $state, $line);
break;
case 'msgstr':
$entry['msgstr'][] = self::convertString($line);
break;
default:
if ($state !== null && (\mb_strpos($state, 'msgstr[') !== false)) {
$entry = $addEntry($entry, $state, $line);
} elseif ($key[0] === '#' && $key[1] !== ' ') {
throw new ParseException([
'message' => \sprintf(
'Parse error! Comments must have a space after them on line: [%s].',
$i
),
]);
} else {
throw new ParseException([
'message' => \sprintf(
'Parse error! Unknown key [%s] on line: [%s].',
$key,
$i
),
'line' => $i,
]);
}
}
return $entry;
} | php | {
"resource": ""
} |
q262704 | PoParser.extractHeaders | test | private static function extractHeaders(array $headers, array $entries): array
{
$currentHeader = null;
foreach ($headers as $header) {
$header = \trim($header);
$header = self::convertString($header);
if ($header === '') {
continue;
}
if (self::isHeaderDefinition($header)) {
$header = \explode(':', $header, 2);
$currentHeader = \trim($header[0]);
$entries['headers'][$currentHeader] = \trim($header[1]);
} else {
$entries['headers'][$currentHeader] = [$entries['headers'][$currentHeader] ?? '', \trim($header)];
}
}
return $entries;
} | php | {
"resource": ""
} |
q262705 | AbstractFileExtractor.isFile | test | protected function isFile(string $file): bool
{
if (! \is_file($file)) {
throw new InvalidArgumentException(\sprintf('The [%s] file does not exist.', $file));
}
return true;
} | php | {
"resource": ""
} |
q262706 | UploadedFile.setError | test | private function setError(int $error): void
{
if (! \in_array($error, self::ERRORS, true)) {
throw new InvalidArgumentException('Invalid error status for UploadedFile.');
}
$this->error = $error;
} | php | {
"resource": ""
} |
q262707 | UploadedFile.setStreamOrFile | test | private function setStreamOrFile($streamOrFile): void
{
if (\is_string($streamOrFile)) {
$this->file = $streamOrFile;
return;
}
if (\is_resource($streamOrFile)) {
$this->stream = new Stream($streamOrFile);
return;
}
if ($streamOrFile instanceof StreamInterface) {
$this->stream = $streamOrFile;
return;
}
throw new InvalidArgumentException('Invalid stream or file provided for UploadedFile.');
} | php | {
"resource": ""
} |
q262708 | UploadedFile.validateActive | test | private function validateActive(): void
{
if ($this->isOk() === false) {
throw new RuntimeException(\sprintf(
'Cannot retrieve stream due to upload error: %s',
self::$errorMessages[$this->error]
));
}
if ($this->isMoved()) {
throw new RuntimeException('Cannot retrieve stream after it has already been moved.');
}
} | php | {
"resource": ""
} |
q262709 | MockContainer.mock | test | public function mock(...$args): MockInterface
{
$id = \array_shift($args);
if (! $this->has($id)) {
throw new InvalidArgumentException(\sprintf('Cannot mock a non-existent service: [%s]', $id));
}
$mock = 'mock::' . $id;
if (! isset($this->mockedServices[$mock])) {
$this->mockedServices[$mock] = \call_user_func_array([Mockery::class, 'mock'], $args);
}
return $this->mockedServices[$mock];
} | php | {
"resource": ""
} |
q262710 | ExpressionParser.parse | test | public static function parse(string $expression): array
{
\preg_match_all('/^\S*|(\[\s*(.*?)\]|[[:alnum:]_-]+\=\*|[[:alnum:]_-]+\?|[[:alnum:]_-]+|-+[[:alnum:]_\-=*]+)/', $expression, $matches);
if (\trim($expression) === '') {
throw new InvalidCommandExpression('The expression was empty.');
}
$tokens = \array_values(\array_filter(\array_map('trim', $matches[0])));
$name = \array_shift($tokens);
$arguments = [];
$options = [];
foreach ($tokens as $token) {
if (self::startsWith($token, '--')) {
throw new InvalidCommandExpression('An option must be enclosed by brackets: [--option].');
}
if (self::isOption($token)) {
$options[] = self::parseOption($token);
} else {
$arguments[] = self::parseArgument($token);
}
}
return [
'name' => $name,
'arguments' => $arguments,
'options' => $options,
];
} | php | {
"resource": ""
} |
q262711 | ExpressionParser.parseArgument | test | private static function parseArgument(string $token): InputArgument
{
[$token, $description] = static::extractDescription($token);
switch (true) {
case self::endsWith($token, '=*]'):
return new InputArgument(\trim($token, '[=*]'), InputArgument::IS_ARRAY, $description);
case self::endsWith($token, '=*'):
return new InputArgument(\trim($token, '=*'), InputArgument::IS_ARRAY | InputArgument::REQUIRED, $description);
case \preg_match('/(.*)\?$/', $token, $matches):
return new InputArgument($matches[1], InputArgument::OPTIONAL, $description);
case \preg_match('/\[(.+)\?\]/', $token, $matches):
return new InputArgument($matches[1], InputArgument::OPTIONAL, $description);
case \preg_match('/\[(.+)\=\*(.+)\]/', $token, $matches):
return new InputArgument($matches[1], InputArgument::IS_ARRAY, $description, \preg_split('/,\s?/', $matches[2]));
case \preg_match('/\[(.+)\=(.+)\]/', $token, $matches):
return new InputArgument($matches[1], InputArgument::OPTIONAL, $description, $matches[2]);
case self::startsWith($token, '[') && self::endsWith($token, ']'):
return new InputArgument(\trim($token, '[]'), InputArgument::OPTIONAL, $description);
default:
return new InputArgument($token, InputArgument::REQUIRED, $description);
}
} | php | {
"resource": ""
} |
q262712 | ExpressionParser.parseOption | test | private static function parseOption(string $token): InputOption
{
[$token, $description] = static::extractDescription(\trim($token, '[]'));
// Shortcut [-y|--yell]
if (\mb_strpos($token, '|') !== false) {
[$shortcut, $token] = \explode('|', $token, 2);
$shortcut = \ltrim($shortcut, '-');
} else {
$shortcut = null;
}
$name = \ltrim($token, '-');
$default = null;
switch (true) {
case self::endsWith($token, '=*'):
return new InputOption(\rtrim($name, '=*'), $shortcut, InputOption::VALUE_REQUIRED | InputOption::VALUE_IS_ARRAY, $description);
case self::endsWith($token, '='):
return new InputOption(\rtrim($name, '='), $shortcut, InputOption::VALUE_REQUIRED, $description);
case \preg_match('/(.+)\=\*(.+)/', $token, $matches):
return new InputOption($matches[1], $shortcut, InputOption::VALUE_OPTIONAL | InputOption::VALUE_IS_ARRAY, $description, \preg_split('/,\s?/', $matches[2]));
case \preg_match('/(.+)\=(.+)/', $token, $matches):
return new InputOption($matches[1], $shortcut, InputOption::VALUE_OPTIONAL, $description, $matches[2]);
default:
return new InputOption($token, $shortcut, InputOption::VALUE_NONE, $description);
}
} | php | {
"resource": ""
} |
q262713 | ExpressionParser.extractDescription | test | private static function extractDescription(string $token): array
{
\preg_match('/(.*)\s:(\s+.*(?<!]))(.*)/', \trim($token), $parts);
return \count($parts) === 4 ? [$parts[1] . $parts[3], \trim($parts[2])] : [$token, ''];
} | php | {
"resource": ""
} |
q262714 | CookieValidatorTrait.validateName | test | protected function validateName(string $name): void
{
if ($name === '') {
throw new InvalidArgumentException('The name cannot be empty.');
}
// Name attribute is a token as per spec in RFC 2616
if (\preg_match('/[\x00-\x20\x22\x28-\x29\x2c\x2f\x3a-\x40\x5b-\x5d\x7b\x7d\x7f]/', $name)) {
throw new InvalidArgumentException(\sprintf(
'Cookie name [%s] must not contain invalid characters: ASCII Control characters (0-31;127), space, tab and the following characters: ()<>@,;:\"/[]?={}',
$name
));
}
} | php | {
"resource": ""
} |
q262715 | CookieValidatorTrait.validateValue | test | protected function validateValue(?string $value = null): void
{
if ($value !== null && \preg_match('/[^\x21\x23-\x2B\x2D-\x3A\x3C-\x5B\x5D-\x7E]/', $value)) {
throw new InvalidArgumentException(
\sprintf(
'The cookie value [%s] contains invalid characters.',
$value
)
);
}
} | php | {
"resource": ""
} |
q262716 | Scope.set | test | public function set(string $key, $value)
{
if ($this->left) {
throw new \LogicException('Left scope is not mutable.');
}
$this->data[$key] = $value;
return $this;
} | php | {
"resource": ""
} |
q262717 | MandrillTransport.getToAddresses | test | protected function getToAddresses(Swift_Mime_SimpleMessage $message): array
{
$to = [];
$getTo = $message->getTo();
if (\is_array($getTo)) {
$to = \array_merge($to, \array_keys($getTo));
}
$cc = $message->getCc();
if (\is_array($cc)) {
$to = \array_merge($to, \array_keys($cc));
}
$bcc = $message->getBcc();
if (\is_array($bcc)) {
$to = \array_merge($to, \array_keys($bcc));
}
return $to;
} | php | {
"resource": ""
} |
q262718 | CacheManager.createMongodbDriver | test | protected function createMongodbDriver(array $config): MongoDBCachePool
{
if (isset($config['username'], $config['password'])) {
$dns = \sprintf(
'mongodb://%s:%s@%s:%s',
$config['username'],
$config['password'],
$config['server'],
$config['port']
);
} else {
$dns = \sprintf('mongodb://%s:%s', $config['server'], $config['port']);
}
$collection = MongoDBCachePool::createCollection(
new MongoDBManager($dns),
$config['database'],
$config['prefix']
);
return new MongoDBCachePool($collection);
} | php | {
"resource": ""
} |
q262719 | CacheManager.createRedisDriver | test | protected function createRedisDriver(array $config): RedisCachePool
{
$client = new Redis();
$client->connect($config['host'], $config['port']);
return new RedisCachePool($client);
} | php | {
"resource": ""
} |
q262720 | CacheManager.createPredisDriver | test | protected function createPredisDriver(array $config): PredisCachePool
{
$client = new PredisClient(\sprintf('tcp:/%s:%s', $config['server'], $config['port']));
return new PredisCachePool($client);
} | php | {
"resource": ""
} |
q262721 | CacheManager.createFilesystemDriver | test | protected function createFilesystemDriver(array $config): FilesystemCachePool
{
$adapter = $this->container->get($config['connection']);
return new FilesystemCachePool(new Flysystem($adapter));
} | php | {
"resource": ""
} |
q262722 | CacheManager.createMemcachedDriver | test | protected function createMemcachedDriver(array $config): MemcachedCachePool
{
$client = new Memcached();
$client->addServer($config['host'], $config['port']);
return new MemcachedCachePool($client);
} | php | {
"resource": ""
} |
q262723 | CacheManager.createMemcacheDriver | test | protected function createMemcacheDriver(array $config): MemcacheCachePool
{
$client = new Memcache();
$client->addServer($config['host'], $config['port']);
return new MemcacheCachePool($client);
} | php | {
"resource": ""
} |
q262724 | Profile.getCollector | test | public function getCollector(string $name): DataCollectorContract
{
if (! isset($this->collectors[$name])) {
throw new CollectorNotFoundException(\sprintf('Collector [%s] not found.', $name));
}
return $this->collectors[$name];
} | php | {
"resource": ""
} |
q262725 | RouteTreeCompiler.compile | test | public function compile(array $routes): string
{
$routeTree = $this->treeOptimizer->optimize(
$this->treeBuilder->build($routes)
);
$code = new PHPCodeCollection();
$code->indent = 1;
$this->compileRouteTree($code, $routeTree);
$rootRouteCode = new PHPCodeCollection();
$rootRouteCode->indent = 2;
$this->compileNotFound($rootRouteCode);
return $this->createRouterClassTemplate(\substr($rootRouteCode->code, 0, -\strlen(\PHP_EOL)), $code->code);
} | php | {
"resource": ""
} |
q262726 | RouteTreeCompiler.createRouterClassTemplate | test | private function createRouterClassTemplate(string $rootRoute, string $body): string
{
$template = <<<'PHP'
<?php
return function ($method, $uri) {
if ($uri === '') {
{root_route}
} elseif ($uri[0] !== '/') {
throw new \RuntimeException("Cannot match route: non-empty uri must be prefixed with '/', '{$uri}' given");
}
$segments = \explode('/', \substr($uri, 1));
{body}
};
PHP;
return \strtr($template, ['{root_route}' => $rootRoute, '{body}' => $body]);
} | php | {
"resource": ""
} |
q262727 | RouteTreeCompiler.compileRouteTree | test | private function compileRouteTree(PHPCodeCollection $code, array $routeTree): void
{
$code->appendLine('switch (count($segments)) {');
$code->indent++;
foreach ($routeTree[1] as $segmentDepth => $nodes) {
$code->appendLine('case ' . $segmentDepth . ':');
$code->indent++;
$segmentVariables = [];
for ($i = 0; $i < $segmentDepth; $i++) {
$segmentVariables[$i] = '$s' . $i;
}
$code->appendLine('[' . \implode(', ', $segmentVariables) . '] = $segments;');
$this->compileSegmentNodes($code, $nodes, $segmentVariables);
$this->compileDisallowedHttpMethodOrNotFound($code);
$code->appendLine('break;');
$code->indent--;
$code->appendLine();
}
$code->appendLine('default:');
$code->indent++;
$this->compileNotFound($code);
$code->indent--;
$code->indent--;
$code->append('}');
} | php | {
"resource": ""
} |
q262728 | RouteTreeCompiler.compiledRouteHttpMethodMatch | test | private function compiledRouteHttpMethodMatch(
PHPCodeCollection $code,
MatchedRouteDataMap $routeDataMap,
array $parameters
): void {
$code->appendLine('switch ($method) {');
$code->indent++;
foreach ($routeDataMap->getHttpMethodRouteDataMap() as $item) {
[$httpMethods, $routeData] = $item;
foreach ($httpMethods as $httpMethod) {
$code->appendLine('case \'' . $httpMethod . '\':');
}
$code->indent++;
$this->compileFoundRoute($code, $routeData, $parameters);
$code->indent--;
}
$code->appendLine('default:');
$code->indent++;
foreach ($routeDataMap->allowedHttpMethods() as $method) {
$code->appendLine('$allowedHttpMethods[] = \'' . $method . '\';');
}
$code->appendLine('break;');
$code->indent--;
$code->indent--;
$code->appendLine('}');
} | php | {
"resource": ""
} |
q262729 | RouteTreeCompiler.compileDisallowedHttpMethodOrNotFound | test | private function compileDisallowedHttpMethodOrNotFound(PHPCodeCollection $code): void
{
$code->appendLine(
'return ' .
'isset($allowedHttpMethods) '
. '? '
. '['
. DispatcherContract::HTTP_METHOD_NOT_ALLOWED
. ', $allowedHttpMethods] '
. ': '
. '['
. DispatcherContract::NOT_FOUND
. '];'
);
} | php | {
"resource": ""
} |
q262730 | RouteTreeCompiler.compileFoundRoute | test | private function compileFoundRoute(PHPCodeCollection $code, array $foundRoute, array $parameterExpressions): void
{
$parameters = '[';
foreach ($foundRoute[0] as $index => $parameterName) {
$parameters .= '\'' . $parameterName . '\' => ' . $parameterExpressions[$index] . ', ';
}
if (\strlen($parameters) > 2) {
$parameters = \substr($parameters, 0, -2);
}
$parameters .= ']';
$code->appendLine(
'return ['
. DispatcherContract::FOUND
. ', '
. '\'' . $foundRoute[1] . '\''
. ', '
. $parameters
. '];'
);
} | php | {
"resource": ""
} |
q262731 | LoggerDataCollector.getDebugLogger | test | private function getDebugLogger(): ?DebugProcessor
{
foreach ($this->logger->getProcessors() as $processor) {
if ($processor instanceof DebugProcessor) {
return $processor;
}
}
return null;
} | php | {
"resource": ""
} |
q262732 | LoggerDataCollector.getComputedErrorsCount | test | private function getComputedErrorsCount(): array
{
$errorCount = 0;
if ($logger = $this->getDebugLogger()) {
$errorCount = $logger->countErrors();
}
$count = [
'error_count' => $errorCount,
'deprecation_count' => 0,
'warning_count' => 0,
'scream_count' => 0,
'priorities' => [],
];
foreach ($this->getLogs() as $log) {
if (isset($count['priorities'][$log['priority']])) {
$count['priorities'][$log['priority']]['count']++;
} else {
$count['priorities'][$log['priority']] = [
'count' => 1,
'name' => $log['priorityName'],
];
}
if ('WARNING' === $log['priorityName']) {
$count['warning_count']++;
}
if ($this->isSilencedOrDeprecationErrorLog($log)) {
if ($log['context']['exception'] instanceof SilencedErrorContext) {
$count['scream_count']++;
} else {
$count['deprecation_count']++;
}
}
}
\ksort($count['priorities']);
return $count;
} | php | {
"resource": ""
} |
q262733 | LoggerDataCollector.groupLogLevels | test | private function groupLogLevels(): array
{
$deprecationLogs = [];
$debugLogs = [];
$infoAndErrorLogs = [];
$silencedLogs = [];
$formatLog = function ($log) {
return[
$log['priorityName'] . '<br>' . '<div class="text-muted">' . \date('H:i:s', $log['timestamp']) . '</div>',
$log['channel'],
$log['message'] . '<br>' . (\count($log['context']) !== 0 ? $this->cloneVar($log['context']) : ''),
];
};
foreach ((array) $this->data['logs'] as $log) {
if (isset($log['priority'])) {
if (\in_array($log['priority'], [Logger::ERROR, Logger::INFO], true)) {
$infoAndErrorLogs[] = $formatLog($log);
} elseif ($log['priority'] === Logger::DEBUG) {
$debugLogs[] = $formatLog($log);
}
} elseif ($this->isSilencedOrDeprecationErrorLog($log)) {
if (isset($log['context']) && $log['context']['exception'] instanceof SilencedErrorContext) {
$silencedLogs[] = $formatLog($log);
} else {
$deprecationLogs[] = $formatLog($log);
}
}
}
return [
'deprecation' => $deprecationLogs,
'debug' => $debugLogs,
'info_error' => $infoAndErrorLogs,
'silenced' => $silencedLogs,
];
} | php | {
"resource": ""
} |
q262734 | ListenerPattern.getListener | test | public function getListener()
{
if ($this->listener === null && $this->provider !== null) {
$this->listener = $this->provider;
$this->provider = null;
}
return $this->listener;
} | php | {
"resource": ""
} |
q262735 | ListenerPattern.bind | test | public function bind(EventManagerContract $dispatcher, string $eventName): void
{
if (isset($this->events[$eventName])) {
return;
}
$dispatcher->attach($eventName, $this->getListener(), $this->priority);
$this->events[$eventName] = true;
} | php | {
"resource": ""
} |
q262736 | ListenerPattern.unbind | test | public function unbind(EventManagerContract $dispatcher): void
{
foreach ($this->events as $eventName => $value) {
$dispatcher->detach($eventName, $this->getListener());
}
$this->events = [];
} | php | {
"resource": ""
} |
q262737 | ListenerPattern.createRegex | test | private function createRegex(string $eventPattern): string
{
return \sprintf('/^%s$/i', \preg_replace(
\array_keys(self::$wildcardsSeparators),
\array_values(self::$wildcardsSeparators),
\str_replace('\#', '#', \preg_quote($eventPattern, '/'))
));
} | php | {
"resource": ""
} |
q262738 | Repository.offsetGet | test | public function offsetGet($key)
{
$value = Arr::get($this->data, $key);
if (\is_array($value)) {
$value = $this->processParameters($value);
} else {
$value = $this->processParameter($value);
}
return $value;
} | php | {
"resource": ""
} |
q262739 | Repository.offsetSet | test | public function offsetSet($key, $value): self
{
$this->data = Arr::set($this->data, $key, $value);
return $this;
} | php | {
"resource": ""
} |
q262740 | Repository.processParameters | test | private function processParameters(array $data): array
{
\array_walk_recursive($data, function (&$parameter): void {
// @codeCoverageIgnoreStart
if (\is_array($parameter)) {
$parameter = $this->processParameters($parameter);
// @codeCoverageIgnoreEnd
} else {
$parameter = $this->processParameter($parameter);
}
});
return $data;
} | php | {
"resource": ""
} |
q262741 | Repository.processParameter | test | private function processParameter($parameter)
{
foreach ($this->parameterProcessors as $processor) {
if ($processor->supports((string) $parameter)) {
return $processor->process($parameter);
}
}
return $parameter;
} | php | {
"resource": ""
} |
q262742 | Handler.render | test | public function render(ConsoleOutputContract $output, Throwable $exception): void
{
$exceptionMessage = $exception->getMessage();
$exceptionName = \get_class($exception);
$output->writeln('');
$output->writeln(\sprintf(
'<bg=red;options=bold>%s</> : <comment>%s</>',
$exceptionName,
$exceptionMessage
));
$output->writeln('');
$this->renderEditor($output, $exception);
$this->renderTrace($output, $exception);
} | php | {
"resource": ""
} |
q262743 | Handler.renderEditor | test | private function renderEditor(ConsoleOutputContract $output, Throwable $exception): void
{
$output->writeln(\sprintf(
'at <fg=green>%s</>' . ':<fg=green>%s</>',
$exception->getFile(),
$exception->getLine()
));
$range = self::getFileLines(
$exception->getFile(),
$exception->getLine() - 5,
10
);
foreach ($range as $k => $code) {
$line = $k + 1;
$code = $exception->getLine() === $line ? \sprintf('<bg=red>%s</>', $code) : $code;
$output->writeln(\sprintf('%s: %s', $line, $code));
}
$output->writeln('');
} | php | {
"resource": ""
} |
q262744 | Handler.renderTrace | test | private function renderTrace(ConsoleOutputContract $output, Throwable $exception): void
{
$output->writeln('<comment>Exception trace:</comment>');
$output->writeln('');
$count = 0;
foreach ($this->getFrames($exception) as $i => $frame) {
if ($i > static::VERBOSITY_NORMAL_FRAMES &&
$output->getVerbosity() < ConsoleOutputContract::VERBOSITY_VERBOSE
) {
$output->writeln('');
$output->writeln(
'<info>Please use the argument <fg=red>-v</> to see all trace.</info>'
);
break;
}
$class = isset($frame['class']) ? $frame['class'] . '::' : '';
$function = $frame['function'] ?? '';
if ($class !== '' && $function !== '') {
$output->writeln(\sprintf(
'<comment><fg=cyan>%s</>%s%s(%s)</comment>',
\str_pad((string) ((int) $i + 1), 4, ' '),
$class,
$function,
isset($frame['args']) ? self::formatsArgs($frame['args']) : ''
));
}
if (isset($frame['file'], $frame['line'])) {
$output->writeln(\sprintf(
' <fg=green>%s</>:<fg=green>%s</>',
$frame['file'],
$frame['line']
));
}
if ($count !== 4) {
$output->writeln('');
}
$count++;
}
} | php | {
"resource": ""
} |
q262745 | Handler.getTrace | test | private function getTrace(Throwable $exception): array
{
$traces = $exception->getTrace();
// Get trace from xdebug if enabled, failure exceptions only trace to the shutdown handler by default
if (! $exception instanceof ErrorException) {
return $traces;
}
if (! self::isLevelFatal($exception->getSeverity())) {
return $traces;
}
if (! \extension_loaded('xdebug') || ! \xdebug_is_enabled()) {
return [];
}
// Use xdebug to get the full stack trace and remove the shutdown handler stack trace
$stack = \array_reverse(\xdebug_get_function_stack());
$trace = \debug_backtrace(\DEBUG_BACKTRACE_IGNORE_ARGS);
return \array_diff_key($stack, $trace);
} | php | {
"resource": ""
} |
q262746 | Handler.getFrames | test | private function getFrames(Throwable $exception): array
{
$frames = $this->getTrace($exception);
// Fill empty line/file info for call_user_func_array usages (PHP Bug #44428)
foreach ($frames as $k => $frame) {
if (empty($frame['file'])) {
// Default values when file and line are missing
$file = '[internal]';
$line = 0;
$nextFrame = \count($frames[$k + 1]) !== 0 ? $frames[$k + 1] : [];
if ($this->isValidNextFrame($nextFrame)) {
$file = $nextFrame['file'];
$line = $nextFrame['line'];
}
$frames[$k]['file'] = $file;
$frames[$k]['line'] = $line;
}
$frames['function'] = $frame['function'] ?? '';
}
// Find latest non-error handling frame index ($i) used to remove error handling frames
$i = 0;
foreach ($frames as $k => $frame) {
if (isset($frame['file'], $frame['line']) &&
$frame['file'] === $exception->getFile() &&
$frame['line'] === $exception->getLine()
) {
$i = $k;
}
}
// Remove error handling frames
if ($i > 0) {
\array_splice($frames, 0, $i);
}
\array_unshift($frames, $this->getFrameFromException($exception));
// show the last 5 frames
return \array_slice($frames, 0, 5);
} | php | {
"resource": ""
} |
q262747 | Handler.formatsArgs | test | private static function formatsArgs(array $arguments, bool $recursive = true): string
{
$result = [];
foreach ($arguments as $argument) {
switch (true) {
case \is_string($argument):
$result[] = '"' . $argument . '"';
break;
case \is_array($argument):
$associative = \array_keys($argument) !== \range(0, \count($argument) - 1);
if ($recursive && $associative && \count($argument) <= 5) {
$result[] = '[' . self::formatsArgs($argument, false) . ']';
}
break;
case \is_object($argument):
$class = \get_class($argument);
$result[] = "Object(${class})";
break;
}
}
return \implode(', ', $result);
} | php | {
"resource": ""
} |
q262748 | Handler.getFileLines | test | private static function getFileLines(string $filePath, int $start, int $length): ?array
{
if (($contents = self::getFileContents($filePath)) !== null) {
$lines = \explode("\n", $contents);
if ($start < 0) {
$start = 0;
}
return \array_slice($lines, $start, $length, true);
}
} | php | {
"resource": ""
} |
q262749 | Handler.getFileContents | test | private static function getFileContents(string $filePath): ?string
{
// Leave the stage early when 'Unknown' is passed
// this would otherwise raise an exception when
// open_basedir is enabled.
if ($filePath === 'Unknown') {
return null;
}
// Return null if the file doesn't actually exist.
if (! \is_file($filePath)) {
return null;
}
return \file_get_contents($filePath);
} | php | {
"resource": ""
} |
q262750 | NormalizeNameTrait.normalizeName | test | protected function normalizeName(string $name): string
{
$delimiter = FinderContract::HINT_PATH_DELIMITER;
if (\mb_strpos($name, $delimiter) === false) {
return \str_replace('/', '.', $name);
}
[$namespace, $name] = \explode($delimiter, $name);
return $namespace . $delimiter . \str_replace('/', '.', $name);
} | php | {
"resource": ""
} |
q262751 | ContainerResolver.resolve | test | public function resolve($subject, array $parameters = [])
{
if ($this->isClass($subject)) {
return $this->resolveClass($subject, $parameters);
}
if ($this->isMethod($subject)) {
return $this->resolveMethod($subject, $parameters);
}
if ($this->isFunction($subject)) {
return $this->resolveFunction($subject, $parameters);
}
$subject = \is_object($subject) ? \get_class($subject) : $subject;
throw new BindingResolutionException(\sprintf(
'[%s] is not resolvable. Build stack : [%s]',
$subject,
\implode(', ', $this->buildStack)
));
} | php | {
"resource": ""
} |
q262752 | ContainerResolver.resolveClass | test | public function resolveClass(string $class, array $parameters = []): object
{
$reflectionClass = new ReflectionClass($class);
if (! $reflectionClass->isInstantiable()) {
throw new BindingResolutionException(
\sprintf(
'Unable to reflect on the class [%s], does the class exist and is it properly autoloaded?',
$class
)
);
}
if (\in_array($class, $this->buildStack, true)) {
$this->buildStack[] = $class;
throw new CyclicDependencyException($class, $this->buildStack);
}
$reflectionMethod = $reflectionClass->getConstructor();
$this->buildStack[] = $reflectionClass->name;
if ($reflectionMethod) {
$reflectionParameters = $reflectionMethod->getParameters();
$parameters = $this->resolveParameters($reflectionParameters, $parameters);
}
\array_pop($this->buildStack);
return $reflectionClass->newInstanceArgs($parameters);
} | php | {
"resource": ""
} |
q262753 | ContainerResolver.resolveMethod | test | public function resolveMethod($method, array $parameters = [])
{
$reflectionMethod = $this->getMethodReflector($method);
$reflectionParameters = $reflectionMethod->getParameters();
$this->buildStack[] = $reflectionMethod->name;
$resolvedParameters = $this->resolveParameters($reflectionParameters, $parameters);
\array_pop($this->buildStack);
return $method(...$resolvedParameters);
} | php | {
"resource": ""
} |
q262754 | ContainerResolver.resolveParameter | test | protected function resolveParameter(ReflectionParameter $parameter, array $parameters = [])
{
$name = $parameter->name;
$index = $parameter->getPosition();
if (isset($parameters[$name])) {
return $parameters[$name];
}
if (isset($parameters[$index])) {
return $parameters[$index];
}
if ($class = $parameter->getClass()) {
return $this->resolve($class->name);
}
if ($parameter->isDefaultValueAvailable()) {
return $parameter->getDefaultValue();
}
throw new BindingResolutionException(\sprintf(
'Unresolvable dependency resolving [%s] in [%s]',
$parameter,
\end($this->buildStack)
));
} | php | {
"resource": ""
} |
q262755 | ContainerResolver.resolveParameters | test | protected function resolveParameters(array $reflectionParameters, array $parameters = []): array
{
$dependencies = [];
foreach ($reflectionParameters as $key => $parameter) {
$dependencies[] = $this->resolveParameter($parameter, $parameters);
}
return $this->mergeParameters($dependencies, $parameters);
} | php | {
"resource": ""
} |
q262756 | ContainerResolver.getMethodReflector | test | protected function getMethodReflector($method): ReflectionMethod
{
if (\is_string($method)) {
return new ReflectionMethod($method);
}
return new ReflectionMethod($method[0], $method[1]);
} | php | {
"resource": ""
} |
q262757 | ContainerResolver.isFunction | test | protected function isFunction($value): bool
{
return \is_callable($value) && ($value instanceof Closure || (\is_string($value) && \function_exists($value)));
} | php | {
"resource": ""
} |
q262758 | ContainerResolver.mergeParameters | test | private function mergeParameters(array $rootParameters, array $parameters = []): array
{
foreach ($parameters as $key => $value) {
if (\is_int($key) && ! isset($rootParameters[$key])) {
$rootParameters[$key] = $value;
}
}
return $rootParameters;
} | php | {
"resource": ""
} |
q262759 | EncryptionWrapper.write | test | public function write(string $path, $contents, array $config = []): bool
{
$contents = $this->encryptString($contents);
return $this->adapter->write($path, $contents, $config);
} | php | {
"resource": ""
} |
q262760 | EncryptionWrapper.put | test | public function put(string $path, $contents, array $config = []): bool
{
if (\is_resource($contents)) {
$contents = $this->encryptStream($contents);
} else {
$contents = $this->encryptString($contents);
}
return $this->adapter->put($path, $contents, $config);
} | php | {
"resource": ""
} |
q262761 | EncryptionWrapper.updateStream | test | public function updateStream(string $path, $resource, array $config = []): bool
{
$resource = $this->encryptStream($resource);
return $this->adapter->updateStream($path, $resource, $config);
} | php | {
"resource": ""
} |
q262762 | EncryptionWrapper.decryptStream | test | private function decryptStream($resource)
{
$out = \fopen('php://memory', 'r+b');
if ($resource !== false) {
try {
File::decrypt($resource, $out, $this->key);
} catch (FileAccessDenied $exception) {
throw new FileAccessDeniedException($exception->getMessage(), $exception->getCode(), $exception);
} catch (FileModified $exception) {
throw new FileModifiedException($exception->getMessage(), $exception->getCode(), $exception);
}
\rewind($out);
}
return $out;
} | php | {
"resource": ""
} |
q262763 | EncryptionWrapper.encryptStream | test | private function encryptStream($resource)
{
$out = \fopen('php://temp', 'w+b');
if ($resource !== false) {
try {
File::encrypt($resource, $out, $this->key);
} catch (FileAccessDenied $exception) {
throw new FileAccessDeniedException($exception->getMessage(), $exception->getCode(), $exception);
} catch (FileModified $exception) {
throw new FileModifiedException($exception->getMessage(), $exception->getCode(), $exception);
}
\rewind($out);
}
return $out;
} | php | {
"resource": ""
} |
q262764 | EncryptionWrapper.decryptString | test | private function decryptString(string $contents): string
{
$resource = $this->getStreamFromString($contents);
return (string) \stream_get_contents($this->decryptStream($resource));
} | php | {
"resource": ""
} |
q262765 | EncryptionWrapper.encryptString | test | private function encryptString(string $contents): string
{
$resource = $this->getStreamFromString($contents);
return (string) \stream_get_contents($this->encryptStream($resource));
} | php | {
"resource": ""
} |
q262766 | EncryptionWrapper.getStreamFromString | test | private function getStreamFromString(string $contents)
{
$path = \bin2hex(\random_bytes(16));
$this->adapter->write($path, $contents);
\sodium_memzero($contents);
$streamContent = $this->adapter->readStream($path);
$this->adapter->delete($path);
if ($streamContent !== false) {
return $streamContent;
}
throw new RuntimeException('Created file for string content cant be read.');
} | php | {
"resource": ""
} |
q262767 | MailServiceProvider.createTransportFactory | test | public static function createTransportFactory(ContainerInterface $container): TransportFactory
{
$transport = new TransportFactory();
if ($container->has(LoggerInterface::class)) {
$transport->setLogger($container->get(LoggerInterface::class));
}
return $transport;
} | php | {
"resource": ""
} |
q262768 | MailServiceProvider.createMailManager | test | public static function createMailManager(ContainerInterface $container): MailManager
{
$manager = new MailManager($container->get('config'), $container->get(TransportFactory::class));
$manager->setContainer($container);
if ($container->has(ViewFactoryContract::class)) {
$manager->setViewFactory($container->get(ViewFactoryContract::class));
}
if ($container->has(EventManagerContract::class)) {
$manager->setEventManager($container->get(EventManagerContract::class));
}
return $manager;
} | php | {
"resource": ""
} |
q262769 | XliffUtils.getVersionNumber | test | public static function getVersionNumber(DOMDocument $dom): string
{
/** @var \DOMNode $xliff */
foreach ($dom->getElementsByTagName('xliff') as $xliff) {
if (($version = $xliff->attributes->getNamedItem('version')) !== null) {
return $version->nodeValue;
}
if ($namespace = $xliff->attributes->getNamedItem('xmlns')) {
if (\substr_compare('urn:oasis:names:tc:xliff:document:', $namespace, 0, 34) !== 0) {
throw new InvalidArgumentException(\sprintf('Not a valid XLIFF namespace [%s].', $namespace));
}
return \mb_substr($namespace, 34);
}
}
return '1.2'; // Falls back to v1.2
} | php | {
"resource": ""
} |
q262770 | XliffUtils.getSchema | test | public static function getSchema(string $xliffVersion): string
{
if ($xliffVersion === '1.2') {
$xmlUri = 'http://www.w3.org/2001/xml.xsd';
$schemaSource = \dirname(__DIR__, 1) . \DIRECTORY_SEPARATOR . 'Resource' . \DIRECTORY_SEPARATOR . 'schemas' . \DIRECTORY_SEPARATOR . 'xliff-core' . \DIRECTORY_SEPARATOR . 'xliff-core-1.2-strict.xsd';
} elseif ($xliffVersion === '2.0') {
$xmlUri = 'informativeCopiesOf3rdPartySchemas/w3c/xml.xsd';
$schemaSource = \dirname(__DIR__, 1) . \DIRECTORY_SEPARATOR . 'Resource' . \DIRECTORY_SEPARATOR . 'schemas' . \DIRECTORY_SEPARATOR . 'xliff-core' . \DIRECTORY_SEPARATOR . 'xliff-core-2.0.xsd';
} else {
throw new InvalidArgumentException(\sprintf('No support implemented for loading XLIFF version [%s].', $xliffVersion));
}
return self::fixLocation(\file_get_contents($schemaSource), $xmlUri);
} | php | {
"resource": ""
} |
q262771 | XliffUtils.fixLocation | test | private static function fixLocation(string $schemaSource, string $xmlUri): string
{
$newPath = \dirname(__DIR__, 1) . \DIRECTORY_SEPARATOR . 'Resource' . \DIRECTORY_SEPARATOR . 'schemas' . \DIRECTORY_SEPARATOR . 'xliff-core' . \DIRECTORY_SEPARATOR . 'xml.xsd';
$parts = \explode(\DIRECTORY_SEPARATOR, $newPath);
if (\mb_stripos($newPath, 'phar://') === 0 && ($tmpFile = \tempnam(\sys_get_temp_dir(), 'narrowspark')) !== false) {
\copy($newPath, $tmpFile);
$parts = \explode(\DIRECTORY_SEPARATOR, $tmpFile);
}
$drive = '\\' === \DIRECTORY_SEPARATOR ? \array_shift($parts) . '/' : '';
$newPath = 'file:///' . $drive . \implode('/', \array_map('rawurlencode', $parts));
return \str_replace($xmlUri, $newPath, $schemaSource);
} | php | {
"resource": ""
} |
q262772 | Filesystem.parseVisibility | test | private function parseVisibility(string $path, string $visibility = null): ?int
{
$type = '';
if (\is_file($path)) {
$type = 'file';
} elseif (\is_dir($path)) {
$type = 'dir';
}
if ($visibility === null || $type === '') {
return null;
}
if ($visibility === FilesystemContract::VISIBILITY_PUBLIC) {
return $this->permissions[$type]['public'];
}
if ($visibility === FilesystemContract::VISIBILITY_PRIVATE) {
return $this->permissions[$type]['private'];
}
throw new InvalidArgumentException('Unknown visibility: ' . $visibility);
} | php | {
"resource": ""
} |
q262773 | Sanitizer.sanitize | test | public function sanitize(array $rules, array $data): array
{
[$data, $rules] = $this->runGlobalSanitizers($rules, $data);
$availableRules = \array_intersect_key($rules, \array_flip(array_keys($data)));
foreach ($availableRules as $field => $ruleset) {
$data[$field] = $this->sanitizeField($data, $field, $ruleset);
}
return $data;
} | php | {
"resource": ""
} |
q262774 | Sanitizer.runGlobalSanitizers | test | private function runGlobalSanitizers(array $rules, array $data): array
{
// Bail out if no global rules were found.
if (! isset($rules['*'])) {
return [$data, $rules];
}
// Get the global rules and remove them from the main ruleset.
$globalRules = $rules['*'];
unset($rules['*']);
// Execute the global sanitiers on each field.
foreach ($data as $field => $value) {
$data[$field] = $this->sanitizeField($data, $field, $globalRules);
}
return [$data, $rules];
} | php | {
"resource": ""
} |
q262775 | Sanitizer.sanitizeField | test | private function sanitizeField(array $data, string $field, $ruleset): string
{
if (! \is_string($ruleset) && ! \is_array($ruleset)) {
throw new InvalidArgumentException(\sprintf(
'The ruleset parameter must be of type string or array, [%s] given.',
\is_object($ruleset) ? \get_class($ruleset) : \gettype($ruleset)
));
}
// If we have a piped ruleset, explode it.
if (\is_string($ruleset)) {
$ruleset = \explode('|', $ruleset);
}
// Get value from data array.
$value = $data[$field];
foreach ($ruleset as $rule) {
$parametersSet = [];
if (\strpos($rule, ':') !== false) {
[$rule, $parameters] = \explode(':', $rule);
$parametersSet = \explode(',', $parameters);
}
\array_unshift($parametersSet, $value);
$sanitizers = $rule;
// Retrieve a sanitizer by key.
if (isset($this->sanitizers[$rule])) {
$sanitizers = $this->sanitizers[$rule];
}
// Execute the sanitizer to mutate the value.
$value = $this->executeSanitizer($sanitizers, $parametersSet);
}
return $value;
} | php | {
"resource": ""
} |
q262776 | Sanitizer.executeSanitizer | test | private function executeSanitizer($sanitizer, array $parameters): string
{
if (\is_callable($sanitizer)) {
return $sanitizer(...$parameters);
}
if ($this->container !== null) {
// Transform a container resolution to a callback.
$sanitizer = $this->resolveCallback($sanitizer);
return $sanitizer(...$parameters);
}
// If the sanitizer can't be called, return the passed value.
return $parameters[0];
} | php | {
"resource": ""
} |
q262777 | Sanitizer.resolveCallback | test | private function resolveCallback(string $callback): array
{
$segments = explode('@', $callback);
$method = \count($segments) === 2 ? $segments[1] : 'sanitize';
// Return the constructed callback.
return [$this->container->get($segments[0]), $method];
} | php | {
"resource": ""
} |
q262778 | CommandResolver.resolve | test | public function resolve(string $expression, $callable, array $aliases = []): StringCommand
{
$this->assertCallableIsValid($callable);
$commandFunction = function (InputInterface $input, OutputInterface $output) use ($callable) {
$parameters = \array_merge(
[
// Injection by parameter name
'input' => $input,
'output' => $output,
// Injections by type-hint
InputInterface::class => $input,
OutputInterface::class => $output,
Input::class => $input,
Output::class => $output,
SymfonyStyle::class => new SymfonyStyle($input, $output),
],
$input->getArguments(),
$input->getOptions()
);
if ($callable instanceof Closure) {
$callable = $callable->bindTo($this->console, $this->console);
}
try {
return $this->invoker->addResolver(new HyphenatedInputResolver())->call($callable, $parameters);
} catch (InvokerInvocationException $exception) {
throw new InvocationException(
\sprintf(
"Impossible to call the '%s' command: %s",
$input->getFirstArgument(),
$exception->getMessage()
),
0,
$exception
);
}
};
$command = self::createCommand($expression, $commandFunction);
$command->setAliases($aliases);
$command->defaults($this->defaultsViaReflection($command, $callable));
return $command;
} | php | {
"resource": ""
} |
q262779 | CommandResolver.createCommand | test | private static function createCommand(string $expression, callable $callable): StringCommand
{
$result = ExpressionParser::parse($expression);
$command = new StringCommand($result['name']);
$command->getDefinition()->addArguments($result['arguments']);
$command->getDefinition()->addOptions($result['options']);
$command->setCode($callable);
return $command;
} | php | {
"resource": ""
} |
q262780 | CommandResolver.defaultsViaReflection | test | private function defaultsViaReflection(StringCommand $command, $callable): array
{
if (! \is_callable($callable)) {
return [];
}
$function = CallableReflection::create($callable);
$definition = $command->getDefinition();
$defaults = [];
foreach ($function->getParameters() as $parameter) {
if (! $parameter->isDefaultValueAvailable()) {
continue;
}
$parameterName = $parameter->name;
$hyphenatedCaseName = Str::snake($parameterName, '-');
if ($definition->hasArgument($hyphenatedCaseName) || $definition->hasOption($hyphenatedCaseName)) {
$parameterName = $hyphenatedCaseName;
}
if (! $definition->hasArgument($parameterName) && ! $definition->hasOption($parameterName)) {
continue;
}
$defaults[$parameterName] = $parameter->getDefaultValue();
}
return $defaults;
} | php | {
"resource": ""
} |
q262781 | CommandResolver.assertCallableIsValid | test | private function assertCallableIsValid($callable): void
{
try {
$this->console->getContainer();
} catch (LogicException $e) {
if ($this->isStaticCallToNonStaticMethod($callable)) {
[$class, $method] = $callable;
$message = "['{$class}', '{$method}'] is not a callable because '{$method}' is a static method.";
$message .= " Either use [new {$class}(), '{$method}'] or configure a dependency injection container that supports autowiring.";
throw new InvalidArgumentException($message);
}
}
} | php | {
"resource": ""
} |
q262782 | CommandResolver.isStaticCallToNonStaticMethod | test | private function isStaticCallToNonStaticMethod($callable): bool
{
if (\is_array($callable) && \is_string($callable[0])) {
[$class, $method] = $callable;
$reflection = new ReflectionMethod($class, $method);
return ! $reflection->isStatic();
}
return false;
} | php | {
"resource": ""
} |
q262783 | CookieServiceProvider.createCookieJar | test | public static function createCookieJar(ContainerInterface $container): JarContract
{
$options = self::resolveOptions($container->get('config'));
return (new CookieJar())->setDefaultPathAndDomain(
$options['path'],
$options['domain'],
$options['secure']
);
} | php | {
"resource": ""
} |
q262784 | XmlDumper.convertElement | test | private function convertElement(DOMDocument $document, $element, $value): void
{
$sequential = self::isArrayAllKeySequential($value);
if (! \is_array($value)) {
$element->nodeValue = \htmlspecialchars((string) $value);
return;
}
foreach ($value as $key => $data) {
if (! $sequential) {
if (($key === '_attributes') || ($key === '@attributes')) {
foreach ($data as $attrKey => $attrVal) {
$element->setAttribute($attrKey, (string) $attrVal);
}
} elseif ((($key === '_value') || ($key === '@value')) && \is_string($data)) {
$element->nodeValue = \htmlspecialchars($data);
} elseif ((($key === '_cdata') || ($key === '@cdata')) && \is_string($data)) {
$element->appendChild($document->createCDATASection($data));
} else {
if (! \is_string($key)) {
throw new DOMException('Invalid Character Error.');
}
$this->addNode($document, $element, $key, $data);
}
} elseif (\is_array($data)) {
$this->addCollectionNode($document, $element, $data);
} else {
$this->addSequentialNode($element, $data);
}
}
} | php | {
"resource": ""
} |
q262785 | XmlDumper.addNode | test | private function addNode(DOMDocument $document, $element, string $key, $value): void
{
$key = \str_replace(' ', '_', $key);
$child = $document->createElement($key);
$element->appendChild($child);
$this->convertElement($document, $child, $value);
} | php | {
"resource": ""
} |
q262786 | XmlDumper.addCollectionNode | test | private function addCollectionNode(DOMDocument $document, $element, $value): void
{
if ($element->childNodes->length === 0 && $element->attributes->length === 0) {
$this->convertElement($document, $element, $value);
}
$child = $element->cloneNode();
$element->parentNode->appendChild($child);
$this->convertElement($document, $child, $value);
} | php | {
"resource": ""
} |
q262787 | XmlDumper.createRootElement | test | private function createRootElement(DOMDocument $document, $rootElement): DOMElement
{
if (\is_string($rootElement)) {
return $document->createElement($rootElement ?: 'root');
}
$rootElementName = $rootElement['rootElementName'] ?? 'root';
$element = $document->createElement($rootElementName);
foreach ($rootElement as $key => $value) {
if ($key !== '_attributes' && $key !== '@attributes') {
continue;
}
foreach ($rootElement[$key] as $attrKey => $attrVal) {
$element->setAttribute($attrKey, $attrVal);
}
}
return $element;
} | php | {
"resource": ""
} |
q262788 | ConsoleFormatter.castObjectClass | test | private function castObjectClass(): object
{
return new class($this->options) {
/**
* Console formatter configuration.
*
* @var array
*/
private $options;
public function __construct(array $options)
{
$this->options = $options;
}
/**
* @param mixed $value
* @param array $array
* @param \Symfony\Component\VarDumper\Cloner\Stub $stub
* @param mixed $isNested
*
* @return array
*/
public function castObject($value, array $array, Stub $stub, $isNested): array
{
if ($this->options['multiline']) {
return $array;
}
if ($isNested && ! $value instanceof DateTimeInterface) {
$stub->cut = -1;
$array = [];
}
return $array;
}
};
} | php | {
"resource": ""
} |
q262789 | TraceableEventManager.getCalledListeners | test | public function getCalledListeners(): array
{
$called = [];
foreach ($this->called as $eventName => $listeners) {
foreach ($listeners as $listener) {
$called[$eventName][] = $listener->getInfo($eventName);
}
}
return $called;
} | php | {
"resource": ""
} |
q262790 | TraceableEventManager.getNotCalledListeners | test | public function getNotCalledListeners(): array
{
try {
$allListeners = $this->eventManager->getListeners();
} catch (Throwable $e) {
$this->logger->info('An exception was thrown while getting the uncalled listeners.', ['exception' => $e]);
// unable to retrieve the uncalled listeners
return [];
}
$notCalled = [];
foreach ($allListeners as $eventName => $listeners) {
foreach ($listeners as $listener) {
$called = false;
if (isset($this->called[$eventName])) {
foreach ($this->called[$eventName] as $calledListener) {
/** @var WrappedListener $calledListener */
if ($calledListener->getWrappedListener() === $listener) {
$called = true;
break;
}
}
}
if (! $called) {
if (! $listener instanceof WrappedListener) {
$listener = new WrappedListener($listener, null, $this->stopwatch, $this);
}
$notCalled[$eventName][] = $listener->getInfo($eventName);
}
}
}
\uasort($notCalled, [$this, 'sortListenersByPriority']);
return $notCalled;
} | php | {
"resource": ""
} |
q262791 | AbstractCookie.validateSameSite | test | protected function validateSameSite($sameSite)
{
if (! \in_array($sameSite, [self::SAMESITE_STRICT, self::SAMESITE_LAX], true)) {
return false;
}
return $sameSite;
} | php | {
"resource": ""
} |
q262792 | AbstractCookie.normalizeExpires | test | protected function normalizeExpires($expiration = null): int
{
$expires = $this->getTimestamp($expiration);
$tsExpires = $expires;
if (\is_string($expires)) {
$tsExpires = \strtotime($expires);
$is32Bit = \PHP_INT_SIZE <= 4;
// if $tsExpires is invalid and PHP is compiled as 32bit. Check if it fail reason is the 2038 bug
if ($is32Bit && ! \is_int($tsExpires)) {
$dateTime = new Chronos($expires);
if ($dateTime->format('Y') > 2038) {
$tsExpires = \PHP_INT_MAX;
}
}
}
if (! \is_int($tsExpires) || $tsExpires < 0) {
throw new InvalidArgumentException('Invalid expires time specified.');
}
return $tsExpires;
} | php | {
"resource": ""
} |
q262793 | AbstractCookie.normalizeDomain | test | protected function normalizeDomain(string $domain = null): ?string
{
if ($domain !== null) {
$domain = \mb_strtolower(\ltrim($domain, '.'));
}
return $domain;
} | php | {
"resource": ""
} |
q262794 | AbstractCookie.normalizePath | test | protected function normalizePath(string $path): string
{
$path = \rtrim($path, '/');
if (empty($path) || \mb_strpos($path, '/')) {
$path = '/';
}
return $path;
} | php | {
"resource": ""
} |
q262795 | AbstractCookie.getTimestamp | test | protected function getTimestamp($expiration): ?string
{
if (\is_int($expiration) && \mb_strlen((string) $expiration) === 10 && $this->isValidTimeStamp($expiration)) {
return Chronos::createFromTimestamp($expiration)->toCookieString();
}
if (\is_int($expiration)) {
return Chronos::now()->addSeconds($expiration)->toCookieString();
}
if ($expiration instanceof DateTimeInterface) {
return $expiration->format(DateTime::COOKIE);
}
if (\is_string($expiration)) {
return $expiration;
}
return null;
} | php | {
"resource": ""
} |
q262796 | TraceableCacheItemDecorator.start | test | private function start(string $name): TraceableCollector
{
$this->calls[] = $event = new TraceableCollector();
$event->name = $name;
$event->start = \microtime(true);
return $event;
} | php | {
"resource": ""
} |
q262797 | Translator.applyHelpers | test | protected function applyHelpers(string $translation)
{
$helpers = $this->filterHelpersFromString($translation);
if (\count($this->helpers) === 0 || \count($helpers) === 0) {
return $translation;
}
foreach ($helpers as $helper) {
if (! isset($this->helpers[$helper['name']])) {
return $translation;
}
\array_unshift($helper['arguments'], $translation);
$translation = \call_user_func_array($this->helpers[$helper['name']], $helper['arguments']);
}
return $translation;
} | php | {
"resource": ""
} |
q262798 | Translator.filterHelpersFromString | test | protected function filterHelpersFromString(string $translation): array
{
$helpers = [];
if (\preg_match('/^(.*?)\\[(.*?)\\]$/', $translation, $match) === 1) {
$helpers = \explode('|', $match[2]);
$helpers = \array_map(static function ($helper) {
$name = $helper;
$arguments = [];
if (\preg_match('/^(.*?)\:(.*)$/', $helper, $match) === 1) {
$name = $match[1];
$arguments = \explode(':', $match[2]);
}
return [
'name' => $name,
'arguments' => $arguments,
];
}, $helpers);
}
return $helpers;
} | php | {
"resource": ""
} |
q262799 | Translator.applyFilters | test | protected function applyFilters(string $translation): string
{
if (\count($this->filters) === 0) {
return $translation;
}
foreach ($this->filters as $filter) {
$translation = $filter($translation);
}
return $translation;
} | php | {
"resource": ""
} |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.