_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q262600 | LintCommand.findArgumentFiles | test | protected function findArgumentFiles(array $paths, array $searchDirectories, array $files): array
{
$search = [];
foreach ($files as $fileName) {
if (\count($searchDirectories) !== 0) {
/** @var \SplFileObject $file */
foreach ($this->getFinder($searchDirectories, $fileName) as $file) {
$search[] = $file->getRealPath();
}
} else {
/** @var \SplFileObject $file */
foreach ($this->getFinder($paths, $fileName) as $file) {
$search[] = $file->getRealPath();
}
}
}
return $search;
} | php | {
"resource": ""
} |
q262601 | ClientIp.getIpAddress | test | public function getIpAddress(): ?string
{
$ipAddress = null;
$request = $this->serverRequest;
$serverParams = $request->getServerParams();
// direct IP address
if (isset($serverParams['REMOTE_ADDR']) && $this->isValidIpAddress($serverParams['REMOTE_ADDR'])) {
$ipAddress = $serverParams['REMOTE_ADDR'];
}
foreach (self::$headersToInspect as $header) {
if ($request->hasHeader($header)) {
$ip = $this->getFirstIpAddressFromHeader($request, $header);
if ($this->isValidIpAddress($ip)) {
$ipAddress = $ip;
break;
}
}
}
return $ipAddress;
} | php | {
"resource": ""
} |
q262602 | ClientIp.isValidIpAddress | test | private function isValidIpAddress(string $ip): bool
{
return (bool) \filter_var($ip, \FILTER_VALIDATE_IP, \FILTER_FLAG_IPV4 | \FILTER_FLAG_IPV6);
} | php | {
"resource": ""
} |
q262603 | ClientIp.getFirstIpAddressFromHeader | test | private function getFirstIpAddressFromHeader(ServerRequestInterface $serverRequest, string $header): string
{
$items = \explode(',', $serverRequest->getHeaderLine($header));
$headerValue = \trim(\reset($items));
if (\ucfirst($header) === 'Forwarded') {
foreach (\explode(';', $headerValue) as $headerPart) {
if (\mb_strtolower(\mb_substr($headerPart, 0, 4)) === 'for=') {
$for = \explode(']', $headerPart);
$headerValue = \trim(\mb_substr(\reset($for), 4), " \t\n\r\0\x0B" . '"[]');
break;
}
}
}
return $headerValue;
} | php | {
"resource": ""
} |
q262604 | MailgunTransport.setDomain | test | public function setDomain(string $domain): self
{
$this->url = $this->baseUrl . '/v3/' . $domain . '/messages.mime';
$this->domain = $domain;
return $this;
} | php | {
"resource": ""
} |
q262605 | MiddlewareValidatorTrait.validateInput | test | protected function validateInput($middleware): void
{
if (\is_array($middleware) || \is_string($middleware) || \is_object($middleware)) {
return;
}
throw new UnexpectedValueException(\sprintf(
'Expected string, object or array; received [%s].',
\gettype($middleware)
));
} | php | {
"resource": ""
} |
q262606 | MiddlewareValidatorTrait.validateMiddleware | test | protected function validateMiddleware($middleware): void
{
$middleware = $this->getMiddlewareClassName($middleware);
$interfaces = \class_implements($middleware);
if (! isset($interfaces[MiddlewareInterface::class])) {
throw new UnexpectedValueException(
\sprintf('%s is not implemented in [%s].', MiddlewareInterface::class, $middleware)
);
}
} | php | {
"resource": ""
} |
q262607 | TranslationServiceProvider.createTranslationManager | test | public static function createTranslationManager(ContainerInterface $container): TranslationManagerContract
{
$options = self::resolveOptions($container->get('config'));
$manager = new TranslationManager($container->get(MessageFormatterContract::class));
if ($container->has(LoaderContract::class)) {
$manager->setLoader($container->get(LoaderContract::class));
}
if (isset($options['locale'])) {
$manager->setLocale($options['locale']);
}
if (isset($options['directories'])) {
$manager->setDirectories($options['directories']);
}
if (isset($options['files'])) {
foreach ((array) $options['files'] as $import) {
$manager->import($import);
}
}
if ($container->has(PsrLoggerInterface::class)) {
$manager->setLogger($container->get(PsrLoggerInterface::class));
}
return $manager;
} | php | {
"resource": ""
} |
q262608 | CronServiceProvider.createSchedule | test | public static function createSchedule(ContainerInterface $container): Schedule
{
$options = self::resolveOptions($container->get('config'));
$scheduler = new Schedule($options['path'], $options['console']);
if ($container->has(CacheItemPoolInterface::class)) {
$scheduler->setCacheItemPool($container->get(CacheItemPoolInterface::class));
}
$scheduler->setContainer($container);
return $scheduler;
} | php | {
"resource": ""
} |
q262609 | TwigDataCollector.getComputedData | test | private function getComputedData(string $index)
{
if (\count($this->computed) === 0) {
$this->computed = $this->generateComputeData($this->getProfile());
}
return $this->computed[$index];
} | php | {
"resource": ""
} |
q262610 | MailManager.createSwiftMailer | test | protected function createSwiftMailer(Swift_Transport $transport): Swift_Mailer
{
if (isset($this->resolvedOptions['domain'])) {
Swift_DependencyContainer::getInstance()
->register('mime.idgenerator.idright')
->asValue($this->resolvedOptions['domain']);
}
return new Swift_Mailer($transport);
} | php | {
"resource": ""
} |
q262611 | MailManager.createMailer | test | private function createMailer(Swift_Transport $transport, array $config): MailerContract
{
$swiftMailer = $this->createSwiftMailer($transport);
if ($this->queueManager !== null) {
$mailer = new QueueMailer($swiftMailer, $this->queueManager, $config);
} else {
$mailer = new Mailer($swiftMailer, $config);
}
if ($this->container !== null) {
$mailer->setContainer($this->container);
}
if ($this->viewFactory !== null) {
$mailer->setViewFactory($this->viewFactory);
}
if ($this->eventManager !== null) {
$mailer->setEventManager($this->eventManager);
}
// Next we will set all of the global addresses on this mailer, which allows
// for easy unification of all "from" addresses as well as easy debugging
// of sent messages since they get be sent into a single email address.
foreach (['from', 'reply_to', 'to'] as $type) {
$this->setGlobalAddress($mailer, $type);
}
return $mailer;
} | php | {
"resource": ""
} |
q262612 | MailManager.setGlobalAddress | test | private function setGlobalAddress(MailerContract $mailer, string $type): void
{
if (! isset($this->resolvedOptions[$type])) {
return;
}
$address = $this->resolvedOptions[$type];
if (\is_array($address) && isset($address['address'])) {
$mailer->{'always' . Str::studly($type)}($address['address'], $address['name']);
}
} | php | {
"resource": ""
} |
q262613 | AbstractDataCollector.createTooltipGroup | test | protected function createTooltipGroup(array $data): string
{
$tooltip = '<div class="profiler-menu-tooltip-group">';
foreach ($data as $strong => $infos) {
$tooltip .= '<div class="profiler-menu-tooltip-group-piece">';
if (\is_array($infos)) {
$tooltip .= '<b>' . $strong . '</b>';
foreach ($infos as $info) {
$class = isset($info['class']) ? ' class="' . $info['class'] . '"' : '';
$tooltip .= '<span' . $class . '>' . $info['value'] . '</span>';
}
} elseif (\is_int($strong) && \is_string($infos)) {
$tooltip .= $infos;
} else {
$tooltip .= '<b>' . $strong . '</b><span>' . $infos . '</span>';
}
$tooltip .= '</div>';
}
$tooltip .= '</div>';
return $tooltip;
} | php | {
"resource": ""
} |
q262614 | AbstractDataCollector.createTabs | test | protected function createTabs(array $data): string
{
$html = '<div class="profiler-tabs row">';
foreach ($data as $key => $value) {
$id = \uniqid($key . '-', true);
$html .= '<div class="profiler-tabs-tab col">';
$html .= '<input type="radio" name="tabgroup" id="tab-' . $id . '">';
$html .= '<label for="tab-' . $id . '">' . $value['name'] . '</label>';
$html .= '<div class="profiler-tabs-tab-content">';
$html .= $value['content'];
$html .= '</div></div>';
}
$html .= '</div>';
return $html;
} | php | {
"resource": ""
} |
q262615 | AbstractDataCollector.createTable | test | protected function createTable(array $data, array $settings = []): string
{
$options = \array_merge([
'name' => null,
'headers' => ['Key', 'Value'],
'vardumper' => true,
'empty_text' => 'Empty',
], $settings);
$html = $options['name'] !== null ? '<h3>' . $options['name'] . '</h3>' : '';
if (\count($data) !== 0) {
$html .= '<table><thead><tr>';
foreach ((array) $options['headers'] as $header) {
$html .= '<th scope="col" class="' . \mb_strtolower($header) . '">' . $header . '</th>';
}
$html .= '</tr></thead><tbody>';
foreach ($data as $key => $values) {
if (\is_string($key)) {
$html .= '<tr>';
$html .= '<th>' . $key . '</th>';
$html .= \sprintf('<td>%s</td>', ($options['vardumper'] ? $this->cloneVar($values) : $values));
$html .= '</tr>';
} else {
$html .= '<tr>';
if (\is_array($values)) {
foreach ($values as $k => $value) {
$html .= \sprintf('<td>%s</td>', ($options['vardumper'] ? $this->cloneVar($value) : $value));
}
} else {
$html .= \sprintf('<td>%s</td>', ($options['vardumper'] ? $this->cloneVar($values) : $values));
}
$html .= '</tr>';
}
}
$html .= '</tbody></table>';
} else {
$html .= \sprintf('<div class="empty">%s</div>', $options['empty_text']);
}
return $html;
} | php | {
"resource": ""
} |
q262616 | AbstractDataCollector.createDropdownMenuContent | test | protected function createDropdownMenuContent(array $data): string
{
$selects = $content = [];
$selected = false;
foreach ($data as $key => $value) {
$id = 'content-' . $key . '-' . \uniqid('', true);
$selected = $selected === false ? $selected = 'selected' : '';
$selects[$key] = '<option value="' . $id . '"' . $selected . '>' . $key . '</option>';
$content[$key] = '<div id="' . $id . '" class="selected-content">' . $value . '</div>';
}
$html = '<select class="content-selector" name="' . $this->getName() . '">';
foreach ($selects as $key => $value) {
$html .= $value;
}
$html .= '</select>';
foreach ($content as $key => $value) {
$html .= $value;
}
return $html;
} | php | {
"resource": ""
} |
q262617 | AbstractDataCollector.createMetrics | test | protected function createMetrics(array $data, ?string $name = null): string
{
$html = $name !== null ? '<h3>' . $name . '</h3>' : '';
$html .= '<ul class="metrics">';
foreach ($data as $key => $value) {
$html .= '<li class="metric">';
$html .= '<span class="value">' . $value . '</span><span class="label">' . $key . '</span>';
$html .= '</li>';
}
$html .= '</ul>';
return $html;
} | php | {
"resource": ""
} |
q262618 | AbstractDataCollector.cloneVar | test | protected function cloneVar($var): ?string
{
$cloneVar = self::getCloner()->cloneVar($this->decorateVar($var), Caster::EXCLUDE_VERBOSE);
$dumper = self::getDumper();
$dumper->dump(
$cloneVar,
self::$htmlDumperOutput
);
$output = self::$htmlDumperOutput->getOutput();
self::$htmlDumperOutput->reset();
return $output;
} | php | {
"resource": ""
} |
q262619 | AbstractDataCollector.getCloner | test | private static function getCloner(): AbstractCloner
{
if (self::$cloner === null) {
self::$cloner = new VarCloner();
self::$cloner->setMaxItems(250);
self::$cloner->addCasters([
Stub::class => static function (Stub $v, array $a, Stub $s, $isNested) {
return $isNested ? $a : StubCaster::castStub($v, $a, $s, true);
},
]);
}
return self::$cloner;
} | php | {
"resource": ""
} |
q262620 | AbstractDataCollector.getDumper | test | private static function getDumper(): HtmlDumper
{
if (self::$htmlDumper === null) {
self::$htmlDumperOutput = new HtmlDumperOutput();
// re-use the same var-dumper instance, so it won't re-render the global styles/scripts on each dump.
self::$htmlDumper = new HtmlDumper(self::$htmlDumperOutput);
}
return self::$htmlDumper;
} | php | {
"resource": ""
} |
q262621 | PHPCodeCollection.append | test | public function append(string $code): void
{
$indent = \str_repeat(' ', 4 * $this->indent);
$this->code .= $indent . \str_replace(\PHP_EOL, \PHP_EOL . $indent, $code);
} | php | {
"resource": ""
} |
q262622 | PHPCodeCollection.appendLine | test | public function appendLine(string $code = ''): void
{
$this->append($code);
$this->code .= \PHP_EOL;
} | php | {
"resource": ""
} |
q262623 | TwigEngine.addExtensions | test | protected function addExtensions(Environment $twig, array $config): Environment
{
if (isset($config['extensions']) && \is_array($config['extensions'])) {
foreach ($config['extensions'] as $extension) {
if ($this->container !== null && \is_string($extension) && $this->container->has($extension)) {
$twig->addExtension($this->container->get($extension));
} elseif (\is_object($extension) && $extension instanceof ExtensionInterface) {
$twig->addExtension($extension);
} else {
throw new RuntimeException(\sprintf(
'Twig extension [%s] is not a object.',
$extension
));
}
}
}
return $twig;
} | php | {
"resource": ""
} |
q262624 | SortedMiddleware.doSortMiddleware | test | protected function doSortMiddleware(array $priorityMap, array $middleware): array
{
$lastIndex = $lastPriorityIndex = 0;
foreach ($middleware as $index => $mware) {
if (\in_array($mware, $priorityMap, true)) {
$priorityIndex = \array_search($mware, $priorityMap, true);
// This middleware is in the priority map. If we have encountered another middleware
// that was also in the priority map and was at a lower priority than the current
// middleware, we will move this middleware to be above the previous encounter.
if (isset($lastPriorityIndex) && $priorityIndex < $lastPriorityIndex) {
return $this->doSortMiddleware(
$priorityMap,
\array_values(
$this->moveMiddleware($middleware, $index, $lastIndex)
)
);
}
// This middleware is in the priority map; but, this is the first middleware we have
// encountered from the map thus far. We'll save its current index plus its index
// from the priority map so we can compare against them on the next iterations.
$lastIndex = $index;
$lastPriorityIndex = $priorityIndex;
}
}
return \array_values(\array_unique($middleware, \SORT_REGULAR));
} | php | {
"resource": ""
} |
q262625 | SortedMiddleware.moveMiddleware | test | protected function moveMiddleware(array $middleware, int $from, int $to): array
{
\array_splice($middleware, $to, 0, $middleware[$from]);
unset($middleware[$from + 1]);
return $middleware;
} | php | {
"resource": ""
} |
q262626 | LogManager.createAggregateDriver | test | protected function createAggregateDriver(array $config): LoggerInterface
{
$handlers = [];
foreach ((array) $config['channels'] as $channel) {
foreach ($this->getDriver($channel)->getHandlers() as $handler) {
$handlers[] = $handler;
}
}
return new Monolog($this->parseChannel($config), $handlers);
} | php | {
"resource": ""
} |
q262627 | LogManager.createEmergencyDriver | test | protected function createEmergencyDriver(): LoggerInterface
{
$handler = new StreamHandler(
$this->getFilePath(),
self::parseLevel('debug'),
$config['bubble'] ?? true,
$config['permission'] ?? null,
$config['locking'] ?? false
);
$handler->setFormatter($this->getConfiguredLineFormatter());
return new Monolog($this->resolvedOptions['name'], [$handler]);
} | php | {
"resource": ""
} |
q262628 | LogManager.createSingleDriver | test | protected function createSingleDriver(array $config): LoggerInterface
{
$handler = new StreamHandler(
$this->getFilePath(),
self::parseLevel($config['level'] ?? 'debug'),
$config['bubble'] ?? true,
$config['permission'] ?? null,
$config['locking'] ?? false
);
$handler->setFormatter($this->getConfiguredLineFormatter());
return new Monolog($this->parseChannel($config), [$handler]);
} | php | {
"resource": ""
} |
q262629 | LogManager.createDailyDriver | test | protected function createDailyDriver(array $config): LoggerInterface
{
$handler = new RotatingFileHandler(
$this->getFilePath(),
$config['days'] ?? 7,
self::parseLevel($config['level'] ?? 'debug'),
$config['bubble'] ?? true,
$config['permission'] ?? null,
$config['locking'] ?? false
);
$handler->setFormatter($this->getConfiguredLineFormatter());
return new Monolog($this->parseChannel($config), [$handler]);
} | php | {
"resource": ""
} |
q262630 | LogManager.createSyslogDriver | test | protected function createSyslogDriver(array $config): LoggerInterface
{
$handler = new SyslogHandler(
$config['name'],
$config['facility'] ?? \LOG_USER,
self::parseLevel($config['level'] ?? 'debug')
);
$handler->setFormatter($this->getConfiguredLineFormatter());
return new Monolog($this->parseChannel($config), [$handler]);
} | php | {
"resource": ""
} |
q262631 | LogManager.createErrorlogDriver | test | protected function createErrorlogDriver(array $config): LoggerInterface
{
$handler = new ErrorLogHandler(
$config['type'] ?? ErrorLogHandler::OPERATING_SYSTEM,
self::parseLevel($config['level'] ?? 'debug')
);
$handler->setFormatter($this->getConfiguredLineFormatter());
return new Monolog($this->parseChannel($config), [$handler]);
} | php | {
"resource": ""
} |
q262632 | LogManager.createSlackDriver | test | protected function createSlackDriver(array $config): LoggerInterface
{
$handler = new SlackWebhookHandler(
$config['url'],
$config['channel'] ?? null,
$config['username'] ?? $this->resolvedOptions['name'],
$config['attachment'] ?? true,
$config['emoji'] ?? ':boom:',
$config['short'] ?? false,
$config['context'] ?? true,
self::parseLevel($config['level'] ?? 'debug'),
$config['bubble'] ?? true,
$config['exclude_fields'] ?? []
);
$handler->setFormatter($this->getConfiguredLineFormatter());
return new Monolog($this->parseChannel($config), [$handler]);
} | php | {
"resource": ""
} |
q262633 | LogManager.createCustomDriver | test | protected function createCustomDriver(array $config): LoggerInterface
{
$via = $config['via'];
$config['name'] = $config['original_name'];
unset($config['original_name']);
if (\is_callable($via)) {
return $via($config);
}
if ($this->container !== null && $this->container->has($via)) {
return $this->container->get($via);
}
throw new RuntimeException(\sprintf(
'Given custom logger [%s] could not be resolved.',
$config['name']
));
} | php | {
"resource": ""
} |
q262634 | LogManager.createMonologDriver | test | protected function createMonologDriver(array $config): LoggerInterface
{
if ($this->container === null) {
throw new RuntimeException('No container instance was found.');
}
$config['name'] = $config['original_name'];
unset($config['original_name']);
if ($this->container->has($config['handler'])) {
$handler = $this->container->get($config['handler']);
if (! \is_a($handler, HandlerInterface::class, true)) {
throw new InvalidArgumentException(\sprintf('[%s] must be an instance of [%s]', $config['handler'], HandlerInterface::class));
}
} else {
throw new InvalidArgumentException(\sprintf('Handler [%s] is not managed by the container.', $config['handler']));
}
if (! isset($config['formatter'])) {
$handler->setFormatter($this->getConfiguredLineFormatter());
} elseif ($config['formatter'] !== 'default') {
$handler->setFormatter($this->container->get($config['formatter']));
}
$monolog = new Monolog($this->parseChannel($config));
$monolog->pushHandler($handler);
return $monolog;
} | php | {
"resource": ""
} |
q262635 | LogManager.pushProcessorsToMonolog | test | protected function pushProcessorsToMonolog(array $config, Monolog $driver): Monolog
{
$processors = $this->processors;
if (isset($config['processors'])) {
$processors = \array_merge($processors, $config['processors']);
}
foreach ($processors as $processor) {
$driver->pushProcessor($processor);
}
return $driver;
} | php | {
"resource": ""
} |
q262636 | ServerRequestBuilder.createFromArray | test | public function createFromArray(
array $server,
array $headers = [],
array $cookie = [],
array $get = [],
array $post = [],
array $files = [],
$body = null
): ServerRequestInterface {
if (isset($server['SERVER_ADDR'])) {
$server['SERVER_ADDR'] = \str_replace('Server IP: ', '', $server['SERVER_ADDR']);
}
$serverRequest = new ServerRequest(
Uri::createFromServer($server),
$this->getMethodFromServer($server),
$headers,
$body,
$this->marshalProtocolVersion($server),
$server
);
return $serverRequest
->withCookieParams($cookie)
->withQueryParams($get)
->withParsedBody($post)
->withUploadedFiles(Util::normalizeFiles($files));
} | php | {
"resource": ""
} |
q262637 | Pluralizer.singular | test | public static function singular(string $value): string
{
$singular = Inflector::singularize($value);
return static::matchCase($singular, $value);
} | php | {
"resource": ""
} |
q262638 | Pluralizer.matchCase | test | protected static function matchCase(string $value, string $comparison): string
{
$functions = ['mb_strtolower', 'mb_strtoupper', 'ucfirst', 'ucwords'];
foreach ($functions as $function) {
if ($function($comparison) === $comparison) {
return $function($value);
}
}
return $value;
} | php | {
"resource": ""
} |
q262639 | LocalConnector.connect | test | public function connect(): AdapterInterface
{
return new Local(
$this->resolvedOptions['path'],
$this->resolvedOptions['write_flags'],
$this->resolvedOptions['link_handling'],
$this->resolvedOptions['permissions']
);
} | php | {
"resource": ""
} |
q262640 | ConsoleServiceProvider.createCerebro | test | public static function createCerebro(ContainerInterface $container): Application
{
$console = new Application();
$console->setContainer($container);
if ($container->has(EventManagerContract::class)) {
$console->setEventManager($container->get(EventManagerContract::class));
}
return $console;
} | php | {
"resource": ""
} |
q262641 | Group.merge | test | public static function merge(array $new, array $old): array
{
if (isset($new['domain'])) {
unset($old['domain']);
}
$new = \array_merge(static::formatAs($new, $old), [
'namespace' => static::formatNamespace($new, $old),
'prefix' => static::formatGroupPrefix($new, $old),
'where' => static::formatWhere($new, $old),
'suffix' => static::formatGroupSuffix($new, $old),
]);
foreach (['namespace', 'prefix', 'suffix', 'where', 'as'] as $name) {
if (isset($old[$name])) {
unset($old[$name]);
}
}
return \array_merge_recursive($old, $new);
} | php | {
"resource": ""
} |
q262642 | Group.formatGroupSuffix | test | protected static function formatGroupSuffix(array $new, array $old): ?string
{
$oldSuffix = $old['suffix'] ?? null;
if (isset($new['suffix'])) {
return \trim($new['suffix']) . \trim($oldSuffix);
}
return $oldSuffix;
} | php | {
"resource": ""
} |
q262643 | LoadEnvironmentVariables.checkForSpecificEnvironmentFile | test | protected static function checkForSpecificEnvironmentFile(KernelContract $kernel, ?string $env): void
{
if ($kernel->isRunningInConsole() && ($input = new ArgvInput())->hasParameterOption(['--env', '-e'])) {
if (static::setEnvironmentFilePath(
$kernel,
$kernel->getEnvironmentFile() . '.' . $input->getParameterOption(['--env', '-e'])
)) {
return;
}
}
if ($env === null) {
return;
}
static::setEnvironmentFilePath($kernel, $kernel->getEnvironmentFile() . '.' . $env);
} | php | {
"resource": ""
} |
q262644 | LoadEnvironmentVariables.setEnvironmentFilePath | test | protected static function setEnvironmentFilePath(KernelContract $kernel, string $file): bool
{
if (\file_exists($kernel->getEnvironmentPath() . \DIRECTORY_SEPARATOR . $file)) {
$kernel->loadEnvironmentFrom($file);
return true;
}
return false;
} | php | {
"resource": ""
} |
q262645 | TransportFactory.getTransport | test | public function getTransport(string $transport, array $config): Swift_Transport
{
// If the given transport has not been created before, we will create the instances
// here and cache it so we can return it next time very quickly. If there is
// already a transport created by this name, we'll just return that instance.
if (! isset($this->transports[$transport])) {
$this->transports[$transport] = $this->createTransport($transport, $config);
}
return $this->transports[$transport];
} | php | {
"resource": ""
} |
q262646 | TransportFactory.createTransport | test | public function createTransport(string $transport, array $config): Swift_Transport
{
$method = 'create' . Str::studly($transport) . 'Transport';
$config['name'] = $transport;
return $this->create($config, $method);
} | php | {
"resource": ""
} |
q262647 | TransportFactory.hasTransport | test | public function hasTransport(string $transport): bool
{
$method = 'create' . Str::studly($transport) . 'Transport';
return \method_exists($this, $method) || isset($this->extensions[$transport]);
} | php | {
"resource": ""
} |
q262648 | TransportFactory.createSmtpTransport | test | protected function createSmtpTransport(array $config): Swift_SmtpTransport
{
// The Swift SMTP transport instance will allow us to use any SMTP backend
// for delivering mail such as Amazon SES, Sendgrid or a custom server
// a developer has available.
$transport = new Swift_SmtpTransport(
$config['host'],
$config['port']
);
if (isset($config['encryption'])) {
$transport->setEncryption($config['encryption']);
}
// Once we have the transport we will check for the presence of a username
// and password.
if (isset($config['username'], $config['password'])) {
$transport->setUsername($config['username']);
$transport->setPassword($config['password']);
}
if (isset($config['stream'])) {
$transport->setStreamOptions($config['stream']);
}
return $transport;
} | php | {
"resource": ""
} |
q262649 | TransportFactory.createMailgunTransport | test | protected function createMailgunTransport(array $config): MailgunTransport
{
return new MailgunTransport(
$this->getHttpClient($config),
$config['secret'],
$config['domain'],
$config['base_url'] ?? null
);
} | php | {
"resource": ""
} |
q262650 | TransportFactory.createSparkPostTransport | test | protected function createSparkPostTransport(array $config): SparkPostTransport
{
return new SparkPostTransport(
$this->getHttpClient($config),
$config['secret'],
$config['options'] ?? [],
$config['endpoint'] ?? null
);
} | php | {
"resource": ""
} |
q262651 | TransportFactory.createSesTransport | test | protected function createSesTransport(array $config): SesTransport
{
$config += [
'version' => 'latest',
'service' => 'email',
];
if (isset($config['key'], $config['secret'])) {
$config['credentials'] = \array_intersect_key($config, \array_flip(['key', 'secret', 'token']));
}
return new SesTransport(new SesClient($config));
} | php | {
"resource": ""
} |
q262652 | ConfigServiceProvider.createRepository | test | public static function createRepository(ContainerInterface $container): RepositoryContract
{
$config = new Repository();
if ($container->has(LoaderContract::class)) {
$config->setLoader($container->get(LoaderContract::class));
}
$config->addParameterProcessor(new EnvParameterProcessor());
return $config;
} | php | {
"resource": ""
} |
q262653 | RouteTreeNode.update | test | public function update(array $matchers, $contents): RouteTreeNode
{
if ($this->matchers === $matchers && $this->contents === $contents) {
return $this;
}
$clone = clone $this;
$clone->matchers = $matchers;
$clone->contents = $contents;
return $clone;
} | php | {
"resource": ""
} |
q262654 | ConsoleHandler.registerEvents | test | public function registerEvents(EventManagerContract $eventManager): void
{
// Before a command is executed, the handler gets activated and the console output
// is set in order to know where to write the logs.
$eventManager->attach(
ConsoleEvents::COMMAND,
function (ConsoleCommandEvent $event): void {
$output = $event->getOutput();
if ($output instanceof ConsoleOutputInterface) {
$output = $output->getErrorOutput();
}
$this->setOutput($output);
},
255
);
// After a command has been executed, it disables the output.
$eventManager->attach(
ConsoleEvents::TERMINATE,
function (): void {
$this->close();
},
-255
);
} | php | {
"resource": ""
} |
q262655 | TwigBridgeServiceProvider.extendTwigEnvironment | test | public static function extendTwigEnvironment(
ContainerInterface $container,
?TwigEnvironment $twig = null
): ?TwigEnvironment {
if ($twig !== null) {
if ($container->has(Lexer::class)) {
$twig->setLexer($container->get(Lexer::class));
}
if ($twig->isDebug() && \class_exists(VarCloner::class)) {
$twig->addExtension(new DumpExtension());
}
self::registerViserioTwigExtension($twig, $container);
}
return $twig;
} | php | {
"resource": ""
} |
q262656 | TwigBridgeServiceProvider.registerViserioTwigExtension | test | protected static function registerViserioTwigExtension(TwigEnvironment $twig, ContainerInterface $container): void
{
if ($container->has(TranslationManagerContract::class)) {
$twig->addExtension(new TranslatorExtension($container->get(TranslationManagerContract::class)));
}
if (\class_exists(Str::class)) {
$twig->addExtension(new StrExtension());
}
if ($container->has(StoreContract::class)) {
$twig->addExtension(new SessionExtension($container->get(StoreContract::class)));
}
if ($container->has(RepositoryContract::class)) {
$twig->addExtension(new ConfigExtension($container->get(RepositoryContract::class)));
}
} | php | {
"resource": ""
} |
q262657 | MatchedRouteDataMap.allowedHttpMethods | test | public function allowedHttpMethods(): array
{
$allowedHttpMethods = [];
foreach ($this->httpMethodRouteMap as $item) {
foreach ($item[0] as $method) {
$allowedHttpMethods[] = $method;
}
}
return \array_values($allowedHttpMethods);
} | php | {
"resource": ""
} |
q262658 | MatchedRouteDataMap.addRoute | test | public function addRoute(RouteContract $route, array $parameterIndexNameMap): void
{
$this->httpMethodRouteMap[] = [$route->getMethods(), [$parameterIndexNameMap, $route->getIdentifier()]];
} | php | {
"resource": ""
} |
q262659 | Stream.isPipe | test | private function isPipe(): bool
{
if ($this->isPipe === null) {
$this->isPipe = false;
if (isset($this->stream)) {
$mode = \fstat($this->stream)['mode'];
$this->isPipe = ($mode & self::FSTAT_MODE_S_IFIFO) !== 0;
}
}
return $this->isPipe;
} | php | {
"resource": ""
} |
q262660 | Parser.addMimeType | test | public function addMimeType(string $mimeType, string $extension): void
{
self::$supportedMimeTypes[$mimeType] = $extension;
} | php | {
"resource": ""
} |
q262661 | Parser.addParser | test | public function addParser(ParserContract $parser, string $extension): void
{
self::$supportedParsers[$extension] = $parser;
} | php | {
"resource": ""
} |
q262662 | Parser.parse | test | public function parse(string $payload): array
{
if ($payload === '') {
return [];
}
$format = $this->getFormat($payload);
if ($format !== 'php' && \is_file($payload)) {
$payload = \file_get_contents($payload);
if ($payload === false) {
throw new RuntimeException(\sprintf('A error occurred during reading [%s]', $payload));
}
}
return $this->getParser($format)->parse($payload);
} | php | {
"resource": ""
} |
q262663 | Parser.getParser | test | public function getParser(string $type): ParserContract
{
if (isset(self::$supportedParsers[$type])) {
return new self::$supportedParsers[$type]();
}
if (isset(self::$supportedMimeTypes[$type])) {
$class = self::$supportedParsers[self::$supportedMimeTypes[$type]];
if (\is_object($class) && $class instanceof ParserContract) {
return $class;
}
return new $class();
}
throw new NotSupportedException(\sprintf('Given extension or mime type [%s] is not supported.', $type));
} | php | {
"resource": ""
} |
q262664 | Parser.getFormat | test | protected function getFormat(string $payload): string
{
$format = '';
if (\is_file($file = $payload)) {
$format = \pathinfo($file, \PATHINFO_EXTENSION);
} elseif (\is_string($payload)) {
// try if content is json
\json_decode($payload);
if (\json_last_error() === \JSON_ERROR_NONE) {
return 'json';
}
$format = (new finfo(\FILEINFO_MIME_TYPE))->buffer($payload);
}
return self::$supportedMimeTypes[$format] ?? $format;
} | php | {
"resource": ""
} |
q262665 | AbstractCase.classSetUp | test | public function classSetUp(): void
{
$this->config = $this->getTestConfig();
$this->configId = $this->isId ? 'orm_default' : null;
} | php | {
"resource": ""
} |
q262666 | TimeDataCollector.getRequestDuration | test | public function getRequestDuration(): float
{
if ($this->requestEndTime !== null) {
return $this->requestEndTime - $this->requestStartTime;
}
return \microtime(true) - $this->requestStartTime;
} | php | {
"resource": ""
} |
q262667 | TimeDataCollector.stopMeasure | test | public function stopMeasure(string $name, array $params = []): void
{
$end = \microtime(true);
if (! $this->hasStartedMeasure($name)) {
throw new RuntimeException(\sprintf(
'Failed stopping measure [%s] because it hasn\'t been started.',
$name
));
}
$this->addMeasure(
$this->startedMeasures[$name]['label'],
$this->startedMeasures[$name]['start'],
$end,
$params,
$this->startedMeasures[$name]['collector']
);
unset($this->startedMeasures[$name]);
} | php | {
"resource": ""
} |
q262668 | TimeDataCollector.addMeasure | test | public function addMeasure(
string $label,
float $start,
float $end,
array $params = [],
?string $collector = null
): void {
$this->measures[] = [
'label' => $label,
'start' => $start,
'relative_start' => $start - $this->requestStartTime,
'end' => $end,
'relative_end' => $end - $this->requestEndTime,
'duration' => $end - $start,
'duration_str' => $this->formatDuration($end - $start),
'params' => $params,
'collector' => $collector,
];
} | php | {
"resource": ""
} |
q262669 | ExceptionIdentifier.identify | test | public static function identify(Throwable $exception): string
{
$hash = \spl_object_hash($exception);
// if we know about the exception, return it's id
if (isset(self::$identification[$hash])) {
return self::$identification[$hash];
}
// cleanup in preparation for the identification
if (\count((array) self::$identification) >= 16) {
\array_shift(self::$identification);
}
// generate, store, and return the id
return self::$identification[$hash] = self::uuid4();
} | php | {
"resource": ""
} |
q262670 | ExceptionIdentifier.uuid4 | test | private static function uuid4(): string
{
$hash = \bin2hex(\random_bytes(16));
$timeHi = \hexdec(\substr($hash, 12, 4)) & 0x0fff;
$timeHi &= ~0xf000;
$timeHi |= 4 << 12;
$clockSeqHi = \hexdec(\substr($hash, 16, 2)) & 0x3f;
$clockSeqHi &= ~0xc0;
$clockSeqHi |= 0x80;
$params = [\substr($hash, 0, 8), \substr($hash, 8, 4), \sprintf('%04x', $timeHi), \sprintf('%02x', $clockSeqHi), \substr($hash, 18, 2), \substr($hash, 20, 12)];
return \vsprintf('%08s-%04s-%04s-%02s%02s-%012s', $params);
} | php | {
"resource": ""
} |
q262671 | AbstractMessage.setHeaders | test | protected function setHeaders(array $headers): void
{
if (\count($headers) === 0) {
return;
}
$this->headerNames = $this->headers = [];
foreach ($headers as $header => $value) {
$value = $this->filterHeaderValue($value);
$normalized = \strtolower($header);
if (isset($this->headerNames[$normalized])) {
$header = (string) $this->headerNames[$normalized];
$this->headers[$header] += $value;
} else {
$this->headerNames[$normalized] = $header;
$this->headers[$header] = $value;
}
}
} | php | {
"resource": ""
} |
q262672 | AbstractMessage.validateProtocolVersion | test | private function validateProtocolVersion(string $version): void
{
if ($version === '') {
throw new InvalidArgumentException('HTTP protocol version can not be empty.');
}
if (! isset(self::$validProtocolVersions[$version])) {
throw new InvalidArgumentException(
\sprintf('Invalid HTTP version. Must be one of: [%s].', \implode(', ', \array_keys(self::$validProtocolVersions)))
);
}
} | php | {
"resource": ""
} |
q262673 | AbstractMessage.arrayContainsOnlyStrings | test | private function arrayContainsOnlyStrings(array $array): bool
{
// Test if a value is a string.
$filterStringValue = static function (bool $carry, $item) {
if (! \is_string($item)) {
return false;
}
return $carry;
};
return \array_reduce($array, $filterStringValue, true);
} | php | {
"resource": ""
} |
q262674 | AbstractMessage.filterHeaderValue | test | private function filterHeaderValue($values): array
{
if (! \is_array($values)) {
$values = [$values];
}
if (\count($values) === 0 || ! $this->arrayContainsOnlyStrings($values)) {
throw new InvalidArgumentException(
'Invalid header value: must be a string or array of strings and cannot be an empty array.'
);
}
$values = \array_map(static function ($value) {
// @see http://tools.ietf.org/html/rfc7230#section-3.2
HeaderSecurity::assertValid($value);
$value = (string) $value;
// Spaces and tabs ought to be excluded by parsers when extracting the field value from a header field.
//
// header-field = field-name ":" OWS field-value OWS
// OWS = *( SP / HTAB )
//
// @see https://tools.ietf.org/html/rfc7230#section-3.2.4
return \trim($value, " \t");
}, \array_values($values));
return \array_map([HeaderSecurity::class, 'filter'], \array_values($values));
} | php | {
"resource": ""
} |
q262675 | DownCommand.getRetryTime | test | protected function getRetryTime(): ?int
{
$retry = $this->option('retry');
return \is_numeric($retry) && $retry > 0 ? (int) $retry : null;
} | php | {
"resource": ""
} |
q262676 | InvokerAwareTrait.getInvoker | test | protected function getInvoker(): Invoker
{
if ($this->invoker === null) {
$this->invoker = new Invoker();
if ($this->container !== null) {
$this->invoker->setContainer($this->container)
->injectByTypeHint(true)
->injectByParameterName(true);
}
}
return $this->invoker;
} | php | {
"resource": ""
} |
q262677 | InvalidArgumentException.invalidType | test | public static function invalidType(string $name, $provided, array $expected, $configClass): self
{
return new self(\sprintf(
'Invalid configuration value provided for [%s]; Expected [%s], but got [%s], in [%s].',
$name,
\count($expected) === 1 ? $expected[0] : \implode('] or [', $expected),
(\is_object($provided) ? \get_class($provided) : \gettype($provided)),
$configClass
));
} | php | {
"resource": ""
} |
q262678 | ProfilerPsr6Psr16CacheBridgeServiceProvider.extendCacheItemPool | test | public static function extendCacheItemPool(
ContainerInterface $container,
?CacheItemPoolInterface $cache = null
): ?CacheItemPoolInterface {
if ($cache !== null) {
if ($cache instanceof PhpCachePoolInterface) {
return new PhpCacheTraceableCacheDecorator($cache);
}
return new TraceableCacheItemDecorator($cache);
}
return $cache;
} | php | {
"resource": ""
} |
q262679 | ProfilerPsr6Psr16CacheBridgeServiceProvider.extendSimpleTraceableCache | test | public static function extendSimpleTraceableCache(
ContainerInterface $container,
?CacheInterface $cache = null
): ?CacheInterface {
if ($cache !== null) {
if ($cache instanceof PhpCachePoolInterface) {
return new PhpCacheTraceableCacheDecorator($cache);
}
return new SimpleTraceableCacheDecorator($cache);
}
return $cache;
} | php | {
"resource": ""
} |
q262680 | Env.get | test | public static function get(string $key, $default = null)
{
$value = \getenv($key);
if ($value === false) {
return $default instanceof Closure ? $default() : $default;
}
if (\preg_match('/base64:|\'base64:|"base64:/', $value) === 1) {
return \base64_decode(\mb_substr($value, 7), true);
}
if (\in_array(
\mb_strtolower($value),
[
'false',
'(false)',
'true',
'(true)',
'yes',
'(yes)',
'no',
'(no)',
'on',
'(on)',
'off',
'(off)',
],
true
)) {
$value = \str_replace(['(', ')'], '', $value);
return \filter_var(
$value,
\FILTER_VALIDATE_BOOLEAN,
\FILTER_NULL_ON_FAILURE
);
}
if ($value === 'null' || $value === '(null)') {
return null;
}
if (\is_numeric($value)) {
return $value + 0;
}
if ($value === 'empty' || $value === '(empty)') {
return '';
}
if (\mb_strlen($value) > 1 &&
\mb_substr($value, 0, \mb_strlen('"')) === '"' &&
\mb_substr($value, -\mb_strlen('"')) === '"'
) {
return \mb_substr($value, 1, -1);
}
return $value;
} | php | {
"resource": ""
} |
q262681 | AbstractParameterProcessor.parseParameter | test | protected function parseParameter(string $parameter): string
{
\preg_match('/\%' . static::getReferenceKeyword() . '\:(.*)\%/', $parameter, $matches);
if (\count($matches) !== 0) {
return $matches[1];
}
return $parameter;
} | php | {
"resource": ""
} |
q262682 | AbstractParameterProcessor.replaceData | test | protected function replaceData(string $data, string $parameterKey, string $newValue)
{
return \str_replace('%' . static::getReferenceKeyword() . ':' . $parameterKey . '%', $newValue, $data);
} | php | {
"resource": ""
} |
q262683 | PdoSessionHandler.createTable | test | public function createTable(): void
{
// connect if we are not yet
$this->getConnection();
switch ($this->driver) {
case 'mysql':
// We use varbinary for the ID column because it prevents unwanted conversions:
// - character set conversions between server and client
// - trailing space removal
// - case-insensitivity
// - language processing like é == e
$sql = "CREATE TABLE {$this->table} ({$this->idCol} VARBINARY(128) NOT NULL PRIMARY KEY, {$this->dataCol} BLOB NOT NULL, {$this->lifetimeCol} MEDIUMINT NOT NULL, {$this->timeCol} INTEGER UNSIGNED NOT NULL) COLLATE utf8_bin, ENGINE = InnoDB";
break;
case 'sqlite':
$sql = "CREATE TABLE {$this->table} ({$this->idCol} TEXT NOT NULL PRIMARY KEY, {$this->dataCol} BLOB NOT NULL, {$this->lifetimeCol} INTEGER NOT NULL, {$this->timeCol} INTEGER NOT NULL)";
break;
case 'pgsql':
$sql = "CREATE TABLE {$this->table} ({$this->idCol} VARCHAR(128) NOT NULL PRIMARY KEY, {$this->dataCol} BYTEA NOT NULL, {$this->lifetimeCol} INTEGER NOT NULL, {$this->timeCol} INTEGER NOT NULL)";
break;
case 'oci':
$sql = "CREATE TABLE {$this->table} ({$this->idCol} VARCHAR2(128) NOT NULL PRIMARY KEY, {$this->dataCol} BLOB NOT NULL, {$this->lifetimeCol} INTEGER NOT NULL, {$this->timeCol} INTEGER NOT NULL)";
break;
case 'sqlsrv':
$sql = "CREATE TABLE {$this->table} ({$this->idCol} VARCHAR(128) NOT NULL PRIMARY KEY, {$this->dataCol} VARBINARY(MAX) NOT NULL, {$this->lifetimeCol} INTEGER NOT NULL, {$this->timeCol} INTEGER NOT NULL)";
break;
default:
throw new DomainException(\sprintf(
'Creating the session table is currently not implemented for PDO driver [%s].',
$this->driver
));
}
try {
$this->pdo->exec($sql);
} catch (PDOException $e) {
$this->rollback();
throw $e;
}
} | php | {
"resource": ""
} |
q262684 | PdoSessionHandler.getConnection | test | private function getConnection(): PDO
{
if ($this->pdo === null) {
$this->connect($this->dsn);
}
return $this->pdo;
} | php | {
"resource": ""
} |
q262685 | PdoSessionHandler.connect | test | private function connect(string $dsn): void
{
$this->pdo = new PDO($dsn, $this->username, $this->password, $this->connectionOptions);
$this->pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$this->driver = $this->pdo->getAttribute(PDO::ATTR_DRIVER_NAME);
} | php | {
"resource": ""
} |
q262686 | AbstractLoadFiles.getFiles | test | protected static function getFiles(string $path, $extensions = 'php'): array
{
if (! \file_exists($path)) {
return [];
}
$files = [];
$dir = new DirectoryIterator($path);
foreach ($dir as $fileinfo) {
if (! $fileinfo->isDot()) {
$extension = \pathinfo($fileinfo->getRealPath(), \PATHINFO_EXTENSION);
if (\in_array($extension, (array) $extensions, true)) {
$filePath = $fileinfo->getRealPath();
$key = \basename($filePath, '.' . $extension);
if (\in_array($key, static::$bypassFiles, true)) {
continue;
}
$files[$key] = $filePath;
}
}
}
\ksort($files, \SORT_NATURAL);
return $files;
} | php | {
"resource": ""
} |
q262687 | AssetsRenderer.renderIntoHtml | test | protected function renderIntoHtml(): string
{
$html = \sprintf('<style>%s</style>', $this->dumpAssetsToString('css'));
$html .= \sprintf('<script type="text/javascript">%s</script>', $this->dumpAssetsToString('js'));
return $html;
} | php | {
"resource": ""
} |
q262688 | AssetsRenderer.getModifiedTime | test | protected function getModifiedTime(string $type): int
{
$files = $this->getAssets($type);
$latest = 0;
foreach ($files as $file) {
$mtime = (int) \filemtime($file);
if ($mtime > $latest) {
$latest = $mtime;
}
}
return $latest;
} | php | {
"resource": ""
} |
q262689 | CallbackCron.run | test | public function run()
{
if ($this->description) {
$item = $this->cachePool->getItem($this->getMutexName());
$item->set($this->getMutexName());
$item->expiresAfter(1440);
$this->cachePool->save($item);
}
$this->callBeforeCallbacks();
try {
$response = $this->getInvoker()->call($this->callback, $this->parameters);
} finally {
if ($this->description) {
$this->cachePool->deleteItem($this->getMutexName());
}
}
$this->callAfterCallbacks();
return $response;
} | php | {
"resource": ""
} |
q262690 | CallbackCron.withoutOverlapping | test | public function withoutOverlapping(): CronContract
{
if ($this->description === null) {
throw new LogicException(
'A scheduled cron job description is required to prevent overlapping. ' .
"Use the 'setDescription' method before 'withoutOverlapping'."
);
}
return $this->skip(function () {
return $this->cachePool->hasItem($this->getMutexName());
});
} | php | {
"resource": ""
} |
q262691 | LoggerDataCollectorServiceProvider.extendLogManager | test | public static function extendLogManager(ContainerInterface $container, $logManager = null)
{
$options = self::resolveOptions($container->get('config'));
if ($logManager !== null && $options['collector']['logs'] === true) {
$logManager->pushProcessor(new DebugProcessor());
}
return $logManager;
} | php | {
"resource": ""
} |
q262692 | LoggerDataCollectorServiceProvider.extendProfiler | test | public static function extendProfiler(
ContainerInterface $container,
?ProfilerContract $profiler = null
): ?ProfilerContract {
if ($profiler !== null) {
$options = self::resolveOptions($container->get('config'));
if ($options['collector']['logs'] === true && $container->has(LogManager::class)) {
$profiler->addCollector(new LoggerDataCollector($container->get(LogManager::class)->getDriver()));
}
}
return $profiler;
} | php | {
"resource": ""
} |
q262693 | XmlUtils.importDom | test | public static function importDom(DOMDocument $dom): SimpleXMLElement
{
$xml = \simplexml_import_dom($dom);
if ($xml === false) {
throw new ParseException(['message' => 'A failure happend on importing a DOMDocument.']);
}
return $xml;
} | php | {
"resource": ""
} |
q262694 | XmlUtils.loadFile | test | public static function loadFile(string $file, $schemaOrCallable = null): DOMDocument
{
if (! \file_exists($file)) {
throw new FileNotFoundException(\sprintf('No such file [%s] found.', $file));
}
return self::loadString(@\file_get_contents($file), $schemaOrCallable);
} | php | {
"resource": ""
} |
q262695 | XmlUtils.loadString | test | public static function loadString(string $content, $schemaOrCallable = null): DOMDocument
{
if (\trim($content) === '') {
throw new InvalidArgumentException('Content does not contain valid XML, it is empty.');
}
$internalErrors = \libxml_use_internal_errors(true);
$disableEntities = \libxml_disable_entity_loader();
\libxml_clear_errors();
$dom = new DOMDocument();
$dom->validateOnParse = true;
if (! $dom->loadXML($content, \LIBXML_NONET | (\defined('LIBXML_COMPACT') ? \LIBXML_COMPACT : 0))) {
\libxml_disable_entity_loader($disableEntities);
if ($errors = XliffUtils::validateSchema($dom)) {
throw new InvalidArgumentException(self::getErrorsAsString($errors));
}
}
$dom->normalizeDocument();
\libxml_use_internal_errors($internalErrors);
\libxml_disable_entity_loader($disableEntities);
foreach ($dom->childNodes as $child) {
if ($child->nodeType === \XML_DOCUMENT_TYPE_NODE) {
throw new InvalidArgumentException('Document types are not allowed.');
}
}
if ($schemaOrCallable !== null) {
self::validateXmlDom($dom, $schemaOrCallable);
}
\libxml_clear_errors();
\libxml_use_internal_errors($internalErrors);
return $dom;
} | php | {
"resource": ""
} |
q262696 | XmlUtils.phpize | test | public static function phpize($value)
{
$value = (string) $value;
$lowercaseValue = \mb_strtolower($value);
switch (true) {
case 'null' === $lowercaseValue:
return;
case \ctype_digit($value):
return self::transformToNumber($value, 0);
case isset($value[1]) && '-' === $value[0] && \ctype_digit(\mb_substr($value, 1)):
return self::transformToNumber($value, 1);
case 'true' === $lowercaseValue:
return true;
case 'false' === $lowercaseValue:
return false;
case isset($value[1]) && '0b' === $value[0] . $value[1]:
return \bindec($value);
case \is_numeric($value):
return '0x' === $value[0] . $value[1] ? \hexdec($value) : (float) $value;
case \preg_match('/^0x[0-9a-f]++$/i', $value):
return \hexdec($value);
case \preg_match('/^(-|\+)?\d+(\.\d+)?$/', $value):
return (float) $value;
default:
return $value;
}
} | php | {
"resource": ""
} |
q262697 | XmlUtils.validateXmlDom | test | private static function validateXmlDom(DOMDocument $dom, $schemaOrCallable): void
{
$internalErrors = \libxml_use_internal_errors(true);
\libxml_clear_errors();
$exception = null;
if (\is_callable($schemaOrCallable)) {
try {
/** @var callable $schemaOrCallable */
$valid = $schemaOrCallable($dom, $internalErrors);
} catch (Throwable $exception) {
$valid = false;
}
} elseif (\is_string($schemaOrCallable) && \is_file($schemaOrCallable)) {
$valid = @$dom->schemaValidateSource(\file_get_contents($schemaOrCallable));
} else {
\libxml_use_internal_errors($internalErrors);
throw new InvalidArgumentException('The schemaOrCallable argument has to be a valid path to XSD file or callable.');
}
if (! $valid) {
$errors = self::getErrorsAsString(self::getXmlErrors($internalErrors));
if ($errors === '') {
$errors = 'The XML file is not valid.';
}
throw new InvalidArgumentException($errors, 0, $exception);
}
} | php | {
"resource": ""
} |
q262698 | PoParser.convertString | test | private static function convertString(string $value): string
{
if ($value === '') {
return '';
}
if ($value[0] === '"') {
$value = \mb_substr($value, 1, -1);
}
return \strtr(
$value,
[
'\\\\' => '\\',
'\\a' => "\x07",
'\\b' => "\x08",
'\\t' => "\t",
'\\n' => "\n",
'\\v' => "\x0b",
'\\f' => "\x0c",
'\\r' => "\r",
'\\"' => '"',
]
);
} | php | {
"resource": ""
} |
q262699 | PoParser.isHeader | test | private static function isHeader(array $entry): bool
{
$headerKeys = [
'Project-Id-Version' => false,
'PO-Revision-Date' => false,
'MIME-Version' => false,
];
$keys = \array_keys($headerKeys);
$headerItems = 0;
$headers = \array_map('trim', $entry['msgstr']);
foreach ($headers as $header) {
\preg_match_all('/(.*):\s/', $header, $matches, \PREG_SET_ORDER);
if (isset($matches[0]) && \in_array($matches[0][1], $keys, true)) {
$headerItems++;
unset($headerKeys[$matches[0][1]]);
$keys = \array_keys($headerKeys);
}
}
return $headerItems !== 0;
} | 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.