public function link($name, array $params = array())
    {
        if ($this->has($name)) {
            $route = $this->routes[$name];
            $url = $route['url'];
            foreach ($params as $key => $val) {
                $url = str_replace('{'.$key.'}', $val, $url);
            }
            $url = preg_replace("/\{\w+\}/", '', $url);
            $name = ltrim(str_replace(AUTO_ROUTE, '', $url), '/');
        }

        return $this->asset($name);
    }

public function link ( $ name , array $ params = array ( ) ) { if ( $ this -> has ( $ name ) ) { $ route = $ this -> routes [ $ name ] ; $ url = $ route [ 'url' ] ; foreach ( $ params as $ key => $ val ) { $ url = str_replace ( '{' . $ key . '}' , $ val , $ url ) ; } $ url = preg_replace ( "/\{\w+\}/" , '' , $ url ) ; $ name = ltrim ( str_replace ( AUTO_ROUTE , '' , $ url ) , '/' ) ; } return $ this -> asset ( $ name ) ; }

Generiert einen Link zu einer bestimmten Route.

@param $name Name der Route oder URL

@return string

Generiert einen Link zu einer bestimmten Route .


public function withProtocolVersion(string $version)
    {
        $this->validateProtocolVersion($version);

        $this->protocol = $version;

        return $this;
    }

public function withProtocolVersion ( string $ version ) { $ this -> validateProtocolVersion ( $ version ) ; $ this -> protocol = $ version ; return $ this ; }

Return an instance with the specified HTTP protocol version.

The version string MUST contain only the HTTP version number (e.g.,
"1.1", "1.0").

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 protocol version.

@param string $version HTTP protocol version

@throws \Valkyrja\HttpMessage\Exceptions\InvalidProtocolVersion

@return static

Return an instance with the specified HTTP protocol version .


protected function assertHeaderValues(string ...$values): array
    {
        foreach ($values as $value) {
            HeaderSecurity::assertValid($value);
        }

        return $values;
    }

protected function assertHeaderValues ( string ... $ values ) : array { foreach ( $ values as $ value ) { HeaderSecurity :: assertValid ( $ value ) ; } return $ values ; }

Filter header values.

@param string[] ...$values Header values

@throws \InvalidArgumentException

@return string[]


protected function injectHeader(string $header, string $value, array $headers = null, bool $override = false): array
    {
        // The headers
        $headers = $headers ?? [];
        // Normalize the content type header
        $normalized = strtolower($header);
        // The original value for the header (if it exists in the headers array)
        // Defaults to the value passed in
        $originalValue = $value;

        // Iterate through all the headers
        foreach ($headers as $headerIndex => $headerValue) {
            // Normalize the header name and check if it matches the normalized
            // passed in header
            if (strtolower($headerIndex) === $normalized) {
                // Set the original value as this header value
                $originalValue = $headerValue;

                // Unset the header as we want to use the header string that was
                // passed in as the header
                unset($headers[$headerIndex]);
            }
        }

        // Set the header in the headers list
        $headers[$header] = [$override ? $originalValue : $value];

        return $headers;
    }

Inject a header in a headers array.

@param string $header   The header to set
@param string $value    The value to set
@param array  $headers  [optional] The headers
@param bool   $override [optional] Whether to override any existing value

@return array


protected function now()
    {
        $dt = new DateTime();
        $dt->setTimezone(new DateTimeZone('UTC'));
        return $dt->format(DateTime::ISO8601);
    }

protected function now ( ) { $ dt = new DateTime ( ) ; $ dt -> setTimezone ( new DateTimeZone ( 'UTC' ) ) ; return $ dt -> format ( DateTime :: ISO8601 ) ; }

Returns current time formatted in ISO-8601 at UTC timezone

@return string

Returns current time formatted in ISO - 8601 at UTC timezone


protected function checkAndUpdateFields(array $cookie, Net_URL2 $setter = null)
    {
        if ($missing = array_diff(array('name', 'value'), array_keys($cookie))) {
            throw new HTTP_Request2_LogicException(
                "Cookie array should contain 'name' and 'value' fields",
                HTTP_Request2_Exception::MISSING_VALUE
            );
        }
        if (preg_match(HTTP_Request2::REGEXP_INVALID_COOKIE, $cookie['name'])) {
            throw new HTTP_Request2_LogicException(
                "Invalid cookie name: '{$cookie['name']}'",
                HTTP_Request2_Exception::INVALID_ARGUMENT
            );
        }
        if (preg_match(HTTP_Request2::REGEXP_INVALID_COOKIE, $cookie['value'])) {
            throw new HTTP_Request2_LogicException(
                "Invalid cookie value: '{$cookie['value']}'",
                HTTP_Request2_Exception::INVALID_ARGUMENT
            );
        }
        $cookie += array('domain' => '', 'path' => '', 'expires' => null, 'secure' => false);

        // Need ISO-8601 date @ UTC timezone
        if (!empty($cookie['expires'])
            && !preg_match('/^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\+0000$/', $cookie['expires'])
        ) {
            try {
                $dt = new DateTime($cookie['expires']);
                $dt->setTimezone(new DateTimeZone('UTC'));
                $cookie['expires'] = $dt->format(DateTime::ISO8601);
            } catch (Exception $e) {
                throw new HTTP_Request2_LogicException($e->getMessage());
            }
        }

        if (empty($cookie['domain']) || empty($cookie['path'])) {
            if (!$setter) {
                throw new HTTP_Request2_LogicException(
                    'Cookie misses domain and/or path component, cookie setter URL needed',
                    HTTP_Request2_Exception::MISSING_VALUE
                );
            }
            if (empty($cookie['domain'])) {
                if ($host = $setter->getHost()) {
                    $cookie['domain'] = $host;
                } else {
                    throw new HTTP_Request2_LogicException(
                        'Setter URL does not contain host part, can\'t set cookie domain',
                        HTTP_Request2_Exception::MISSING_VALUE
                    );
                }
            }
            if (empty($cookie['path'])) {
                $path = $setter->getPath();
                $cookie['path'] = empty($path)? '/': substr($path, 0, strrpos($path, '/') + 1);
            }
        }

        if ($setter && !$this->domainMatch($setter->getHost(), $cookie['domain'])) {
            throw new HTTP_Request2_MessageException(
                "Domain " . $setter->getHost() . " cannot set cookies for "
                . $cookie['domain']
            );
        }

        return $cookie;
    }

Checks cookie array for correctness, possibly updating its 'domain', 'path' and 'expires' fields

The checks are as follows:
- cookie array should contain 'name' and 'value' fields;
- name and value should not contain disallowed symbols;
- 'expires' should be either empty parseable by DateTime;
- 'domain' and 'path' should be either not empty or an URL where
cookie was set should be provided.
- if $setter is provided, then document at that URL should be allowed
to set a cookie for that 'domain'. If $setter is not provided,
then no domain checks will be made.

'expires' field will be converted to ISO8601 format from COOKIE format,
'domain' and 'path' will be set from setter URL if empty.

@param array    $cookie cookie data, as returned by
{@link HTTP_Request2_Response::getCookies()}
@param Net_URL2 $setter URL of the document that sent Set-Cookie header

@return   array    Updated cookie array
@throws   HTTP_Request2_LogicException
@throws   HTTP_Request2_MessageException

Checks cookie array for correctness possibly updating its domain path and expires fields


public function store(array $cookie, Net_URL2 $setter = null)
    {
        $cookie = $this->checkAndUpdateFields($cookie, $setter);

        if (strlen($cookie['value'])
            && (is_null($cookie['expires']) || $cookie['expires'] > $this->now())
        ) {
            if (!isset($this->cookies[$cookie['domain']])) {
                $this->cookies[$cookie['domain']] = array();
            }
            if (!isset($this->cookies[$cookie['domain']][$cookie['path']])) {
                $this->cookies[$cookie['domain']][$cookie['path']] = array();
            }
            $this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']] = $cookie;

        } elseif (isset($this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']])) {
            unset($this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']]);
        }
    }

public function store ( array $ cookie , Net_URL2 $ setter = null ) { $ cookie = $ this -> checkAndUpdateFields ( $ cookie , $ setter ) ; if ( strlen ( $ cookie [ 'value' ] ) && ( is_null ( $ cookie [ 'expires' ] ) || $ cookie [ 'expires' ] > $ this -> now ( ) ) ) { if ( ! isset ( $ this -> cookies [ $ cookie [ 'domain' ] ] ) ) { $ this -> cookies [ $ cookie [ 'domain' ] ] = array ( ) ; } if ( ! isset ( $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] ) ) { $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] = array ( ) ; } $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] [ $ cookie [ 'name' ] ] = $ cookie ; } elseif ( isset ( $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] [ $ cookie [ 'name' ] ] ) ) { unset ( $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] [ $ cookie [ 'name' ] ] ) ; } }

Stores a cookie in the jar

@param array    $cookie cookie data, as returned by
{@link HTTP_Request2_Response::getCookies()}
@param Net_URL2 $setter URL of the document that sent Set-Cookie header

@throws   HTTP_Request2_Exception


public function addCookiesFromResponse(HTTP_Request2_Response $response, Net_URL2 $setter)
    {
        foreach ($response->getCookies() as $cookie) {
            $this->store($cookie, $setter);
        }
    }

public function addCookiesFromResponse ( HTTP_Request2_Response $ response , Net_URL2 $ setter ) { foreach ( $ response -> getCookies ( ) as $ cookie ) { $ this -> store ( $ cookie , $ setter ) ; } }

Adds cookies set in HTTP response to the jar

@param HTTP_Request2_Response $response HTTP response message
@param Net_URL2               $setter   original request URL, needed for
setting default domain/path


public function getMatching(Net_URL2 $url, $asString = false)
    {
        $host   = $url->getHost();
        $path   = $url->getPath();
        $secure = 0 == strcasecmp($url->getScheme(), 'https');

        $matched = $ret = array();
        foreach (array_keys($this->cookies) as $domain) {
            if ($this->domainMatch($host, $domain)) {
                foreach (array_keys($this->cookies[$domain]) as $cPath) {
                    if (0 === strpos($path, $cPath)) {
                        foreach ($this->cookies[$domain][$cPath] as $name => $cookie) {
                            if (!$cookie['secure'] || $secure) {
                                $matched[$name][strlen($cookie['path'])] = $cookie;
                            }
                        }
                    }
                }
            }
        }
        foreach ($matched as $cookies) {
            krsort($cookies);
            $ret = array_merge($ret, $cookies);
        }
        if (!$asString) {
            return $ret;
        } else {
            $str = '';
            foreach ($ret as $c) {
                $str .= (empty($str)? '': '; ') . $c['name'] . '=' . $c['value'];
            }
            return $str;
        }
    }

public
function
getMatching
(
Net_URL2
$
url
,
$
asString
=
false
)
{
$
host
=
$
url
->
getHost
(
)
;
$
path
=
$
url
->
getPath
(
)
;
$
secure
=
0
==
strcasecmp
(
$
url
->
getScheme
(
)
,
'https'
)
;
$
matched
=
$
ret
=
array
(
)
;
foreach
(
array_keys
(
$
this
->
cookies
)
as
$
domain
)
{
if
(
$
this
->
domainMatch
(
$
host
,
$
domain
)
)
{
foreach
(
array_keys
(
$
this
->
cookies
[
$
domain
]
)
as
$
cPath
)
{
if
(
0
===
strpos
(
$
path
,
$
cPath
)
)
{
foreach
(
$
this
->
cookies
[
$
domain
]
[
$
cPath
]
as
$
name
=>
$
cookie
)
{
if
(
!
$
cookie
[
'secure'
]
||
$
secure
)
{
$
matched
[
$
name
]
[
strlen
(
$
cookie
[
'path'
]
)
]
=
$
cookie
;
}
}
}
}
}
}
foreach
(
$
matched
as
$
cookies
)
{
krsort
(
$
cookies
)
;
$
ret
=
array_merge
(
$
ret
,
$
cookies
)
;
}
if
(
!
$
asString
)
{
return
$
ret
;
}
else
{
$
str
=
''
;
foreach
(
$
ret
as
$
c
)
{
$
str
.=
(
empty
(
$
str
)
''
:
'; '
)
.
$
c
[
'name'
]
.
'='
.
$
c
[
'value'
]
;
}
return
$
str
;
}
}

Returns all cookies matching a given request URL

The following checks are made:
- cookie domain should match request host
- cookie path should be a prefix for request path
- 'secure' cookies will only be sent for HTTPS requests

@param Net_URL2 $url      Request url
@param bool     $asString Whether to return cookies as string for "Cookie: " header

@return array|string Matching cookies


public function getAll()
    {
        $cookies = array();
        foreach (array_keys($this->cookies) as $domain) {
            foreach (array_keys($this->cookies[$domain]) as $path) {
                foreach ($this->cookies[$domain][$path] as $name => $cookie) {
                    $cookies[] = $cookie;
                }
            }
        }
        return $cookies;
    }

public function getAll ( ) { $ cookies = array ( ) ; foreach ( array_keys ( $ this -> cookies ) as $ domain ) { foreach ( array_keys ( $ this -> cookies [ $ domain ] ) as $ path ) { foreach ( $ this -> cookies [ $ domain ] [ $ path ] as $ name => $ cookie ) { $ cookies [ ] = $ cookie ; } } } return $ cookies ; }

Returns all cookies stored in a jar

@return array


public function serialize()
    {
        $cookies = $this->getAll();
        if (!$this->serializeSession) {
            for ($i = count($cookies) - 1; $i >= 0; $i--) {
                if (empty($cookies[$i]['expires'])) {
                    unset($cookies[$i]);
                }
            }
        }
        return serialize(array(
            'cookies'          => $cookies,
            'serializeSession' => $this->serializeSession,
            'useList'          => $this->useList
        ));
    }

public function serialize ( ) { $ cookies = $ this -> getAll ( ) ; if ( ! $ this -> serializeSession ) { for ( $ i = count ( $ cookies ) - 1 ; $ i >= 0 ; $ i -- ) { if ( empty ( $ cookies [ $ i ] [ 'expires' ] ) ) { unset ( $ cookies [ $ i ] ) ; } } } return serialize ( array ( 'cookies' => $ cookies , 'serializeSession' => $ this -> serializeSession , 'useList' => $ this -> useList ) ) ; }

Returns string representation of object

@return string

@see    Serializable::serialize()


public function unserialize($serialized)
    {
        $data = unserialize($serialized);
        $now  = $this->now();
        $this->serializeSessionCookies($data['serializeSession']);
        $this->usePublicSuffixList($data['useList']);
        foreach ($data['cookies'] as $cookie) {
            if (!empty($cookie['expires']) && $cookie['expires'] <= $now) {
                continue;
            }
            if (!isset($this->cookies[$cookie['domain']])) {
                $this->cookies[$cookie['domain']] = array();
            }
            if (!isset($this->cookies[$cookie['domain']][$cookie['path']])) {
                $this->cookies[$cookie['domain']][$cookie['path']] = array();
            }
            $this->cookies[$cookie['domain']][$cookie['path']][$cookie['name']] = $cookie;
        }
    }

public function unserialize ( $ serialized ) { $ data = unserialize ( $ serialized ) ; $ now = $ this -> now ( ) ; $ this -> serializeSessionCookies ( $ data [ 'serializeSession' ] ) ; $ this -> usePublicSuffixList ( $ data [ 'useList' ] ) ; foreach ( $ data [ 'cookies' ] as $ cookie ) { if ( ! empty ( $ cookie [ 'expires' ] ) && $ cookie [ 'expires' ] <= $ now ) { continue ; } if ( ! isset ( $ this -> cookies [ $ cookie [ 'domain' ] ] ) ) { $ this -> cookies [ $ cookie [ 'domain' ] ] = array ( ) ; } if ( ! isset ( $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] ) ) { $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] = array ( ) ; } $ this -> cookies [ $ cookie [ 'domain' ] ] [ $ cookie [ 'path' ] ] [ $ cookie [ 'name' ] ] = $ cookie ; } }

Constructs the object from serialized string

@param string $serialized string representation

@see   Serializable::unserialize()


public function domainMatch($requestHost, $cookieDomain)
    {
        if ($requestHost == $cookieDomain) {
            return true;
        }
        // IP address, we require exact match
        if (preg_match('/^(?:\d{1,3}\.){3}\d{1,3}$/', $requestHost)) {
            return false;
        }
        if ('.' != $cookieDomain[0]) {
            $cookieDomain = '.' . $cookieDomain;
        }
        // prevents setting cookies for '.com' and similar domains
        if (!$this->useList && substr_count($cookieDomain, '.') < 2
            || $this->useList && !self::getRegisteredDomain($cookieDomain)
        ) {
            return false;
        }
        return substr('.' . $requestHost, -strlen($cookieDomain)) == $cookieDomain;
    }

Checks whether a cookie domain matches a request host.

The method is used by {@link store()} to check for whether a document
at given URL can set a cookie with a given domain attribute and by
{@link getMatching()} to find cookies matching the request URL.

@param string $requestHost  request host
@param string $cookieDomain cookie domain

@return   bool    match success

Checks whether a cookie domain matches a request host .


function &factory($command, &$config)
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
            $a = PEAR::raiseError("unknown command `$command'");
            return $a;
        }
        $class = $GLOBALS['_PEAR_Command_commandlist'][$command];
        if (!class_exists($class)) {
            require_once $GLOBALS['_PEAR_Command_objects'][$class];
        }
        if (!class_exists($class)) {
            $a = PEAR::raiseError("unknown command `$command'");
            return $a;
        }
        $ui =& PEAR_Command::getFrontendObject();
        $obj = &new $class($ui, $config);
        return $obj;
    }

function
&
factory
(
$
command
,
&
$
config
)
{
if
(
empty
(
$
GLOBALS
[
'_PEAR_Command_commandlist'
]
)
)
{
PEAR_Command
::
registerCommands
(
)
;
}
if
(
isset
(
$
GLOBALS
[
'_PEAR_Command_shortcuts'
]
[
$
command
]
)
)
{
$
command
=
$
GLOBALS
[
'_PEAR_Command_shortcuts'
]
[
$
command
]
;
}
if
(
!
isset
(
$
GLOBALS
[
'_PEAR_Command_commandlist'
]
[
$
command
]
)
)
{
$
a
=
PEAR
::
raiseError
(
"unknown command `$command'"
)
;
return
$
a
;
}
$
class
=
$
GLOBALS
[
'_PEAR_Command_commandlist'
]
[
$
command
]
;
if
(
!
class_exists
(
$
class
)
)
{
require_once
$
GLOBALS
[
'_PEAR_Command_objects'
]
[
$
class
]
;
}
if
(
!
class_exists
(
$
class
)
)
{
$
a
=
PEAR
::
raiseError
(
"unknown command `$command'"
)
;
return
$
a
;
}
$
ui
=
&
PEAR_Command
::
getFrontendObject
(
)
;
$
obj
=
&
new
$
class
(
$
ui
,
$
config
)
;
return
$
obj
;
}

Get the right object for executing a command.

@param string $command The name of the command
@param object $config  Instance of PEAR_Config object

@return object the command object or a PEAR error

@access public
@static

Get the right object for executing a command .


function getGetoptArgs($command, &$short_args, &$long_args)
    {
        if (empty($GLOBALS['_PEAR_Command_commandlist'])) {
            PEAR_Command::registerCommands();
        }
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (!isset($GLOBALS['_PEAR_Command_commandlist'][$command])) {
            return null;
        }
        $obj = &PEAR_Command::getObject($command);
        return $obj->getGetoptArgs($command, $short_args, $long_args);
    }

function getGetoptArgs ( $ command , & $ short_args , & $ long_args ) { if ( empty ( $ GLOBALS [ '_PEAR_Command_commandlist' ] ) ) { PEAR_Command :: registerCommands ( ) ; } if ( isset ( $ GLOBALS [ '_PEAR_Command_shortcuts' ] [ $ command ] ) ) { $ command = $ GLOBALS [ '_PEAR_Command_shortcuts' ] [ $ command ] ; } if ( ! isset ( $ GLOBALS [ '_PEAR_Command_commandlist' ] [ $ command ] ) ) { return null ; } $ obj = & PEAR_Command :: getObject ( $ command ) ; return $ obj -> getGetoptArgs ( $ command , $ short_args , $ long_args ) ; }

Compiles arguments for getopt.

@param string $command     command to get optstring for
@param string $short_args  (reference) short getopt format
@param array  $long_args   (reference) long getopt format

@return void

@access public
@static


function getHelp($command)
    {
        $cmds = PEAR_Command::getCommands();
        if (isset($GLOBALS['_PEAR_Command_shortcuts'][$command])) {
            $command = $GLOBALS['_PEAR_Command_shortcuts'][$command];
        }
        if (isset($cmds[$command])) {
            $obj = &PEAR_Command::getObject($command);
            return $obj->getHelp($command);
        }
        return false;
    }

function getHelp ( $ command ) { $ cmds = PEAR_Command :: getCommands ( ) ; if ( isset ( $ GLOBALS [ '_PEAR_Command_shortcuts' ] [ $ command ] ) ) { $ command = $ GLOBALS [ '_PEAR_Command_shortcuts' ] [ $ command ] ; } if ( isset ( $ cmds [ $ command ] ) ) { $ obj = & PEAR_Command :: getObject ( $ command ) ; return $ obj -> getHelp ( $ command ) ; } return false ; }

Get help for command.

@param string $command Name of the command to return help for

@access public
@static


function &singleton($type = null)
    {
        if ($type === null) {
            if (!isset($GLOBALS['_PEAR_FRONTEND_SINGLETON'])) {
                $a = false;
                return $a;
            }
            return $GLOBALS['_PEAR_FRONTEND_SINGLETON'];
        }

        $a = PEAR_Frontend::setFrontendClass($type);
        return $a;
    }

function & singleton ( $ type = null ) { if ( $ type === null ) { if ( ! isset ( $ GLOBALS [ '_PEAR_FRONTEND_SINGLETON' ] ) ) { $ a = false ; return $ a ; } return $ GLOBALS [ '_PEAR_FRONTEND_SINGLETON' ] ; } $ a = PEAR_Frontend :: setFrontendClass ( $ type ) ; return $ a ; }

Retrieve the frontend object
@return PEAR_Frontend_CLI|PEAR_Frontend_Web|PEAR_Frontend_Gtk
@static


public function convert(Expression $expression, NumberSystem $targetSystem)
    {
        $parsingResult   = $expression->value();
        $expressionParts = $this->getExpressionParts($expression);

        foreach ($expressionParts as $part) {
            $parsedPart = $this->parseExpressionPart($part, $expression->getNumberSystem(), $targetSystem);

            if ($parsedPart !== $part) {
                $parsingResult = preg_replace('/'.$part.'/', $parsedPart, $parsingResult, 1);
            }
        }

        return new Expression($parsingResult, $targetSystem);
    }

public function convert ( Expression $ expression , NumberSystem $ targetSystem ) { $ parsingResult = $ expression -> value ( ) ; $ expressionParts = $ this -> getExpressionParts ( $ expression ) ; foreach ( $ expressionParts as $ part ) { $ parsedPart = $ this -> parseExpressionPart ( $ part , $ expression -> getNumberSystem ( ) , $ targetSystem ) ; if ( $ parsedPart !== $ part ) { $ parsingResult = preg_replace ( '/' . $ part . '/' , $ parsedPart , $ parsingResult , 1 ) ; } } return new Expression ( $ parsingResult , $ targetSystem ) ; }

Convert expression from one NumberSystem to another

@param Expression   $expression
@param NumberSystem $targetSystem

@return Expression


protected function parseExpressionPart($part, NumberSystem $sourceSystem, NumberSystem $targetSystem)
    {
        try {
            // if it is a valid number of the source-system convert it
            $sourceNumber = new Number($part, $sourceSystem);

            return $sourceNumber->convert($targetSystem)->value();
        } catch (NumberParseException $e) {
            return $part;
        }
    }

Parse the part of an expression.

@param $part

@return Number


protected function _processKey($config, $key, $value)
    {
        if (strpos($key, $this->_nestSeparator) !== false) {
            $pieces = explode($this->_nestSeparator, $key, 2);
            if (strlen($pieces[0]) && strlen($pieces[1])) {
                if (!isset($config[$pieces[0]])) {
                    if ($pieces[0] === '0' && !empty($config)) {
                        // convert the current values in $config into an array
                        $config = array($pieces[0] => $config);
                    } else {
                        $config[$pieces[0]] = array();
                    }
                } elseif (!is_array($config[$pieces[0]])) {
                    /**
                     * @see Zend_Config_Exception
                     */

                    throw new Zend_Config_Exception("Cannot create sub-key for '{$pieces[0]}' as key already exists");
                }
                $config[$pieces[0]] = $this->_processKey($config[$pieces[0]], $pieces[1], $value);
            } else {
                /**
                 * @see Zend_Config_Exception
                 */

                throw new Zend_Config_Exception("Invalid key '$key'");
            }
        } else {
            $config[$key] = $value;
        }
        return $config;
    }

/**
                     * @see Zend_Config_Exception
                     */

/**
                 * @see Zend_Config_Exception
                 */

Assign the key's value to the property list. Handles the
nest separator for sub-properties.

@param  array  $config
@param  string $key
@param  string $value
@throws Zend_Config_Exception
@return array

Assign the key s value to the property list . Handles the nest separator for sub - properties .


protected function _unicodeTrim($value, $charlist = '\\\\s')
    {
        $chars = preg_replace(
            array( '/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'),
            array( '\\\\\\0', '\\', '\/' ),
            $charlist
        );

        $pattern = '^[' . $chars . ']*|[' . $chars . ']*$';
        return preg_replace("/$pattern/sSD", '', $value);
    }

protected function _unicodeTrim ( $ value , $ charlist = '\\\\s' ) { $ chars = preg_replace ( array ( '/[\^\-\]\\\]/S' , '/\\\{4}/S' , '/\//' ) , array ( '\\\\\\0' , '\\' , '\/' ) , $ charlist ) ; $ pattern = '^[' . $ chars . ']*|[' . $ chars . ']*$' ; return preg_replace ( "/$pattern/sSD" , '' , $ value ) ; }

Unicode aware trim method
Fixes a PHP problem

@param string $value
@param string $charlist
@return string


public function setEncoding($encoding = null)
    {
        if ($encoding !== null) {
            if (!function_exists('mb_strtoupper')) {

                throw new Zend_Filter_Exception('mbstring is required for this feature');
            }

            $encoding = (string) $encoding;
            if (!in_array(strtolower($encoding), array_map('strtolower', mb_list_encodings()))) {

                throw new Zend_Filter_Exception("The given encoding '$encoding' is not supported by mbstring");
            }
        }

        $this->_encoding = $encoding;
        return $this;
    }

Set the input encoding for the given string

@param  string $encoding
@return Zend_Filter_StringToUpper Provides a fluent interface
@throws Zend_Filter_Exception


protected function _createIteratorException(
        $message = null,
        $code = null,
        RootException $previous = null,
        IteratorInterface $iterator
    ) {
        return new IteratorException($message, $code, $previous, $iterator);
    }

protected function _createIteratorException ( $ message = null , $ code = null , RootException $ previous = null , IteratorInterface $ iterator ) { return new IteratorException ( $ message , $ code , $ previous , $ iterator ) ; }

Creates a new iterator exception instance.

@since [*next-version*]

@param string|Stringable|null $message  The error message, if any.
@param int|null               $code     The error code, if any.
@param RootException|null     $previous The previous exception for chaining, if any.
@param IteratorInterface      $iterator The iterator instance that erred.

@return IteratorException The created exception instance.

Creates a new iterator exception instance .


public function init()
    {
        parent::init();
        if (empty($this->languages)) {
            $this->languages = [Reaction::$app->language];
        }
        $this->initUrlLanguagePrefixes();
        if (!isset($this->translations['rct']) && !isset($this->translations['rct*'])) {
            $this->translations['rct'] = [
                'class' => 'Reaction\I18n\PhpMessageSource',
                'sourceLanguage' => 'en-US',
                'basePath' => '@reaction/Messages',
            ];
        }

        if (!isset($this->translations['app']) && !isset($this->translations['app*']) && !isset($this->translations['*'])) {
            $this->translations['app'] = [
                'class' => 'Reaction\I18n\PhpMessageSource',
                'sourceLanguage' => Reaction::$app->sourceLanguage,
                'basePath' => '@app/Messages',
            ];
        }
    }

public function init ( ) { parent :: init ( ) ; if ( empty ( $ this -> languages ) ) { $ this -> languages = [ Reaction :: $ app -> language ] ; } $ this -> initUrlLanguagePrefixes ( ) ; if ( ! isset ( $ this -> translations [ 'rct' ] ) && ! isset ( $ this -> translations [ 'rct*' ] ) ) { $ this -> translations [ 'rct' ] = [ 'class' => 'Reaction\I18n\PhpMessageSource' , 'sourceLanguage' => 'en-US' , 'basePath' => '@reaction/Messages' , ] ; } if ( ! isset ( $ this -> translations [ 'app' ] ) && ! isset ( $ this -> translations [ 'app*' ] ) && ! isset ( $ this -> translations [ '*' ] ) ) { $ this -> translations [ 'app' ] = [ 'class' => 'Reaction\I18n\PhpMessageSource' , 'sourceLanguage' => Reaction :: $ app -> sourceLanguage , 'basePath' => '@app/Messages' , ] ; } }

Initializes the component by configuring the default message categories.

Initializes the component by configuring the default message categories .


protected function initUrlLanguagePrefixes()
    {
        $prefixes = $this->languagePrefixes;
        $defaultLanguage = isset($prefixes['']) ? $prefixes[''] : reset($this->languages);
        $prefixes[''] = $defaultLanguage;
        foreach ($this->languages as $language) {
            if (in_array($language, $prefixes)) {
                continue;
            }
            $prefix = Reaction\Helpers\Inflector::slug($language);
            $prefixes[$prefix] = $language;
        }
        $this->languagePrefixes = $prefixes;
    }

protected function initUrlLanguagePrefixes ( ) { $ prefixes = $ this -> languagePrefixes ; $ defaultLanguage = isset ( $ prefixes [ '' ] ) ? $ prefixes [ '' ] : reset ( $ this -> languages ) ; $ prefixes [ '' ] = $ defaultLanguage ; foreach ( $ this -> languages as $ language ) { if ( in_array ( $ language , $ prefixes ) ) { continue ; } $ prefix = Reaction \ Helpers \ Inflector :: slug ( $ language ) ; $ prefixes [ $ prefix ] = $ language ; } $ this -> languagePrefixes = $ prefixes ; }


public function getMessageFormatter()
    {
        if ($this->_messageFormatter === null) {
            $this->_messageFormatter = new MessageFormatter();
        } elseif (is_array($this->_messageFormatter) || is_string($this->_messageFormatter)) {
            $this->_messageFormatter = Reaction::create($this->_messageFormatter);
        }

        return $this->_messageFormatter;
    }

public function getMessageFormatter ( ) { if ( $ this -> _messageFormatter === null ) { $ this -> _messageFormatter = new MessageFormatter ( ) ; } elseif ( is_array ( $ this -> _messageFormatter ) || is_string ( $ this -> _messageFormatter ) ) { $ this -> _messageFormatter = Reaction :: create ( $ this -> _messageFormatter ) ; } return $ this -> _messageFormatter ; }

Returns the message formatter instance.
@return MessageFormatter the message formatter to be used to format message via ICU message format.

Returns the message formatter instance .


public function start()
    {
        try {
            if ($this->state == self::STATE_STARTED) {
                throw new Exception\TransactionException(__METHOD__ . " Starting transaction on an already started one is not permitted.");
            }
            $this->adapter->getDriver()->getConnection()->beginTransaction();
            $this->state = self::STATE_STARTED;
        } catch (\Exception $e) {
            throw new Exception\TransactionException(__METHOD__ . ". Cannot start transaction '{$e->getMessage()}'.");
        }
        return $this;
    }

Start a new transaction

@throws Exception\TransactionException
@return Transaction


public function getApiRequestUrl(Event $event)
    {
        return sprintf("%s?%s", $this->apiUrl, http_build_query($this->getApiRequestParams($event)));
    }

public function getApiRequestUrl ( Event $ event ) { return sprintf ( "%s?%s" , $ this -> apiUrl , http_build_query ( $ this -> getApiRequestParams ( $ event ) ) ) ; }

Get the url for the API request

@param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
@return string


protected function getApiRequestParams(Event $event)
    {
        $params = $event->getCustomParams();
        $user = $params[0];

        return array(
            'format' => 'json',
            'api_key' => $this->apiKey,
            'method' => 'user.getrecenttracks',
            'user' => $user,
            'limit' => '1'
        );
    }

protected function getApiRequestParams ( Event $ event ) { $ params = $ event -> getCustomParams ( ) ; $ user = $ params [ 0 ] ; return array ( 'format' => 'json' , 'api_key' => $ this -> apiKey , 'method' => 'user.getrecenttracks' , 'user' => $ user , 'limit' => '1' ) ; }

Returns a querystring parameters array

@param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
@return array


public function getSuccessLines(Event $event, $apiResponse)
    {
        $response = json_decode($apiResponse);
        if (isset($response->recenttracks)) {
            $messages = array($this->getSuccessMessage($response));
        } else {
            $messages = $this->getNoResultsLines($event);
        }

        return $messages;
    }

public function getSuccessLines ( Event $ event , $ apiResponse ) { $ response = json_decode ( $ apiResponse ) ; if ( isset ( $ response -> recenttracks ) ) { $ messages = array ( $ this -> getSuccessMessage ( $ response ) ) ; } else { $ messages = $ this -> getNoResultsLines ( $ event ) ; } return $ messages ; }

Returns an array of lines to send back to IRC when the http request is successful

@param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
@param string $apiResponse
@return array


protected function getSuccessMessage($response)
    {
        $track = (is_array($response->recenttracks->track))
            ? $response->recenttracks->track[0]
            : $response->recenttracks->track;

        return sprintf(
            "%s %s listening to %s by %s %s[ %s ]",
            $response->recenttracks->{'@attr'}->user,
            (isset($track->{'@attr'}->nowplaying)) ? "is" : "was",
            $track->name,
            $track->artist->{'#text'},
            (!isset($track->{'@attr'}->nowplaying)) ? age($track->date->uts) . "ago " : "",
            $track->url
        );
    }

protected
function
getSuccessMessage
(
$
response
)
{
$
track
=
(
is_array
(
$
response
->
recenttracks
->
track
)
)
$
response
->
recenttracks
->
track
[
0
]
:
$
response
->
recenttracks
->
track
;
return
sprintf
(
"%s %s listening to %s by %s %s[ %s ]"
,
$
response
->
recenttracks
->
{
'@attr'
}
->
user
,
(
isset
(
$
track
->
{
'@attr'
}
->
nowplaying
)
)
"is"
:
"was"
,
$
track
->
name
,
$
track
->
artist
->
{
'#text'
}
,
(
!
isset
(
$
track
->
{
'@attr'
}
->
nowplaying
)
)
age
(
$
track
->
date
->
uts
)
.
"ago "
:
""
,
$
track
->
url
)
;
}

Returns a message generated from the api request to use in the final response

@param object $response
@return string


public function findAllByAccountId($accountId)
    {
        $this->addWhere('account_id', $accountId);
        $this->addOrder('budget_parent_id', 'ASC');
        $this->addOrder('budget_name', 'ASC');

        $budgets = array();
        foreach ($this->select() as $budget) {
            if ($budget->getParentId() === 0) {
                $budgets[$budget->getId()] = $budget;
            } else {
                $budgets[$budget->getParentId()]->addChild($budget);
            }
        }

        return $budgets;
    }

public function findAllByAccountId ( $ accountId ) { $ this -> addWhere ( 'account_id' , $ accountId ) ; $ this -> addOrder ( 'budget_parent_id' , 'ASC' ) ; $ this -> addOrder ( 'budget_name' , 'ASC' ) ; $ budgets = array ( ) ; foreach ( $ this -> select ( ) as $ budget ) { if ( $ budget -> getParentId ( ) === 0 ) { $ budgets [ $ budget -> getId ( ) ] = $ budget ; } else { $ budgets [ $ budget -> getParentId ( ) ] -> addChild ( $ budget ) ; } } return $ budgets ; }

Get budgets by account id.

@param  int $accountId
@return Budget[]


public function getCurrentLanguage() {
		if ( $this->currentLang === null ) {
			$lang = $this->defaultLanguage;
			if ( isset( $_REQUEST['uselang'] ) ) {
				$lang = $_REQUEST['uselang'];

			} elseif ( isset( $_SESSION['uselang'] ) ) {
				$lang = $_SESSION['uselang'];

			} else {
				$wants = self::parseAcceptLanguage();
				$bestMatches = array_intersect(
					$wants, $this->getAvailableLanguages()
				);
				if ( $bestMatches ) {
					$lang = current( $bestMatches );
				}
			}

			$this->setCurrentLanguage( $lang );
		}
		return $this->currentLang;
	}

public function getCurrentLanguage ( ) { if ( $ this -> currentLang === null ) { $ lang = $ this -> defaultLanguage ; if ( isset ( $ _REQUEST [ 'uselang' ] ) ) { $ lang = $ _REQUEST [ 'uselang' ] ; } elseif ( isset ( $ _SESSION [ 'uselang' ] ) ) { $ lang = $ _SESSION [ 'uselang' ] ; } else { $ wants = self :: parseAcceptLanguage ( ) ; $ bestMatches = array_intersect ( $ wants , $ this -> getAvailableLanguages ( ) ) ; if ( $ bestMatches ) { $ lang = current ( $ bestMatches ) ; } } $ this -> setCurrentLanguage ( $ lang ) ; } return $ this -> currentLang ; }

Get current language.

If no language has been set or detected, this will attempt to detect
the user's preferred language by examining the current request, session
and HTTP headers.

The key 'uselang' is checked in the HTTP request and PHP session. If
not set in either, the Accept-Language header from the request is
parsed to determine potential langauges to select. In all cases, the
current list of known localizations is consulted and if no match is
found, the configured system wide default language is used as
a fallback.

@return string


public static function parseAcceptLanguage() {
		if ( !isset( $_SERVER['HTTP_ACCEPT_LANGUAGE'] ) ) {
			return array();
		}

		$weighted = array();

		// Strip any whitespace in the header value
		$hdr = preg_replace( '/\s+/', '', $_SERVER['HTTP_ACCEPT_LANGUAGE'] );
		// Split on commas
		$parts = explode( ',', $hdr );
		foreach ( $parts as $idx => $part ) {
			if ( strpos( $part, ';q=' ) ) {
				// Extract relative weight from component
				list( $lang, $weight ) = explode( ';q=', $part );
				$weight = (float)$weight;

			} else {
				$lang = $part;
				$weight = 1;
			}

			if ( $lang != '*' && $weight > 0 ) {
				// Decorate the weight with the original position to make sort
				// stable
				$weighted[strtolower( $lang )] = array( $weight, -$idx );
			}
		}

		arsort( $weighted );
		return array_keys( $weighted );
	}

Parse the Accept-Language header present in the request and return an
ordered list of languages preferred by the user-agent.

@return array List of preferred languages

Parse the Accept - Language header present in the request and return an ordered list of languages preferred by the user - agent .


public function bind($binding, $value)
    {
        $callback = function() use($value) {
            return $this->make($value);
        };

        $callback->bindTo($this);

        $this->bindings[$binding] = $callback;
    }

public function bind ( $ binding , $ value ) { $ callback = function ( ) use ( $ value ) { return $ this -> make ( $ value ) ; } ; $ callback -> bindTo ( $ this ) ; $ this -> bindings [ $ binding ] = $ callback ; }

Binds given value into the container.

@param string $binding
@param string|object $value
@return void


public function make($class, array $dependencies = [])
    {
        if ($class instanceof Raw) {
            return $class->getValue();
        }

        if ( ! is_string($class)) {
            return $class;
        }

        if (array_key_exists($class, $this->bindings)) {
            return $this->bindings[$class]();
        }

        if ( ! class_exists($class)) {
            throw new Exceptions\ClassDoesNotExistException($class);
        }

        $reflector = new ReflectionClass($class);

        $isInstantiable =
            is_null($reflector->getConstructor()) ?: $reflector->getConstructor()->isPublic();

        if ($reflector->isAbstract() or ! $isInstantiable) {
            throw new Exceptions\ClassIsNotInstantiableException($class);
        }

        if (count($dependencies) > 0) {
            return $reflector->newInstanceArgs(array_map([$this, "make"], $dependencies));
        }

        if ( ! $resolved = $this->attemptToResolve($reflector)) {
            throw new Exceptions\ResolutionException($class);
        }

        return $resolved;
    }

public function make ( $ class , array $ dependencies = [ ] ) { if ( $ class instanceof Raw ) { return $ class -> getValue ( ) ; } if ( ! is_string ( $ class ) ) { return $ class ; } if ( array_key_exists ( $ class , $ this -> bindings ) ) { return $ this -> bindings [ $ class ] ( ) ; } if ( ! class_exists ( $ class ) ) { throw new Exceptions \ ClassDoesNotExistException ( $ class ) ; } $ reflector = new ReflectionClass ( $ class ) ; $ isInstantiable = is_null ( $ reflector -> getConstructor ( ) ) ? : $ reflector -> getConstructor ( ) -> isPublic ( ) ; if ( $ reflector -> isAbstract ( ) or ! $ isInstantiable ) { throw new Exceptions \ ClassIsNotInstantiableException ( $ class ) ; } if ( count ( $ dependencies ) > 0 ) { return $ reflector -> newInstanceArgs ( array_map ( [ $ this , "make" ] , $ dependencies ) ) ; } if ( ! $ resolved = $ this -> attemptToResolve ( $ reflector ) ) { throw new Exceptions \ ResolutionException ( $ class ) ; } return $ resolved ; }

Resolves the given class' dependencies.

@param string|mixed $class
@param array $dependencies
@throws Exceptions\ClassDoesNotExistException
@throws Exceptions\ClassIsNotInstantiableException
@throws Exceptions\ResolutionException
@return mixed


private function validate(string $url): void {
    if(filter_var($url, FILTER_VALIDATE_URL) === false) {
      throw new InvalidArgumentException('Expected URL, but got [' . var_export($url, true) . '] instead');
    }
  }

private
function
validate
(
string
$
url
)
:
void
{
if
(
filter_var
(
$
url
,
FILTER_VALIDATE_URL
)
===
false
)
{
throw
new
InvalidArgumentException
(
'Expected URL, but got ['
.
var_export
(
$
url
,
true
)
.
'] instead'
)
;
}
}

Ensures the URL passed in is valid

@throws  InvalidArgumentException  If the value is not a valid URL

@param  string  $url  The value to validate

@return  void


public function isLiveVar($fieldName)
    {
        return $this->liveVars && (!is_array($this->liveVars) || in_array($fieldName, $this->liveVars));
    }

public function isLiveVar ( $ fieldName ) { return $ this -> liveVars && ( ! is_array ( $ this -> liveVars ) || in_array ( $ fieldName , $ this -> liveVars ) ) ; }

Is this variable live in published mode?
@param string $field
@return bool


public function obj($fieldName, $arguments = null, $forceReturnedObject = true, $cache = false, $cacheName = null)
    {
        $value = parent::obj($fieldName, $arguments, $forceReturnedObject, $cache, $cacheName);

        // if we're publishing and this variable is qualified, output php code instead
        if (
            $this->failover
            && $this->liveVars
            && isset($this->varName)
            && LivePubHelper::is_publishing()
            && $this->isLiveVar($fieldName)
        ) {
            $accessor = "get{$fieldName}";
            $php = '';

            // find out how we got the data
            if ($this->failover instanceof ArrayData) {
                $php = '$' . $this->varName . '["' . $fieldName . '"]';
            } elseif (is_callable(array($this->failover, $fieldName))) {
                // !@TODO respect arguments
                $php = '$' . $this->varName . '->' . $fieldName . '()';
            } elseif (is_callable(array($this->failover, $accessor))) {
                // !@TODO respect arguments
                $php = '$' . $this->varName . '->' . $accessor . '()';
            } elseif (isset($this->failover, $fieldName)) {
                $php = '$' . $this->varName . '->' . $fieldName;
            }

            // return the appropriate php
            if ($php) {
                if (is_object($value)) {
                    if ($value instanceof ViewableWrapper) {
                        LivePubHelper::$init_code[] = '<?php $' . $value->getVar() . ' = ' . $php . ' ?>';
                    }
                    // !@TODO: only other option is DataObjectSet - check that this is handled right
                } else {
                    $value = in_array($fieldName, $this->liveVarsUnescaped)
                        ? '<?php echo ' . $php . '; ?>'
                        : '<?php echo htmlentities(' . $php . '); ?>';
                    if ($forceReturnedObject) {
                        $value = new HTMLText($value);
                    }
                }
            }
        }

        return $value;
    }


protected function wrapObject($obj)
    {
        if (is_object($obj)) {
            // if it's an object, just check the type and wrap if needed
            if ($obj instanceof ViewableWrapper) {
                return $obj;
            } else {
                return new ViewableWrapper($obj);
            }
        } elseif (is_array($obj)) {
            // if it's an assoc array just wrap it, otherwise make a dataobjectset
            if (ArrayLib::is_associative($obj)) {
                return new ViewableWrapper($obj);
            } else {
                $set = new ArrayList();

                foreach ($obj as $i => $item) {
                    $wrap = $this->wrapObject($item);
                    $set->push($wrap);
                }

                return $set;
            }
        } else {
            // it's a simple type, just return it
            return $obj;
        }
    }

if an object isn't already wrapped in Silverstripe's stuff,
wrap it appropriately either in a viewableWrapper or dataobject set

if an object isn t already wrapped in Silverstripe s stuff wrap it appropriately either in a viewableWrapper or dataobject set


public function AsDate($field)
    {
        $d = $this->$field;
        return DBField::create('Date', is_numeric($d) ? date('Y-m-d H:i:s', $d) : $d);
    }

public
function
AsDate
(
$
field
)
{
$
d
=
$
this
->
$
field
;
return
DBField
::
create
(
'Date'
,
is_numeric
(
$
d
)
date
(
'Y-m-d H:i:s'
,
$
d
)
:
$
d
)
;
}

returns the given field as a casted date object


public function makeSessionIdentifier(string $sessionId): string
    {
        return (string) openssl_digest($sessionId . $this->appKey, $this->hashAlgorithm);
    }

public function makeSessionIdentifier ( string $ sessionId ) : string { return ( string ) openssl_digest ( $ sessionId . $ this -> appKey , $ this -> hashAlgorithm ) ; }

Makes a session identifier based on the session id.

@param  string $sessionId The session id.
@return string The session identifier.

Makes a session identifier based on the session id .


public function encryptSessionData(string $sessionId, string $sessionData): string
    {
        $ivLength = (int) openssl_cipher_iv_length($this->encryptionAlgorithm);
        $initVector = (string) openssl_random_pseudo_bytes($ivLength);

        $encryptionKey = $this->getEncryptionKey($sessionId);
        $encryptedData = openssl_encrypt($sessionData, $this->encryptionAlgorithm, $encryptionKey, 0, $initVector);

        return (string) json_encode(
            [
                'data' => $encryptedData,
                'initVector' => base64_encode($initVector)
            ]
        );
    }

public function encryptSessionData ( string $ sessionId , string $ sessionData ) : string { $ ivLength = ( int ) openssl_cipher_iv_length ( $ this -> encryptionAlgorithm ) ; $ initVector = ( string ) openssl_random_pseudo_bytes ( $ ivLength ) ; $ encryptionKey = $ this -> getEncryptionKey ( $ sessionId ) ; $ encryptedData = openssl_encrypt ( $ sessionData , $ this -> encryptionAlgorithm , $ encryptionKey , 0 , $ initVector ) ; return ( string ) json_encode ( [ 'data' => $ encryptedData , 'initVector' => base64_encode ( $ initVector ) ] ) ; }

Encrypts the session data.

@param  string $sessionId   The session id.
@param  string $sessionData The session data.
@return string The encrypted session data.


public function decryptSessionData(string $sessionId, string $sessionData): string
    {
        if (!$sessionData) {
            return '';
        }

        $encryptedData = json_decode($sessionData);

        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new UnableToDecryptException();
        }

        $initVector = base64_decode($encryptedData->initVector, true);
        if ($initVector === false) {
            throw new UnableToDecryptException();
        }

        $encryptionKey = $this->getEncryptionKey($sessionId);

        $decryptedData = @openssl_decrypt($encryptedData->data, $this->encryptionAlgorithm, $encryptionKey, 0, $initVector);
        if ($decryptedData === false) {
            throw new UnableToDecryptException();
        }

        return $decryptedData;
    }

public function decryptSessionData ( string $ sessionId , string $ sessionData ) : string { if ( ! $ sessionData ) { return '' ; } $ encryptedData = json_decode ( $ sessionData ) ; if ( json_last_error ( ) !== JSON_ERROR_NONE ) { throw new UnableToDecryptException ( ) ; } $ initVector = base64_decode ( $ encryptedData -> initVector , true ) ; if ( $ initVector === false ) { throw new UnableToDecryptException ( ) ; } $ encryptionKey = $ this -> getEncryptionKey ( $ sessionId ) ; $ decryptedData = @ openssl_decrypt ( $ encryptedData -> data , $ this -> encryptionAlgorithm , $ encryptionKey , 0 , $ initVector ) ; if ( $ decryptedData === false ) { throw new UnableToDecryptException ( ) ; } return $ decryptedData ; }

Decrypts the session data.

@throws UnableToDecryptException
@param  string $sessionId   The session id.
@param  string $sessionData The encrypted session data.
@return string The decrypted session data.


private function getEncryptionKey(string $sessionId): string
    {
        return (string) openssl_digest($this->appKey . $sessionId, $this->hashAlgorithm);
    }

private function getEncryptionKey ( string $ sessionId ) : string { return ( string ) openssl_digest ( $ this -> appKey . $ sessionId , $ this -> hashAlgorithm ) ; }

Calculates the key to be used in the session encryption.

@param  string $sessionId Id of the session
@return string Encryption key

Calculates the key to be used in the session encryption .


public function setEncryptionAlgorithm(string $algorithm): void
    {
        $knownAlgorithms = openssl_get_cipher_methods(true);

        if (!in_array($algorithm, $knownAlgorithms)) {
            $errorMessage = "The encryption algorithm \"$algorithm\" is unknow. " .
                'For a list of valid algorithms, see openssl_get_cipher_methods(true).';
            throw new UnableToEncryptException($errorMessage);
        }

        $this->encryptionAlgorithm = $algorithm;
    }

Sets the encryption algorithm

To get a list of valid algorithms, see openssl_get_cipher_methods(true)

@throws UnableToEncryptException
@param string $algorithm For a list of valid algorithm, see openssl_get_cipher_methods(true).
@return void


public function setHashAlgorithm(string $algorithm): void
    {
        $knownAlgorithms = openssl_get_md_methods(true);

        if (!in_array($algorithm, $knownAlgorithms)) {
            $errorMessage = "The hash algorithm \"$algorithm\" is unknown." .
                'For a list of valid algorithms, see openssl_get_md_methods(true).';
            throw new UnableToHashException($errorMessage);
        }

        $this->hashAlgorithm = $algorithm;
    }

Sets the hashing algorithm

To get a list of valid algorithms, see openssl_get_md_methods(true)

@throws UnableToHashException
@param string $algorithm For a list of valid algorithms, see openssl_get_md_methods(true).
@return void


protected function prepareUpdateSets($table, $columns, $params = [])
    {
        $tableSchema = $this->db->getSchema()->getTableSchema($table);
        $columnSchemas = $tableSchema !== null ? $tableSchema->columns : [];
        $sets = [];
        foreach ($columns as $name => $value) {

            $value = isset($columnSchemas[$name]) ? $columnSchemas[$name]->dbTypecast($value) : $value;
            if ($value instanceof ExpressionInterface) {
                $placeholder = $this->buildExpression($value, $params);
            } else {
                $placeholder = $this->bindParam($value, $params);
            }

            $sets[] = $this->db->quoteColumnName($name) . '=' . $placeholder;
        }
        return [$sets, $params];
    }

protected function prepareUpdateSets ( $ table , $ columns , $ params = [ ] ) { $ tableSchema = $ this -> db -> getSchema ( ) -> getTableSchema ( $ table ) ; $ columnSchemas = $ tableSchema !== null ? $ tableSchema -> columns : [ ] ; $ sets = [ ] ; foreach ( $ columns as $ name => $ value ) { $ value = isset ( $ columnSchemas [ $ name ] ) ? $ columnSchemas [ $ name ] -> dbTypecast ( $ value ) : $ value ; if ( $ value instanceof ExpressionInterface ) { $ placeholder = $ this -> buildExpression ( $ value , $ params ) ; } else { $ placeholder = $ this -> bindParam ( $ value , $ params ) ; } $ sets [ ] = $ this -> db -> quoteColumnName ( $ name ) . '=' . $ placeholder ; } return [ $ sets , $ params ] ; }

Prepares a `SET` parts for an `UPDATE` SQL statement.
@param string $table the table to be updated.
@param array $columns the column data (name => value) to be updated.
@param array $params the binding parameters that will be modified by this method
so that they can be bound to the DB command later.
@return array an array `SET` parts for an `UPDATE` SQL statement (the first array element) and params (the second array element).

Prepares a SET parts for an UPDATE SQL statement .


function initService(){

       if(isset($_GET["service"]) && $_GET['service'] != ''){
            list($module, $action) =  explode('~',$_GET["service"]);
        }else{
            throw new jException('jsoap~errors.service.param.required');
        }

        $this->params['module'] = $module;
        $this->params['action'] = $action;

        $this->soapMsg = file_get_contents("php://input");

        $this->_initUrlData(); //Need to be called manually before coordinator call of init because needed for the WSDL generation
    }

Paramameters initalisation prior to request handling


public function getParam($name, $defaultValue=null, $useDefaultIfEmpty=false){
        if (!isset($this->params[$name])) {
            return $defaultValue;
        }
        // we cannot use the empty() function because 0 returns true. And maybe we want 0
        // as a normal value...
        if (is_scalar($this->params[$name])) {
            if ($useDefaultIfEmpty && trim($this->params[$name]) == '' ) {
                return $defaultValue;
            }
            else {
                return $this->params[$name];
            }
        }
        else{
            // array or object
            if ( $useDefaultIfEmpty && empty($this->params[$name]) ) {
                return $defaultValue;
            }
            else {
                return $this->params[$name];
            }
        }
    }

Gets the value of a request parameter. If not defined, gets its default value.
@param string  $name           the name of the request parameter
@param mixed   $defaultValue   the default returned value if the parameter doesn't exists
@param boolean $useDefaultIfEmpty true: says to return the default value if the parameter value is ""
@return mixed the request parameter value

Gets the value of a request parameter . If not defined gets its default value .


private function checkTargetRelationExistence($model, $attribute)
    {
        /** @var ActiveQuery $relationQuery */
        $relationQuery = $model->{'get' . ucfirst($this->targetRelation)}();

        if ($this->filter instanceof \Closure) {
            call_user_func($this->filter, $relationQuery);
        } elseif ($this->filter !== null) {
            $relationQuery->andWhere($this->filter);
        }

        return $relationQuery->exists()
            ->then(null, function() use ($model, $attribute) {
                $this->addError($model, $attribute, $this->message);
                return null;
            });
    }

private
function
checkTargetRelationExistence
(
$
model
,
$
attribute
)
{
/** @var ActiveQuery $relationQuery */
$
relationQuery
=
$
model
->
{
'get'
.
ucfirst
(
$
this
->
targetRelation
)
}
(
)
;
if
(
$
this
->
filter
instanceof
\
Closure
)
{
call_user_func
(
$
this
->
filter
,
$
relationQuery
)
;
}
elseif
(
$
this
->
filter
!==
)
{
$
relationQuery
->
andWhere
(
$
this
->
filter
)
;
}
return
$
relationQuery
->
exists
(
)
->
then
(
,
function
(
)
use
(
$
model
,
$
attribute
)
{
$
this
->
addError
(
$
model
,
$
attribute
,
$
this
->
message
)
;
return
;
}
)
;
}

Validates existence of the current attribute based on relation name
@param \Reaction\Db\Orm\ActiveRecord $model the data model to be validated
@param string                        $attribute the name of the attribute to be validated.
@return ExtendedPromiseInterface


private function checkTargetAttributeExistence($model, $attribute)
    {
        $targetAttribute = $this->targetAttribute === null ? $attribute : $this->targetAttribute;
        $params = $this->prepareConditions($targetAttribute, $model, $attribute);
        $conditions = [$this->targetAttributeJunction == 'or' ? 'or' : 'and'];

        if (!$this->allowArray) {
            foreach ($params as $key => $value) {
                if (is_array($value)) {
                    $this->addError($model, $attribute, Reaction::t('rct', '{attribute} is invalid.'));

                    return null;
                }
                $conditions[] = [$key => $value];
            }
        } else {
            $conditions[] = $params;
        }

        $targetClass = $this->targetClass === null ? get_class($model) : $this->targetClass;
        $query = $this->createQuery($targetClass, $conditions);

        return $this->valueExists($query, $model->$attribute)
            ->then(null, function() use (&$model, $attribute) {
                $this->addError($model, $attribute, $this->message);
                return null;
            });
    }

private
function
checkTargetAttributeExistence
(
$
model
,
$
attribute
)
{
$
targetAttribute
=
$
this
->
targetAttribute
===
$
attribute
:
$
this
->
targetAttribute
;
$
params
=
$
this
->
prepareConditions
(
$
targetAttribute
,
$
model
,
$
attribute
)
;
$
conditions
=
[
$
this
->
targetAttributeJunction
==
'or'
'or'
:
'and'
]
;
if
(
!
$
this
->
allowArray
)
{
foreach
(
$
params
as
$
key
=>
$
value
)
{
if
(
is_array
(
$
value
)
)
{
$
this
->
addError
(
$
model
,
$
attribute
,
Reaction
::
t
(
'rct'
,
'{attribute} is invalid.'
)
)
;
return
;
}
$
conditions
[
]
=
[
$
key
=>
$
value
]
;
}
}
else
{
$
conditions
[
]
=
$
params
;
}
$
targetClass
=
$
this
->
targetClass
===
get_class
(
$
model
)
:
$
this
->
targetClass
;
$
query
=
$
this
->
createQuery
(
$
targetClass
,
$
conditions
)
;
return
$
this
->
valueExists
(
$
query
,
$
model
->
$
attribute
)
->
then
(
,
function
(
)
use
(
&
$
model
,
$
attribute
)
{
$
this
->
addError
(
$
model
,
$
attribute
,
$
this
->
message
)
;
return
;
}
)
;
}

Validates existence of the current attribute based on targetAttribute
@param \Reaction\Base\Model $model the data model to be validated
@param string $attribute the name of the attribute to be validated.


private function valueExists($query, $value)
    {
        if (is_array($value)) {
            return $query->count("DISTINCT [[$this->targetAttribute]]")
                ->then(function($count) use ($value) {
                    return $count == count($value) ? true : reject(new Error("Not exists (count mismatch)"));
                });
        }
        return $query->exists();
    }

private
function
valueExists
(
$
query
,
$
value
)
{
if
(
is_array
(
$
value
)
)
{
return
$
query
->
count
(
"DISTINCT [[$this->targetAttribute]]"
)
->
then
(
function
(
$
count
)
use
(
$
value
)
{
return
$
count
==
count
(
$
value
)
true
:
reject
(
new
Error
(
"Not exists (count mismatch)"
)
)
;
}
)
;
}
return
$
query
->
exists
(
)
;
}

Check whether value exists in target table

@param QueryInterface $query
@param mixed $value the value want to be checked
@return ExtendedPromiseInterface


protected final function getClause(TableInterface $table): string
    {
       $mySql = "";
       $column = $table->get($table::ATTR_COLUMN);
       foreach ($table->get($table::ATTR_CLAUSE) as $key => $clause) {
           $mySql .= rtrim(" " . $this->constant($clause->getType()) . " "
                   . $clause->getSubject() . " "
                   . $this->constant($clause->getOperator()));
           if ($clause->getOperator()) {
               $type = isset($column[$clause->getSubject()])
                     ? $column[$clause->getSubject()]->getParam()
                     : (is_int($clause->getValue())
                     ? PDO::PARAM_INT
                     : (is_string($clause->getValue())
                     ? PDO::PARAM_STR
                     : PDO::PARAM_NULL));
               $id = ":c" . $key . "_" . ($clause->getSubject()
                     ? str_replace(".", "_", $clause->getSubject())
                     : "");
               $this->setParam($id, $clause->getValue(), $type);
               $mySql .= " " . $id;
           }
       }
       return ltrim($mySql);
    }

protected
final
function
getClause
(
TableInterface
$
table
)
:
string
{
$
mySql
=
""
;
$
column
=
$
table
->
get
(
$
table
::
ATTR_COLUMN
)
;
foreach
(
$
table
->
get
(
$
table
::
ATTR_CLAUSE
)
as
$
key
=>
$
clause
)
{
$
mySql
.=
rtrim
(
" "
.
$
this
->
constant
(
$
clause
->
getType
(
)
)
.
" "
.
$
clause
->
getSubject
(
)
.
" "
.
$
this
->
constant
(
$
clause
->
getOperator
(
)
)
)
;
if
(
$
clause
->
getOperator
(
)
)
{
$
type
=
isset
(
$
column
[
$
clause
->
getSubject
(
)
]
)
$
column
[
$
clause
->
getSubject
(
)
]
->
getParam
(
)
:
(
is_int
(
$
clause
->
getValue
(
)
)
PDO
::
PARAM_INT
:
(
is_string
(
$
clause
->
getValue
(
)
)
PDO
::
PARAM_STR
:
PDO
::
PARAM_NULL
)
)
;
$
id
=
":c"
.
$
key
.
"_"
.
(
$
clause
->
getSubject
(
)
str_replace
(
"."
,
"_"
,
$
clause
->
getSubject
(
)
)
:
""
)
;
$
this
->
setParam
(
$
id
,
$
clause
->
getValue
(
)
,
$
type
)
;
$
mySql
.=
" "
.
$
id
;
}
}
return
ltrim
(
$
mySql
)
;
}

Get clause to MySql syntaxe

@param TableInterface $table table
@return string clause to MySql syntaxe


public function render(Modal $modal, $template = 'EkynaCoreBundle:Modal:modal.xml.twig')
    {
        $response = new Response();

        // Translations
        $modal->setTitle($this->translator->trans($modal->getTitle()));
        $buttons = $modal->getButtons();
        foreach($buttons as &$button) {
            $button['label'] = $this->translator->trans($button['label']);
        }
        $modal->setButtons($buttons);

        $response->setContent($this->twig->render($template, ['modal' => $modal]));

        $response->headers->add(['Content-Type' => 'application/xml; charset='.strtolower($this->charset)]);

        return $response;
    }

public
function
render
(
Modal
$
modal
,
$
template
=
'EkynaCoreBundle:Modal:modal.xml.twig'
)
{
$
response
=
new
Response
(
)
;
// Translations
$
modal
->
setTitle
(
$
this
->
translator
->
trans
(
$
modal
->
getTitle
(
)
)
)
;
$
buttons
=
$
modal
->
getButtons
(
)
;
foreach
(
$
buttons
as
&
$
button
)
{
$
button
[
'label'
]
=
$
this
->
translator
->
trans
(
$
button
[
'label'
]
)
;
}
$
modal
->
setButtons
(
$
buttons
)
;
$
response
->
setContent
(
$
this
->
twig
->
render
(
$
template
,
[
'modal'
=>
$
modal
]
)
)
;
$
response
->
headers
->
add
(
[
'Content-Type'
=>
'application/xml; charset='
.
strtolower
(
$
this
->
charset
)
]
)
;
return
$
response
;
}

Renders and returns the modal response.

@param Modal $modal
@param string $template
@return Response

Renders and returns the modal response .


public function localize($file, $language = null, $sourceLanguage = null)
    {
        return $this->proxyWithLanguage(__FUNCTION__, [$file, $language, $sourceLanguage], -2);
    }

public function localize ( $ file , $ language = null , $ sourceLanguage = null ) { return $ this -> proxyWithLanguage ( __FUNCTION__ , [ $ file , $ language , $ sourceLanguage ] , - 2 ) ; }

Returns the localized version of a specified file.

The searching is based on the specified language code. In particular,
a file with the same name will be looked for under the subdirectory
whose name is the same as the language code. For example, given the file "path/to/view.php"
and language code "zh-CN", the localized file will be looked for as
"path/to/zh-CN/view.php". If the file is not found, it will try a fallback with just a language code that is
"zh" i.e. "path/to/zh/view.php". If it is not found as well the original file will be returned.

If the target and the source language codes are the same,
the original file will be returned.

@param string $file the original file
@param string $language the target language that the file should be localized to.
If not set, the value of [[\yii\base\Application::language]] will be used.
@param string $sourceLanguage the language that the original file is in.
If not set, the value of [[\yii\base\Application::sourceLanguage]] will be used.
@return string the matching localized file, or the original file if the localized version is not found.
If the target and the source language codes are the same, the original file will be returned.
@see \Reaction\Helpers\FileHelper::localize()

Returns the localized version of a specified file .


public function detach()
    {
        $previous_stream = $this->stream;
        $this->stream = null;
        $this->meta_data = null;

        return $previous_stream;
    }

public function detach ( ) { $ previous_stream = $ this -> stream ; $ this -> stream = null ; $ this -> meta_data = null ; return $ previous_stream ; }

Separates any underlying resources from the stream.
After the stream has been detached, the stream is in an unusable state.

@return resource|null Underlying PHP stream, if any

Separates any underlying resources from the stream . After the stream has been detached the stream is in an unusable state .


public function read($length)
    {
        if (!$this->isReadable()) {
            throw new \RuntimeException('Could not read the stream because it is not readable');
        }

        $string = fread($this->stream, (int)$length);
        if ($string === false) {
            throw new \RuntimeException('Could not read the stream because of an error on fread()');
        }

        return $string;
    }

Read data from the stream.

@param int $length Read up to $length bytes from the object and return
them. Fewer than $length bytes may be returned if underlying stream
call returns fewer bytes.
@return string Returns the data read from the stream, or an empty string
if no bytes are available.
@throws \RuntimeException if an error occurs.


public static function factory(
        array $query = [],
        array $request = [],
        array $attributes = [],
        array $cookies = [],
        array $files = [],
        array $server = [],
        $content = null
    ): Request {
        return new static(
            $query,
            $request,
            $attributes,
            $cookies,
            $files,
            $server,
            $content
        );
    }

public static function factory ( array $ query = [ ] , array $ request = [ ] , array $ attributes = [ ] , array $ cookies = [ ] , array $ files = [ ] , array $ server = [ ] , $ content = null ) : Request { return new static ( $ query , $ request , $ attributes , $ cookies , $ files , $ server , $ content ) ; }

Create a new Request instance.

@param array           $query      The GET parameters
@param array           $request    The POST parameters
@param array           $attributes The request attributes (parameters
parsed from the PATH_INFO, ...)
@param array           $cookies    The COOKIE parameters
@param array           $files      The FILES parameters
@param array           $server     The SERVER parameters
@param string|resource $content    The raw body data

@return \Valkyrja\Http\Request


public static function createFromGlobals(): Request
    {
        // Create a new request from the PHP globals
        /** @var Request $request */
        $request = new static($_GET, $_POST, [], $_COOKIE, $_FILES, $_SERVER);

        if (
            0 === strpos(
                $request->headers()->get('Content-Type'),
                'application/x-www-form-urlencoded'
            )
            &&
            \in_array(
                strtoupper(
                    $request->server()->get(
                        'REQUEST_METHOD',
                        RequestMethod::GET
                    )
                ),
                [
                    RequestMethod::PUT,
                    RequestMethod::DELETE,
                    RequestMethod::PATCH,
                ],
                true
            )
        ) {
            parse_str($request->getContent(), $data);
            $request->request = new Collection($data);
        }

        return $request;
    }

Creates a new request with values from PHP super globals.

@return \Valkyrja\Http\Request

Creates a new request with values from PHP super globals .


public function setServer(array $server = []): Request
    {
        $server = $server
            ?: $_SERVER;

        $this->server = new Server($server);

        return $this;
    }

public function setServer ( array $ server = [ ] ) : Request { $ server = $ server ? : $ _SERVER ; $ this -> server = new Server ( $ server ) ; return $ this ; }

Set the SERVER parameters.

@param array $server

@return \Valkyrja\Http\Request


public function setHeaders(array $headers = []): Request
    {
        $headers = $headers ?: $this->server()->getHeaders();

        $this->headers = new Headers($headers);

        return $this;
    }

public function setHeaders ( array $ headers = [ ] ) : Request { $ headers = $ headers ? : $ this -> server ( ) -> getHeaders ( ) ; $ this -> headers = new Headers ( $ headers ) ; return $ this ; }

Set the headers parameters.

@param array $headers

@return \Valkyrja\Http\Request


public function getPath(): string
    {
        if (null === $this->path) {
            $this->path = $this->server()->get('REQUEST_URI');
        }

        return $this->path;
    }

public function getPath ( ) : string { if ( null === $ this -> path ) { $ this -> path = $ this -> server ( ) -> get ( 'REQUEST_URI' ) ; } return $ this -> path ; }

Returns the path being requested relative to the executed script.

@return string

Returns the path being requested relative to the executed script .


public function getPathOnly(): string
    {
        $requestUri = $this->getPath();

        // Determine if the request uri has any query parameters
        if (false !== $queryPosition = strpos($requestUri, '?')) {
            // If so get the substring of the uri from start until the query param position
            $requestUri = substr($requestUri, 0, $queryPosition);
        }

        return $requestUri;
    }

Returns the path being requested with no query string.

@return string

Returns the path being requested with no query string .


public function getHttpHost(): string
    {
        $scheme = $this->getScheme();
        $port   = $this->getPort();

        if (
            ('http' === $scheme && $port === 80)
            || ('https' === $scheme && $port === 443)
        ) {
            return $this->getHost();
        }

        return $this->getHost() . ':' . $port;
    }

public function getHttpHost ( ) : string { $ scheme = $ this -> getScheme ( ) ; $ port = $ this -> getPort ( ) ; if ( ( 'http' === $ scheme && $ port === 80 ) || ( 'https' === $ scheme && $ port === 443 ) ) { return $ this -> getHost ( ) ; } return $ this -> getHost ( ) . ':' . $ port ; }

Returns the HTTP host being requested.

The port name will be appended to the host if it's non-standard.

@return string


public function setMethod(string $method): Request
    {
        $this->method = null;
        $this->server->set('REQUEST_METHOD', $method);

        return $this;
    }

public function setMethod ( string $ method ) : Request { $ this -> method = null ; $ this -> server -> set ( 'REQUEST_METHOD' , $ method ) ; return $ this ; }

Sets the request method.

@param string $method

@return \Valkyrja\Http\Request


public function getMethod(): string
    {
        if (null === $this->method) {
            $this->method = strtoupper(
                $this->server->get('REQUEST_METHOD', RequestMethod::GET)
            );

            if (RequestMethod::POST === $this->method) {
                if ($method = $this->headers->get('X-HTTP-METHOD-OVERRIDE')) {
                    $this->method = strtoupper($method);
                } elseif (self::$httpMethodParameterOverride) {
                    $this->method = strtoupper(
                        $this->request->get(
                            '_method',
                            $this->query->get(
                                '_method',
                                RequestMethod::POST
                            )
                        )
                    );
                }
            }
        }

        return $this->method;
    }

public function getMethod ( ) : string { if ( null === $ this -> method ) { $ this -> method = strtoupper ( $ this -> server -> get ( 'REQUEST_METHOD' , RequestMethod :: GET ) ) ; if ( RequestMethod :: POST === $ this -> method ) { if ( $ method = $ this -> headers -> get ( 'X-HTTP-METHOD-OVERRIDE' ) ) { $ this -> method = strtoupper ( $ method ) ; } elseif ( self :: $ httpMethodParameterOverride ) { $ this -> method = strtoupper ( $ this -> request -> get ( '_method' , $ this -> query -> get ( '_method' , RequestMethod :: POST ) ) ) ; } } } return $ this -> method ; }

Gets the request "intended" method.

@return string The request method

@see getRealMethod()


public function getMimeType(string $format): string
    {
        return isset(static::$formats[$format])
            ? static::$formats[$format][0]
            : null;
    }

public function getMimeType ( string $ format ) : string { return isset ( static :: $ formats [ $ format ] ) ? static :: $ formats [ $ format ] [ 0 ] : null ; }

Gets the mime type associated with the format.

@param string $format The format

@return string

Gets the mime type associated with the format .


public function getFormat(string $mimeType): string
    {
        $canonicalMimeType = null;

        if (false !== $pos = strpos($mimeType, ';')) {
            $canonicalMimeType = substr($mimeType, 0, $pos);
        }

        foreach (static::FORMATS as $format => $mimeTypes) {
            if (\in_array($mimeType, $mimeTypes, true)) {
                return $format;
            }

            if (
                null !== $canonicalMimeType
                && \in_array(
                    $canonicalMimeType,
                    $mimeTypes,
                    true
                )
            ) {
                return $format;
            }
        }

        return 'html';
    }

public function getFormat ( string $ mimeType ) : string { $ canonicalMimeType = null ; if ( false !== $ pos = strpos ( $ mimeType , ';' ) ) { $ canonicalMimeType = substr ( $ mimeType , 0 , $ pos ) ; } foreach ( static :: FORMATS as $ format => $ mimeTypes ) { if ( \ in_array ( $ mimeType , $ mimeTypes , true ) ) { return $ format ; } if ( null !== $ canonicalMimeType && \ in_array ( $ canonicalMimeType , $ mimeTypes , true ) ) { return $ format ; } } return 'html' ; }

Gets the format associated with the mime type.

@param string $mimeType The associated mime type

@return string

Gets the format associated with the mime type .


public function getRequestFormat(string $default = 'html'): string
    {
        if (null === $this->format) {
            $this->format = $this->attributes->get('_format', $default);
        }

        return $this->format;
    }

public function getRequestFormat ( string $ default = 'html' ) : string { if ( null === $ this -> format ) { $ this -> format = $ this -> attributes -> get ( '_format' , $ default ) ; } return $ this -> format ; }

Gets the request format.

@param string $default The default format

@return string


public function render($controller, $method, $parameters) {
		$templateMapping = [];
		foreach ($this->templateRoots as $templateRoot) {
			if ($templateRoot['name']) {
				$templateMapping[$templateRoot['name']] = $templateRoot['directory'];
			}
		}

		foreach ($this->templateRoots as $templateRoot) {
			try {
				return $this->renderingChain->render(
					$templateRoot['directory'],
					\str_replace($templateRoot['trim'], '', $controller) . DIRECTORY_SEPARATOR . $method,
					$parameters,
					$templateMapping
				);
			} catch (TemplateNotFoundException $e) {
				//pass
			}
		}
		throw new TemplateNotFoundException('No template available for ' . $controller . '::' . $method .
			' in directories ' . \implode(', ', \array_keys($this->templateRoots)));
	}

public
function
render
(
$
controller
,
$
method
,
$
parameters
)
{
$
templateMapping
=
[
]
;
foreach
(
$
this
->
templateRoots
as
$
templateRoot
)
{
if
(
$
templateRoot
[
'name'
]
)
{
$
templateMapping
[
$
templateRoot
[
'name'
]
]
=
$
templateRoot
[
'directory'
]
;
}
}
foreach
(
$
this
->
templateRoots
as
$
templateRoot
)
{
try
{
return
$
this
->
renderingChain
->
render
(
$
templateRoot
[
'directory'
]
,
\
str_replace
(
$
templateRoot
[
'trim'
]
,
''
,
$
controller
)
.
DIRECTORY_SEPARATOR
.
$
method
,
$
parameters
,
$
templateMapping
)
;
}
catch
(
TemplateNotFoundException
$
e
)
{
//pass
}
}
throw
new
TemplateNotFoundException
(
'No template available for '
.
$
controller
.
'::'
.
$
method
.
' in directories '
.
\
implode
(
', '
,
\
array_keys
(
$
this
->
templateRoots
)
)
)
;
}

Render the template.

@param string $controller
@param string $method
@param array  $parameters

@return string

@throws TemplateNotFoundException


public function initHttp()
    {
        $this->socket = Reaction::create(SocketServerInterface::class);
        $this->http = Reaction::create(Http::class, [$this->middleware]);
        $this->http->listen($this->socket);
        //Exception handler
        $this->http->on('error', function(\Throwable $error) {
            $this->logger->alert($error);
        });
    }

public
function
initHttp
(
)
{
$
this
->
socket
=
Reaction
::
create
(
SocketServerInterface
::
class
)
;
$
this
->
http
=
Reaction
::
create
(
Http
::
class
,
[
$
this
->
middleware
]
)
;
$
this
->
http
->
listen
(
$
this
->
socket
)
;
//Exception handler
$
this
->
http
->
on
(
'error'
,
function
(
\
Throwable
$
error
)
{
$
this
->
logger
->
alert
(
$
error
)
;
}
)
;
}

Initialize with React HTTP and Socket servers
Used in web application


public function addMiddleware($middleware) {
        if (!is_callable($middleware) && !is_array($middleware)) {
            throw new InvalidArgumentException("Middleware must be a valid callable");
        } else {
            $this->middleware[] = $middleware;
        }
    }

public
function
addMiddleware
(
$
middleware
)
{
if
(
!
is_callable
(
$
middleware
)
&&
!
is_array
(
$
middleware
)
)
{
throw
new
InvalidArgumentException
(
"Middleware must be a valid callable"
)
;
}
else
{
$
this
->
middleware
[
]
=
$
middleware
;
}
}

Add middleware to application
@param callable|array $middleware


public function createRequestApplication(ServerRequestInterface $request)
    {
        $config = Reaction::$config->get('appRequest');
        $config = ['request' => $request] + $config;
        $app = Reaction::create($config);
        return $app;
    }

public function createRequestApplication ( ServerRequestInterface $ request ) { $ config = Reaction :: $ config -> get ( 'appRequest' ) ; $ config = [ 'request' => $ request ] + $ config ; $ app = Reaction :: create ( $ config ) ; return $ app ; }

Create RequestApplicationInterface instance from react request
@param ServerRequestInterface $request
@return RequestApplicationInterface


public function setAlias($alias, $path)
    {
        if (strncmp($alias, '@', 1)) {
            $alias = '@' . $alias;
        }
        $pos = strpos($alias, '/');
        $root = $pos === false ? $alias : substr($alias, 0, $pos);
        if ($path !== null) {
            $path = strncmp($path, '@', 1) ? rtrim($path, '\\/') : $this->getAlias($path);
            if (!isset($this->aliases[$root])) {
                if ($pos === false) {
                    $this->aliases[$root] = $path;
                } else {
                    $this->aliases[$root] = [$alias => $path];
                }
            } elseif (is_string($this->aliases[$root])) {
                if ($pos === false) {
                    $this->aliases[$root] = $path;
                } else {
                    $this->aliases[$root] = [
                        $alias => $path,
                        $root => $this->aliases[$root],
                    ];
                }
            } else {
                $this->aliases[$root][$alias] = $path;
                krsort($this->aliases[$root]);
            }
        } elseif (isset($this->aliases[$root])) {
            if (is_array($this->aliases[$root])) {
                unset($this->aliases[$root][$alias]);
            } elseif ($pos === false) {
                unset($this->aliases[$root]);
            }
        }
    }

public function setAlias ( $ alias , $ path ) { if ( strncmp ( $ alias , '@' , 1 ) ) { $ alias = '@' . $ alias ; } $ pos = strpos ( $ alias , '/' ) ; $ root = $ pos === false ? $ alias : substr ( $ alias , 0 , $ pos ) ; if ( $ path !== null ) { $ path = strncmp ( $ path , '@' , 1 ) ? rtrim ( $ path , '\\/' ) : $ this -> getAlias ( $ path ) ; if ( ! isset ( $ this -> aliases [ $ root ] ) ) { if ( $ pos === false ) { $ this -> aliases [ $ root ] = $ path ; } else { $ this -> aliases [ $ root ] = [ $ alias => $ path ] ; } } elseif ( is_string ( $ this -> aliases [ $ root ] ) ) { if ( $ pos === false ) { $ this -> aliases [ $ root ] = $ path ; } else { $ this -> aliases [ $ root ] = [ $ alias => $ path , $ root => $ this -> aliases [ $ root ] , ] ; } } else { $ this -> aliases [ $ root ] [ $ alias ] = $ path ; krsort ( $ this -> aliases [ $ root ] ) ; } } elseif ( isset ( $ this -> aliases [ $ root ] ) ) { if ( is_array ( $ this -> aliases [ $ root ] ) ) { unset ( $ this -> aliases [ $ root ] [ $ alias ] ) ; } elseif ( $ pos === false ) { unset ( $ this -> aliases [ $ root ] ) ; } } }

Registers a path alias.

A path alias is a short name representing a long path (a file path, a URL, etc.)
For example, we use '@reaction' as the alias of the path to the Reaction framework directory.

A path alias must start with the character '@' so that it can be easily differentiated
from non-alias paths.

Note that this method does not check if the given path exists or not. All it does is
to associate the alias with the path.

Any trailing '/' and '\' characters in the given path will be trimmed.

See the [guide article on aliases](guide:concept-aliases) for more information.

@param string $alias the alias name (e.g. "@yii"). It must start with a '@' character.
It may contain the forward slash '/' which serves as boundary character when performing
alias translation by [[getAlias()]].
@param string $path the path corresponding to the alias. If this is null, the alias will
be removed. Trailing '/' and '\' characters will be trimmed. This can be

- a directory or a file path (e.g. `/tmp`, `/tmp/main.txt`)
- a URL (e.g. `http://www.example.com`)
- a path alias (e.g. `@root/config`). In this case, the path alias will be converted into the
actual path first by calling [[getAlias()]].

@see getAlias()


public function setAliases($aliases)
    {
        foreach ($aliases as $alias => $path) {
            $this->setAlias($alias, $path);
        }
    }

public function setAliases ( $ aliases ) { foreach ( $ aliases as $ alias => $ path ) { $ this -> setAlias ( $ alias , $ path ) ; } }

Set aliases from config
@param array $aliases


protected function getErrorLogLevel($code)
    {
        $levels = [
            E_ERROR => ['error', [Console::FG_RED, Console::BOLD]],
            E_WARNING => ['warning', [Console::FG_YELLOW, Console::BOLD]],
            E_PARSE => ['parse error', Console::FG_RED],
            E_NOTICE => ['notice', Console::FG_YELLOW],
            E_CORE_ERROR => ['core error', Console::FG_RED],
            E_CORE_WARNING => ['core warning', Console::FG_YELLOW],
            E_STRICT => ['strict warning', Console::FG_BLUE],
        ];
        foreach ($levels as $mask => $level) {
            if ($mask & $code) {
                return $level;
            }
        }
        return ['low error', Console::FG_GREY];
    }

protected
function
getErrorLogLevel
(
$
code
)
{
$
levels
=
[
E_ERROR
=>
[
'error'
,
[
Console
::
FG_RED
,
Console
::
BOLD
]
]
,
E_WARNING
=>
[
'warning'
,
[
Console
::
FG_YELLOW
,
Console
::
BOLD
]
]
,
E_PARSE
=>
[
'parse error'
,
Console
::
FG_RED
]
,
E_NOTICE
=>
[
'notice'
,
Console
::
FG_YELLOW
]
,
E_CORE_ERROR
=>
[
'core error'
,
Console
::
FG_RED
]
,
E_CORE_WARNING
=>
[
'core warning'
,
Console
::
FG_YELLOW
]
,
E_STRICT
=>
[
'strict warning'
,
Console
::
FG_BLUE
]
,
]
;
foreach
(
$
levels
as
$
mask
=>
$
level
)
{
if
(
$
mask
&
$
code
)
{
return
$
level
;
}
}
return
[
'low error'
,
Console
::
FG_GREY
]
;
}

Get error log level by error code
@param int $code
@return array|mixed


public static function generate($originalClassName, array $methods = null, array $properties = null,
                                    $proxyClassName = '', $callAutoload = false)
    {

        self::$exposeMethods = false;
        self::$exposeProperties = false;

        if ($proxyClassName == '') {
            $key = md5(
                $originalClassName . serialize($methods) . serialize($properties)
            );

            if (isset(self::$cache[$key])) {
                return self::$cache[$key];
            }
        }

        if (!empty($methods)) {
            self::$exposeMethods = true;
        }

        if (!empty($properties)) {
            self::$exposeProperties = true;
        }

        $proxy = self::generateProxy(
            $originalClassName, $methods, $properties, $proxyClassName, $callAutoload
        );

        if (isset($key)) {
            self::$cache[$key] = $proxy;
        }

        return $proxy;
    }

public static function generate ( $ originalClassName , array $ methods = null , array $ properties = null , $ proxyClassName = '' , $ callAutoload = false ) { self :: $ exposeMethods = false ; self :: $ exposeProperties = false ; if ( $ proxyClassName == '' ) { $ key = md5 ( $ originalClassName . serialize ( $ methods ) . serialize ( $ properties ) ) ; if ( isset ( self :: $ cache [ $ key ] ) ) { return self :: $ cache [ $ key ] ; } } if ( ! empty ( $ methods ) ) { self :: $ exposeMethods = true ; } if ( ! empty ( $ properties ) ) { self :: $ exposeProperties = true ; } $ proxy = self :: generateProxy ( $ originalClassName , $ methods , $ properties , $ proxyClassName , $ callAutoload ) ; if ( isset ( $ key ) ) { self :: $ cache [ $ key ] = $ proxy ; } return $ proxy ; }

Gets the data to be used for the actual reflection.

If the class has already been reflected in the same configuration,
it will be fetched from the local cache.

@static

@param string     $originalClassName Name of the class to be reflected.
@param array|null $methods           (Optional) List of methods to be exposed.
@param array|null $properties        (Optional) List of properties to be exposed.
@param string     $proxyClassName    (Optional) Name to be used for the reflected class.
@param bool       $callAutoload      (Optional) Switch to run the autoloader.

@return array The data to be used for the actual reflection.

Gets the data to be used for the actual reflection .


public static function getMethodCallParameters($method)
    {
        $parameters = array();
        foreach ($method->getParameters() as $i => $parameter) {
            $parameters[] = '$' . $parameter->getName();
        }

        return join(', ', $parameters);
    }

public
static
function
getMethodCallParameters
(
$
method
)
{
$
parameters
=
array
(
)
;
foreach
(
$
method
->
getParameters
(
)
as
$
i
=>
$
parameter
)
{
$
parameters
[
]
=
'$'
.
$
parameter
->
getName
(
)
;
}
return
join
(
', '
,
$
parameters
)
;
}

Gets the arguments the proxied method expectes.

@param \ReflectionMethod $method

@return array List of parameters to be passed to the proxied method.

Gets the arguments the proxied method expectes .


protected static function generateProxy($originalClassName, array $methods = null, array $properties = null,
                                            $proxyClassName = '', $callAutoload = false)
    {
        $templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR;
        $classTemplate = self::createTemplateObject(
            $templateDir . 'proxied_class.tpl'
        );

        $proxyClassName = self::generateProxyClassName(
            $originalClassName, $proxyClassName
        );

        if (interface_exists($proxyClassName['fullClassName'], $callAutoload)) {
            throw new GeneratorException(sprintf(
                '"%s" is an interface.', $proxyClassName['fullClassName']
            ), GeneratorException::IS_INTERFACE);
        }

        if (!class_exists($proxyClassName['fullClassName'], $callAutoload)) {
            throw new GeneratorException(sprintf(
                'Class "%s" does not exists.', $proxyClassName['fullClassName']
            ), GeneratorException::CLASS_NOT_FOUND);
        }

        $class = new \ReflectionClass($proxyClassName['fullClassName']);

        if ($class->isFinal()) {
            throw new GeneratorException(sprintf(
                'Class "%s" is declared "final". Cannot create proxy.', $proxyClassName['fullClassName']
            ), GeneratorException::CLASS_IS_FINAL);
        }

        if (!empty($proxyClassName['namespaceName'])) {
            $prologue = 'namespace ' . $proxyClassName['namespaceName'] . ";\n\n";
        }

        $classTemplate->setVar(
            array(
                'prologue' => isset($prologue) ? $prologue : '',
                'class_declaration' => $proxyClassName['proxyClassName'] . ' extends ' . $originalClassName,
                'methods' => self::getProxiedMethods($proxyClassName['fullClassName'], $class, $methods),
                'properties' => self::getProxiedProperties($proxyClassName['fullClassName'], $class, $properties),
            )
        );

        return array(
            'code' => $classTemplate->render(),
            'proxyClassName' => $proxyClassName['proxyClassName'],
            'namespaceName' => $proxyClassName['namespaceName']
        );
    }

Generates the data to be used for the actual reflection.

@static

@param string     $originalClassName Name of the class to be reflected.
@param array|null $methods           (Optional) List of methods to be exposed.
@param array|null $properties        (Optional) List of properties to be exposed.
@param string     $proxyClassName    (Optional) Name to be used for the reflected class.
@param bool       $callAutoload      (Optional) Switch to run the autoloader.

@return array The data to be used for the actual reflection.
@throws \lapistano\ProxyObject\GeneratorException

Generates the data to be used for the actual reflection .


protected static function getProxiedProperties($fullClassName, \ReflectionClass $class, array $properties = null)
    {
        $proxiedProperties = '';
        $templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR;
        $proxyProperties = $class->getProperties(\ReflectionMethod::IS_PROTECTED | \ReflectionMethod::IS_PRIVATE);

        if (empty($properties)) {
            foreach ($proxyProperties as $property) {
                $proxiedProperties .= self::generateProxiedPropertyDefinition($templateDir, $property, $class);
            }
        } else {

            foreach ($properties as $propertyName) {

                if ($class->hasProperty($propertyName)) {
                    $property = $class->getProperty($propertyName);
                    $proxiedProperties .= self::generateProxiedPropertyDefinition($templateDir, $property, $class);
                    continue;
                }

                throw new GeneratorException(
                    sprintf(
                        'Class "%s" has no protected or private property "%s".', $fullClassName, $propertyName
                    ),
                    GeneratorException::NO_PROTECTED_OR_PRIVATE_PROPERTY_DEFINED
                );
            }
        }

        return $proxiedProperties;
    }

Generate string representing the set of properties to be reflected.

@param string           $fullClassName
@param \ReflectionClass $class
@param array            $properties

@return string
@throws \lapistano\ProxyObject\GeneratorException

Generate string representing the set of properties to be reflected .


protected static function getProxiedMethods($fullClassName, \ReflectionClass $class, array $methods = null)
    {
        $proxyMethods = array();
        $proxiedMethods = '';
        $templateDir = __DIR__ . DIRECTORY_SEPARATOR . 'Generator' . DIRECTORY_SEPARATOR;

        if (is_array($methods) && count($methods) > 0) {

            foreach ($methods as $methodName) {

                if ($class->hasMethod($methodName)) {

                    $method = $class->getMethod($methodName);

                    if (self::canProxyMethod($method)) {
                        $proxyMethods[] = $method;
                        continue;
                    }

                    throw new GeneratorException(
                        sprintf('Can not proxy method "%s" of class "%s".', $methodName, $fullClassName),
                        GeneratorException::CANNOT_PROXY_METHOD
                    );
                }

                throw new GeneratorException(
                    sprintf('Class "%s" has no protected method "%s".', $fullClassName, $methodName),
                    GeneratorException::NO_PROTECTED_METHOD_DEFINED
                );
            }
        } else {

            $proxyMethods = self::canProxyMethods($class->getMethods(\ReflectionMethod::IS_PROTECTED));

            if (empty($proxyMethods ) && self::$exposeProperties === false) {
                throw new GeneratorException(
                    sprintf('Class "%s" has no protected methods.', $fullClassName),
                    GeneratorException::NO_PROTECTED_METHOD_DEFINED
                );
            }
        }

        foreach ($proxyMethods as $method) {
            $proxiedMethods .= self::generateProxiedMethodDefinition($templateDir, $method);
        }

        return $proxiedMethods;
    }

Generate string representing the set of methods to be reflected.

@param array            $fullClassName
@param \ReflectionClass $class
@param array            $methods

@return array Information about the method to be proxied.

@throws GeneratorException

Generate string representing the set of methods to be reflected .


protected static function generateProxyClassName($originalClassName, $proxyClassName)
    {
        $classNameParts = explode('\\', $originalClassName);
        $namespaceName = '';
        $fullClassName = $originalClassName;

        if (count($classNameParts) > 1) {
            $originalClassName = array_pop($classNameParts);
            $namespaceName = implode('\\', $classNameParts);
            $fullClassName = $namespaceName . '\\' . $originalClassName;

            // eval does identifies namespaces with leading backslash as constant.
            $namespaceName = (0 === stripos($namespaceName, '\\') ? substr($namespaceName, 1) : $namespaceName);
        }

        if ($proxyClassName == '') {
            do {
                $proxyClassName = 'Proxy_' . $originalClassName . '_' . substr(md5(microtime()), 0, 8);
            } while (class_exists($proxyClassName, false));
        }

        return array(
            'proxyClassName' => $proxyClassName,
            'className' => $originalClassName,
            'fullClassName' => $fullClassName,
            'namespaceName' => $namespaceName
        );
    }

Generates a unique name to be used to identify the created proxyclass.

@param  string $originalClassName Name of the class to be reflected.
@param  string $proxyClassName    Name to be used for the reflected class.

@return array Information of the class to be reflected.

Generates a unique name to be used to identify the created proxyclass .