_id
stringlengths 2
7
| title
stringlengths 3
151
| partition
stringclasses 3
values | text
stringlengths 83
13k
| language
stringclasses 1
value | meta_information
dict |
---|---|---|---|---|---|
q262900 | ViewServiceProvider.registerMarkdownEngine | test | protected static function registerMarkdownEngine(EngineResolver $engines, ContainerInterface $container): void
{
$markdown = null;
if ($container->has(ParsedownExtra::class)) {
$markdown = $container->get(ParsedownExtra::class);
} elseif ($container->has(Parsedown::class)) {
$markdown = $container->get(Parsedown::class);
}
$engines->register('md', static function () use ($markdown) {
return new MarkdownEngine($markdown);
});
} | php | {
"resource": ""
} |
q262901 | PoDumper.cleanExport | test | protected function cleanExport(string $string): string
{
$replaces = [
'\\' => '\\\\',
'"' => '\"',
"\t" => '\t',
];
$string = \str_replace(\array_keys($replaces), \array_values($replaces), $string);
$po = '"' . \implode('$' . "\n" . '"' . $this->eol . '"', \explode($this->eol, $string)) . '"';
// remove empty strings
return \str_replace($this->eol . '""', '', $po);
} | php | {
"resource": ""
} |
q262902 | PoDumper.addTCommentToOutput | test | private function addTCommentToOutput(array $entry, string $output): array
{
if (isset($entry['tcomment']) && \count($entry['tcomment']) !== 0) {
foreach ($entry['tcomment'] as $comment) {
$output .= '# ' . $comment . $this->eol;
}
}
return [$entry, $output];
} | php | {
"resource": ""
} |
q262903 | PoDumper.addReferencesToOutput | test | private function addReferencesToOutput(array $entry, string $output): array
{
if (isset($entry['references']) && \count($entry['references']) !== 0) {
foreach ($entry['references'] as $ref => $value) {
$output .= '#: ' . \str_replace(['{', '}'], '', $ref) . $this->eol;
}
}
return [$entry, $output];
} | php | {
"resource": ""
} |
q262904 | PoDumper.addFlagsToOutput | test | private function addFlagsToOutput(array $entry, string $output): array
{
if (isset($entry['flags']) && \count($entry['flags']) !== 0) {
$output .= '#, ' . \implode(', ', $entry['flags']) . $this->eol;
}
return [$entry, $output];
} | php | {
"resource": ""
} |
q262905 | PoDumper.addPreviousToOutput | test | private function addPreviousToOutput(array $entry, string $output): array
{
if (isset($entry['previous']) && \count($entry['previous']) !== 0) {
foreach ((array) $entry['previous'] as $key => $value) {
if (\is_string($value)) {
$output .= '#| ' . $key . ' ' . $this->cleanExport($value) . $this->eol;
} elseif (\is_array($value) && \count($value) > 0) {
foreach ($value as $line) {
$output .= '#| ' . $key . ' ' . $this->cleanExport($line) . $this->eol;
}
}
}
}
return [$entry, $output];
} | php | {
"resource": ""
} |
q262906 | PoDumper.addMsgidToOutput | test | private function addMsgidToOutput(array $entry, string $output, bool $isObsolete): array
{
if (isset($entry['msgid'])) {
// Special clean for msgid
if (\is_string($entry['msgid'])) {
$msgid = \explode($this->eol, $entry['msgid']);
} elseif (\is_array($entry['msgid']) && \count($entry['msgid']) !== 0) {
$msgid = $entry['msgid'];
} else {
throw new DumpException('msgid not string or array.');
}
$output .= 'msgid ';
foreach ((array) $msgid as $i => $id) {
if ($i > 0 && $isObsolete) {
$output .= '#~ ';
}
$output .= $this->cleanExport($id) . $this->eol;
}
}
return [$entry, $output];
} | php | {
"resource": ""
} |
q262907 | PoDumper.addMsgidPluralToOutput | test | private function addMsgidPluralToOutput(array $entry, string $output): array
{
if (isset($entry['msgid_plural'])) {
// Special clean for msgid_plural
if (\is_string($entry['msgid_plural'])) {
$msgidPlural = \explode($this->eol, $entry['msgid_plural']);
} elseif (\is_array($entry['msgid_plural']) && \count($entry['msgid_plural']) !== 0) {
$msgidPlural = $entry['msgid_plural'];
} else {
throw new DumpException('msgid_plural not string or array.');
}
$output .= 'msgid_plural ';
foreach ((array) $msgidPlural as $plural) {
$output .= $this->cleanExport($plural) . $this->eol;
}
}
return [$entry, $output];
} | php | {
"resource": ""
} |
q262908 | PoDumper.addMsgstrToOutput | test | private function addMsgstrToOutput(array $entry, bool $isPlural, string $output, bool $isObsolete): string
{
// checks if there is a key starting with msgstr
if (\count(\preg_grep('/^msgstr/', \array_keys($entry))) !== 0) {
if ($isPlural) {
$noTranslation = true;
foreach ($entry as $key => $value) {
if (\mb_strpos($key, 'msgstr[') === false) {
continue;
}
$output .= $key . ' ';
$noTranslation = false;
foreach ($value as $i => $t) {
$output .= $this->cleanExport($t) . $this->eol;
}
}
if ($noTranslation) {
$output .= 'msgstr[0] ' . $this->cleanExport('') . $this->eol;
$output .= 'msgstr[1] ' . $this->cleanExport('') . $this->eol;
}
} else {
foreach ((array) $entry['msgstr'] as $i => $t) {
if ($isObsolete) {
$output .= '#~ ';
}
if ($i === 0) {
$output .= 'msgstr ';
}
$output .= $this->cleanExport($t) . $this->eol;
}
}
}
return $output;
} | php | {
"resource": ""
} |
q262909 | PoDumper.addHeaderToOutput | test | private function addHeaderToOutput(array $data, string $output): array
{
if (isset($data['headers']) && \count($data['headers']) !== 0) {
$output .= 'msgid ""' . $this->eol;
$output .= 'msgstr ""' . $this->eol;
foreach ($data['headers'] as $key => $value) {
if (\is_array($value)) {
$first = true;
foreach ($value as $h) {
if ($first) {
$first = false;
$output .= \sprintf('"%s: %s"', $key, $h) . $this->eol;
} else {
$output .= \sprintf('"%s\n"', $h) . $this->eol;
}
}
} else {
$output .= \sprintf('"%s: %s\n"', $key, $value) . $this->eol;
}
}
unset($data['headers']);
$output .= $this->eol;
}
return [$data, $output];
} | php | {
"resource": ""
} |
q262910 | SemanticUi.getPaginationsLinks | test | private function getPaginationsLinks(array $items, $pagination): void
{
foreach ($items as $item) {
if (\is_string($item)) {
$pagination .= '<a class="icon item disabled">' . $item . '</a>';
}
// Array Of Links
if (\is_array($item)) {
foreach ($item as $page => $url) {
if ($this->paginator->getCurrentPage() === $page) {
$pagination .= '<a class="item active">' . $page . '</a>';
} else {
$pagination .= '<a class="item" href="' . $url . '">' . $page . '</a>';
}
}
}
}
} | php | {
"resource": ""
} |
q262911 | CachedFactory.createConnector | test | protected function createConnector(array $config): CacheInterface
{
$cacheConfig = $config['cache'];
if (($cache = $this->cacheManager) !== null) {
if ($cache->hasDriver($cacheConfig['driver'])) {
return new Psr6Cache(
$cache->getDriver($cacheConfig['driver']),
$cacheConfig['key'],
$cacheConfig['expire']
);
}
}
if ($this->manager->hasConnection($cacheConfig['driver'])) {
return new Adapter(
$this->manager->createConnection($config),
$cacheConfig['key'],
$cacheConfig['expire']
);
}
throw new InvalidArgumentException(\sprintf('Unsupported driver [%s].', $cacheConfig['driver']));
} | php | {
"resource": ""
} |
q262912 | Cron.ensureCorrectUser | test | protected function ensureCorrectUser(string $command): string
{
if ($this->user && ! $this->isWindows()) {
return 'sudo -u ' . $this->user . ' -- sh -c \'' . $command . '\'';
}
// http://de2.php.net/manual/en/function.exec.php#56599
// The "start" command will start a detached process, a similar effect to &. The "/B" option prevents
// start from opening a new terminal window if the program you are running is a console application.
if ($this->user && $this->isWindows()) {
// https://superuser.com/questions/42537/is-there-any-sudo-command-for-windows
// Options for runas : [{/profile|/noprofile}] [/env] [/netonly] [/smartcard] [/showtrustlevels] [/trustlevel] /user:UserAccountName
return 'runas ' . $this->user . 'start /B ' . $command;
}
if ($this->isWindows()) {
return 'start /B ' . $command;
}
return $command;
} | php | {
"resource": ""
} |
q262913 | Cron.expressionPasses | test | protected function expressionPasses(): bool
{
$date = Chronos::now();
if ($this->timezone !== null) {
$date->setTimezone($this->timezone);
}
return CronExpression::factory($this->expression)->isDue($date->toDateTimeString());
} | php | {
"resource": ""
} |
q262914 | Cron.runCommandInForeground | test | protected function runCommandInForeground(): int
{
$this->callBeforeCallbacks();
$process = Process::fromShellCommandline(
\trim($this->buildCommand(), ' &'),
$this->path,
null,
null,
null
);
$run = $process->run();
$this->callAfterCallbacks();
return $run;
} | php | {
"resource": ""
} |
q262915 | Cron.runCommandInBackground | test | protected function runCommandInBackground(): int
{
$process = Process::fromShellCommandline(
$this->buildCommand(),
$this->path,
null,
null,
null
);
return $process->run();
} | php | {
"resource": ""
} |
q262916 | Cron.callBeforeCallbacks | test | protected function callBeforeCallbacks(): void
{
foreach ($this->beforeCallbacks as $callback) {
$this->getInvoker()->call($callback);
}
} | php | {
"resource": ""
} |
q262917 | Cron.callAfterCallbacks | test | protected function callAfterCallbacks(): void
{
foreach ($this->afterCallbacks as $callback) {
$this->getInvoker()->call($callback);
}
} | php | {
"resource": ""
} |
q262918 | Cron.inTimeInterval | test | protected function inTimeInterval(string $startTime, string $endTime): Closure
{
if ($this->isMidnightBetween($startTime, $endTime)) {
$endTime .= ' +1 day';
}
return function () use ($startTime, $endTime) {
return Chronos::now($this->timezone)->between(
Chronos::parse($startTime, $this->timezone),
Chronos::parse($endTime, $this->timezone)
);
};
} | php | {
"resource": ""
} |
q262919 | Cron.isMidnightBetween | test | private function isMidnightBetween(string $startTime, string $endTime): bool
{
return \strtotime($startTime) > \strtotime($endTime);
} | php | {
"resource": ""
} |
q262920 | MatcherOptimizer.mergeMatchers | test | public static function mergeMatchers(array $parentMatchers, array $childMatchers): array
{
$mergedMatchers = $parentMatchers;
foreach ($childMatchers as $segment => $childMatcher) {
if (isset($mergedMatchers[$segment])) {
$mergedMatchers[$segment] = new CompoundMatcher([$mergedMatchers[$segment], $childMatcher]);
} else {
$mergedMatchers[$segment] = $childMatcher;
}
}
return $mergedMatchers;
} | php | {
"resource": ""
} |
q262921 | MatcherOptimizer.optimizeMatchers | test | public static function optimizeMatchers(array $matchers): array
{
foreach ($matchers as $key => $matcher) {
$matchers[$key] = self::optimizeMatcher($matcher);
}
return self::optimizeMatcherOrder($matchers);
} | php | {
"resource": ""
} |
q262922 | MatcherOptimizer.optimizeMatcher | test | private static function optimizeMatcher(SegmentMatcherContract $matcher): SegmentMatcherContract
{
if ($matcher instanceof RegexMatcher && $matcher->getGroupCount() === 1) {
$parameterKeys = $matcher->getParameterKeys();
switch ($matcher->getRegex()) {
case '/^(' . Pattern::ANY . ')$/':
return new AnyMatcher($parameterKeys);
case '/^(' . Pattern::DIGITS . ')$/':
return new ExpressionMatcher('ctype_digit({segment})', $parameterKeys);
case '/^(' . Pattern::ALPHA . ')$/':
return new ExpressionMatcher('ctype_alpha({segment})', $parameterKeys);
case '/^(' . Pattern::ALPHA_LOWER . ')$/':
return new ExpressionMatcher('ctype_lower({segment})', $parameterKeys);
case '/^(' . Pattern::ALPHA_UPPER . ')$/':
return new ExpressionMatcher('ctype_upper({segment})', $parameterKeys);
case '/^(' . Pattern::ALPHA_NUM . ')$/':
return new ExpressionMatcher('ctype_alnum({segment})', $parameterKeys);
case '/^(' . Pattern::ALPHA_NUM_DASH . ')$/':
return new ExpressionMatcher('ctype_alnum(str_replace(\'-\', \'\', {segment}))', $parameterKeys);
default:
return $matcher;
}
}
return $matcher;
} | php | {
"resource": ""
} |
q262923 | MatcherOptimizer.optimizeMatcherOrder | test | private static function optimizeMatcherOrder(array $matchers): array
{
$computationalCostOrder = [
AnyMatcher::class,
StaticMatcher::class,
ExpressionMatcher::class,
RegexMatcher::class,
// Unknown types last
SegmentMatcherContract::class,
];
$groups = [];
foreach ($computationalCostOrder as $type) {
foreach ($matchers as $index => $matcher) {
if ($matcher instanceof $type) {
unset($matchers[$index]);
$groups[$index] = $matcher;
}
}
}
return $groups;
} | php | {
"resource": ""
} |
q262924 | HttpExceptionServiceProvider.createHtmlDisplayer | test | public static function createHtmlDisplayer(ContainerInterface $container): HtmlDisplayer
{
return new HtmlDisplayer(
$container->get(ResponseFactoryInterface::class),
$container->get('config')
);
} | php | {
"resource": ""
} |
q262925 | HttpExceptionServiceProvider.createViewDisplayer | test | public static function createViewDisplayer(ContainerInterface $container): ViewDisplayer
{
return new ViewDisplayer(
$container->get(ResponseFactoryInterface::class),
$container->get(FactoryContract::class)
);
} | php | {
"resource": ""
} |
q262926 | HttpExceptionServiceProvider.createWhoopsPrettyDisplayer | test | public static function createWhoopsPrettyDisplayer(ContainerInterface $container): WhoopsPrettyDisplayer
{
return new WhoopsPrettyDisplayer(
$container->get(ResponseFactoryInterface::class),
$container->get('config')
);
} | php | {
"resource": ""
} |
q262927 | AbstractTransport.numberOfRecipients | test | protected function numberOfRecipients(Swift_Mime_SimpleMessage $message): int
{
$to = $message->getTo() ?? [];
$cc = $message->getCc() ?? [];
$bcc = $message->getBcc() ?? [];
return \count(\array_merge($to, $cc, $bcc));
} | php | {
"resource": ""
} |
q262928 | Kernel.bootstrap | test | public function bootstrap(): void
{
$container = $this->getContainer();
$bootstrapManager = $container->get(BootstrapManager::class);
if (! $bootstrapManager->hasBeenBootstrapped()) {
$bootstraps = [];
foreach ($this->getPreparedBootstraps() as $classes) {
/** @var \Viserio\Component\Contract\Foundation\BootstrapState $class */
foreach ($classes as $class) {
if (\in_array(BootstrapStateContract::class, \class_implements($class), true)) {
$method = 'add' . $class::getType() . 'Bootstrapping';
$bootstrapManager->{$method}($class::getBootstrapper(), [$class, 'bootstrap']);
} else {
/** @var \Viserio\Component\Contract\Foundation\Bootstrap $class */
$bootstraps[] = $class;
}
}
}
$bootstrapManager->bootstrapWith($bootstraps);
if ($this->isDebug() && ! isset($_ENV['SHELL_VERBOSITY']) && ! isset($_SERVER['SHELL_VERBOSITY'])) {
\putenv('SHELL_VERBOSITY=3');
$_ENV['SHELL_VERBOSITY'] = 3;
$_SERVER['SHELL_VERBOSITY'] = 3;
}
$dispatcher = $container->get(DispatcherContract::class);
if ($dispatcher instanceof MiddlewareBasedDispatcher) {
$dispatcher->setMiddlewarePriorities($this->resolvedOptions['middleware_priority']);
$dispatcher->withMiddleware($this->resolvedOptions['route_middleware']);
foreach ($this->resolvedOptions['middleware_groups'] as $key => $middleware) {
$dispatcher->setMiddlewareGroup($key, $middleware);
}
}
}
} | php | {
"resource": ""
} |
q262929 | Kernel.handleRequest | test | protected function handleRequest(
ServerRequestInterface $serverRequest,
?EventManagerContract $events
): ResponseInterface {
try {
if ($events !== null) {
$events->trigger(new KernelFinishRequestEvent($this, $serverRequest));
}
$response = $this->sendRequestThroughRouter($serverRequest);
} catch (Throwable $exception) {
$this->reportException($exception);
$response = $this->renderException($serverRequest, $exception);
if ($events !== null) {
$events->trigger(new KernelExceptionEvent($this, $serverRequest, $response));
}
}
return $response;
} | php | {
"resource": ""
} |
q262930 | Kernel.renderException | test | protected function renderException(ServerRequestInterface $request, Throwable $exception): ResponseInterface
{
$container = $this->getContainer();
if ($container->has(HttpHandlerContract::class)) {
return $container->get(HttpHandlerContract::class)->render($request, $exception);
}
throw $exception;
} | php | {
"resource": ""
} |
q262931 | Kernel.pipeRequestThroughMiddlewareAndRouter | test | protected function pipeRequestThroughMiddlewareAndRouter(
ServerRequestInterface $request,
RouterContract $router
): ResponseInterface {
$container = $this->getContainer();
return (new RoutingPipeline())
->setContainer($container)
->send($request)
->through($this->resolvedOptions['skip_middleware'] ? [] : $this->resolvedOptions['middleware'])
->then(static function ($request) use ($router, $container) {
$container->instance(ServerRequestInterface::class, $request);
return $router->dispatch($request);
});
} | php | {
"resource": ""
} |
q262932 | Schedule.compileParameters | test | protected function compileParameters(array $parameters): string
{
$keys = \array_keys($parameters);
$items = \array_map(static function ($value, $key) {
if (\is_array($value)) {
$value = \array_map('escapeshellarg', $value);
$value = \implode(' ', $value);
} elseif (! \is_numeric($value) && ! \preg_match('/^(-.$|--.*)/', $value)) {
$value = \escapeshellarg($value);
}
return \is_numeric($key) ? $value : \sprintf('%s=%s', $key, $value);
}, $parameters, $keys);
return \implode(' ', \array_combine($keys, $items));
} | php | {
"resource": ""
} |
q262933 | Container.offsetSet | test | public function offsetSet($offset, $value): void
{
if (\is_string($value)) {
$this->bindPlain($offset, $value);
} else {
$this->bindService($offset, $value);
}
} | php | {
"resource": ""
} |
q262934 | Container.getInvoker | test | protected function getInvoker(): InvokerInterface
{
if (! $this->invoker) {
$parameterResolver = [
new NumericArrayResolver(),
new AssociativeArrayResolver(),
new DefaultValueResolver(),
new TypeHintContainerResolver($this),
new ParameterNameContainerResolver($this),
];
$this->invoker = new Invoker(new ResolverChain($parameterResolver), $this);
}
return $this->invoker;
} | php | {
"resource": ""
} |
q262935 | Container.bindPlain | test | protected function bindPlain(string $abstract, $concrete): void
{
$this->bindings[$abstract] = [
TypesContract::VALUE => $concrete,
TypesContract::IS_RESOLVED => false,
TypesContract::BINDING_TYPE => TypesContract::PLAIN,
];
} | php | {
"resource": ""
} |
q262936 | Container.bindService | test | protected function bindService(string $abstract, $concrete): void
{
$this->bindings[$abstract] = [
TypesContract::VALUE => $concrete,
TypesContract::IS_RESOLVED => false,
TypesContract::BINDING_TYPE => TypesContract::SERVICE,
];
} | php | {
"resource": ""
} |
q262937 | Container.bindSingleton | test | protected function bindSingleton(string $abstract, $concrete): void
{
$this->bindings[$abstract] = [
TypesContract::VALUE => $concrete,
TypesContract::IS_RESOLVED => false,
TypesContract::BINDING_TYPE => TypesContract::SINGLETON,
];
} | php | {
"resource": ""
} |
q262938 | Container.resolvePlain | test | protected function resolvePlain(string $abstract)
{
$binding = &$this->bindings[$abstract];
$binding[TypesContract::IS_RESOLVED] = true;
return $binding[TypesContract::VALUE];
} | php | {
"resource": ""
} |
q262939 | Container.resolveService | test | protected function resolveService(string $abstract, array $parameters = [])
{
$binding = &$this->bindings[$abstract];
$binding[TypesContract::IS_RESOLVED] = true;
return parent::resolve($binding[TypesContract::VALUE], $parameters);
} | php | {
"resource": ""
} |
q262940 | Container.resolveSingleton | test | protected function resolveSingleton(string $abstract, array $parameters = [])
{
$binding = &$this->bindings[$abstract];
$binding[TypesContract::VALUE] = parent::resolve($binding[TypesContract::VALUE], $parameters);
$binding[TypesContract::IS_RESOLVED] = true;
return $binding[TypesContract::VALUE];
} | php | {
"resource": ""
} |
q262941 | Container.extendResolved | test | protected function extendResolved($abstract, &$resolved): void
{
if (! isset($this->extenders[$abstract])) {
return;
}
$binding = $this->bindings[$abstract];
foreach ($this->extenders[$abstract] as $extender) {
$resolved = $this->extendConcrete($resolved, $extender);
}
if ($binding && $binding[TypesContract::BINDING_TYPE] !== TypesContract::SERVICE) {
unset($this->extenders[$abstract]);
$this->bindings[$abstract][TypesContract::VALUE] = $resolved;
}
} | php | {
"resource": ""
} |
q262942 | Container.contextualBindingFormat | test | protected function contextualBindingFormat($implementation, ReflectionClass $parameterClass)
{
if ($implementation instanceof Closure || $implementation instanceof $parameterClass->name) {
return $implementation;
}
return static function (ContainerContract $container) use ($implementation) {
return $container->resolve($implementation);
};
} | php | {
"resource": ""
} |
q262943 | PostmarkTransport.getMessageId | test | protected function getMessageId(?ResponseInterface $response): string
{
if ($response === null) {
return '';
}
$content = \json_decode($response->getBody()->getContents(), true);
return $content['MessageID'];
} | php | {
"resource": ""
} |
q262944 | PostmarkTransport.convertEmailsArray | test | protected function convertEmailsArray(array $emails): array
{
$convertedEmails = [];
foreach ($emails as $email => $name) {
$convertedEmails[] = $name ?
'"' . \str_replace('"', '\\"', $name) . "\" <{$email}>" :
$email;
}
return $convertedEmails;
} | php | {
"resource": ""
} |
q262945 | PostmarkTransport.getMIMEPart | test | protected function getMIMEPart(Swift_Mime_SimpleMessage $message, $mimeType): ?Swift_Mime_SimpleMimeEntity
{
foreach ($message->getChildren() as $part) {
if (! ($part instanceof Swift_Mime_Attachment) && \mb_strpos($part->getContentType(), $mimeType) === 0) {
return $part;
}
}
return null;
} | php | {
"resource": ""
} |
q262946 | PostmarkTransport.getMessagePayload | test | protected function getMessagePayload(Swift_Mime_SimpleMessage $message): array
{
$payload = [];
$payload = $this->processRecipients($payload, $message);
$payload = $this->processMessageParts($payload, $message);
return $this->processHeaders($payload, $message);
} | php | {
"resource": ""
} |
q262947 | PostmarkTransport.processRecipients | test | protected function processRecipients(array $payload, Swift_Mime_SimpleMessage $message): array
{
$payload['From'] = \implode(',', $this->convertEmailsArray($message->getFrom()));
$payload['To'] = \implode(',', $this->convertEmailsArray($message->getTo()));
$payload['Subject'] = $message->getSubject() ?? '';
$tags = $message->getHeaders()->getAll('tag');
/** @var \Swift_Mime_Header $tag */
$tag = \end($tags);
$payload['Tag'] = $tag !== false ? $tag->getFieldBody() : '';
$cc = $message->getCc();
if (\is_array($cc)) {
$payload['Cc'] = \implode(',', $this->convertEmailsArray($cc));
}
$replyTo = $message->getReplyTo();
if (\is_string($replyTo)) {
$payload['ReplyTo'] = $replyTo;
}
$bcc = $message->getBcc();
if (\is_array($bcc)) {
$payload['Bcc'] = \implode(',', $this->convertEmailsArray($bcc));
}
return $payload;
} | php | {
"resource": ""
} |
q262948 | PostmarkTransport.processMessageParts | test | protected function processMessageParts(array $payload, Swift_Mime_SimpleMessage $message): array
{
//Get the primary message.
switch ($message->getContentType()) {
case 'text/html':
case 'multipart/mixed':
case 'multipart/related':
case 'multipart/alternative':
$payload['HtmlBody'] = $message->getBody();
break;
default:
$payload['TextBody'] = $message->getBody();
break;
}
// Provide an alternate view from the secondary parts.
if ($plain = $this->getMIMEPart($message, 'text/plain')) {
$payload['TextBody'] = $plain->getBody();
}
if ($html = $this->getMIMEPart($message, 'text/html')) {
$payload['HtmlBody'] = $html->getBody();
}
if ($message->getChildren()) {
$payload['Attachments'] = [];
foreach ($message->getChildren() as $attachment) {
if (\is_object($attachment) && $attachment instanceof Swift_Mime_Attachment) {
$attachments = [
'Name' => $attachment->getFilename(),
'Content' => \base64_encode($attachment->getBody()),
'ContentType' => $attachment->getContentType(),
];
if ($attachment->getDisposition() !== 'attachment' &&
$attachment->getId() !== null
) {
$attachments['ContentID'] = 'cid:' . $attachment->getId();
}
$payload['Attachments'][] = $attachments;
}
}
}
return $payload;
} | php | {
"resource": ""
} |
q262949 | PostmarkTransport.processHeaders | test | protected function processHeaders(array $payload, Swift_Mime_SimpleMessage $message): array
{
$headers = [];
foreach ($message->getHeaders()->getAll() as $key => $value) {
$fieldName = $value->getFieldName();
$excludedHeaders = ['Subject', 'Content-Type', 'MIME-Version', 'Date'];
if (! \in_array($fieldName, $excludedHeaders, true)) {
if ($value instanceof Swift_Mime_Headers_UnstructuredHeader) {
$headers[] = [
'Name' => $fieldName,
'Value' => $value->getValue(),
];
} elseif ($value instanceof Swift_Mime_Headers_DateHeader ||
$value instanceof Swift_Mime_Headers_IdentificationHeader ||
$value instanceof Swift_Mime_Headers_ParameterizedHeader ||
$value instanceof Swift_Mime_Headers_PathHeader
) {
$headers[] = [
'Name' => $fieldName,
'Value' => $value->getFieldBody(),
];
if ($value->getFieldName() === 'Message-ID') {
$headers[] = [
'Name' => 'X-PM-KeepID',
'Value' => 'true',
];
}
}
}
}
$payload['Headers'] = $headers;
return $payload;
} | php | {
"resource": ""
} |
q262950 | ServerCommandRequirementsCheckTrait.checkRequirements | test | protected function checkRequirements(): int
{
if ($this->documentRoot === null) {
if ($this->hasOption('docroot')) {
$this->documentRoot = $this->option('docroot');
} else {
$this->error('The document root directory must be either passed as first argument of the constructor or through the "--docroot" input option.');
return 1;
}
}
if ($this->environment === null) {
if ($this->hasOption('env')) {
if (\is_string($env = $this->option('env'))) {
$this->environment = $env;
} else {
$this->error('The environment must be either passed as second argument of the constructor or through the "--env" input option.');
return 1;
}
} else {
$this->error('The environment must be passed as second argument of the constructor.');
return 1;
}
}
if ($this->environment === 'prod') {
$this->error('Running this server in production environment is NOT recommended!');
}
return 0;
} | php | {
"resource": ""
} |
q262951 | ViewFactory.getExtension | test | protected function getExtension(string $path): ?string
{
$callback = function ($value) use ($path) {
return $this->endsWith($path, $value);
};
foreach (\array_keys(self::$extensions) as $key => $value) {
if ($callback($value)) {
return $value;
}
}
return null;
} | php | {
"resource": ""
} |
q262952 | ViewFactory.getView | test | protected function getView(
FactoryContract $factory,
EngineContract $engine,
string $view,
array $fileInfo,
$data = []
): View {
return new View($factory, $engine, $view, $fileInfo, $data);
} | php | {
"resource": ""
} |
q262953 | ViewFactory.endsWith | test | private function endsWith(string $haystack, string $needle): bool
{
$length = \mb_strlen($needle);
if ($length === 0) {
return true;
}
return \mb_substr($haystack, -$length) === $needle;
} | php | {
"resource": ""
} |
q262954 | RequestCookies.renderIntoCookieHeader | test | public function renderIntoCookieHeader(ServerRequestInterface $request): ServerRequestInterface
{
$cookieString = \implode('; ', $this->cookies);
return $request->withHeader('cookie', $cookieString);
} | php | {
"resource": ""
} |
q262955 | RequestCookies.listFromCookieString | test | protected static function listFromCookieString(string $string): array
{
$cookies = self::splitOnAttributeDelimiter($string);
return \array_map(static function ($cookiePair) {
return self::oneFromCookiePair($cookiePair);
}, $cookies);
} | php | {
"resource": ""
} |
q262956 | ConsoleErrorEvent.setError | test | public function setError(Throwable $error): void
{
$this->parameters['error'] = $error;
$this->parameters['exit_code'] = $error->getCode() ?: 1;
} | php | {
"resource": ""
} |
q262957 | ConsoleErrorEvent.setExitCode | test | public function setExitCode(int $exitCode): void
{
$this->parameters['exit_code'] = $exitCode;
$r = new ReflectionProperty($this->parameters['error'], 'code');
$r->setAccessible(true);
$r->setValue($this->parameters['error'], $this->parameters['exit_code']);
} | php | {
"resource": ""
} |
q262958 | UrlGenerator.toRoute | test | protected function toRoute(RouteContract $route, array $parameters, int $referenceType): string
{
$path = $this->prepareRoutePath($route, $parameters);
$uri = $this->uriFactory->createUri('/' . \ltrim($path, '/'));
if (($host = $route->getDomain()) !== null) {
$uri = $uri->withHost($host);
} else {
$uri = $uri->withHost($this->request->getUri()->getHost());
}
$requiredSchemes = $this->isSchemeRequired($route);
if ($referenceType === self::ABSOLUTE_URL || $requiredSchemes || $referenceType === self::NETWORK_PATH) {
$uri = $this->addPortAndSchemeToUri($uri, $route);
}
if ($referenceType === self::ABSOLUTE_URL || $requiredSchemes) {
return (string) $uri;
}
if ($referenceType === self::NETWORK_PATH) {
$uri = $uri->withScheme('');
return (string) $uri;
}
return '/' . self::getRelativePath('//' . $uri->getHost() . '/', (string) $uri);
} | php | {
"resource": ""
} |
q262959 | UrlGenerator.prepareRoutePath | test | protected function prepareRoutePath(RouteContract $route, array $parameters): string
{
$parameters = \array_replace($route->getParameters(), $parameters);
// First we will construct the entire URI including the root and query string. Once it
// has been constructed, we'll make sure we don't have any missing parameters or we
// will need to throw the exception to let the developers know one was not given.
$path = $this->addQueryString(
$this->replaceRouteParameters($route->getUri(), $parameters),
$parameters
);
\preg_match('/\\{(.*?)\\}/', $path, $matches);
if (isset($matches[1]) && $matches[1] !== '') {
throw new UrlGenerationException($route);
}
$path = $this->replacePathSegments($path);
// Once we have ensured that there are no missing parameters in the URI we will encode
// the URI and prepare it for returning to the developer.
return \strtr(\rawurlencode($path), self::$dontEncode);
} | php | {
"resource": ""
} |
q262960 | UrlGenerator.isSchemeRequired | test | protected function isSchemeRequired(RouteContract $route): bool
{
$requiredSchemes = false;
$requestScheme = $this->request->getUri()->getScheme();
if ($route->isHttpOnly()) {
$requiredSchemes = $requestScheme !== 'http';
} elseif ($route->isHttpsOnly()) {
$requiredSchemes = $requestScheme !== 'https';
}
return $requiredSchemes;
} | php | {
"resource": ""
} |
q262961 | UrlGenerator.addPortAndSchemeToUri | test | protected function addPortAndSchemeToUri(UriInterface $uri, RouteContract $route): UriInterface
{
if ($route->isHttpOnly()) {
$secure = 'http';
$port = 80;
} elseif ($route->isHttpsOnly()) {
$secure = 'https';
$port = 443;
} else {
$requestUri = $this->request->getUri();
$secure = $requestUri->getScheme();
$port = $requestUri->getPort();
}
$uri = $uri->withScheme($secure);
return $uri->withPort($port);
} | php | {
"resource": ""
} |
q262962 | UrlGenerator.replaceRouteParameters | test | protected function replaceRouteParameters(string $path, array &$parameters): string
{
$path = $this->replaceNamedParameters($path, $parameters);
$path = \preg_replace_callback('/\{.*?\}/', static function ($match) use (&$parameters) {
if (\count($parameters) === 0 && ! (\substr($match[0], -\strlen('?}')) === '?}')) {
return $match[0];
}
return \array_shift($parameters);
}, $path);
return \trim(\preg_replace('/\{.*?\?\}/', '', $path), '/');
} | php | {
"resource": ""
} |
q262963 | UrlGenerator.replaceNamedParameters | test | protected function replaceNamedParameters(string $path, array &$parameters): string
{
return \preg_replace_callback('/\{(.*?)\??\}/', static function ($m) use (&$parameters) {
if (isset($parameters[$m[1]]) && $parameters[$m[1]] !== '') {
$parameter = $parameters[$m[1]];
unset($parameters[$m[1]]);
return $parameter;
}
return $m[0];
}, $path);
} | php | {
"resource": ""
} |
q262964 | UrlGenerator.addQueryString | test | protected function addQueryString(string $uri, array $parameters): string
{
// If the URI has a fragment we will move it to the end of this URI since it will
// need to come after any query string that may be added to the URL else it is
// not going to be available. We will remove it then append it back on here.
if (null !== ($fragment = \parse_url($uri, \PHP_URL_FRAGMENT))) {
$uri = \preg_replace('/#.*/', '', $uri);
}
$uri .= $this->getRouteQueryString($parameters);
if (null === $fragment) {
return $uri;
}
return $uri . '#' . \strtr(\rawurlencode($fragment), ['%2F' => '/', '%3F' => '?']);
} | php | {
"resource": ""
} |
q262965 | UrlGenerator.getRouteQueryString | test | protected function getRouteQueryString(array $parameters): string
{
// First we will get all of the string parameters that are remaining after we
// have replaced the route wildcards. We'll then build a query string from
// these string parameters then use it as a starting point for the rest.
if (\count($parameters) === 0 || \in_array(null, $parameters, true)) {
return '';
}
$query = \http_build_query(
$keyed = $this->getStringParameters($parameters),
'',
'&',
\PHP_QUERY_RFC3986
);
// Lastly, if there are still parameters remaining, we will fetch the numeric
// parameters that are in the array and add them to the query string or we
// will make the initial query string if it wasn't started with strings.
if (\count($keyed) < \count($parameters)) {
$query .= '&' . \implode(
'&',
$this->getNumericParameters($parameters)
);
}
// "/" and "?" can be left decoded for better user experience, see
// http://tools.ietf.org/html/rfc3986#section-3.4
return '?' . \trim(\strtr($query, ['%2F' => '/']), '&');
} | php | {
"resource": ""
} |
q262966 | Route.parseWhere | test | protected function parseWhere($name, ?string $expression): array
{
if (\is_string($name)) {
return [$name => $expression];
}
$arr = [];
foreach ($name as $paramName) {
$arr[$paramName] = $expression;
}
return $arr;
} | php | {
"resource": ""
} |
q262967 | Route.getControllerMiddleware | test | protected function getControllerMiddleware(): array
{
if (! $this->isControllerAction()) {
return [];
}
$controller = $this->getController();
if (\method_exists($controller, 'gatherMiddleware')) {
return $controller->gatherMiddleware();
}
return [];
} | php | {
"resource": ""
} |
q262968 | Route.getControllerDisabledMiddleware | test | protected function getControllerDisabledMiddleware(): array
{
if (! $this->isControllerAction()) {
return [];
}
$controller = $this->getController();
if (\method_exists($controller, 'gatherDisabledMiddleware')) {
return $controller->gatherDisabledMiddleware();
}
return [];
} | php | {
"resource": ""
} |
q262969 | AbstractCookieCollector.add | test | public function add($cookie): self
{
if ($cookie instanceof Cookie || $cookie instanceof SetCookie) {
$clone = clone $this;
$clone->cookies[$cookie->getName()] = $cookie;
return $clone;
}
throw new InvalidArgumentException(\sprintf(
'The object [%s] must be an instance of [%s] or [%s].',
\get_class($cookie),
Cookie::class,
SetCookie::class
));
} | php | {
"resource": ""
} |
q262970 | AbstractCookieCollector.splitCookiePair | test | protected static function splitCookiePair(string $string): array
{
$pairParts = \explode('=', $string, 2);
if (\count($pairParts) === 1) {
$pairParts[1] = '';
}
return \array_map(static function ($part) {
if ($part === null) {
return '';
}
return \urldecode($part);
}, $pairParts);
} | php | {
"resource": ""
} |
q262971 | InjectContentTypeTrait.injectContentType | test | private function injectContentType(string $contentType, array $headers): array
{
$hasContentType = \array_reduce(\array_keys($headers), static function ($carry, $item) {
return $carry ?: (\strtolower($item) === 'content-type');
}, false);
if (! $hasContentType) {
$headers['Content-Type'] = [$contentType];
}
return $headers;
} | php | {
"resource": ""
} |
q262972 | Str.words | test | public static function words(string $value, int $words = 100, string $end = '...'): string
{
\preg_match('/^\s*+(?:\S++\s*+){1,' . $words . '}/u', $value, $matches);
if (! isset($matches[0]) || \mb_strlen($value) === \mb_strlen($matches[0])) {
return $value;
}
return \rtrim($matches[0]) . $end;
} | php | {
"resource": ""
} |
q262973 | Str.random | test | public static function random(int $length = 64, string $characters = CharacterType::PRINTABLE_ASCII): string
{
$str = '';
$l = self::length($characters) - 1;
for ($i = 0; $i < $length; $i++) {
$r = \random_int(0, $l);
$str .= $characters[$r];
}
return $str;
} | php | {
"resource": ""
} |
q262974 | Str.replaceFirst | test | public static function replaceFirst(string $search, string $replace, string $subject): string
{
if ($search === '') {
return $subject;
}
$position = \mb_strpos($subject, $search);
return self::replaceByPosition($subject, $replace, $position, $search);
} | php | {
"resource": ""
} |
q262975 | Str.replaceLast | test | public static function replaceLast(string $search, string $replace, string $subject): string
{
$position = \mb_strrpos($subject, $search);
return self::replaceByPosition($subject, $replace, $position, $search);
} | php | {
"resource": ""
} |
q262976 | Str.replaceByPosition | test | private static function replaceByPosition(string $subject, string $replace, $position, string $search): string
{
if ($position !== false) {
return \substr_replace($subject, $replace, $position, \mb_strlen($search));
}
return $subject;
} | php | {
"resource": ""
} |
q262977 | AbstractCommand.getVerbosity | test | public function getVerbosity($level = null): int
{
if ($level === null) {
return $this->verbosity;
}
if (isset($this->verbosityMap[$level])) {
return $this->verbosityMap[$level];
}
return (int) $level;
} | php | {
"resource": ""
} |
q262978 | AbstractCommand.run | test | public function run(InputInterface $input, OutputInterface $output): int
{
$this->input = $input;
$this->output = new SymfonyStyle(
$input,
$output instanceof ConsoleOutputInterface ? $output->getErrorOutput() : $output
);
return parent::run($input, $output);
} | php | {
"resource": ""
} |
q262979 | AbstractCommand.call | test | public function call(string $command, array $arguments = []): int
{
return $this->getApplication()->call($command, $arguments, $this->getOutput());
} | php | {
"resource": ""
} |
q262980 | AbstractCommand.callSilent | test | public function callSilent(string $command, array $arguments = []): int
{
return $this->getApplication()->call($command, $arguments, new NullOutput());
} | php | {
"resource": ""
} |
q262981 | AbstractCommand.argument | test | public function argument(?string $key = null)
{
if ($key === null) {
return $this->input->getArguments();
}
return $this->input->getArgument($key);
} | php | {
"resource": ""
} |
q262982 | AbstractCommand.option | test | public function option(?string $key = null)
{
if ($key === null) {
return $this->input->getOptions();
}
return $this->input->getOption($key);
} | php | {
"resource": ""
} |
q262983 | AbstractCommand.ask | test | public function ask(string $question, ?string $default = null): ?string
{
return $this->getOutput()->ask($question, $default);
} | php | {
"resource": ""
} |
q262984 | AbstractCommand.anticipate | test | public function anticipate(string $question, array $choices, string $default = null): ?string
{
return $this->askWithCompletion($question, $choices, $default);
} | php | {
"resource": ""
} |
q262985 | AbstractCommand.choice | test | public function choice(
string $question,
array $choices,
?string $default = null,
$attempts = null,
bool $multiple = false
): ?string {
$question = new ChoiceQuestion($question, $choices, $default);
$question->setMaxAttempts($attempts)->setMultiselect($multiple);
return $this->getOutput()->askQuestion($question);
} | php | {
"resource": ""
} |
q262986 | AbstractCommand.table | test | public function table(array $headers, $rows, string $style = 'default', array $columnStyles = []): void
{
$table = new Table($this->output);
if ($rows instanceof Arrayable) {
$rows = $rows->toArray();
}
$table->setHeaders($headers)->setRows($rows)->setStyle($style);
foreach ($columnStyles as $columnIndex => $columnStyle) {
$table->setColumnStyle($columnIndex, $columnStyle);
}
$table->render();
} | php | {
"resource": ""
} |
q262987 | AbstractCommand.line | test | public function line(string $string, ?string $style = null, $verbosityLevel = null): void
{
$styledString = $style ? "<${style}>${string}</${style}>" : $string;
$this->getOutput()->writeln($styledString, $this->getVerbosity($verbosityLevel));
} | php | {
"resource": ""
} |
q262988 | AbstractCommand.info | test | public function info(string $string, $verbosityLevel = null): void
{
$this->line($string, 'info', $verbosityLevel);
} | php | {
"resource": ""
} |
q262989 | AbstractCommand.comment | test | public function comment(string $string, $verbosityLevel = null): void
{
$this->line($string, 'comment', $verbosityLevel);
} | php | {
"resource": ""
} |
q262990 | AbstractCommand.question | test | public function question(string $string, $verbosityLevel = null): void
{
$this->line($string, 'question', $verbosityLevel);
} | php | {
"resource": ""
} |
q262991 | AbstractCommand.error | test | public function error(string $string, $verbosityLevel = null): void
{
$this->line($string, 'error', $verbosityLevel);
} | php | {
"resource": ""
} |
q262992 | AbstractCommand.warn | test | public function warn(string $string, $verbosityLevel = null): void
{
if (! $this->getOutput()->getFormatter()->hasStyle('warning')) {
$style = new OutputFormatterStyle('yellow');
$this->getOutput()->getFormatter()->setStyle('warning', $style);
}
$this->line($string, 'warning', $verbosityLevel);
} | php | {
"resource": ""
} |
q262993 | AbstractCommand.configureUsingFluentDefinition | test | private function configureUsingFluentDefinition(): void
{
$data = ExpressionParser::parse($this->signature);
parent::__construct($data['name']);
foreach ($data['arguments'] as $argument) {
$this->getDefinition()->addArgument($argument);
}
foreach ($data['options'] as $option) {
$this->getDefinition()->addOption($option);
}
} | php | {
"resource": ""
} |
q262994 | AbstractCommand.specifyParameters | test | private function specifyParameters(): void
{
// We will loop through all of the arguments and options for the command and
// set them all on the base command instance. This specifies what can get
// passed into these commands as "parameters" to control the execution.
foreach ($this->getArguments() as $arguments) {
$this->addArgument(...$arguments);
}
foreach ($this->getOptions() as $options) {
$this->addOption(...$options);
}
} | php | {
"resource": ""
} |
q262995 | SparkPostTransport.getTransmissionId | test | protected function getTransmissionId(ResponseInterface $response): ?string
{
$object = \json_decode($response->getBody()->getContents());
foreach (['results', 'id'] as $segment) {
if (! \is_object($object) || ! isset($object->{$segment})) {
return null;
}
$object = $object->{$segment};
}
return $object;
} | php | {
"resource": ""
} |
q262996 | SparkPostTransport.getRecipients | test | protected function getRecipients(Swift_Mime_SimpleMessage $message): array
{
$recipients = [];
if ($message->getTo() !== null) {
foreach ($message->getTo() as $email => $name) {
$recipients[] = ['address' => \compact('name', 'email')];
}
}
if ($message->getCc() !== null) {
foreach ($message->getCc() as $email => $name) {
$recipients[] = ['address' => \compact('name', 'email')];
}
}
if ($message->getBcc() !== null) {
foreach ($message->getBcc() as $email => $name) {
$recipients[] = ['address' => \compact('name', 'email')];
}
}
return $recipients;
} | php | {
"resource": ""
} |
q262997 | HtmlDisplayer.render | test | protected function render(array $info): string
{
$content = \file_get_contents($this->resolvedOptions['template_path']);
foreach ($info as $key => $val) {
$content = \str_replace("{{ $${key} }}", $val, $content);
}
return $content;
} | php | {
"resource": ""
} |
q262998 | ErrorHandler.addShouldntReport | test | public function addShouldntReport(Throwable $exception): HandlerContract
{
$this->dontReport[\get_class($exception)] = $exception;
return $this;
} | php | {
"resource": ""
} |
q262999 | ErrorHandler.report | test | public function report(Throwable $exception): void
{
if ($this->shouldntReport($exception)) {
return;
}
$level = $this->getLevel($exception);
$id = ExceptionIdentifier::identify($exception);
if ($exception instanceof FatalErrorException) {
if ($exception instanceof FatalThrowableError) {
$message = $exception->getMessage();
} else {
$message = 'Fatal ' . $exception->getMessage();
}
} elseif ($exception instanceof ErrorException) {
$message = 'Uncaught ' . $exception->getMessage();
} else {
$message = 'Uncaught Exception: ' . $exception->getMessage();
}
$this->logger->{$level}(
$message,
['exception' => $exception, 'identification' => ['id' => $id]]
);
} | 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.