public function question(string $string, $verbosityLevel = null): void
    {
        $this->line($string, 'question', $verbosityLevel);
    }

public function question ( string $ string , $ verbosityLevel = null ) : void { $ this -> line ( $ string , 'question' , $ verbosityLevel ) ; }

Write a string as question output.

@param string          $string
@param null|int|string $verbosityLevel

@return void


public function error(string $string, $verbosityLevel = null): void
    {
        $this->line($string, 'error', $verbosityLevel);
    }

public function error ( string $ string , $ verbosityLevel = null ) : void { $ this -> line ( $ string , 'error' , $ verbosityLevel ) ; }

Write a string as error output.

@param string          $string
@param null|int|string $verbosityLevel

@return void


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);
    }

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 ) ; }

Write a string as warning output.

@param string          $string
@param null|int|string $verbosityLevel

@return void


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);
        }
    }

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 ) ; } }

Configure the console command using a fluent definition.

@throws \Symfony\Component\Console\Exception\LogicException
@throws \Viserio\Component\Contract\Console\Exception\InvalidCommandExpression

@return void

Configure the console command using a fluent definition .


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);
        }
    }

Specify the arguments and options on the command.

@return void

Specify the arguments and options on the command .


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;
    }

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 ; }

Get the transmission ID from the response.

@param \Psr\Http\Message\ResponseInterface $response

@return null|string

Get the transmission ID from the response .


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;
    }

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 ; }

Get all the addresses this message should be sent to.

Note that SparkPost still respects CC, BCC headers in raw message itself.

@param \Swift_Mime_SimpleMessage $message

@return array

Get all the addresses this message should be sent to .


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;
    }

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
;
}

Render the page with given info.

@param array $info

@return string


public function addShouldntReport(Throwable $exception): HandlerContract
    {
        $this->dontReport[\get_class($exception)] = $exception;

        return $this;
    }

public function addShouldntReport ( Throwable $ exception ) : HandlerContract { $ this -> dontReport [ \ get_class ( $ exception ) ] = $ exception ; return $ this ; }

Determine if the exception shouldn't be reported.

@param \Throwable $exception

@return $this

Determine if the exception shouldn t be reported .


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]]
        );
    }

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
]
]
)
;
}

Report or log an exception.

@param \Throwable $exception

@return void


public function addTransformer(TransformerContract $transformer): HandlerContract
    {
        $this->transformers[\get_class($transformer)] = $transformer;

        return $this;
    }

public function addTransformer ( TransformerContract $ transformer ) : HandlerContract { $ this -> transformers [ \ get_class ( $ transformer ) ] = $ transformer ; return $ this ; }

Add the transformed instance.

@param \Viserio\Component\Contract\Exception\Transformer $transformer

@return $this


public function handleError(int $type, string $message, string $file = '', int $line = 0): bool
    {
        if (\error_reporting() === 0) {
            return false;
        }

        // Level is the current error reporting level to manage silent error.
        // Strong errors are not authorized to be silenced.
        $severity = \error_reporting() | \E_RECOVERABLE_ERROR | \E_USER_ERROR | \E_DEPRECATED | \E_USER_DEPRECATED;

        if ($severity) {
            throw new FatalErrorException($message, 0, $severity, $file, $line);
        }

        return true;
    }

Convert errors into ErrorException objects.

This method catches PHP errors and converts them into ErrorException objects;
these ErrorException objects are then thrown and caught by Viserio's
built-in or custom error handlers.

@param int    $type    The numeric type of the Error
@param string $message The error message
@param string $file    The absolute path to the affected file
@param int    $line    The line number of the error in the affected file

@throws \Symfony\Component\Debug\Exception\FatalErrorException

@return bool Returns false when no handling happens so that the PHP engine can handle the error itself

@internal

Convert errors into ErrorException objects .


public function handleShutdown(): void
    {
        if ($this->reservedMemory === null) {
            return;
        }

        $this->reservedMemory = null;

        // If an error has occurred that has not been displayed, we will create a fatal
        // error exception instance and pass it into the regular exception handling
        // code so it can be displayed back out to the developer for information.
        $error     = \error_get_last();
        $exception = null;

        if ($error !== null && self::isLevelFatal($error['type'])) {
            $trace = $error['backtrace'] ?? null;

            if (\strpos($error['message'], 'Allowed memory') === 0 || \strpos($error['message'], 'Out of memory') === 0) {
                $exception = new OutOfMemoryException(self::$levels[$error['type']] . ': ' . $error['message'], 0, $error['type'], $error['file'], $error['line'], 2, false, $trace);
            } else {
                // Create a new fatal exception instance from an error array.
                $exception = new FatalErrorException(self::$levels[$error['type']] . ': ' . $error['message'], 0, $error['type'], $error['file'], $error['line'], 2, true, $trace);
            }
        }

        if ($exception !== null) {
            $this->handleException($exception);
        }
    }

Shutdown registered function for handling PHP fatal errors.

@throws \Throwable

@return void

@internal

Shutdown registered function for handling PHP fatal errors .


protected function registerExceptionHandler(): void
    {
        if (\in_array(\PHP_SAPI, ['cli', 'phpdbg'], true)) {
            \ini_set('display_errors', '0');
        } elseif (! \filter_var(\ini_get('log_errors'), \FILTER_VALIDATE_BOOLEAN) || \filter_var(\ini_get('error_log'), \FILTER_VALIDATE_BOOLEAN)) {
            // CLI - display errors only if they're not already logged to STDERR
            \ini_set('display_errors', '1');
        }

        \set_exception_handler([$this, 'handleException']);
    }

Register the PHP exception handler.

@return void


protected function registerShutdownHandler(): void
    {
        if ($this->reservedMemory === null) {
            $this->reservedMemory = \str_repeat('x', 10240);
            \register_shutdown_function([$this, 'handleShutdown']);
        }
    }

protected function registerShutdownHandler ( ) : void { if ( $ this -> reservedMemory === null ) { $ this -> reservedMemory = \ str_repeat ( 'x' , 10240 ) ; \ register_shutdown_function ( [ $ this , 'handleShutdown' ] ) ; } }

Register the PHP shutdown handler.

@return void


protected function prepareException($exception)
    {
        if (! $exception instanceof Exception && ! $exception instanceof Error) {
            $exception = new FatalThrowableError($exception);
        } elseif ($exception instanceof Error) {
            $trace = $exception->getTrace();

            $exception = new FatalErrorException(
                $exception->getMessage(),
                $exception->getCode(),
                \E_ERROR,
                $exception->getFile(),
                $exception->getLine(),
                \count($trace),
                \count($trace) !== 0,
                $trace
            );
        }

        return $exception;
    }

protected function prepareException ( $ exception ) { if ( ! $ exception instanceof Exception && ! $ exception instanceof Error ) { $ exception = new FatalThrowableError ( $ exception ) ; } elseif ( $ exception instanceof Error ) { $ trace = $ exception -> getTrace ( ) ; $ exception = new FatalErrorException ( $ exception -> getMessage ( ) , $ exception -> getCode ( ) , \ E_ERROR , $ exception -> getFile ( ) , $ exception -> getLine ( ) , \ count ( $ trace ) , \ count ( $ trace ) !== 0 , $ trace ) ; } return $ exception ; }

Prepare exception in a fatal error handler.

@param \Error|\Exception|\Throwable $exception

@return \Error|\Symfony\Component\Debug\FatalErrorHandler\FatalErrorHandlerInterface|\Throwable

Prepare exception in a fatal error handler .


protected function getTransformed(Throwable $exception): Throwable
    {
        if (! $exception instanceof OutOfMemoryException || \count($this->transformers) === 0) {
            return $exception;
        }

        foreach ($this->transformers as $transformer) {
            /** @var TransformerContract $transformer */
            $exception = $transformer->transform($exception);
        }

        return $exception;
    }

Get the transformed exception.

@param \Throwable $exception

@return \Throwable


private function getLevel(Throwable $exception): string
    {
        foreach ($this->resolvedOptions['levels'] as $class => $level) {
            if ($exception instanceof $class) {
                return $level;
            }
        }

        if ($exception instanceof FatalErrorException) {
            return self::$loggers[$exception->getSeverity()];
        }

        return LogLevel::ERROR;
    }

private function getLevel ( Throwable $ exception ) : string { foreach ( $ this -> resolvedOptions [ 'levels' ] as $ class => $ level ) { if ( $ exception instanceof $ class ) { return $ level ; } } if ( $ exception instanceof FatalErrorException ) { return self :: $ loggers [ $ exception -> getSeverity ( ) ] ; } return LogLevel :: ERROR ; }

Get the exception level.

@param \Throwable $exception

@return string


private function shouldntReport(Throwable $exception): bool
    {
        foreach ($this->dontReport as $type) {
            if ($exception instanceof $type) {
                return true;
            }
        }

        return false;
    }

private function shouldntReport ( Throwable $ exception ) : bool { foreach ( $ this -> dontReport as $ type ) { if ( $ exception instanceof $ type ) { return true ; } } return false ; }

Determine if the exception is in the "do not report" list.

@param \Throwable $exception

@return bool

Determine if the exception is in the do not report list .


public function addDumper(DumperContract $dumper, string $extension): void
    {
        self::$supportedDumper[$extension] = $dumper;
    }

public function addDumper ( DumperContract $ dumper , string $ extension ) : void { self :: $ supportedDumper [ $ extension ] = $ dumper ; }

Add a new dumper.

@param \Viserio\Component\Contract\Parser\Dumper $dumper
@param string                                    $extension

@return void


public function dump(array $data, string $format): string
    {
        $dumper = $this->getDumper($format);

        return $dumper->dump($data);
    }

public function dump ( array $ data , string $ format ) : string { $ dumper = $ this -> getDumper ( $ format ) ; return $ dumper -> dump ( $ data ) ; }

Dump data in your choosing format.

@param array  $data
@param string $format

@throws \Viserio\Component\Contract\Parser\Exception\DumpException
@throws \Viserio\Component\Contract\Parser\Exception\NotSupportedException

@return string


public function getDumper(string $type): DumperContract
    {
        if (isset(self::$supportedDumper[$type])) {
            return new self::$supportedDumper[$type]();
        }

        if (isset(self::$supportedMimeTypes[$type])) {
            $class = self::$supportedDumper[self::$supportedMimeTypes[$type]];

            if (\is_object($class) && $class instanceof DumperContract) {
                return $class;
            }

            return new $class();
        }

        throw new NotSupportedException(\sprintf('Given extension or mime type [%s] is not supported.', $type));
    }

Get supported dumper on extension or mime type.

@param string $type

@throws \Viserio\Component\Contract\Parser\Exception\NotSupportedException

@return \Viserio\Component\Contract\Parser\Dumper

Get supported dumper on extension or mime type .


protected function getMimeEntityString(Swift_Message $entity): string
    {
        $string = (string) $entity->getHeaders() . \PHP_EOL . $entity->getBody();

        foreach ($entity->getChildren() as $children) {
            $string .= \PHP_EOL . \PHP_EOL . $this->getMimeEntityString($children);
        }

        return $string;
    }

protected function getMimeEntityString ( Swift_Message $ entity ) : string { $ string = ( string ) $ entity -> getHeaders ( ) . \ PHP_EOL . $ entity -> getBody ( ) ; foreach ( $ entity -> getChildren ( ) as $ children ) { $ string .= \ PHP_EOL . \ PHP_EOL . $ this -> getMimeEntityString ( $ children ) ; } return $ string ; }

Get a loggable string out of a Swiftmailer entity.

@param \Swift_Message $entity

@return string

Get a loggable string out of a Swiftmailer entity .


public function getParameters(
        ReflectionFunctionAbstract $reflection,
        array $providedParameters,
        array $resolvedParameters
    ): array {
        $parameters = [];

        foreach ($reflection->getParameters() as $index => $parameter) {
            $parameters[\mb_strtolower($parameter->name)] = $index;
        }

        foreach ($providedParameters as $name => $value) {
            $normalizedName = \mb_strtolower(\str_replace('-', '', $name));

            // Skip parameters that do not exist with the normalized name
            if (! \array_key_exists($normalizedName, $parameters)) {
                continue;
            }

            $normalizedParameterIndex = $parameters[$normalizedName];

            // Skip parameters already resolved
            if (\array_key_exists($normalizedParameterIndex, $resolvedParameters)) {
                continue;
            }

            $resolvedParameters[$normalizedParameterIndex] = $value;
        }

        return $resolvedParameters;
    }

Tries to maps hyphenated parameters to a similarly-named,
non-hyphenated parameters in the function signature.

E.g. `->call($callable, ['dry-run' => true])` will inject the boolean `true`
for a parameter named either `$dryrun` or `$dryRun`.

@param \ReflectionFunctionAbstract $reflection
@param array                       $providedParameters
@param array                       $resolvedParameters

@return array

Tries to maps hyphenated parameters to a similarly - named non - hyphenated parameters in the function signature .


private static function codePointToUtf8(int $num): string
    {
        if ($num <= 0x7F) {
            return \chr($num);
        }

        if ($num <= 0x7FF) {
            return \chr(($num>>6) + 0xC0) . \chr(($num&0x3F) + 0x80);
        }

        if ($num <= 0xFFFF) {
            return \chr(($num>>12) + 0xE0) . \chr((($num>>6)&0x3F) + 0x80) . \chr(($num&0x3F) + 0x80);
        }

        if ($num <= 0x1FFFFF) {
            return \chr(($num>>18) + 0xF0) . \chr((($num>>12)&0x3F) + 0x80)
                . \chr((($num>>6)&0x3F) + 0x80) . \chr(($num&0x3F) + 0x80);
        }

        throw new Error('Invalid UTF-8 codepoint escape sequence: Codepoint too large.');
    }

Converts a Unicode code point to its UTF-8 encoded representation.

@param int $num Code point

@return string UTF-8 representation of code point

@codeCoverageIgnore

Converts a Unicode code point to its UTF - 8 encoded representation .


public static function registerBusQueueingDispatcher(ContainerInterface $container): QueueingDispatcherContract
    {
        return new QueueingDispatcher($container, static function ($connection = null) use ($container) {
            return $container->get(FactoryContract::class)->connection($connection);
        });
    }

public static function registerBusQueueingDispatcher ( ContainerInterface $ container ) : QueueingDispatcherContract { return new QueueingDispatcher ( $ container , static function ( $ connection = null ) use ( $ container ) { return $ container -> get ( FactoryContract :: class ) -> connection ( $ connection ) ; } ) ; }

Create a new QueueingDispatcher instance.

@param \Psr\Container\ContainerInterface $container

@return \Viserio\Component\Contract\Bus\QueueingDispatcher

Create a new QueueingDispatcher instance .


public function optimize(array $routeTree): array
    {
        $segmentDepthNodeMap = $routeTree[1];

        foreach ($segmentDepthNodeMap as $segmentDepth => $nodes) {
            $segmentDepthNodeMap[$segmentDepth] = $this->optimizeNodes($nodes);
        }

        return [$routeTree[0], $segmentDepthNodeMap];
    }

public function optimize ( array $ routeTree ) : array { $ segmentDepthNodeMap = $ routeTree [ 1 ] ; foreach ( $ segmentDepthNodeMap as $ segmentDepth => $ nodes ) { $ segmentDepthNodeMap [ $ segmentDepth ] = $ this -> optimizeNodes ( $ nodes ) ; } return [ $ routeTree [ 0 ] , $ segmentDepthNodeMap ] ; }

Optimizes the supplied route tree.

@param array $routeTree

@return array


private function extractCommonParentNode(RouteTreeNode $node1, RouteTreeNode $node2): ?RouteTreeNode
    {
        $matcherCompare = static function (SegmentMatcherContract $matcher, SegmentMatcherContract $matcher2) {
            return \strcmp($matcher->getHash(), $matcher2->getHash());
        };

        $commonMatchers = \array_uintersect_assoc($node1->getMatchers(), $node2->getMatchers(), $matcherCompare);

        if (\count($commonMatchers) === 0) {
            return null;
        }

        $children = [];
        $nodes    = [$node1, $node2];

        foreach ($nodes as $node) {
            $specificMatchers  = \array_udiff_assoc($node->getMatchers(), $commonMatchers, $matcherCompare);
            $duplicateMatchers = \array_uintersect_assoc($node->getMatchers(), $commonMatchers, $matcherCompare);

            foreach ($duplicateMatchers as $segmentDepth => $matcher) {
                $commonMatchers[$segmentDepth]->mergeParameterKeys($matcher);
            }

            if (\count($specificMatchers) === 0 && $node->isParentNode()) {
                foreach ($node->getContents()->getChildren() as $childNode) {
                    $children[] = $childNode;
                }
            } else {
                $children[] = $node->update($specificMatchers, $node->getContents());
            }
        }

        return new RouteTreeNode($commonMatchers, new ChildrenNodeCollection($children));
    }

private function extractCommonParentNode ( RouteTreeNode $ node1 , RouteTreeNode $ node2 ) : ? RouteTreeNode { $ matcherCompare = static function ( SegmentMatcherContract $ matcher , SegmentMatcherContract $ matcher2 ) { return \ strcmp ( $ matcher -> getHash ( ) , $ matcher2 -> getHash ( ) ) ; } ; $ commonMatchers = \ array_uintersect_assoc ( $ node1 -> getMatchers ( ) , $ node2 -> getMatchers ( ) , $ matcherCompare ) ; if ( \ count ( $ commonMatchers ) === 0 ) { return null ; } $ children = [ ] ; $ nodes = [ $ node1 , $ node2 ] ; foreach ( $ nodes as $ node ) { $ specificMatchers = \ array_udiff_assoc ( $ node -> getMatchers ( ) , $ commonMatchers , $ matcherCompare ) ; $ duplicateMatchers = \ array_uintersect_assoc ( $ node -> getMatchers ( ) , $ commonMatchers , $ matcherCompare ) ; foreach ( $ duplicateMatchers as $ segmentDepth => $ matcher ) { $ commonMatchers [ $ segmentDepth ] -> mergeParameterKeys ( $ matcher ) ; } if ( \ count ( $ specificMatchers ) === 0 && $ node -> isParentNode ( ) ) { foreach ( $ node -> getContents ( ) -> getChildren ( ) as $ childNode ) { $ children [ ] = $ childNode ; } } else { $ children [ ] = $ node -> update ( $ specificMatchers , $ node -> getContents ( ) ) ; } } return new RouteTreeNode ( $ commonMatchers , new ChildrenNodeCollection ( $ children ) ) ; }

Extract parent nodes from route tree nood.

@param \Viserio\Component\Routing\TreeGenerator\RouteTreeNode $node1
@param \Viserio\Component\Routing\TreeGenerator\RouteTreeNode $node2

@return null|\Viserio\Component\Routing\TreeGenerator\RouteTreeNode

Extract parent nodes from route tree nood .


public function getSqlWithParams($quotationChar = '<>'): string
    {
        if (($l = \mb_strlen($quotationChar)) > 1) {
            $quoteLeft  = \mb_substr($quotationChar, 0, $l / 2);
            $quoteRight = \mb_substr($quotationChar, $l / 2);
        } else {
            $quoteLeft = $quoteRight = $quotationChar;
        }
        $sql = $this->sql;

        foreach ($this->parameters as $k => $v) {
            $v = "{$quoteLeft}{$v}{$quoteRight}";

            if (! \is_numeric($k)) {
                $sql = \str_replace($k, $v, $sql);
            } else {
                $p   = \mb_strpos($sql, '?');
                $sql = \mb_substr($sql, 0, $p) . $v . \mb_substr($sql, $p + 1);
            }
        }

        return $sql;
    }

public function getSqlWithParams ( $ quotationChar = '<>' ) : string { if ( ( $ l = \ mb_strlen ( $ quotationChar ) ) > 1 ) { $ quoteLeft = \ mb_substr ( $ quotationChar , 0 , $ l / 2 ) ; $ quoteRight = \ mb_substr ( $ quotationChar , $ l / 2 ) ; } else { $ quoteLeft = $ quoteRight = $ quotationChar ; } $ sql = $ this -> sql ; foreach ( $ this -> parameters as $ k => $ v ) { $ v = "{$quoteLeft}{$v}{$quoteRight}" ; if ( ! \ is_numeric ( $ k ) ) { $ sql = \ str_replace ( $ k , $ v , $ sql ) ; } else { $ p = \ mb_strpos ( $ sql , '?' ) ; $ sql = \ mb_substr ( $ sql , 0 , $ p ) . $ v . \ mb_substr ( $ sql , $ p + 1 ) ; } } return $ sql ; }

Returns the SQL string with any parameters used embedded.

@param string $quotationChar

@return string

Returns the SQL string with any parameters used embedded .


public static function tryFopen(string $filename, string $mode)
    {
        $ex = null;

        \set_error_handler(static function () use ($filename, $mode, &$ex): void {
            $ex = new RuntimeException(\sprintf(
                'Unable to open [%s] using mode %s: %s',
                $filename,
                $mode,
                \func_get_args()[1]
            ));
        });

        $handle = \fopen($filename, $mode);

        \restore_error_handler();

        if ($ex instanceof Throwable) {
            // @var $ex \RuntimeException
            throw $ex;
        }

        return $handle;
    }

public
static
function
tryFopen
(
string
$
filename
,
string
$
mode
)
{
$
ex
=
;
\
set_error_handler
(
static
function
(
)
use
(
$
filename
,
$
mode
,
&
$
ex
)
:
void
{
$
ex
=
new
RuntimeException
(
\
sprintf
(
'Unable to open [%s] using mode %s: %s'
,
$
filename
,
$
mode
,
\
func_get_args
(
)
[
1
]
)
)
;
}
)
;
$
handle
=
\
fopen
(
$
filename
,
$
mode
)
;
\
restore_error_handler
(
)
;
if
(
$
ex
instanceof
Throwable
)
{
// @var $ex \RuntimeException
throw
$
ex
;
}
return
$
handle
;
}

Safely opens a PHP stream resource using a filename.

When fopen fails, PHP normally raises a warning. This function adds an
error handler that checks for errors and throws an exception instead.

@param string $filename File to open
@param string $mode     Mode used to open the file

@throws \Viserio\Component\Contract\Http\Exception\RuntimeException if the file cannot be opened

@return false|resource

Safely opens a PHP stream resource using a filename .


public static function createStreamFor($resource = '', array $options = []): StreamInterface
    {
        if (\is_scalar($resource)) {
            $stream = self::tryFopen('php://temp', 'r+');

            if ($resource !== '') {
                \fwrite($stream, (string) $resource);
                \fseek($stream, 0);
            }

            return new Stream($stream, $options);
        }

        $type = \gettype($resource);

        if ($type === 'resource') {
            return new Stream($resource, $options);
        }

        if ($type === 'object') {
            if ($resource instanceof StreamInterface) {
                return $resource;
            }

            if ($resource instanceof Iterator) {
                return new PumpStream(static function () use ($resource) {
                    if (! $resource->valid()) {
                        return false;
                    }

                    $result = $resource->current();
                    $resource->next();

                    return $result;
                }, $options);
            }

            if (\method_exists($resource, '__toString')) {
                return self::createStreamFor($resource->__toString(), $options);
            }
        }

        if ($type === 'NULL') {
            return new Stream(self::tryFopen('php://temp', 'r+'), $options);
        }

        if (\is_callable($resource)) {
            return new PumpStream($resource, $options);
        }

        throw new InvalidArgumentException('Invalid resource type: ' . \gettype($resource));
    }

public
static
function
createStreamFor
(
$
resource
=
''
,
array
$
options
=
[
]
)
:
StreamInterface
{
if
(
\
is_scalar
(
$
resource
)
)
{
$
stream
=
self
::
tryFopen
(
'php://temp'
,
'r+'
)
;
if
(
$
resource
!==
''
)
{
\
fwrite
(
$
stream
,
(
string
)
$
resource
)
;
\
fseek
(
$
stream
,
0
)
;
}
return
new
Stream
(
$
stream
,
$
options
)
;
}
$
type
=
\
gettype
(
$
resource
)
;
if
(
$
type
===
'resource'
)
{
return
new
Stream
(
$
resource
,
$
options
)
;
}
if
(
$
type
===
'object'
)
{
if
(
$
resource
instanceof
StreamInterface
)
{
return
$
resource
;
}
if
(
$
resource
instanceof
Iterator
)
{
return
new
PumpStream
(
static
function
(
)
use
(
$
resource
)
{
if
(
!
$
resource
->
valid
(
)
)
{
return
false
;
}
$
result
=
$
resource
->
current
(
)
;
$
resource
->
next
(
)
;
return
$
result
;
}
,
$
options
)
;
}
if
(
\
method_exists
(
$
resource
,
'__toString'
)
)
{
return
self
::
createStreamFor
(
$
resource
->
__toString
(
)
,
$
options
)
;
}
}
if
(
$
type
===
'NULL'
)
{
return
new
Stream
(
self
::
tryFopen
(
'php://temp'
,
'r+'
)
,
$
options
)
;
}
if
(
\
is_callable
(
$
resource
)
)
{
return
new
PumpStream
(
$
resource
,
$
options
)
;
}
throw
new
InvalidArgumentException
(
'Invalid resource type: '
.
\
gettype
(
$
resource
)
)
;
}

Create a new stream based on the input type.

Options is an associative array that can contain the following keys:
- metadata: Array of custom metadata.
- size: Size of the stream.

@param null|bool|callable|float|int|\Iterator|resource|StreamInterface|string $resource Entity body data
@param array                                                                  $options  Additional options

@throws \Viserio\Component\Contract\Http\Exception\InvalidArgumentException if the $resource arg is not valid

@return \Psr\Http\Message\StreamInterface

Create a new stream based on the input type .


public static function copyToString(StreamInterface $stream, int $maxLen = -1): string
    {
        $buffer = '';

        if ($maxLen === -1) {
            while (! $stream->eof()) {
                $buf = $stream->read(1048576);
                // Using a loose equality here to match on '' and false.
                if (empty($buf)) {
                    break;
                }

                $buffer .= $buf;
            }

            return $buffer;
        }

        $len = 0;

        while (! $stream->eof() && $len < $maxLen) {
            $buf = $stream->read($maxLen - $len);
            // Using a loose equality here to match on '' and false.
            if (empty($buf)) {
                break;
            }

            $buffer .= $buf;
            $len = \strlen($buffer);
        }

        return $buffer;
    }

Copy the contents of a stream into a string until the given number of
bytes have been read.

@param \Psr\Http\Message\StreamInterface $stream Stream to read
@param int                               $maxLen Maximum number of bytes to read. Pass -1
to read the entire stream.

@throws \RuntimeException

@return string

Copy the contents of a stream into a string until the given number of bytes have been read .


public static function copyToStream(StreamInterface $source, StreamInterface $dest, int $maxLen = -1): void
    {
        if ($maxLen === -1) {
            while (! $source->eof()) {
                if (! (bool) $dest->write($source->read(1048576))) {
                    break;
                }
            }

            return;
        }

        $bufferSize = 8192;

        if ($maxLen === -1) {
            while (! $source->eof()) {
                if (! (bool) $dest->write($source->read($bufferSize))) {
                    break;
                }
            }
        } else {
            $remaining = $maxLen;

            while ($remaining > 0 && ! $source->eof()) {
                $buf = $source->read(\min($bufferSize, $remaining));
                $len = \strlen($buf);

                if (! $len) {
                    break;
                }

                $remaining -= $len;
                $dest->write($buf);
            }
        }
    }

public static function copyToStream ( StreamInterface $ source , StreamInterface $ dest , int $ maxLen = - 1 ) : void { if ( $ maxLen === - 1 ) { while ( ! $ source -> eof ( ) ) { if ( ! ( bool ) $ dest -> write ( $ source -> read ( 1048576 ) ) ) { break ; } } return ; } $ bufferSize = 8192 ; if ( $ maxLen === - 1 ) { while ( ! $ source -> eof ( ) ) { if ( ! ( bool ) $ dest -> write ( $ source -> read ( $ bufferSize ) ) ) { break ; } } } else { $ remaining = $ maxLen ; while ( $ remaining > 0 && ! $ source -> eof ( ) ) { $ buf = $ source -> read ( \ min ( $ bufferSize , $ remaining ) ) ; $ len = \ strlen ( $ buf ) ; if ( ! $ len ) { break ; } $ remaining -= $ len ; $ dest -> write ( $ buf ) ; } } }

Copy the contents of a stream into another stream until the given number
of bytes have been read.

@param \Psr\Http\Message\StreamInterface $source Stream to read from
@param \Psr\Http\Message\StreamInterface $dest   Stream to write to
@param int                               $maxLen Maximum number of bytes to read. Pass -1
to read the entire stream.

@throws \RuntimeException

Copy the contents of a stream into another stream until the given number of bytes have been read .


public static function readline(StreamInterface $stream, int $maxLength = null): string
    {
        $buffer = '';
        $size   = 0;

        while (! $stream->eof()) {
            $byte = $stream->read(1);
            // Using a loose equality here to match on '' and false.
            if ($byte === '' || $byte === false || $byte === null) {
                return $buffer;
            }

            $buffer .= $byte;

            // Break when a new line is found or the max length - 1 is reached
            if ($byte === "\n" || ++$size === $maxLength - 1) {
                break;
            }
        }

        return $buffer;
    }

Read a line from the stream up to the maximum allowed buffer length.

@param \Psr\Http\Message\StreamInterface $stream    Stream to read from
@param int                               $maxLength Maximum buffer length

@return string

Read a line from the stream up to the maximum allowed buffer length .


public function setDefaultPathAndDomain(string $path, string $domain, bool $secure = false): self
    {
        [$this->path, $this->domain, $this->secure] = [$path, $domain, $secure];

        return $this;
    }

public function setDefaultPathAndDomain ( string $ path , string $ domain , bool $ secure = false ) : self { [ $ this -> path , $ this -> domain , $ this -> secure ] = [ $ path , $ domain , $ secure ] ; return $ this ; }

Set the default path and domain for the jar.

@param string $path
@param string $domain
@param bool   $secure

@return $this

Set the default path and domain for the jar .


protected function getPathAndDomain(?string $path, ?string $domain, bool $secure = false): array
    {
        return [$path ?? $this->path, $domain ?? $this->domain, $secure ?? $this->secure];
    }

protected function getPathAndDomain ( ? string $ path , ? string $ domain , bool $ secure = false ) : array { return [ $ path ?? $ this -> path , $ domain ?? $ this -> domain , $ secure ?? $ this -> secure ] ; }

Get the path and domain, or the default values.

@param null|string $path
@param null|string $domain
@param bool        $secure

@return array

Get the path and domain or the default values .


protected function getHandler(): Handler
    {
        $handler = new PrettyPageHandler();

        $handler->handleUnconditionally(true);

        foreach ($this->resolvedOptions['blacklist'] as $key => $secrets) {
            foreach ($secrets as $secret) {
                $handler->blacklist($key, $secret);
            }
        }

        $handler->setApplicationPaths($this->resolvedOptions['application_paths']);

        return $handler;
    }

protected function getHandler ( ) : Handler { $ handler = new PrettyPageHandler ( ) ; $ handler -> handleUnconditionally ( true ) ; foreach ( $ this -> resolvedOptions [ 'blacklist' ] as $ key => $ secrets ) { foreach ( $ secrets as $ secret ) { $ handler -> blacklist ( $ key , $ secret ) ; } } $ handler -> setApplicationPaths ( $ this -> resolvedOptions [ 'application_paths' ] ) ; return $ handler ; }

Get the Whoops handler.

@return \Whoops\Handler\Handler


private function updateHostFromUri(): void
    {
        $host = $this->uri->getHost();

        if ($host === '') {
            return;
        }

        if (($port = $this->uri->getPort()) !== null) {
            $host .= ':' . $port;
        }

        $this->headerNames['host'] = 'Host';

        // Remove an existing host header if present, regardless of current
        // de-normalization of the header name.
        // @see https://github.com/zendframework/zend-diactoros/issues/91
        foreach (\array_keys($this->headers) as $oldHeader) {
            if (\strtolower($oldHeader) === 'host') {
                unset($this->headers[$oldHeader]);
            }
        }

        // Ensure Host is the first header.
        // See: http://tools.ietf.org/html/rfc7230#section-5.4
        $this->headers = ['Host' => [$host]] + $this->headers;
    }

Retrieve the host from the URI instance.

@return void

Retrieve the host from the URI instance .


private function filterMethod(?string $method): string
    {
        if ($method === null) {
            return self::METHOD_GET;
        }

        if (! \preg_match("/^[!#$%&'*+.^_`|~0-9a-z-]+$/i", $method)) {
            throw new InvalidArgumentException(\sprintf(
                'Unsupported HTTP method [%s].',
                $method
            ));
        }

        return $method;
    }

private
function
filterMethod
(
string
$
method
)
:
string
{
if
(
$
method
===
)
{
return
self
::
METHOD_GET
;
}
if
(
!
\
preg_match
(
"/^[!#$%&'*+.^_`|~0-9a-z-]+$/i"
,
$
method
)
)
{
throw
new
InvalidArgumentException
(
\
sprintf
(
'Unsupported HTTP method [%s].'
,
$
method
)
)
;
}
return
$
method
;
}

Validate the HTTP method.

@param null|string $method

@throws \Viserio\Component\Contract\Http\Exception\InvalidArgumentException on invalid HTTP method

@return string


private function createUri($uri): UriInterface
    {
        if ($uri instanceof UriInterface) {
            return $uri;
        }

        if (\is_string($uri)) {
            return Uri::createFromString($uri);
        }

        if ($uri === null) {
            return Uri::createFromString();
        }

        throw new InvalidArgumentException(
            'Invalid URI provided; must be null, a string or a [\Psr\Http\Message\UriInterface] instance.'
        );
    }

Create and return a URI instance.

If `$uri` is a already a `UriInterface` instance, returns it.

If `$uri` is a string, passes it to the `Uri` constructor to return an
instance.

If `$uri is null, creates and returns an empty `Uri` instance.

Otherwise, it raises an exception.

@param null|string|UriInterface $uri

@throws \Viserio\Component\Contract\Http\Exception\InvalidArgumentException

@return \Psr\Http\Message\UriInterface


public function withoutExtension(string $path, string $extension = null): string
    {
        $path = $this->getTransformedPath($path);

        if ($extension !== null) {
            // remove extension and trailing dot
            return \rtrim(\basename($path, $extension), '.');
        }

        return \pathinfo($path, \PATHINFO_FILENAME);
    }

public
function
withoutExtension
(
string
$
path
,
string
$
extension
=
)
:
string
{
$
path
=
$
this
->
getTransformedPath
(
$
path
)
;
if
(
$
extension
!==
)
{
// remove extension and trailing dot
return
\
rtrim
(
\
basename
(
$
path
,
$
extension
)
,
'.'
)
;
}
return
\
pathinfo
(
$
path
,
\
PATHINFO_FILENAME
)
;
}

Returns the filename without the extension from a file path.

@param string      $path      The path string
@param null|string $extension If specified, only that extension is cut off
(may contain leading dot)

@return string Filename without extension

Returns the filename without the extension from a file path .


public function changeExtension(string $path, string $extension): string
    {
        $path = $this->getTransformedPath($path);

        $explode    = \explode('.', $path);
        $substrPath = \mb_substr($path, -1);

        // No extension for paths
        if ($substrPath === '/' || \is_dir($path)) {
            return $path;
        }

        $actualExtension = null;
        $extension       = \ltrim($extension, '.');

        if (\count($explode) >= 2 && ! \is_dir($path)) {
            $actualExtension = \mb_strtolower($extension);
        }

        // No actual extension in path
        if ($actualExtension === null) {
            return $path . ($substrPath === '.' ? '' : '.') . $extension;
        }

        return \mb_substr($path, 0, -\mb_strlen($actualExtension)) . $extension;
    }

public
function
changeExtension
(
string
$
path
,
string
$
extension
)
:
string
{
$
path
=
$
this
->
getTransformedPath
(
$
path
)
;
$
explode
=
\
explode
(
'.'
,
$
path
)
;
$
substrPath
=
\
mb_substr
(
$
path
,
1
)
;
// No extension for paths
if
(
$
substrPath
===
'/'
||
\
is_dir
(
$
path
)
)
{
return
$
path
;
}
$
actualExtension
=
;
$
extension
=
\
ltrim
(
$
extension
,
'.'
)
;
if
(
\
count
(
$
explode
)
>=
2
&&
!
\
is_dir
(
$
path
)
)
{
$
actualExtension
=
\
mb_strtolower
(
$
extension
)
;
}
// No actual extension in path
if
(
$
actualExtension
===
)
{
return
$
path
.
(
$
substrPath
===
'.'
''
:
'.'
)
.
$
extension
;
}
return
\
mb_substr
(
$
path
,
0
,
\
mb_strlen
(
$
actualExtension
)
)
.
$
extension
;
}

Changes the extension of a path string.

@param string $path      The path string with filename.ext to change
@param string $extension New extension (with or without leading dot)

@return string The path string with new file extension

Changes the extension of a path string .


public static function createCacheManager(ContainerInterface $container): CacheManagerContract
    {
        $cache = new CacheManager($container->get('config'));
        $cache->setContainer($container);

        return $cache;
    }

public static function createCacheManager ( ContainerInterface $ container ) : CacheManagerContract { $ cache = new CacheManager ( $ container -> get ( 'config' ) ) ; $ cache -> setContainer ( $ container ) ; return $ cache ; }

Create a cache manger instance.

@param \Psr\Container\ContainerInterface $container

@return \Viserio\Component\Contract\Cache\Manager


public static function shouldReceive()
    {
        $name = static::getInstanceIdentifier();

        if (static::isMock()) {
            $mock = static::$resolvedInstance[$name];
        } else {
            $mock = static::createFreshMockInstance($name);
        }

        return $mock->shouldReceive(...\func_get_args());
    }

public static function shouldReceive ( ) { $ name = static :: getInstanceIdentifier ( ) ; if ( static :: isMock ( ) ) { $ mock = static :: $ resolvedInstance [ $ name ] ; } else { $ mock = static :: createFreshMockInstance ( $ name ) ; } return $ mock -> shouldReceive ( ... \ func_get_args ( ) ) ; }

Initiate a mock expectation on the static proxy.

@return \Mockery\ExpectationInterface|\Mockery\HigherOrderMessage

Initiate a mock expectation on the static proxy .


protected static function resolveStaticalProxyInstance($name): object
    {
        if (\is_object($name)) {
            return $name;
        }

        if (isset(static::$resolvedInstance[$name])) {
            return static::$resolvedInstance[$name];
        }

        return static::$resolvedInstance[$name] = static::$container->get($name);
    }

protected static function resolveStaticalProxyInstance ( $ name ) : object { if ( \ is_object ( $ name ) ) { return $ name ; } if ( isset ( static :: $ resolvedInstance [ $ name ] ) ) { return static :: $ resolvedInstance [ $ name ] ; } return static :: $ resolvedInstance [ $ name ] = static :: $ container -> get ( $ name ) ; }

Resolve the statical proxy root instance from the app.

@param object|string $name

@return object

Resolve the statical proxy root instance from the app .


protected static function isMock(): bool
    {
        $name = static::getInstanceIdentifier();

        return isset(static::$resolvedInstance[$name]) &&
                static::$resolvedInstance[$name] instanceof MockInterface;
    }

protected static function isMock ( ) : bool { $ name = static :: getInstanceIdentifier ( ) ; return isset ( static :: $ resolvedInstance [ $ name ] ) && static :: $ resolvedInstance [ $ name ] instanceof MockInterface ; }

Determines whether a mock is set as the instance of the static proxy.

@return bool

Determines whether a mock is set as the instance of the static proxy .


protected function inflectSegment($command, int $segment): string
    {
        $className = \get_class($command);

        // Get the given segment from a given class handler.
        if (isset($this->mappings[$className])) {
            return \explode('@', $this->mappings[$className])[$segment];
        }

        // Get the given segment from a given class handler using the custom mapper.
        if (\is_callable($this->mapper)) {
            return \explode('@', \call_user_func($this->mapper, [$command]))[$segment];
        }

        throw new InvalidArgumentException(\sprintf('No handler registered for command [%s].', $className));
    }

Get the given handler segment for the given command.

@param mixed $command
@param int   $segment

@throws \InvalidArgumentException

@return string

Get the given handler segment for the given command .


public function setFile(
        $file,
        string $contentDisposition = null,
        bool $autoETag             = false,
        bool $autoLastModified     = true
    ): ResponseInterface {
        if (! $file instanceof File) {
            if ($file instanceof SplFileInfo) {
                $file = new File($file->getPathname());
            } elseif (\is_string($file)) {
                $file = new File($file);
            } else {
                throw new InvalidArgumentException(\sprintf(
                    'Invalid content [%s] provided to %s.',
                    (\is_object($file) ? \get_class($file) : \gettype($file)),
                    __CLASS__
                ));
            }
        }

        if (! $file->isReadable()) {
            throw new FileException('File must be readable.');
        }

        $this->file = $file;

        if ($autoETag === true) {
            $this->setAutoEtag();
        }

        if ($autoLastModified === true) {
            $this->setAutoLastModified();
        }

        if ($contentDisposition) {
            $this->headers['Content-Length']      = [$this->file->getSize()];
            $this->headers['Content-Disposition'] = [
                InteractsWithDisposition::makeDisposition(
                    $contentDisposition,
                    $this->file->getFilename(),
                    InteractsWithDisposition::encodedFallbackFilename($this->file->getFilename())
                ),
            ];

            $this->headerNames['content-length']      = 'Content-Length';
            $this->headerNames['content-disposition'] = 'Content-Disposition';

            if (! $this->hasHeader('Content-Type')) {
                $this->headers['Content-Type']     = [$this->file->getMimeType() ?? 'application/octet-stream'];
                $this->headerNames['content-type'] = 'Content-Type';
            }
        }

        return $this;
    }

public
function
setFile
(
$
file
,
string
$
contentDisposition
=
,
bool
$
autoETag
=
false
,
bool
$
autoLastModified
=
true
)
:
ResponseInterface
{
if
(
!
$
file
instanceof
File
)
{
if
(
$
file
instanceof
SplFileInfo
)
{
$
file
=
new
File
(
$
file
->
getPathname
(
)
)
;
}
elseif
(
\
is_string
(
$
file
)
)
{
$
file
=
new
File
(
$
file
)
;
}
else
{
throw
new
InvalidArgumentException
(
\
sprintf
(
'Invalid content [%s] provided to %s.'
,
(
\
is_object
(
$
file
)
\
get_class
(
$
file
)
:
\
gettype
(
$
file
)
)
,
__CLASS__
)
)
;
}
}
if
(
!
$
file
->
isReadable
(
)
)
{
throw
new
FileException
(
'File must be readable.'
)
;
}
$
this
->
file
=
$
file
;
if
(
$
autoETag
===
true
)
{
$
this
->
setAutoEtag
(
)
;
}
if
(
$
autoLastModified
===
true
)
{
$
this
->
setAutoLastModified
(
)
;
}
if
(
$
contentDisposition
)
{
$
this
->
headers
[
'Content-Length'
]
=
[
$
this
->
file
->
getSize
(
)
]
;
$
this
->
headers
[
'Content-Disposition'
]
=
[
InteractsWithDisposition
::
makeDisposition
(
$
contentDisposition
,
$
this
->
file
->
getFilename
(
)
,
InteractsWithDisposition
::
encodedFallbackFilename
(
$
this
->
file
->
getFilename
(
)
)
)
,
]
;
$
this
->
headerNames
[
'content-length'
]
=
'Content-Length'
;
$
this
->
headerNames
[
'content-disposition'
]
=
'Content-Disposition'
;
if
(
!
$
this
->
hasHeader
(
'Content-Type'
)
)
{
$
this
->
headers
[
'Content-Type'
]
=
[
$
this
->
file
->
getMimeType
(
)
??
'application/octet-stream'
]
;
$
this
->
headerNames
[
'content-type'
]
=
'Content-Type'
;
}
}
return
$
this
;
}

Transform a SplFileInfo to a Http File and check if the file exists.

@param \SplFileInfo|string|\Viserio\Component\Http\File\File $file
@param string                                                $contentDisposition
@param bool                                                  $autoETag
@param bool                                                  $autoLastModified

@throws \Viserio\Component\Contract\Http\Exception\FileNotFoundException
@throws \Viserio\Component\Contract\Http\Exception\InvalidArgumentException
@throws \Viserio\Component\Contract\Http\Exception\FileException

@return \Psr\Http\Message\ResponseInterface

Transform a SplFileInfo to a Http File and check if the file exists .


public function setContentDisposition(
        string $disposition,
        string $filename         = '',
        string $filenameFallback = ''
    ): ResponseInterface {
        if ($filenameFallback === '') {
            $filenameFallback = InteractsWithDisposition::encodedFallbackFilename($filename);
        }

        return InteractsWithDisposition::appendDispositionHeader($this, $disposition, $filename, $filenameFallback);
    }

public function setContentDisposition ( string $ disposition , string $ filename = '' , string $ filenameFallback = '' ) : ResponseInterface { if ( $ filenameFallback === '' ) { $ filenameFallback = InteractsWithDisposition :: encodedFallbackFilename ( $ filename ) ; } return InteractsWithDisposition :: appendDispositionHeader ( $ this , $ disposition , $ filename , $ filenameFallback ) ; }

Sets the Content-Disposition header with the given filename.

@param string $disposition      ResponseHeaderBag::DISPOSITION_INLINE or ResponseHeaderBag::DISPOSITION_ATTACHMENT
@param string $filename         Optionally use this UTF-8 encoded filename instead of the real name of the file
@param string $filenameFallback A fallback filename, containing only ASCII characters. Defaults to an automatically encoded filename

@throws \InvalidArgumentException

@return \Psr\Http\Message\ResponseInterface

Sets the Content - Disposition header with the given filename .


protected function setAutoLastModified(): void
    {
        $date = DateTime::createFromFormat('U', (string) $this->file->getMTime());
        $date = DateTimeImmutable::createFromMutable($date);
        $date = $date->setTimezone(new \DateTimeZone('UTC'));

        $this->headers['Last-Modified']     = [$date->format('D, d M Y H:i:s') . ' GMT'];
        $this->headerNames['last-modified'] = 'Last-Modified';
    }

protected
function
setAutoLastModified
(
)
:
void
{
$
date
=
DateTime
::
createFromFormat
(
'U'
,
(
string
)
$
this
->
file
->
getMTime
(
)
)
;
$
date
=
DateTimeImmutable
::
createFromMutable
(
$
date
)
;
$
date
=
$
date
->
setTimezone
(
new
\
DateTimeZone
(
'UTC'
)
)
;
$
this
->
headers
[
'Last-Modified'
]
=
[
$
date
->
format
(
'D, d M Y H:i:s'
)
.
' GMT'
]
;
$
this
->
headerNames
[
'last-modified'
]
=
'Last-Modified'
;
}

Automatically sets the Last-Modified header according the file modification date.

@return void

Automatically sets the Last - Modified header according the file modification date .


public function withValue(?string $value = null): Cookie
    {
        $this->validateValue($value);

        $new        = clone $this;
        $new->value = $value;

        return $new;
    }

public function withValue ( ? string $ value = null ) : Cookie { $ this -> validateValue ( $ value ) ; $ new = clone $ this ; $ new -> value = $ value ; return $ new ; }

Sets the value.

@param null|string $value

@return $this


public function describe(OutputInterface $output, $object, array $options = []): void
    {
        /** @var Application $application */
        $application = $object->getApplication();

        $this->describeTitle($application, $output);

        $describedNamespace = $options['namespace'] ?? null;

        if ($describedNamespace !== null) {
            $output->write(\sprintf(
                "<comment>Available commands for the [%s] namespace</comment>\n\n",
                $describedNamespace
            ));
        }

        $this->describeUsage($output);
        $this->describeCommands($application, $object, $options);
    }

Describes an object if supported.

@param \Symfony\Component\Console\Output\OutputInterface  $output
@param \Viserio\Component\Console\Command\AbstractCommand $object
@param array                                              $options

@return void


private function describeCommands(Application $application, AbstractCommand $command, array $options): void
    {
        $description = new ApplicationDescription(
            $application,
            $options['namespace'] ?? null,
            $options['show-hidden'] ?? false
        );

        Table::setStyleDefinition('zero', self::getZeroBorderStyle());

        $rows                        = [];
        $namespaceSortedCommandInfos = $this->getNamespaceSortedCommandInfos(
            $description->getCommands()
        );

        foreach ($namespaceSortedCommandInfos as $namespace => $infos) {
            $stringCommands     = '';
            $stringDescriptions = '';

            foreach ($infos as $info) {
                $description = '';

                if ($options['show-description'] ?? false) {
                    $description = $info['description'];
                }

                $stringCommands     .= '<fg=green>' . $info['command'] . "</>\n";
                $stringDescriptions .= $description . "\n";
            }

            $rows[] = [$namespace, $stringCommands, $stringDescriptions];
        }

        $command->table([], $rows, 'zero');
    }

private function describeCommands ( Application $ application , AbstractCommand $ command , array $ options ) : void { $ description = new ApplicationDescription ( $ application , $ options [ 'namespace' ] ?? null , $ options [ 'show-hidden' ] ?? false ) ; Table :: setStyleDefinition ( 'zero' , self :: getZeroBorderStyle ( ) ) ; $ rows = [ ] ; $ namespaceSortedCommandInfos = $ this -> getNamespaceSortedCommandInfos ( $ description -> getCommands ( ) ) ; foreach ( $ namespaceSortedCommandInfos as $ namespace => $ infos ) { $ stringCommands = '' ; $ stringDescriptions = '' ; foreach ( $ infos as $ info ) { $ description = '' ; if ( $ options [ 'show-description' ] ?? false ) { $ description = $ info [ 'description' ] ; } $ stringCommands .= '<fg=green>' . $ info [ 'command' ] . "</>\n" ; $ stringDescriptions .= $ description . "\n" ; } $ rows [ ] = [ $ namespace , $ stringCommands , $ stringDescriptions ] ; } $ command -> table ( [ ] , $ rows , 'zero' ) ; }

Describes the application commands.

@param \Viserio\Component\Console\Application             $application
@param \Viserio\Component\Console\Command\AbstractCommand $command
@param array                                              $options

@return void


private function getNamespaceSortedCommandInfos(array $commands): array
    {
        $namespaceSortedInfos = [];
        $regex                = '/^(.*)\:/';
        $binary               = Application::cerebroBinary();

        /** @var AbstractCommand $command */
        foreach ($commands as $name => $command) {
            \preg_match($regex, $name, $matches, \PREG_OFFSET_CAPTURE);

            $commandInfo = [
                'command'     => $binary . ' ' . $command->getSynopsis(),
                'description' => $command->getDescription(),
            ];

            if (\count($matches) === 0) {
                $namespaceSortedInfos[$name][] = $commandInfo;
            } else {
                $namespaceSortedInfos[$matches[1][0]][] = $commandInfo;
            }
        }

        return $namespaceSortedInfos;
    }

private
function
getNamespaceSortedCommandInfos
(
array
$
commands
)
:
array
{
$
namespaceSortedInfos
=
[
]
;
$
regex
=
'/^(.*)\:/'
;
$
binary
=
Application
::
cerebroBinary
(
)
;
/** @var AbstractCommand $command */
foreach
(
$
commands
as
$
name
=>
$
command
)
{
\
preg_match
(
$
regex
,
$
name
,
$
matches
,
\
PREG_OFFSET_CAPTURE
)
;
$
commandInfo
=
[
'command'
=>
$
binary
.
' '
.
$
command
->
getSynopsis
(
)
,
'description'
=>
$
command
->
getDescription
(
)
,
]
;
if
(
\
count
(
$
matches
)
===
0
)
{
$
namespaceSortedInfos
[
$
name
]
[
]
=
$
commandInfo
;
}
else
{
$
namespaceSortedInfos
[
$
matches
[
1
]
[
0
]
]
[
]
=
$
commandInfo
;
}
}
return
$
namespaceSortedInfos
;
}

Sort all application commands on namespace.

@param array $commands

@return array

Sort all application commands on namespace .


protected function createCookieTab(ServerRequestInterface $serverRequest, ResponseInterface $response): array
    {
        if (! (\class_exists(RequestCookies::class) && \class_exists(ResponseCookies::class))) {
            return [];
        }

        $requestCookies = $responseCookies = [];

        /** @var Cookie $cookie */
        foreach (RequestCookies::fromRequest($serverRequest)->getAll() as $cookie) {
            $requestCookies[$cookie->getName()] = $cookie->getValue();
        }

        /** @var CookieContract $cookie */
        foreach (ResponseCookies::fromResponse($response)->getAll() as $cookie) {
            $responseCookies[$cookie->getName()] = $cookie->getValue();
        }

        return [
            'name'    => 'Cookies',
            'content' => $this->createTable(
                $requestCookies,
                [
                    'name'       => 'Request Cookies',
                    'empty_text' => 'No request cookies',
                ]
            ) . $this->createTable(
                $responseCookies,
                [
                    'name'       => 'Response Cookies',
                    'empty_text' => 'No response cookies',
                ]
            ),
        ];
    }

protected
function
createCookieTab
(
ServerRequestInterface
$
serverRequest
,
ResponseInterface
$
response
)
:
array
{
if
(
!
(
\
class_exists
(
RequestCookies
::
class
)
&&
\
class_exists
(
ResponseCookies
::
class
)
)
)
{
return
[
]
;
}
$
requestCookies
=
$
responseCookies
=
[
]
;
/** @var Cookie $cookie */
foreach
(
RequestCookies
::
fromRequest
(
$
serverRequest
)
->
getAll
(
)
as
$
cookie
)
{
$
requestCookies
[
$
cookie
->
getName
(
)
]
=
$
cookie
->
getValue
(
)
;
}
/** @var CookieContract $cookie */
foreach
(
ResponseCookies
::
fromResponse
(
$
response
)
->
getAll
(
)
as
$
cookie
)
{
$
responseCookies
[
$
cookie
->
getName
(
)
]
=
$
cookie
->
getValue
(
)
;
}
return
[
'name'
=>
'Cookies'
,
'content'
=>
$
this
->
createTable
(
$
requestCookies
,
[
'name'
=>
'Request Cookies'
,
'empty_text'
=>
'No request cookies'
,
]
)
.
$
this
->
createTable
(
$
responseCookies
,
[
'name'
=>
'Response Cookies'
,
'empty_text'
=>
'No response cookies'
,
]
)
,
]
;
}

Prepare request and response cookie infos and create a cookie tab.

@param \Psr\Http\Message\ServerRequestInterface $serverRequest
@param \Psr\Http\Message\ResponseInterface      $response

@return array

Prepare request and response cookie infos and create a cookie tab .


protected function prepareRequestAttributes(array $attributes): array
    {
        $preparedAttributes = [];

        foreach ($attributes as $key => $value) {
            if ($key === '_route') {
                if (\is_object($value) && $value instanceof RouteContract) {
                    /** @var RouteContract $route */
                    $route = $value;
                    $value = [
                        'Uri'        => $route->getUri(),
                        'Parameters' => $route->getParameters(),
                    ];
                }

                $preparedAttributes[$key] = $value;
            } elseif ($value instanceof StoreContract) {
                $preparedAttributes[$key] = $value->getId();
            } else {
                $preparedAttributes[$key] = $value;
            }
        }

        return $preparedAttributes;
    }

protected
function
prepareRequestAttributes
(
array
$
attributes
)
:
array
{
$
preparedAttributes
=
[
]
;
foreach
(
$
attributes
as
$
key
=>
$
value
)
{
if
(
$
key
===
'_route'
)
{
if
(
\
is_object
(
$
value
)
&&
$
value
instanceof
RouteContract
)
{
/** @var RouteContract $route */
$
route
=
$
value
;
$
value
=
[
'Uri'
=>
$
route
->
getUri
(
)
,
'Parameters'
=>
$
route
->
getParameters
(
)
,
]
;
}
$
preparedAttributes
[
$
key
]
=
$
value
;
}
elseif
(
$
value
instanceof
StoreContract
)
{
$
preparedAttributes
[
$
key
]
=
$
value
->
getId
(
)
;
}
else
{
$
preparedAttributes
[
$
key
]
=
$
value
;
}
}
return
$
preparedAttributes
;
}

Prepare request attributes, check of route object.

@param array $attributes

@return array

Prepare request attributes check of route object .


protected function prepareRequestHeaders(array $headers): array
    {
        $preparedHeaders = [];

        foreach ($headers as $key => $value) {
            if (\count((array) $value) === 1) {
                $preparedHeaders[$key] = $value[0];
            } else {
                $preparedHeaders[$key] = $value;
            }
        }

        return $preparedHeaders;
    }

protected function prepareRequestHeaders ( array $ headers ) : array { $ preparedHeaders = [ ] ; foreach ( $ headers as $ key => $ value ) { if ( \ count ( ( array ) $ value ) === 1 ) { $ preparedHeaders [ $ key ] = $ value [ 0 ] ; } else { $ preparedHeaders [ $ key ] = $ value ; } } return $ preparedHeaders ; }

Prepare request headers.

@param array $headers

@return array


protected function prepareServerParams(array $params): array
    {
        $preparedParams = [];

        foreach ($params as $key => $value) {
            if (\preg_match('/(_KEY|_PASSWORD|_PW|_SECRET)/', $key)) {
                $preparedParams[$key] = '******';
            } else {
                $preparedParams[$key] = $value;
            }
        }

        return $preparedParams;
    }

protected function prepareServerParams ( array $ params ) : array { $ preparedParams = [ ] ; foreach ( $ params as $ key => $ value ) { if ( \ preg_match ( '/(_KEY|_PASSWORD|_PW|_SECRET)/' , $ key ) ) { $ preparedParams [ $ key ] = '******' ; } else { $ preparedParams [ $ key ] = $ value ; } } return $ preparedParams ; }

Prepare server parameter.
Hide all keys with a _KEY|_PASSWORD|_PW|_SECRET in it.

@param array $params

@return array

Prepare server parameter . Hide all keys with a _KEY|_PASSWORD|_PW|_SECRET in it .


private function getParsedBody(ServerRequestInterface $request): array
    {
        $parsedBody = $request->getParsedBody();

        if (\is_object($parsedBody)) {
            return (array) $parsedBody;
        }

        if ($parsedBody === null) {
            return [];
        }

        return $parsedBody;
    }

private function getParsedBody ( ServerRequestInterface $ request ) : array { $ parsedBody = $ request -> getParsedBody ( ) ; if ( \ is_object ( $ parsedBody ) ) { return ( array ) $ parsedBody ; } if ( $ parsedBody === null ) { return [ ] ; } return $ parsedBody ; }

Post Parameters from parsed body.

@param \Psr\Http\Message\ServerRequestInterface $request

@return array


private static function export($value): string
    {
        if (null === $value) {
            return 'null';
        }

        if (\is_bool($value)) {
            return $value ? 'true' : 'false';
        }

        if (\is_numeric($value)) {
            return '"' . $value . '"';
        }

        return \sprintf('"%s"', $value);
    }

private static function export ( $ value ) : string { if ( null === $ value ) { return 'null' ; } if ( \ is_bool ( $ value ) ) { return $ value ? 'true' : 'false' ; } if ( \ is_numeric ( $ value ) ) { return '"' . $ value . '"' ; } return \ sprintf ( '"%s"' , $ value ) ; }

Converts the supplied value into a valid ini representation.

@param mixed $value

@return string

Converts the supplied value into a valid ini representation .


public function cryptedConnection(EncryptionKey $key, string $name = null): EncryptionWrapper
    {
        return new EncryptionWrapper($this->getConnection($name), $key);
    }

public function cryptedConnection ( EncryptionKey $ key , string $ name = null ) : EncryptionWrapper { return new EncryptionWrapper ( $ this -> getConnection ( $ name ) , $ key ) ; }

Get a crypted aware connection instance.

@param \ParagonIE\Halite\Symmetric\EncryptionKey $key
@param null|string                               $name

@return \Viserio\Component\Filesystem\Encryption\EncryptionWrapper

Get a crypted aware connection instance .


protected function getCacheConfig(string $name): array
    {
        $cache = $this->resolvedOptions['cached'];

        if (! \is_array($config = ($cache[$name] ?? false)) && ! $config) {
            throw new InvalidArgumentException(\sprintf('Cache [%s] not configured.', $name));
        }

        $config['name'] = $name;

        return $config;
    }

protected
function
getCacheConfig
(
string
$
name
)
:
array
{
$
cache
=
$
this
->
resolvedOptions
[
'cached'
]
;
if
(
!
\
is_array
(
$
config
=
(
$
cache
[
$
name
]
??
false
)
)
&&
!
$
config
)
{
throw
new
InvalidArgumentException
(
\
sprintf
(
'Cache [%s] not configured.'
,
$
name
)
)
;
}
$
config
[
'name'
]
=
$
name
;
return
$
config
;
}

Get the cache configuration.

@param string $name

@throws \Viserio\Component\Contract\Filesystem\Exception\InvalidArgumentException

@return array


protected function adapt(AdapterInterface $adapter, array $config): FilesystemContract
    {
        if (isset($config['cache']) && \is_array($config['cache'])) {
            $cacheFactory = new CachedFactory($this, $this->getCacheManager());

            $adapter = new CachedAdapter($adapter, $cacheFactory->getConnection($config));

            unset($config['cache']);
        }

        return new FilesystemAdapter($adapter, $config);
    }

protected function adapt ( AdapterInterface $ adapter , array $ config ) : FilesystemContract { if ( isset ( $ config [ 'cache' ] ) && \ is_array ( $ config [ 'cache' ] ) ) { $ cacheFactory = new CachedFactory ( $ this , $ this -> getCacheManager ( ) ) ; $ adapter = new CachedAdapter ( $ adapter , $ cacheFactory -> getConnection ( $ config ) ) ; unset ( $ config [ 'cache' ] ) ; } return new FilesystemAdapter ( $ adapter , $ config ) ; }

Adapt the filesystem implementation.

@param \League\Flysystem\AdapterInterface $adapter
@param array                              $config

@return \Viserio\Component\Contract\Filesystem\Filesystem


public static function parse(string $route, array $conditions): array
    {
        if (\strlen($route) > 1 && $route[0] !== '/') {
            throw new InvalidRoutePatternException(\sprintf(
                'Invalid route pattern: non-root route must be prefixed with \'/\', \'%s\' given.',
                $route
            ));
        }

        $segments        = [];
        $matches         = [];
        $names           = [];
        $patternSegments = \explode('/', $route);

        \array_shift($patternSegments);

        foreach ($patternSegments as $key => $patternSegment) {
            if (self::matchRouteParameters($route, $patternSegment, $conditions, $matches, $names)) {
                $segments[] = new ParameterMatcher(
                    $names,
                    self::generateRegex($matches, $conditions)
                );
            } else {
                $segments[] = new StaticMatcher($patternSegment);
            }
        }

        return $segments;
    }

Parses the supplied route pattern into an array of route segments.

Example: '/user/{id}/create'
Should return: [
\Viserio\Component\Routing\Matcher\StaticMatcher{ $value => 'user' },
\Viserio\Component\Routing\Matcher\ParameterMatcher{ $name => 'id', $match => '[0-9]+' },
\Viserio\Component\Routing\Matcher\StaticMatcher{ $value => 'create' },
]

@param string   $route
@param string[] $conditions

@throws \Viserio\Component\Contract\Routing\Exception\InvalidArgumentException
@throws \Viserio\Component\Contract\Routing\Exception\InvalidRoutePatternException

@return array

Parses the supplied route pattern into an array of route segments .


private static function generateRegex(array $matches, array $parameterPatterns): string
    {
        $regex = '/^';

        foreach ($matches as $match) {
            [$type, $part] = $match;

            if ($type === self::STATIC_PART) {
                $regex .= \preg_quote($part, '/');
            } else {
                // Parameter, $part is the parameter name
                $pattern = $parameterPatterns[$part] ?? Pattern::ANY;
                $regex .= '(' . $pattern . ')';
            }
        }

        return $regex . '$/';
    }

Generate a segment regex.

@param array $matches
@param array $parameterPatterns

@return string


private function getInvoker(): InvokerInterface
    {
        if ($this->invoker === null) {
            $resolvers = \array_merge([
                new AssociativeArrayResolver(),
                new NumericArrayResolver(),
                new TypeHintResolver(),
                new DefaultValueResolver(),
            ], $this->resolvers);

            if (($container = $this->container) !== null) {
                if (isset($this->inject['type'])) {
                    $resolvers[] = new TypeHintContainerResolver($container);
                }

                if (isset($this->inject['parameter'])) {
                    $resolvers[] = new ParameterNameContainerResolver($container);
                }

                $this->invoker = new DiInvoker(new ResolverChain($resolvers), $container);
            } else {
                $this->invoker = new DiInvoker(new ResolverChain($resolvers));
            }
        }

        return $this->invoker;
    }

private function getInvoker ( ) : InvokerInterface { if ( $ this -> invoker === null ) { $ resolvers = \ array_merge ( [ new AssociativeArrayResolver ( ) , new NumericArrayResolver ( ) , new TypeHintResolver ( ) , new DefaultValueResolver ( ) , ] , $ this -> resolvers ) ; if ( ( $ container = $ this -> container ) !== null ) { if ( isset ( $ this -> inject [ 'type' ] ) ) { $ resolvers [ ] = new TypeHintContainerResolver ( $ container ) ; } if ( isset ( $ this -> inject [ 'parameter' ] ) ) { $ resolvers [ ] = new ParameterNameContainerResolver ( $ container ) ; } $ this -> invoker = new DiInvoker ( new ResolverChain ( $ resolvers ) , $ container ) ; } else { $ this -> invoker = new DiInvoker ( new ResolverChain ( $ resolvers ) ) ; } } return $ this -> invoker ; }

Get a full configured invoker class.

@return \Invoker\InvokerInterface


protected function exists($object, bool $autoload = true): bool
    {
        return \class_exists($object, $autoload)  ||
            \interface_exists($object, $autoload) ||
            \trait_exists($object, $autoload);
    }

protected function exists ( $ object , bool $ autoload = true ) : bool { return \ class_exists ( $ object , $ autoload ) || \ interface_exists ( $ object , $ autoload ) || \ trait_exists ( $ object , $ autoload ) ; }

Checks various object types for existence.

@param mixed $object
@param bool  $autoload

@return bool

Checks various object types for existence .


private function getTargetLanguageFromFile(DOMDocument $xliffContents): ?string
    {
        foreach ($xliffContents->getElementsByTagName('file')[0]->attributes ?? [] as $attribute) {
            if ($attribute->nodeName === 'target-language') {
                return $attribute->nodeValue;
            }
        }

        return null;
    }

private function getTargetLanguageFromFile ( DOMDocument $ xliffContents ) : ? string { foreach ( $ xliffContents -> getElementsByTagName ( 'file' ) [ 0 ] -> attributes ?? [ ] as $ attribute ) { if ( $ attribute -> nodeName === 'target-language' ) { return $ attribute -> nodeValue ; } } return null ; }

Get the target language from file.

@param \DOMDocument $xliffContents

@return null|string


public static function createVarDumpConnection(ContainerInterface $container): Connection
    {
        $resolvedOptions  = self::resolveOptions($container->get('config'));
        $contextProviders = [];

        if ($container->has(ServerRequestInterface::class) && $container->has(RequestContextProvider::class)) {
            $contextProviders['request'] = $container->get(RequestContextProvider::class);
        }

        if ($container->has(SourceContextProvider::class)) {
            $contextProviders['source'] = $container->get(SourceContextProvider::class);
        }

        return new Connection(
            $resolvedOptions['debug_server']['host'],
            $contextProviders
        );
    }

public static function createVarDumpConnection ( ContainerInterface $ container ) : Connection { $ resolvedOptions = self :: resolveOptions ( $ container -> get ( 'config' ) ) ; $ contextProviders = [ ] ; if ( $ container -> has ( ServerRequestInterface :: class ) && $ container -> has ( RequestContextProvider :: class ) ) { $ contextProviders [ 'request' ] = $ container -> get ( RequestContextProvider :: class ) ; } if ( $ container -> has ( SourceContextProvider :: class ) ) { $ contextProviders [ 'source' ] = $ container -> get ( SourceContextProvider :: class ) ; } return new Connection ( $ resolvedOptions [ 'debug_server' ] [ 'host' ] , $ contextProviders ) ; }

Create a new VarDump Connection instance.

@param \Psr\Container\ContainerInterface $container

@return \Symfony\Component\VarDumper\Server\Connection

Create a new VarDump Connection instance .


public static function createDumpServer(ContainerInterface $container): DumpServer
    {
        $connection = $container->get(Connection::class);
        // @codeCoverageIgnoreStart
        VarDumper::setHandler(static function ($var) use ($connection): void {
            $data = (new VarCloner())->cloneVar($var);

            if ($connection->write($data)) {
                (new CliDumper())->dump($data);
            }
        });
        // @codeCoverageIgnoreEnd
        $logger = null;

        if ($container->has(LoggerInterface::class)) {
            $logger = $container->get(LoggerInterface::class);
        }

        $resolvedOptions = self::resolveOptions($container->get('config'));

        return new DumpServer(
            $resolvedOptions['debug_server']['host'],
            $logger
        );
    }

public
static
function
createDumpServer
(
ContainerInterface
$
container
)
:
DumpServer
{
$
connection
=
$
container
->
get
(
Connection
::
class
)
;
// @codeCoverageIgnoreStart
VarDumper
::
setHandler
(
static
function
(
$
var
)
use
(
$
connection
)
:
void
{
$
data
=
(
new
VarCloner
(
)
)
->
cloneVar
(
$
var
)
;
if
(
$
connection
->
write
(
$
data
)
)
{
(
new
CliDumper
(
)
)
->
dump
(
$
data
)
;
}
}
)
;
// @codeCoverageIgnoreEnd
$
logger
=
;
if
(
$
container
->
has
(
LoggerInterface
::
class
)
)
{
$
logger
=
$
container
->
get
(
LoggerInterface
::
class
)
;
}
$
resolvedOptions
=
self
::
resolveOptions
(
$
container
->
get
(
'config'
)
)
;
return
new
DumpServer
(
$
resolvedOptions
[
'debug_server'
]
[
'host'
]
,
$
logger
)
;
}

Create a new DumpServer instance.

@param \Psr\Container\ContainerInterface $container

@return \Symfony\Component\VarDumper\Server\DumpServer


public function has(string $path): bool
    {
        $has = $this->driver->has($path);

        if ($has === null) {
            return false;
        }

        if (\is_array($has)) {
            return $has['path'] !== '';
        }

        return $has;
    }

public function has ( string $ path ) : bool { $ has = $ this -> driver -> has ( $ path ) ; if ( $ has === null ) { return false ; } if ( \ is_array ( $ has ) ) { return $ has [ 'path' ] !== '' ; } return $ has ; }

Check whether a file exists.

@param string $path

@return bool


protected function getTransformedPath(string $path): string
    {
        $prefix = '';

        if (\method_exists($this->driver, 'getPathPrefix')) {
            $prefix = $this->driver->getPathPrefix();
        }

        return $prefix . $path;
    }

protected function getTransformedPath ( string $ path ) : string { $ prefix = '' ; if ( \ method_exists ( $ this -> driver , 'getPathPrefix' ) ) { $ prefix = $ this -> driver -> getPathPrefix ( ) ; } return $ prefix . $ path ; }

Get normalize or prefixed path.

@param string $path

@return string


private function getContents(string $directory, string $typ, bool $recursive = false): array
    {
        $contents = $this->driver->listContents($directory, $recursive);

        return $this->filterContentsByType($contents, $typ);
    }

private function getContents ( string $ directory , string $ typ , bool $ recursive = false ) : array { $ contents = $ this -> driver -> listContents ( $ directory , $ recursive ) ; return $ this -> filterContentsByType ( $ contents , $ typ ) ; }

Get content from a dir.

@param string $directory
@param string $typ
@param bool   $recursive

@return array


private function filterContentsByType(array $contents, string $type): array
    {
        $results = [];

        foreach ($contents as $key => $value) {
            if (isset($value['type']) && $value['type'] === $type) {
                $results[$key] = $value['path'];
            }
        }

        return $results;
    }

private function filterContentsByType ( array $ contents , string $ type ) : array { $ results = [ ] ; foreach ( $ contents as $ key => $ value ) { if ( isset ( $ value [ 'type' ] ) && $ value [ 'type' ] === $ type ) { $ results [ $ key ] = $ value [ 'path' ] ; } } return $ results ; }

Filter directory contents by type.

@param array  $contents
@param string $type

@return array


protected function tokensMatch(ServerRequestInterface $request): bool
    {
        $sessionToken = $request->getAttribute('session')->getToken();
        $token        = $request->getAttribute('_token') ?? $request->getHeaderLine('x-csrf-token');
        $header       = $request->getHeaderLine('x-xsrf-token');

        if ($token === '' && $header !== '') {
            try {
                $key          = KeyFactory::loadEncryptionKey($this->manager->getConfig()['key_path']);
                $hiddenString = Crypto::decrypt($header, $key);
                $token        = $hiddenString->getString();
            } catch (InvalidMessage $exception) {
                $token = $header;
            }
        }

        if (! \is_string($sessionToken) || ! \is_string($token)) {
            return false;
        }

        return \hash_equals($sessionToken, $token);
    }

protected function tokensMatch ( ServerRequestInterface $ request ) : bool { $ sessionToken = $ request -> getAttribute ( 'session' ) -> getToken ( ) ; $ token = $ request -> getAttribute ( '_token' ) ?? $ request -> getHeaderLine ( 'x-csrf-token' ) ; $ header = $ request -> getHeaderLine ( 'x-xsrf-token' ) ; if ( $ token === '' && $ header !== '' ) { try { $ key = KeyFactory :: loadEncryptionKey ( $ this -> manager -> getConfig ( ) [ 'key_path' ] ) ; $ hiddenString = Crypto :: decrypt ( $ header , $ key ) ; $ token = $ hiddenString -> getString ( ) ; } catch ( InvalidMessage $ exception ) { $ token = $ header ; } } if ( ! \ is_string ( $ sessionToken ) || ! \ is_string ( $ token ) ) { return false ; } return \ hash_equals ( $ sessionToken , $ token ) ; }

Determine if the session and input CSRF tokens match.

@param \Psr\Http\Message\ServerRequestInterface $request

@return bool

Determine if the session and input CSRF tokens match .


protected function addCookieToResponse(
        ServerRequestInterface $request,
        ResponseInterface $response
    ): ResponseInterface {
        $uri = $request->getUri();

        $setCookie = new SetCookie(
            'XSRF-TOKEN',
            $request->getAttribute('session')->getToken(),
            $this->lifetime,
            $this->cookieConfig['path'],
            $this->cookieConfig['domain'] ?? $uri->getHost(),
            $this->cookieConfig['secure'] ?? ($uri->getScheme() === 'https'),
            false,
            $this->cookieConfig['samesite']
        );

        return $response->withAddedHeader('set-cookie', (string) $setCookie);
    }

protected function addCookieToResponse ( ServerRequestInterface $ request , ResponseInterface $ response ) : ResponseInterface { $ uri = $ request -> getUri ( ) ; $ setCookie = new SetCookie ( 'XSRF-TOKEN' , $ request -> getAttribute ( 'session' ) -> getToken ( ) , $ this -> lifetime , $ this -> cookieConfig [ 'path' ] , $ this -> cookieConfig [ 'domain' ] ?? $ uri -> getHost ( ) , $ this -> cookieConfig [ 'secure' ] ?? ( $ uri -> getScheme ( ) === 'https' ) , false , $ this -> cookieConfig [ 'samesite' ] ) ; return $ response -> withAddedHeader ( 'set-cookie' , ( string ) $ setCookie ) ; }

Add the CSRF token to the response cookies.

@param \Psr\Http\Message\ServerRequestInterface $request
@param \Psr\Http\Message\ResponseInterface      $response

@throws \InvalidArgumentException

@return \Psr\Http\Message\ResponseInterface

Add the CSRF token to the response cookies .


protected function sanitizeCollectedMessages(array $messages): array
    {
        $result = [];

        foreach ($messages as $key => $message) {
            $messageId = $message['locale'] . '.' . $message['domain'] . '.' . $message['id'];

            if (! isset($result[$messageId])) {
                $message['count']              = 1;
                $message['parameters']         = ! isset($message['parameters']) ? [$message['parameters']] : [];
                $messages[$key]['translation'] = $message['translation'];
                $result[$messageId]            = $message;
            } else {
                if (! isset($message['parameters'])) {
                    $result[$messageId]['parameters'][] = $message['parameters'];
                }

                $result[$messageId]['count']++;
            }
            unset($messages[$key]);
        }

        return $result;
    }

protected function sanitizeCollectedMessages ( array $ messages ) : array { $ result = [ ] ; foreach ( $ messages as $ key => $ message ) { $ messageId = $ message [ 'locale' ] . '.' . $ message [ 'domain' ] . '.' . $ message [ 'id' ] ; if ( ! isset ( $ result [ $ messageId ] ) ) { $ message [ 'count' ] = 1 ; $ message [ 'parameters' ] = ! isset ( $ message [ 'parameters' ] ) ? [ $ message [ 'parameters' ] ] : [ ] ; $ messages [ $ key ] [ 'translation' ] = $ message [ 'translation' ] ; $ result [ $ messageId ] = $ message ; } else { if ( ! isset ( $ message [ 'parameters' ] ) ) { $ result [ $ messageId ] [ 'parameters' ] [ ] = $ message [ 'parameters' ] ; } $ result [ $ messageId ] [ 'count' ] ++ ; } unset ( $ messages [ $ key ] ) ; } return $ result ; }

Sanitize collected messages.

@param array $messages

@return array


protected function computeCount(array $messages): array
    {
        $count = [
            TranslatorContract::MESSAGE_DEFINED         => 0,
            TranslatorContract::MESSAGE_MISSING         => 0,
            TranslatorContract::MESSAGE_EQUALS_FALLBACK => 0,
        ];

        foreach ($messages as $message) {
            $count[$message['state']]++;
        }

        return $count;
    }

protected function computeCount ( array $ messages ) : array { $ count = [ TranslatorContract :: MESSAGE_DEFINED => 0 , TranslatorContract :: MESSAGE_MISSING => 0 , TranslatorContract :: MESSAGE_EQUALS_FALLBACK => 0 , ] ; foreach ( $ messages as $ message ) { $ count [ $ message [ 'state' ] ] ++ ; } return $ count ; }

Counter for message types.

@param array $messages

@return array


protected function getSortedMessages(array $messages): array
    {
        $sortedMessages = [
            TranslatorContract::MESSAGE_MISSING         => [],
            TranslatorContract::MESSAGE_EQUALS_FALLBACK => [],
            TranslatorContract::MESSAGE_DEFINED         => [],
        ];

        foreach ($messages as $key => $value) {
            if ($value['state'] === TranslatorContract::MESSAGE_MISSING) {
                $sortedMessages[TranslatorContract::MESSAGE_MISSING][$value['id']] = [
                    $value['locale'],
                    $value['domain'],
                    $value['count'],
                    $value['id'],
                    $value['translation'],
                ];
            } elseif ($value['state'] === TranslatorContract::MESSAGE_EQUALS_FALLBACK) {
                $sortedMessages[TranslatorContract::MESSAGE_EQUALS_FALLBACK][$value['id']] = [
                    $value['locale'],
                    $value['domain'],
                    $value['count'],
                    $value['id'],
                    $value['translation'],
                ];
            } elseif ($value['state'] === TranslatorContract::MESSAGE_DEFINED) {
                $sortedMessages[TranslatorContract::MESSAGE_DEFINED][$value['id']] = [
                    $value['locale'],
                    $value['domain'],
                    $value['count'],
                    $value['id'],
                    $value['translation'],
                ];
            }
        }

        return $sortedMessages;
    }

protected function getSortedMessages ( array $ messages ) : array { $ sortedMessages = [ TranslatorContract :: MESSAGE_MISSING => [ ] , TranslatorContract :: MESSAGE_EQUALS_FALLBACK => [ ] , TranslatorContract :: MESSAGE_DEFINED => [ ] , ] ; foreach ( $ messages as $ key => $ value ) { if ( $ value [ 'state' ] === TranslatorContract :: MESSAGE_MISSING ) { $ sortedMessages [ TranslatorContract :: MESSAGE_MISSING ] [ $ value [ 'id' ] ] = [ $ value [ 'locale' ] , $ value [ 'domain' ] , $ value [ 'count' ] , $ value [ 'id' ] , $ value [ 'translation' ] , ] ; } elseif ( $ value [ 'state' ] === TranslatorContract :: MESSAGE_EQUALS_FALLBACK ) { $ sortedMessages [ TranslatorContract :: MESSAGE_EQUALS_FALLBACK ] [ $ value [ 'id' ] ] = [ $ value [ 'locale' ] , $ value [ 'domain' ] , $ value [ 'count' ] , $ value [ 'id' ] , $ value [ 'translation' ] , ] ; } elseif ( $ value [ 'state' ] === TranslatorContract :: MESSAGE_DEFINED ) { $ sortedMessages [ TranslatorContract :: MESSAGE_DEFINED ] [ $ value [ 'id' ] ] = [ $ value [ 'locale' ] , $ value [ 'domain' ] , $ value [ 'count' ] , $ value [ 'id' ] , $ value [ 'translation' ] , ] ; } } return $ sortedMessages ; }

Sorte messages to the right type.

@param array $messages

@return array


public function addStream(StreamInterface $stream): void
    {
        if (! $stream->isReadable()) {
            throw new InvalidArgumentException('Each stream must be readable.');
        }

        // The stream is only seekable if all streams are seekable
        if (! $stream->isSeekable()) {
            $this->seekable = false;
        }

        $this->streams[] = $stream;
    }

Add a stream to the AppendStream.

@param \Psr\Http\Message\StreamInterface $stream Stream to append. Must be readable.

@throws \Viserio\Component\Contract\Http\Exception\InvalidArgumentException if the stream is not readable


public function close(): void
    {
        $this->pos      = $this->current      = 0;
        $this->seekable = true;

        foreach ($this->streams as $stream) {
            $stream->close();
        }

        $this->streams = [];
    }

public function close ( ) : void { $ this -> pos = $ this -> current = 0 ; $ this -> seekable = true ; foreach ( $ this -> streams as $ stream ) { $ stream -> close ( ) ; } $ this -> streams = [ ] ; }

Closes each attached stream.

{@inheritdoc}


public function decode()
    {
        $gif = new Decoded;

        // read header
        $gif->setHeader($this->getNextBytes(6));

        // read logocal screen descriptor
        $gif->setlogicalScreenDescriptor($this->getNextBytes(7));

        // read global color table
        if ($gif->hasGlobalColorTable()) {
            $gif->setGlobalColorTable($this->getNextBytes(
                $gif->countGlobalColors() * 3
            ));
        }

        // read body
        while ( ! feof($this->handle)) {

            switch ($this->getNextBytes(1)) {

                case self::EXTENSION_BLOCK_MARKER:
                    $this->decodeExtension($gif);
                    break;

                case self::IMAGE_SEPARATOR:
                    $this->decodeImageDescriptor($gif);
                    $this->decodeImageData($gif);
                    break;

                case self::TRAILER_MARKER:
                    # code...
                    break 2;

                default:
                    throw new \Intervention\Image\Exception\NotReadableException(
                        "Unable to decode GIF image."
                    );
                    break;
            }
        }

        return $gif;
    }

public
function
decode
(
)
{
$
gif
=
new
Decoded
;
// read header
$
gif
->
setHeader
(
$
this
->
getNextBytes
(
6
)
)
;
// read logocal screen descriptor
$
gif
->
setlogicalScreenDescriptor
(
$
this
->
getNextBytes
(
7
)
)
;
// read global color table
if
(
$
gif
->
hasGlobalColorTable
(
)
)
{
$
gif
->
setGlobalColorTable
(
$
this
->
getNextBytes
(
$
gif
->
countGlobalColors
(
)
*
3
)
)
;
}
// read body
while
(
!
feof
(
$
this
->
handle
)
)
{
switch
(
$
this
->
getNextBytes
(
1
)
)
{
case
self
::
EXTENSION_BLOCK_MARKER
:
$
this
->
decodeExtension
(
$
gif
)
;
break
;
case
self
::
IMAGE_SEPARATOR
:
$
this
->
decodeImageDescriptor
(
$
gif
)
;
$
this
->
decodeImageData
(
$
gif
)
;
break
;
case
self
::
TRAILER_MARKER
:
# code...
break
2
;
default
:
throw
new
\
Intervention
\
Image
\
Exception
\
NotReadableException
(
"Unable to decode GIF image."
)
;
break
;
}
}
return
$
gif
;
}


private function decodeExtension(Decoded $gif)
    {
        switch ($this->getNextBytes(1)) {

            case self::GRAPHICS_CONTROL_EXTENSION_MARKER:
                $gif->addGraphicsControlExtension($this->getNextBytes(6));
                break;

            case self::APPLICATION_EXTENSION_MARKER:
                $application_block_size = $this->getNextBytes(1);
                $application_block_size = unpack('C', $application_block_size)[1];
                $application_block = $this->getNextBytes($application_block_size);

                // only save netscape application extension
                if ($application_block == self::NETSCAPE_EXTENSION_MARKER) {

                    $data_block_size = $this->getNextBytes(1);
                    $data_block_size = unpack('C', $data_block_size)[1];
                    $data_block = $this->getNextBytes($data_block_size);

                    $extension = "\x0B";
                    $extension .= self::NETSCAPE_EXTENSION_MARKER;
                    $extension .= "\x03";
                    $extension .= $data_block;
                    $extension .= "\x00";
                    $gif->setNetscapeExtension($extension);

                } elseif ($application_block == self::XMP_EXTENSION_MARKER) {

                    do {
                        // skip xmp data for now
                        $byte = $this->getNextBytes(1);
                    } while ($byte != "\x00");

                } else {

                    $data_block_size = $this->getNextBytes(1);
                    $data_block_size = unpack('C', $data_block_size)[1];
                    $data_block = $this->getNextBytes($data_block_size);

                }

                // subblock
                $this->getNextBytes(1);

                break;

            case self::PLAINTEXT_EXTENSION_MARKER:
                $blocksize = $this->getNextBytes(1);
                $blocksize = unpack('C', $blocksize)[1];
                $gif->setPlaintextExtension($this->getNextBytes($blocksize));
                $this->getNextBytes(1); // null byte
                break;

            case self::COMMENT_EXTENSION_MARKER:
                $blocksize = $this->getNextBytes(1);
                $blocksize = unpack('C', $blocksize);
                $gif->setCommentExtension($this->getNextBytes($blocksize));
                $this->getNextBytes(1); // null byte
                break;

            default:
                # code...
                break;
        }
    }

Decode extension in image stream

@param  Decoded $gif
@return void


private function decodeImageDescriptor(Decoded $gif)
    {
        $descriptor = $this->getNextBytes(9);

        // determine if descriptor has local color table
        $flag = substr($descriptor, 8, 1);
        $flag = unpack('C', $flag)[1];
        $flag = (bool) ($flag & bindec('10000000'));
        if ($flag) {
            // read local color table
            $byte = substr($descriptor, 8, 1);
            $byte = unpack('C', $byte)[1];
            $size = (int) ($byte & bindec('00000111'));
            $size = 3 * pow(2, $size + 1);

            $gif->addLocalColorTable($this->getNextBytes($size));

        } else {
            $gif->addLocalColorTable(null);
        }

        // determine if image is marked as interlaced
        $interlaced = substr($descriptor, 8, 1);
        $interlaced = unpack('C', $interlaced)[1];
        $interlaced = (bool) ($interlaced & bindec('01000000'));
        $gif->addInterlaced($interlaced);

        // decode image offsets
        $left = substr($descriptor, 0, 2);
        $left = unpack('C', $left)[1];
        $top = substr($descriptor, 2, 2);
        $top = unpack('C', $top)[1];
        $gif->addOffset($left, $top);

        // decode image dimensions
        $width = substr($descriptor, 4, 2);
        $width = unpack('v', $width)[1];
        $height = substr($descriptor, 6, 2);
        $height = unpack('v', $height)[1];
        $gif->addSize($width, $height);

        $gif->addImageDescriptors($descriptor);
    }

Decode Image Descriptor from image stream

@param  Decoded $gif
@return void


private function decodeImageData(Decoded $gif)
    {
        $data = '';

        // LZW minimum code size
        $data .= $this->getNextBytes(1);

        do {

            $byte = $this->getNextBytes(1);

            if ($byte !== self::BLOCK_TERMINATOR) {
                $size = unpack('C', $byte)[1];
                $data .= $byte;
                $data .= $this->getNextBytes($size);
            } else {
                $data .= self::BLOCK_TERMINATOR;
            }

        } while ($byte !== self::BLOCK_TERMINATOR);

        $gif->addImageData($data);
    }

private
function
decodeImageData
(
Decoded
$
gif
)
{
$
data
=
''
;
// LZW minimum code size
$
data
.=
$
this
->
getNextBytes
(
1
)
;
do
{
$
byte
=
$
this
->
getNextBytes
(
1
)
;
if
(
$
byte
!==
self
::
BLOCK_TERMINATOR
)
{
$
size
=
unpack
(
'C'
,
$
byte
)
[
1
]
;
$
data
.=
$
byte
;
$
data
.=
$
this
->
getNextBytes
(
$
size
)
;
}
else
{
$
data
.=
self
::
BLOCK_TERMINATOR
;
}
}
while
(
$
byte
!==
self
::
BLOCK_TERMINATOR
)
;
$
gif
->
addImageData
(
$
data
)
;
}

Decode Image data from image stream

@param  Decoded $gif
@return void


public function setOrderDir($orderDir = CDRCollection::ORDER_ASC)
    {
        if ($orderDir != self::ORDER_ASC && $orderDir != self::ORDER_DESC) {
            throw new CDRCollectionException("Unknown order direction");
        }
        $this->orderDir = $orderDir;
    }

public
function
setOrderDir
(
$
orderDir
=
CDRCollection
::
ORDER_ASC
)
{
if
(
$
orderDir
!=
self
::
ORDER_ASC
&&
$
orderDir
!=
self
::
ORDER_DESC
)
{
throw
new
CDRCollectionException
(
"Unknown order direction"
)
;
}
$
this
->
orderDir
=
$
orderDir
;
}

set orderDir property
@param string $orderDir
@throws CDRCollectionException


public function getList()
    {
        if (!$this->_loaded) {
            $this->load();
            $this->_loaded = true;
        }
        return $this->_list;
    }

public function getList ( ) { if ( ! $ this -> _loaded ) { $ this -> load ( ) ; $ this -> _loaded = true ; } return $ this -> _list ; }

get data set of collection
@return array