public static function closeOutputBuffers(int $targetLevel, bool $flush): void
    {
        $status = ob_get_status(true);
        $level  = \count($status);
        // PHP_OUTPUT_HANDLER_* are not defined on HHVM 3.3
        $flags = \defined('PHP_OUTPUT_HANDLER_REMOVABLE')
            ? PHP_OUTPUT_HANDLER_REMOVABLE | ($flush
                ? PHP_OUTPUT_HANDLER_FLUSHABLE
                : PHP_OUTPUT_HANDLER_CLEANABLE)
            : -1;

        while (
            $level-- > $targetLevel && ($s = $status[$level]) &&
            ($s['del'] ?? ! isset($s['flags']) || $flags === ($s['flags'] & $flags))
        ) {
            if ($flush) {
                ob_end_flush();
            } else {
                ob_end_clean();
            }
        }
    }

Cleans or flushes output buffers up to target level.

Resulting level can be greater than target level if a non-removable
buffer has been encountered.

@param int  $targetLevel The target output buffering level
@param bool $flush       Whether to flush or clean the buffers

@return void

Cleans or flushes output buffers up to target level .


protected function initialize(
        Uri $uri = null,
        string $method = null,
        Stream $body = null,
        array $headers = null
    ): void {
        $this->uri     = $uri ?? new NativeUri();
        $this->method  = $method ?? RequestMethod::GET;
        $this->body    = $body ?? new NativeStream('php://input');
        $this->headers = $headers ?? [];

        $this->setHeaders($headers);
        $this->validateMethod($this->method);
        $this->validateProtocolVersion($this->protocol);

        if ($this->hasHeader(static::$HOST_NAME) && $this->uri->getHost()) {
            $this->headerNames[static::$HOST_NAME_NORM] = static::$HOST_NAME;
            $this->headers[static::$HOST_NAME]          = [
                $this->uri->getHost(),
            ];
        }
    }

protected function initialize ( Uri $ uri = null , string $ method = null , Stream $ body = null , array $ headers = null ) : void { $ this -> uri = $ uri ?? new NativeUri ( ) ; $ this -> method = $ method ?? RequestMethod :: GET ; $ this -> body = $ body ?? new NativeStream ( 'php://input' ) ; $ this -> headers = $ headers ?? [ ] ; $ this -> setHeaders ( $ headers ) ; $ this -> validateMethod ( $ this -> method ) ; $ this -> validateProtocolVersion ( $ this -> protocol ) ; if ( $ this -> hasHeader ( static :: $ HOST_NAME ) && $ this -> uri -> getHost ( ) ) { $ this -> headerNames [ static :: $ HOST_NAME_NORM ] = static :: $ HOST_NAME ; $ this -> headers [ static :: $ HOST_NAME ] = [ $ this -> uri -> getHost ( ) , ] ; } }

Initialize the Request.

@param Uri    $uri     [optional] The uri
@param string $method  [optional] The method
@param Stream $body    [optional] The body stream
@param array  $headers [optional] The headers

@throws \InvalidArgumentException
@throws \Valkyrja\HttpMessage\Exceptions\InvalidMethod
@throws \Valkyrja\HttpMessage\Exceptions\InvalidPath
@throws \Valkyrja\HttpMessage\Exceptions\InvalidPort
@throws \Valkyrja\HttpMessage\Exceptions\InvalidProtocolVersion
@throws \Valkyrja\HttpMessage\Exceptions\InvalidQuery
@throws \Valkyrja\HttpMessage\Exceptions\InvalidScheme
@throws \Valkyrja\HttpMessage\Exceptions\InvalidStream

@return void


protected function validateMethod(string $method): void
    {
        if (! RequestMethod::isValid($method)) {
            throw new InvalidMethod(
                sprintf(
                    'Unsupported HTTP method "%s" provided',
                    $method
                )
            );
        }
    }

protected
function
validateMethod
(
string
$
method
)
:
void
{
if
(
!
RequestMethod
::
isValid
(
$
method
)
)
{
throw
new
InvalidMethod
(
sprintf
(
'Unsupported HTTP method "%s" provided'
,
$
method
)
)
;
}
}

Validate a method.

@param string $method The method

@throws \Valkyrja\HttpMessage\Exceptions\InvalidMethod

@return void


public function locate($command)
    {
        $paths = $this->locateAll($command);

        return empty($paths) ? null : $paths[0];
    }

public function locate ( $ command ) { $ paths = $ this -> locateAll ( $ command ) ; return empty ( $ paths ) ? null : $ paths [ 0 ] ; }

Locates the given command in the user's path.

@api
@param string $command The command to locate.
@return string|null The full path to the command or null if not path
found.

Locates the given command in the user s path .


public function locateAll($command)
    {
        return array_values(array_filter($this->_pathBuilder->getPermutations($command), $this->_executableTester));
    }

public function locateAll ( $ command ) { return array_values ( array_filter ( $ this -> _pathBuilder -> getPermutations ( $ command ) , $ this -> _executableTester ) ) ; }

Locates all versions of the given command in the user's path.

@api
@param string $command The command to locate.
@return array The locations where the command exists.

Locates all versions of the given command in the user s path .


function &download()
    {
        if (isset($this->_packagefile)) {
            return $this->_packagefile;
        }

        if (isset($this->_downloadURL['url'])) {
            $this->_isvalid = false;
            $info = $this->getParsedPackage();
            foreach ($info as $i => $p) {
                $info[$i] = strtolower($p);
            }

            $err = $this->_fromUrl($this->_downloadURL['url'],
                $this->_registry->parsedPackageNameToString($this->_parsedname, true));
            $newinfo = $this->getParsedPackage();
            foreach ($newinfo as $i => $p) {
                $newinfo[$i] = strtolower($p);
            }

            if ($info != $newinfo) {
                do {
                    if ($info['channel'] == 'pecl.php.net' && $newinfo['channel'] == 'pear.php.net') {
                        $info['channel'] = 'pear.php.net';
                        if ($info == $newinfo) {
                            // skip the channel check if a pecl package says it's a PEAR package
                            break;
                        }
                    }
                    if ($info['channel'] == 'pear.php.net' && $newinfo['channel'] == 'pecl.php.net') {
                        $info['channel'] = 'pecl.php.net';
                        if ($info == $newinfo) {
                            // skip the channel check if a pecl package says it's a PEAR package
                            break;
                        }
                    }

                    return PEAR::raiseError('CRITICAL ERROR: We are ' .
                        $this->_registry->parsedPackageNameToString($info) . ', but the file ' .
                        'downloaded claims to be ' .
                        $this->_registry->parsedPackageNameToString($this->getParsedPackage()));
                } while (false);
            }

            if (PEAR::isError($err) || !$this->_valid) {
                return $err;
            }
        }

        $this->_type = 'local';
        return $this->_packagefile;
    }

Retrieve any non-local packages
@return PEAR_PackageFile_v1|PEAR_PackageFile_v2|PEAR_Error


function removeInstalled(&$params)
    {
        if (!isset($params[0])) {
            return;
        }

        $options = $params[0]->_downloader->getOptions();
        if (!isset($options['downloadonly'])) {
            foreach ($params as $i => $param) {
                $package = $param->getPackage();
                $channel = $param->getChannel();
                // remove self if already installed with this version
                // this does not need any pecl magic - we only remove exact matches
                if ($param->_installRegistry->packageExists($package, $channel)) {
                    $packageVersion = $param->_installRegistry->packageInfo($package, 'version', $channel);
                    if (version_compare($packageVersion, $param->getVersion(), '==')) {
                        if (!isset($options['force'])) {
                            $info = $param->getParsedPackage();
                            unset($info['version']);
                            unset($info['state']);
                            if (!isset($options['soft'])) {
                                $param->_downloader->log(1, 'Skipping package "' .
                                    $param->getShortName() .
                                    '", already installed as version ' . $packageVersion);
                            }
                            $params[$i] = false;
                        }
                    } elseif (!isset($options['force']) && !isset($options['upgrade']) &&
                          !isset($options['soft'])) {
                        $info = $param->getParsedPackage();
                        $param->_downloader->log(1, 'Skipping package "' .
                            $param->getShortName() .
                            '", already installed as version ' . $packageVersion);
                        $params[$i] = false;
                    }
                }
            }
        }

        PEAR_Downloader_Package::removeDuplicates($params);
    }

Remove packages to be downloaded that are already installed
@param array of PEAR_Downloader_Package objects
@static


function detectStupidDuplicates($params, &$errorparams)
    {
        $existing = array();
        foreach ($params as $i => $param) {
            $package = $param->getPackage();
            $channel = $param->getChannel();
            $group   = $param->getGroup();
            if (!isset($existing[$channel . '/' . $package])) {
                $existing[$channel . '/' . $package] = array();
            }

            if (!isset($existing[$channel . '/' . $package][$group])) {
                $existing[$channel . '/' . $package][$group] = array();
            }

            $existing[$channel . '/' . $package][$group][] = $i;
        }

        $indices = array();
        foreach ($existing as $package => $groups) {
            foreach ($groups as $group => $dupes) {
                if (count($dupes) > 1) {
                    $indices = $indices + $dupes;
                }
            }
        }

        $indices = array_unique($indices);
        foreach ($indices as $index) {
            $errorparams[] = $params[$index];
        }

        return count($errorparams);
    }

function detectStupidDuplicates ( $ params , & $ errorparams ) { $ existing = array ( ) ; foreach ( $ params as $ i => $ param ) { $ package = $ param -> getPackage ( ) ; $ channel = $ param -> getChannel ( ) ; $ group = $ param -> getGroup ( ) ; if ( ! isset ( $ existing [ $ channel . '/' . $ package ] ) ) { $ existing [ $ channel . '/' . $ package ] = array ( ) ; } if ( ! isset ( $ existing [ $ channel . '/' . $ package ] [ $ group ] ) ) { $ existing [ $ channel . '/' . $ package ] [ $ group ] = array ( ) ; } $ existing [ $ channel . '/' . $ package ] [ $ group ] [ ] = $ i ; } $ indices = array ( ) ; foreach ( $ existing as $ package => $ groups ) { foreach ( $ groups as $ group => $ dupes ) { if ( count ( $ dupes ) > 1 ) { $ indices = $ indices + $ dupes ; } } } $ indices = array_unique ( $ indices ) ; foreach ( $ indices as $ index ) { $ errorparams [ ] = $ params [ $ index ] ; } return count ( $ errorparams ) ; }

Detect duplicate package names with differing versions

If a user requests to install Date 1.4.6 and Date 1.4.7,
for instance, this is a logic error.  This method
detects this situation.

@param array $params array of PEAR_Downloader_Package objects
@param array $errorparams empty array
@return array array of stupid duplicated packages in PEAR_Downloader_Package obejcts


function _fromFile(&$param)
    {
        $saveparam = $param;
        if (is_string($param)) {
            if (!@file_exists($param)) {
                $test = explode('#', $param);
                $group = array_pop($test);
                if (@file_exists(implode('#', $test))) {
                    $this->setGroup($group);
                    $param = implode('#', $test);
                    $this->_explicitGroup = true;
                }
            }

            if (@is_file($param)) {
                $this->_type = 'local';
                $options = $this->_downloader->getOptions();
                $pkg = &$this->getPackagefileObject($this->_config, $this->_downloader->_debug);
                PEAR::pushErrorHandling(PEAR_ERROR_RETURN);
                $pf = &$pkg->fromAnyFile($param, PEAR_VALIDATE_INSTALLING);
                PEAR::popErrorHandling();
                if (PEAR::isError($pf)) {
                    $this->_valid = false;
                    $param = $saveparam;
                    return $pf;
                }
                $this->_packagefile = &$pf;
                if (!$this->getGroup()) {
                    $this->setGroup('default'); // install the default dependency group
                }
                return $this->_valid = true;
            }
        }
        $param = $saveparam;
        return $this->_valid = false;
    }

function
_fromFile
(
&
$
param
)
{
$
saveparam
=
$
param
;
if
(
is_string
(
$
param
)
)
{
if
(
!
@
file_exists
(
$
param
)
)
{
$
test
=
explode
(
'#'
,
$
param
)
;
$
group
=
array_pop
(
$
test
)
;
if
(
@
file_exists
(
implode
(
'#'
,
$
test
)
)
)
{
$
this
->
setGroup
(
$
group
)
;
$
param
=
implode
(
'#'
,
$
test
)
;
$
this
->
_explicitGroup
=
true
;
}
}
if
(
@
is_file
(
$
param
)
)
{
$
this
->
_type
=
'local'
;
$
options
=
$
this
->
_downloader
->
getOptions
(
)
;
$
pkg
=
&
$
this
->
getPackagefileObject
(
$
this
->
_config
,
$
this
->
_downloader
->
_debug
)
;
PEAR
::
pushErrorHandling
(
PEAR_ERROR_RETURN
)
;
$
pf
=
&
$
pkg
->
fromAnyFile
(
$
param
,
PEAR_VALIDATE_INSTALLING
)
;
PEAR
::
popErrorHandling
(
)
;
if
(
PEAR
::
isError
(
$
pf
)
)
{
$
this
->
_valid
=
false
;
$
param
=
$
saveparam
;
return
$
pf
;
}
$
this
->
_packagefile
=
&
$
pf
;
if
(
!
$
this
->
getGroup
(
)
)
{
$
this
->
setGroup
(
'default'
)
;
// install the default dependency group
}
return
$
this
->
_valid
=
true
;
}
}
$
param
=
$
saveparam
;
return
$
this
->
_valid
=
false
;
}

This will retrieve from a local file if possible, and parse out
a group name as well.  The original parameter will be modified to reflect this.
@param string|array can be a parsed package name as well
@access private

This will retrieve from a local file if possible and parse out a group name as well . The original parameter will be modified to reflect this .


public function getParameters()
    {
        $bodyParams = json_decode($this->body, true);
        if (!$bodyParams) {
            return array();
        }

        $parameters = array();
        foreach ($bodyParams as $paramName => $paramValue) {
            $parameters[$paramName] = $paramValue;
        }

        return $parameters;
    }

public function getParameters ( ) { $ bodyParams = json_decode ( $ this -> body , true ) ; if ( ! $ bodyParams ) { return array ( ) ; } $ parameters = array ( ) ; foreach ( $ bodyParams as $ paramName => $ paramValue ) { $ parameters [ $ paramName ] = $ paramValue ; } return $ parameters ; }

Gets extracted parametrs.

@return array Extracted parameters.


public static function enable(int $errorReportingLevel = E_ALL, bool $displayErrors = false): void
    {
        // If debug is already enabled
        if (static::$enabled) {
            // Don't do things twice
            return;
        }

        // Debug is enabled
        static::$enabled = true;

        // The exception handler
        $exceptionHandler = new ExceptionHandler($displayErrors);
        // The error handler
        $errorHandler = new ErrorHandler();

        // Set the error reporting level
        error_reporting($errorReportingLevel);

        // Set the error handler
        set_error_handler(
            [
                $errorHandler,
                'handleError',
            ]
        );

        // Set the exception handler
        set_exception_handler(
            [
                $exceptionHandler,
                'handleException',
            ]
        );

        // Register a shutdown function
        register_shutdown_function(
            [
                $exceptionHandler,
                'handleShutdown',
            ]
        );
    }

public
static
function
enable
(
int
$
errorReportingLevel
=
E_ALL
,
bool
$
displayErrors
=
false
)
:
void
{
// If debug is already enabled
if
(
static
::
$
enabled
)
{
// Don't do things twice
return
;
}
// Debug is enabled
static
::
$
enabled
=
true
;
// The exception handler
$
exceptionHandler
=
new
ExceptionHandler
(
$
displayErrors
)
;
// The error handler
$
errorHandler
=
new
ErrorHandler
(
)
;
// Set the error reporting level
error_reporting
(
$
errorReportingLevel
)
;
// Set the error handler
set_error_handler
(
[
$
errorHandler
,
'handleError'
,
]
)
;
// Set the exception handler
set_exception_handler
(
[
$
exceptionHandler
,
'handleException'
,
]
)
;
// Register a shutdown function
register_shutdown_function
(
[
$
exceptionHandler
,
'handleShutdown'
,
]
)
;
}

Enable debug mode.

@param int  $errorReportingLevel [optional] The error reporting level
@param bool $displayErrors       [optional] Whether to display errors

@return void


public function getAmountDifference()
    {
        $amount = ($this->hasChildren() ? $this->getGlobalAmount() : $this->getAmount());
        return ($amount - $this->getTransactionsAmount());
    }

public function getAmountDifference ( ) { $ amount = ( $ this -> hasChildren ( ) ? $ this -> getGlobalAmount ( ) : $ this -> getAmount ( ) ) ; return ( $ amount - $ this -> getTransactionsAmount ( ) ) ; }

Get budget amount difference

@return float


public function addMonthToBitmask($month)
    {
        $month = (int) $month;
        if ($month < 1 || $month > 12) {
            throw new \RangeException('Month is invalid!');
        }

        $bit     = pow(2, $month - 1);
        $bitmask = $this->getMonthBitmask() | $bit;

        $this->setMonthBitmask($bitmask);

        return $this;
    }

public
function
addMonthToBitmask
(
$
month
)
{
$
month
=
(
int
)
$
month
;
if
(
$
month
<
1
||
$
month
>
12
)
{
throw
new
\
RangeException
(
'Month is invalid!'
)
;
}
$
bit
=
pow
(
2
,
$
month
1
)
;
$
bitmask
=
$
this
->
getMonthBitmask
(
)
|
$
bit
;
$
this
->
setMonthBitmask
(
$
bitmask
)
;
return
$
this
;
}

Add month to bitmask

@param  int $month Month number (January: 1, February: 2, March: 3, April: 4...)
@return self


public function hasMonth($month)
    {
        $bitmask = $this->getMonthBitmask();
        $month   = (int) $month;

        $bit = pow(2, $month - 1);

        return ($bit === ($bit & $bitmask));
    }

public function hasMonth ( $ month ) { $ bitmask = $ this -> getMonthBitmask ( ) ; $ month = ( int ) $ month ; $ bit = pow ( 2 , $ month - 1 ) ; return ( $ bit === ( $ bit & $ bitmask ) ) ; }

Check if bitmask have given month.

@param  int $month Month number (January: 1, February: 2, March: 3, April: 4...)
@return bool


public function getLength()
    {
        $boundaryLength     = strlen($this->getBoundary());
        $headerParamLength  = strlen($this->_headerParam) - 4 + $boundaryLength;
        $headerUploadLength = strlen($this->_headerUpload) - 8 + $boundaryLength;
        $length             = $boundaryLength + 6;
        foreach ($this->_params as $p) {
            $length += $headerParamLength + strlen($p[0]) + strlen($p[1]) + 2;
        }
        foreach ($this->_uploads as $u) {
            $length += $headerUploadLength + strlen($u['name']) + strlen($u['type']) +
                       strlen($u['filename']) + $u['size'] + 2;
        }
        return $length;
    }

public function getLength ( ) { $ boundaryLength = strlen ( $ this -> getBoundary ( ) ) ; $ headerParamLength = strlen ( $ this -> _headerParam ) - 4 + $ boundaryLength ; $ headerUploadLength = strlen ( $ this -> _headerUpload ) - 8 + $ boundaryLength ; $ length = $ boundaryLength + 6 ; foreach ( $ this -> _params as $ p ) { $ length += $ headerParamLength + strlen ( $ p [ 0 ] ) + strlen ( $ p [ 1 ] ) + 2 ; } foreach ( $ this -> _uploads as $ u ) { $ length += $ headerUploadLength + strlen ( $ u [ 'name' ] ) + strlen ( $ u [ 'type' ] ) + strlen ( $ u [ 'filename' ] ) + $ u [ 'size' ] + 2 ; } return $ length ; }

Returns the length of the body to use in Content-Length header

@return   integer

Returns the length of the body to use in Content - Length header


public function getBoundary()
    {
        if (empty($this->_boundary)) {
            $this->_boundary = '--' . md5('PEAR-HTTP_Request2-' . microtime());
        }
        return $this->_boundary;
    }

public function getBoundary ( ) { if ( empty ( $ this -> _boundary ) ) { $ this -> _boundary = '--' . md5 ( 'PEAR-HTTP_Request2-' . microtime ( ) ) ; } return $ this -> _boundary ; }

Returns the boundary to use in Content-Type header

@return   string

Returns the boundary to use in Content - Type header


public function loadUserByUsername($username)
    {
        $qb = $this->_conn->createQueryBuilder();

        $qb->select('su.username, su.password')
            ->from('security_users', 'su')
            ->where(
                $qb->expr()->orX(
                    $qb->expr()->eq('su.username', ':username'),
                    $qb->expr()->eq('su.email', ':username')
                )
            )
            ->setParameter(':username', strtolower($username));
        $stmt = $qb->execute();

        if (!$user = $stmt->fetch()) {
            throw new UsernameNotFoundException(
                sprintf('Username "%s" does not exist.', $username)
            );
        }

        $qb->select('sr.role')
            ->leftJoin('su', 'security_users_roles', 'sur', 'su.id = sur.user_id')
            ->innerJoin('sur', 'security_roles', 'sr', 'sur.role_id = sr.id');

        $stmt = $qb->execute();
        $roles = $stmt->fetchAll(\PDO::FETCH_COLUMN);

        return new User($user['username'], $user['password'], $roles);
    }

public
function
loadUserByUsername
(
$
username
)
{
$
qb
=
$
this
->
_conn
->
createQueryBuilder
(
)
;
$
qb
->
select
(
'su.username, su.password'
)
->
from
(
'security_users'
,
'su'
)
->
where
(
$
qb
->
expr
(
)
->
orX
(
$
qb
->
expr
(
)
->
eq
(
'su.username'
,
':username'
)
,
$
qb
->
expr
(
)
->
eq
(
'su.email'
,
':username'
)
)
)
->
setParameter
(
':username'
,
strtolower
(
$
username
)
)
;
$
stmt
=
$
qb
->
execute
(
)
;
if
(
!
$
user
=
$
stmt
->
fetch
(
)
)
{
throw
new
UsernameNotFoundException
(
sprintf
(
'Username "%s" does not exist.'
,
$
username
)
)
;
}
$
qb
->
select
(
'sr.role'
)
->
leftJoin
(
'su'
,
'security_users_roles'
,
'sur'
,
'su.id = sur.user_id'
)
->
innerJoin
(
'sur'
,
'security_roles'
,
'sr'
,
'sur.role_id = sr.id'
)
;
$
stmt
=
$
qb
->
execute
(
)
;
$
roles
=
$
stmt
->
fetchAll
(
\
PDO
::
FETCH_COLUMN
)
;
return
new
User
(
$
user
[
'username'
]
,
$
user
[
'password'
]
,
$
roles
)
;
}

Loads the user for the given username.

This method must throw UsernameNotFoundException if the user is not
found.

@param string $username The username

@return UserInterface

@see UsernameNotFoundException

@throws UsernameNotFoundException if the user is not found


public function create($sendWelcome = true) {
        if ($this->getIsNewRecord() == false) {
            throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
        }

        $this->confirmed_at = time();
        $this->password = $this->password == null ? Password::generate(8) : $this->password;

        $this->trigger(self::BEFORE_CREATE);

        if (!$this->save()) {
            return false;
        }
        if($sendWelcome) {
            $this->mailer->sendWelcomeMessage($this, null, true);
        }
        $this->trigger(self::AFTER_CREATE);

        return true;
    }

public
function
create
(
$
sendWelcome
=
true
)
{
if
(
$
this
->
getIsNewRecord
(
)
==
false
)
{
throw
new
\
RuntimeException
(
'Calling "'
.
__CLASS__
.
'::'
.
__METHOD__
.
'" on existing user'
)
;
}
$
this
->
confirmed_at
=
time
(
)
;
$
this
->
password
=
$
this
->
password
==
Password
::
generate
(
8
)
:
$
this
->
password
;
$
this
->
trigger
(
self
::
BEFORE_CREATE
)
;
if
(
!
$
this
->
save
(
)
)
{
return
false
;
}
if
(
$
sendWelcome
)
{
$
this
->
mailer
->
sendWelcomeMessage
(
$
this
,
,
true
)
;
}
$
this
->
trigger
(
self
::
AFTER_CREATE
)
;
return
true
;
}

Creates new user account. It generates password if it is not provided by user.

@return bool

Creates new user account . It generates password if it is not provided by user .


public function setIpAddress($ip, $port = 80) {
        if (false !== strpos($ip, ':')) {
            list($ip, $port) = explode(':', $ip);
        }
        if (empty($ip)) {
            $ip = '127.0.0.1';
        }
        $this->ip = $ip;
        $this->port = intval($port);
        return $this;
    }

public function setIpAddress ( $ ip , $ port = 80 ) { if ( false !== strpos ( $ ip , ':' ) ) { list ( $ ip , $ port ) = explode ( ':' , $ ip ) ; } if ( empty ( $ ip ) ) { $ ip = '127.0.0.1' ; } $ this -> ip = $ ip ; $ this -> port = intval ( $ port ) ; return $ this ; }

SET IP AND PORT
@param string $ip
@param int $port
@return $this


protected function renderView($view, array $parameters = array())
    {
        if ($this->_oContainer->has('templating')) {
            return $this->_oContainer->get('templating')->render($view, $parameters);
        }

        if (!$this->_oContainer->has('twig')) {
            throw new \LogicException('You can not use the "renderView" method if the Templating Component or the Twig Bundle are not available.');
        }

        return $this->_oContainer->get('twig')->render($view, $parameters);
    }

Returns a rendered view.

@param string $view       The view name
@param array  $parameters An array of parameters to pass to the view

@return string The rendered view


protected function publishStream(StreamInterface $stream): EventStoreRepository
    {
        foreach ($stream as $domainEventMessage) {
            $this
                ->getEventPublisher()
                ->publish($domainEventMessage);
        }

        return $this;
    }

protected function publishStream ( StreamInterface $ stream ) : EventStoreRepository { foreach ( $ stream as $ domainEventMessage ) { $ this -> getEventPublisher ( ) -> publish ( $ domainEventMessage ) ; } return $ this ; }

Publish stream to event listeners.

@param StreamInterface $stream
@return EventStoreRepository


public function onResourceMaterialize(ResourceMaterializeEvent $e)
    {
        /** @var $resource MaterializedResource */
        $resource = $e->getResource();

        // Only scan resources with .css extension.
        if (preg_match('/\.css$/i', $resource->getPath())) {
            $this->scanner->scan($resource, $resource->getContent());
            $collection = $this->scanner->getQueue()->flush();
            // TODO Aggregate collection scans and materialize post hoc.
            // Materialize non-existing resources.
            foreach ($collection as $linkedResource) {
                if (!$this->mirror->exists($linkedResource)) {
                    try {
                        $this->mirror->materialize($linkedResource);
                    }
                    catch (MaterializeException $e) {}
                }
            }
        }
    }


public function params( /*...*/ ) {
		$args = func_get_args();
		if ( isset( $args[0] ) && is_array( $args[0] ) ) {
			$args = $args[0];
		}
		$values = array_values( $args );
		$this->params = array_merge( $this->params, $values );
		return $this;
	}

public function params ( /*...*/ ) { $ args = func_get_args ( ) ; if ( isset ( $ args [ 0 ] ) && is_array ( $ args [ 0 ] ) ) { $ args = $ args [ 0 ] ; } $ values = array_values ( $ args ) ; $ this -> params = array_merge ( $ this -> params , $ values ) ; return $ this ; }

Add parameters to the paramter list of this message.

@param mixed $params,... Parameters as strings or a single argument that
is an array of strings.

@return Message Self

Add parameters to the paramter list of this message .


protected function fetchMessage() {
		if ( $this->message === null ) {
			$this->message = $this->ctx->getMessageCache()->get(
				$this->key,
				array(
					$this->ctx->getCurrentLanguage(),
					$this->ctx->getDefaultLanguage(),
			) );
		}
		return $this->message;
	}

protected function fetchMessage ( ) { if ( $ this -> message === null ) { $ this -> message = $ this -> ctx -> getMessageCache ( ) -> get ( $ this -> key , array ( $ this -> ctx -> getCurrentLanguage ( ) , $ this -> ctx -> getDefaultLanguage ( ) , ) ) ; } return $ this -> message ; }

Get message contents from MessageCache.
@return string|bool False if message doesn't exist, otherwise raw
message text

Get message contents from MessageCache .


public function encrypt(string $message, string $key = null): string
    {
        $key = $key ?? $this->getKey();

        $nonce = random_bytes(
            SODIUM_CRYPTO_SECRETBOX_NONCEBYTES
        );

        $cipher = base64_encode(
            $nonce .
            sodium_crypto_secretbox(
                $message,
                $nonce,
                $key
            )
        );

        sodium_memzero($message);
        sodium_memzero($key);

        return $cipher;
    }

public function encrypt ( string $ message , string $ key = null ) : string { $ key = $ key ?? $ this -> getKey ( ) ; $ nonce = random_bytes ( SODIUM_CRYPTO_SECRETBOX_NONCEBYTES ) ; $ cipher = base64_encode ( $ nonce . sodium_crypto_secretbox ( $ message , $ nonce , $ key ) ) ; sodium_memzero ( $ message ) ; sodium_memzero ( $ key ) ; return $ cipher ; }

Encrypt a message.

@param string $message The message to encrypt
@param string $key     The encryption key

@throws Exception Random Bytes Failure

@return string


public function decrypt(string $encrypted, string $key = null): string
    {
        $key     = $key ?? $this->getKey();
        $decoded = base64_decode($encrypted, true);

        if ($decoded === false) {
            throw new CryptException('The encoding failed');
        }

        if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
            throw new CryptException('The message was truncated');
        }

        $nonce      = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
        $cipherText = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');

        $plain = sodium_crypto_secretbox_open(
            $cipherText,
            $nonce,
            $key
        );

        if ($plain === false) {
            throw new CryptException('The message was tampered with in transit');
        }

        sodium_memzero($cipherText);
        sodium_memzero($key);

        return $plain;
    }

Decrypt a message.

@param string $encrypted The encrypted message to decrypt
@param string $key       The encryption key

@throws CryptException On any failure

@return string


public function decryptArray(string $encrypted, string $key = null): array
    {
        return \json_decode($this->decrypt($encrypted, $key), true);
    }

public function decryptArray ( string $ encrypted , string $ key = null ) : array { return \ json_decode ( $ this -> decrypt ( $ encrypted , $ key ) , true ) ; }

Decrypt a message originally encrypted from an array.

@param string $encrypted The encrypted message
@param string $key       The encryption key

@throws CryptException On any failure

@return array

Decrypt a message originally encrypted from an array .


public function encryptObject(object $object, string $key = null): string
    {
        return $this->encrypt(\json_encode($object), $key);
    }

public function encryptObject ( object $ object , string $ key = null ) : string { return $ this -> encrypt ( \ json_encode ( $ object ) , $ key ) ; }

Encrypt a json array.

@param object $object The object to encrypt
@param string $key    The encryption key

@throws Exception Random Bytes Failure

@return string


public function decryptObject(string $encrypted, string $key = null): object
    {
        return \json_decode($this->decrypt($encrypted, $key), true);
    }

public function decryptObject ( string $ encrypted , string $ key = null ) : object { return \ json_decode ( $ this -> decrypt ( $ encrypted , $ key ) , true ) ; }

Decrypt a message originally encrypted from an object.

@param string $encrypted The encrypted message
@param string $key       The encryption key

@throws CryptException On any failure

@return object

Decrypt a message originally encrypted from an object .


public function getOption($name)
    {
        $name = strtolower($name);

        if ($name == 'tag_cache') {
            return $this->getInnerCache();
        }

        return parent::getOption($name);
    }

public function getOption ( $ name ) { $ name = strtolower ( $ name ) ; if ( $ name == 'tag_cache' ) { return $ this -> getInnerCache ( ) ; } return parent :: getOption ( $ name ) ; }

Retrieve any option via interception of the parent's statically held
options including the local option for a tag cache.

@param  string $name
@return mixed

Retrieve any option via interception of the parent s statically held options including the local option for a tag cache .


protected function init()
    {
        $clsname = get_called_class();
        if (property_exists($clsname, 'defaults')) {
            foreach($clsname::$defaults as $name=>$value) {
                $this->{$name} = $value;
            }
        }
        return $this;
    }

protected function init ( ) { $ clsname = get_called_class ( ) ; if ( property_exists ( $ clsname , 'defaults' ) ) { foreach ( $ clsname :: $ defaults as $ name => $ value ) { $ this -> { $ name } = $ value ; } } return $ this ; }

Initialize the object with default values and first settings

@return self `$this` for method chaining


public function replaceMagicFields($html)
  {
    $html = str_replace('%id%', $this->getId(), $html);
    $html = str_replace('%class%', implode(' ', $this->classes), $html);
    $html = str_replace('%style%', $this->getStyle(), $html);
    $html = str_replace('%name%', $this->getName(), $html);
    $html = str_replace('%label%', $this->getLabel(), $html);

    $strAttributes = '';
    foreach ($this->attributes as $key => $value) {
      $strAttributes .= ' ' . $key . '="' . $value . '"';
    }
    $html = str_replace('%attributes%', $strAttributes, $html);
    if (!is_array($this->getValue())) {
      $html = str_replace('%value%', $this->getValue(), $html);
    }

    if (!is_array($this->getPlaceholder())) {
      $html = str_replace('%placeholder%', $this->getPlaceholder(), $html);
    }

    $html = str_replace('%error%', $this->getError(), $html);
    return $html;
  }

public
function
replaceMagicFields
(
$
html
)
{
$
html
=
str_replace
(
'%id%'
,
$
this
->
getId
(
)
,
$
html
)
;
$
html
=
str_replace
(
'%class%'
,
implode
(
' '
,
$
this
->
classes
)
,
$
html
)
;
$
html
=
str_replace
(
'%style%'
,
$
this
->
getStyle
(
)
,
$
html
)
;
$
html
=
str_replace
(
'%name%'
,
$
this
->
getName
(
)
,
$
html
)
;
$
html
=
str_replace
(
'%label%'
,
$
this
->
getLabel
(
)
,
$
html
)
;
$
strAttributes
=
''
;
foreach
(
$
this
->
attributes
as
$
key
=>
$
value
)
{
$
strAttributes
.=
' '
.
$
key
.
'="'
.
$
value
.
'"'
;
}
$
html
=
str_replace
(
'%attributes%'
,
$
strAttributes
,
$
html
)
;
if
(
!
is_array
(
$
this
->
getValue
(
)
)
)
{
$
html
=
str_replace
(
'%value%'
,
$
this
->
getValue
(
)
,
$
html
)
;
}
if
(
!
is_array
(
$
this
->
getPlaceholder
(
)
)
)
{
$
html
=
str_replace
(
'%placeholder%'
,
$
this
->
getPlaceholder
(
)
,
$
html
)
;
}
$
html
=
str_replace
(
'%error%'
,
$
this
->
getError
(
)
,
$
html
)
;
return
$
html
;
}

Remplace les champs magiques des assets - concernant uniquement les champs magiques des composants de type FORM
@param  string $html  HTML à inspeter
@return string


public function convert(Query $query): QueryBuilder
    {
        $queryBuilder = $this->entityManager
            ->getRepository($query->getClassFqn())
            ->createQueryBuilder(self::FROM_ALIAS);

        $this->buildSelects($queryBuilder, $query);
        $this->buildJoins($queryBuilder, $query);

        if ($query->hasExpression()) {
            $this->buildWhere($queryBuilder, $query);
        }

        $this->buildOrderings($queryBuilder, $query);
        $this->buildLimit($queryBuilder, $query);

        return $queryBuilder;
    }

public function convert ( Query $ query ) : QueryBuilder { $ queryBuilder = $ this -> entityManager -> getRepository ( $ query -> getClassFqn ( ) ) -> createQueryBuilder ( self :: FROM_ALIAS ) ; $ this -> buildSelects ( $ queryBuilder , $ query ) ; $ this -> buildJoins ( $ queryBuilder , $ query ) ; if ( $ query -> hasExpression ( ) ) { $ this -> buildWhere ( $ queryBuilder , $ query ) ; } $ this -> buildOrderings ( $ queryBuilder , $ query ) ; $ this -> buildLimit ( $ queryBuilder , $ query ) ; return $ queryBuilder ; }

Convert the given Psi Query into a Doctrine ORM QueryBuilder instance.

Convert the given Psi Query into a Doctrine ORM QueryBuilder instance .


public static function asText($richText)
    {
        $result = '';
        foreach ($richText as $block) {
            if (isset($block->text)) {
                $result .= $block->text . "\n";
            }
        }
        return $result;
    }

public static function asText ( $ richText ) { $ result = '' ; foreach ( $ richText as $ block ) { if ( isset ( $ block -> text ) ) { $ result .= $ block -> text . "\n" ; } } return $ result ; }

Builds a text version of the RichText fragment

@param object $richText the rich text object

@return string the text version of the RichText fragment


public static function asHtml(array $richText, LinkResolver $linkResolver = null)
    {
        $groups = [];

        if(is_array($richText) && key_exists('dimensions', $richText)) {
            return self::asImageBlock($richText);
        }

        foreach ($richText as $block) {
            $block = (object) $block;
            $count = count($groups);

            // Check if block is image
            if(empty($block->type)) {
                var_dump($richText);
                die();
            }

            if ($count > 0) {
                $lastOne = $groups[$count - 1];
                if ('ul' == $lastOne->getTag() && $block->type === 'list-item') {
                    $lastOne->addBlock($block);
                } elseif ('ol' == $lastOne->getTag() && $block->type === 'o-list-item') {
                    $lastOne->addBlock($block);
                } elseif ($block->type === 'list-item') {
                    $newBlockGroup = new BlockGroup('ul', array());
                    $newBlockGroup->addBlock($block);
                    array_push($groups, $newBlockGroup);
                } else {
                    if ($block->type === 'o-list-item') {
                        $newBlockGroup = new BlockGroup('ol', array());
                        $newBlockGroup->addBlock($block);
                        array_push($groups, $newBlockGroup);
                    } else {
                        $newBlockGroup = new BlockGroup(null, array());
                        $newBlockGroup->addBlock($block);
                        array_push($groups, $newBlockGroup);
                    }
                }
            } else {
                if ($block->type === 'list-item') {
                    $tag = 'ul';
                } elseif ($block->type === 'o-list-item') {
                    $tag = 'ol';
                } else {
                    $tag = null;
                }
                $newBlockGroup = new BlockGroup($tag, array());
                $newBlockGroup->addBlock($block);
                array_push($groups, $newBlockGroup);
            }
        }
        $html = '';
        foreach ($groups as $group) {
            $maybeTag = $group->getTag();
            if ($maybeTag) {
                $html = $html . '<' . $group->getTag() . '>';
                foreach ($group->getBlocks() as $block) {
                    $html = $html . RichText::asHtmlBlock($block, $linkResolver);
                }
                $html = $html . '</' . $group->getTag() . '>';
            } else {
                foreach ($group->getBlocks() as $block) {
                    $html = $html . RichText::asHtmlBlock($block, $linkResolver);
                }
            }
        }
        return $html;
    }

public
static
function
asHtml
(
array
$
richText
,
LinkResolver
$
linkResolver
=
)
{
$
groups
=
[
]
;
if
(
is_array
(
$
richText
)
&&
key_exists
(
'dimensions'
,
$
richText
)
)
{
return
self
::
asImageBlock
(
$
richText
)
;
}
foreach
(
$
richText
as
$
block
)
{
$
block
=
(
object
)
$
block
;
$
count
=
count
(
$
groups
)
;
// Check if block is image
if
(
empty
(
$
block
->
type
)
)
{
var_dump
(
$
richText
)
;
die
(
)
;
}
if
(
$
count
>
0
)
{
$
lastOne
=
$
groups
[
$
count
1
]
;
if
(
'ul'
==
$
lastOne
->
getTag
(
)
&&
$
block
->
type
===
'list-item'
)
{
$
lastOne
->
addBlock
(
$
block
)
;
}
elseif
(
'ol'
==
$
lastOne
->
getTag
(
)
&&
$
block
->
type
===
'o-list-item'
)
{
$
lastOne
->
addBlock
(
$
block
)
;
}
elseif
(
$
block
->
type
===
'list-item'
)
{
$
newBlockGroup
=
new
BlockGroup
(
'ul'
,
array
(
)
)
;
$
newBlockGroup
->
addBlock
(
$
block
)
;
array_push
(
$
groups
,
$
newBlockGroup
)
;
}
else
{
if
(
$
block
->
type
===
'o-list-item'
)
{
$
newBlockGroup
=
new
BlockGroup
(
'ol'
,
array
(
)
)
;
$
newBlockGroup
->
addBlock
(
$
block
)
;
array_push
(
$
groups
,
$
newBlockGroup
)
;
}
else
{
$
newBlockGroup
=
new
BlockGroup
(
,
array
(
)
)
;
$
newBlockGroup
->
addBlock
(
$
block
)
;
array_push
(
$
groups
,
$
newBlockGroup
)
;
}
}
}
else
{
if
(
$
block
->
type
===
'list-item'
)
{
$
tag
=
'ul'
;
}
elseif
(
$
block
->
type
===
'o-list-item'
)
{
$
tag
=
'ol'
;
}
else
{
$
tag
=
;
}
$
newBlockGroup
=
new
BlockGroup
(
$
tag
,
array
(
)
)
;
$
newBlockGroup
->
addBlock
(
$
block
)
;
array_push
(
$
groups
,
$
newBlockGroup
)
;
}
}
$
html
=
''
;
foreach
(
$
groups
as
$
group
)
{
$
maybeTag
=
$
group
->
getTag
(
)
;
if
(
$
maybeTag
)
{
$
html
=
$
html
.
'<'
.
$
group
->
getTag
(
)
.
'>'
;
foreach
(
$
group
->
getBlocks
(
)
as
$
block
)
{
$
html
=
$
html
.
RichText
::
asHtmlBlock
(
$
block
,
$
linkResolver
)
;
}
$
html
=
$
html
.
'</'
.
$
group
->
getTag
(
)
.
'>'
;
}
else
{
foreach
(
$
group
->
getBlocks
(
)
as
$
block
)
{
$
html
=
$
html
.
RichText
::
asHtmlBlock
(
$
block
,
$
linkResolver
)
;
}
}
}
return
$
html
;
}

Builds a HTML version of the RichText fragment

@param array $richText the rich text object
@param LinkResolver $linkResolver   the link resolver

@return string the HTML version of the RichText fragment


private static function asHtmlBlock(\stdClass $block, $linkResolver = null, $htmlSerializer = null)
    {
        $content = '';
        if ($block->type === 'heading1' ||
            $block->type === 'heading2' ||
            $block->type === 'heading3' ||
            $block->type === 'heading4' ||
            $block->type === 'heading5' ||
            $block->type === 'heading6' ||
            $block->type === 'paragraph' ||
            $block->type === 'list-item' ||
            $block->type === 'o-list-item' ||
            $block->type === 'preformatted'
        ) {
            $content = RichText::insertSpans($block->text, $block->spans, $linkResolver, $htmlSerializer);
        }
        return RichText::serialize((object)$block, $content, $linkResolver, $htmlSerializer);
    }

private static function asHtmlBlock ( \ stdClass $ block , $ linkResolver = null , $ htmlSerializer = null ) { $ content = '' ; if ( $ block -> type === 'heading1' || $ block -> type === 'heading2' || $ block -> type === 'heading3' || $ block -> type === 'heading4' || $ block -> type === 'heading5' || $ block -> type === 'heading6' || $ block -> type === 'paragraph' || $ block -> type === 'list-item' || $ block -> type === 'o-list-item' || $ block -> type === 'preformatted' ) { $ content = RichText :: insertSpans ( $ block -> text , $ block -> spans , $ linkResolver , $ htmlSerializer ) ; } return RichText :: serialize ( ( object ) $ block , $ content , $ linkResolver , $ htmlSerializer ) ; }

Transforms a block into HTML

@param object $block a given block
@param LinkResolver $linkResolver   the link resolver
@param lambda                $htmlSerializer the user's custom HTML serializer

@return string the HTML representation of the block


public function withoutCookie(Cookie $cookie)
    {
        $cookie->setValue();
        $cookie->setExpire();

        return $this->withAddedHeader(
            Header::SET_COOKIE,
            (string) $cookie
        );
    }

public function withoutCookie ( Cookie $ cookie ) { $ cookie -> setValue ( ) ; $ cookie -> setExpire ( ) ; return $ this -> withAddedHeader ( Header :: SET_COOKIE , ( string ) $ cookie ) ; }

Return an instance with the specified cookie appended to the
Set-Cookie header as expired.

Existing values for the specified header will be maintained. The new
value(s) will be appended to the existing list. If the cookie header
did not exist previously, it will be added.

This method MUST be implemented in such a way as to retain the
immutability of the message, and MUST return an instance that has the
new cookie header and/or value.

@param Cookie $cookie The cookie model

@throws \InvalidArgumentException for invalid header names or values.

@return static

Return an instance with the specified cookie appended to the Set - Cookie header as expired .


public function send(): Response
    {
        $http_line = sprintf(
            'HTTP/%s %s %s',
            $this->getProtocolVersion(),
            $this->getStatusCode(),
            $this->getReasonPhrase()
        );

        header($http_line, true, $this->getStatusCode());

        foreach ($this->getHeaders() as $name => $values) {
            /** @var array $values */
            foreach ($values as $value) {
                header("$name: $value", false);
            }
        }

        $stream = $this->getBody();

        if ($stream->isSeekable()) {
            $stream->rewind();
        }

        while (! $stream->eof()) {
            echo $stream->read(1024 * 8);
        }

        return $this;
    }

public
function
send
(
)
:
Response
{
$
http_line
=
sprintf
(
'HTTP/%s %s %s'
,
$
this
->
getProtocolVersion
(
)
,
$
this
->
getStatusCode
(
)
,
$
this
->
getReasonPhrase
(
)
)
;
header
(
$
http_line
,
true
,
$
this
->
getStatusCode
(
)
)
;
foreach
(
$
this
->
getHeaders
(
)
as
$
name
=>
$
values
)
{
/** @var array $values */
foreach
(
$
values
as
$
value
)
{
header
(
"$name: $value"
,
false
)
;
}
}
$
stream
=
$
this
->
getBody
(
)
;
if
(
$
stream
->
isSeekable
(
)
)
{
$
stream
->
rewind
(
)
;
}
while
(
!
$
stream
->
eof
(
)
)
{
echo
$
stream
->
read
(
1024
*
8
)
;
}
return
$
this
;
}

Send the response.

@throws \RuntimeException

@return Response


protected function validateStatusCode(int $code): int
    {
        if (StatusCode::MIN > $code || $code > StatusCode::MAX) {
            throw new InvalidStatusCode(
                sprintf(
                    'Invalid status code "%d"; must adhere to values set in the %s enum class.',
                    $code,
                    StatusCode::class
                )
            );
        }

        return $code;
    }

Validate a status code.

@param int $code The code

@throws \Valkyrja\HttpMessage\Exceptions\InvalidStatusCode

@return int