public function order($order, $desc = null)
    {
        // Case with comma-separated fields or first argument being an array
        if (is_string($order) && strpos($order, ',') !== false) {
            $order = explode(',', $order);
        }

        if (is_array($order)) {
            if ($desc !== null) {
                throw new Exception(
                    'If first argument is array, second argument must not be used'
                );
            }
            foreach (array_reverse($order) as $o) {
                $this->order($o);
            }

            return $this;
        }

        // First argument may contain space, to divide field and ordering keyword.
        // Explode string only if ordering keyword is 'desc' or 'asc'.
        if ($desc === null && is_string($order) && strpos($order, ' ') !== false) {
            $_chunks = explode(' ', $order);
            $_desc = strtolower(array_pop($_chunks));
            if (in_array($_desc, ['desc', 'asc'])) {
                $order = implode(' ', $_chunks);
                $desc = $_desc;
            }
        }

        if (is_bool($desc)) {
            $desc = $desc ? 'desc' : '';
        } elseif (strtolower($desc) === 'asc') {
            $desc = '';
        } else {
            // allows custom order like "order by name desc nulls last" for Oracle
        }

        $this->args['order'][] = [$order, $desc];

        return $this;
    }

Orders results by field or Expression. See documentation for full
list of possible arguments.

$q->order('name');
$q->order('name desc');
$q->order('name desc, id asc')
$q->order('name',true);

@param string|array $order Order by
@param string|bool  $desc  true to sort descending

@return $this

Orders results by field or Expression . See documentation for full list of possible arguments .


public function mode($mode)
    {
        $prop = 'template_'.$mode;

        if (isset($this->{$prop})) {
            $this->mode = $mode;
            $this->template = $this->{$prop};
        } else {
            throw new Exception([
                'Query does not have this mode',
                'mode' => $mode,
            ]);
        }

        return $this;
    }

public
function
mode
(
$
mode
)
{
$
prop
=
'template_'
.
$
mode
;
if
(
isset
(
$
this
->
{
$
prop
}
)
)
{
$
this
->
mode
=
$
mode
;
$
this
->
template
=
$
this
->
{
$
prop
}
;
}
else
{
throw
new
Exception
(
[
'Query does not have this mode'
,
'mode'
=>
$
mode
,
]
)
;
}
return
$
this
;
}

Switch template for this query. Determines what would be done
on execute.

By default it is in SELECT mode

@param string $mode

@return $this

Switch template for this query . Determines what would be done on execute .


public function limit($cnt, $shift = null)
    {
        // This is for pre- 12c version
        $this->template_select = $this->template_select_limit;

        return parent::limit($cnt, $shift);
    }

public
function
limit
(
$
cnt
,
$
shift
=
)
{
// This is for pre- 12c version
$
this
->
template_select
=
$
this
->
template_select_limit
;
return
parent
::
limit
(
$
cnt
,
$
shift
)
;
}

Limit how many rows will be returned.

@param int $cnt   Number of rows to return
@param int $shift Offset, how many rows to skip

@return $this


private function parseString($value)
    {
        $single = false;
        $regex = self::REGEX_QUOTE_DOUBLE_STRING;
        $symbol = '"';

        if ($this->parser->string_helper->startsWith('\'', $value)) {
            $single = true;
            $regex =  self::REGEX_QUOTE_SINGLE_STRING;
            $symbol = "'";
        }

        $matches = $this->fetchStringMatches($value, $regex, $symbol);

        $value = trim($matches[0], $symbol);
        $value = strtr($value, self::$character_map);

        return ($single) ? $value : $this->variable_parser->parse($value, true);
    }

private function parseString ( $ value ) { $ single = false ; $ regex = self :: REGEX_QUOTE_DOUBLE_STRING ; $ symbol = '"' ; if ( $ this -> parser -> string_helper -> startsWith ( '\'' , $ value ) ) { $ single = true ; $ regex = self :: REGEX_QUOTE_SINGLE_STRING ; $ symbol = "'" ; } $ matches = $ this -> fetchStringMatches ( $ value , $ regex , $ symbol ) ; $ value = trim ( $ matches [ 0 ] , $ symbol ) ; $ value = strtr ( $ value , self :: $ character_map ) ; return ( $ single ) ? $ value : $ this -> variable_parser -> parse ( $ value , true ) ; }

Parses a .env string

@param string $value    The value to parse

@return string The parsed string


private function fetchStringMatches($value, $regex, $symbol)
    {
        if (!preg_match('/'.$regex.'/', $value, $matches)) {
            throw new ParseException(
                sprintf('Missing end %s quote', $symbol),
                $value,
                $this->parser->line_num
            );
        }

        return $matches;
    }

private
function
fetchStringMatches
(
$
value
,
$
regex
,
$
symbol
)
{
if
(
!
preg_match
(
'/'
.
$
regex
.
'/'
,
$
value
,
$
matches
)
)
{
throw
new
ParseException
(
sprintf
(
'Missing end %s quote'
,
$
symbol
)
,
$
value
,
$
this
->
parser
->
line_num
)
;
}
return
$
matches
;
}

Gets the regex matches in the string

@param string $regex    The regex to use
@param string $value    The value to parse
@param string $symbol   The symbol we're parsing for

@throws \M1\Env\Exception\ParseException If the string has a missing end quote

@return string[] The matches based on the regex and the value


private function createMessage($message, $line, $line_num)
    {
        if (!is_null($line)) {
            $message .= sprintf(" near %s", $line);
        }

        if (!is_null($line_num)) {
            $message .= sprintf(" at line %d", $line_num);
        }

        return $message;
    }

private
function
createMessage
(
$
message
,
$
line
,
$
line_num
)
{
if
(
!
is_null
(
$
line
)
)
{
$
message
.=
sprintf
(
" near %s"
,
$
line
)
;
}
if
(
!
is_null
(
$
line_num
)
)
{
$
message
.=
sprintf
(
" at line %d"
,
$
line_num
)
;
}
return
$
message
;
}

Constructs a ParseException message

@param string $message          The value to parse
@param string $line             The line of the value
@param int    $line_num         The line num of the value

@return string The exception message


public function startsWith($string, $line)
    {
        return $string === "" || strrpos($line, $string, -strlen($line)) !== false;
    }

public function startsWith ( $ string , $ line ) { return $ string === "" || strrpos ( $ line , $ string , - strlen ( $ line ) ) !== false ; }

Returns if value starts with a value

@param string $string The value to search for
@param string $line   The line to test

@return bool Returns if the line starts with value


private function fetchVariableMatches($value)
    {
        preg_match_all('/' . self::REGEX_ENV_VARIABLE . '/', $value, $matches);

        if (!is_array($matches) || !isset($matches[0]) || empty($matches[0])) {
            return false;
        }

        return $matches;
    }

private function fetchVariableMatches ( $ value ) { preg_match_all ( '/' . self :: REGEX_ENV_VARIABLE . '/' , $ value , $ matches ) ; if ( ! is_array ( $ matches ) || ! isset ( $ matches [ 0 ] ) || empty ( $ matches [ 0 ] ) ) { return false ; } return $ matches ; }

Get variable matches inside a string

@param string $value The value to parse

@return array The variable matches


private function hasParameterExpansion($variable)
    {
        if ((strpos($variable, self::SYMBOL_DEFAULT_VALUE) !== false) ||
            (strpos($variable, self::SYMBOL_ASSIGN_DEFAULT_VALUE) !== false)
        ) {
            return true;
        }

        return false;
    }

private function hasParameterExpansion ( $ variable ) { if ( ( strpos ( $ variable , self :: SYMBOL_DEFAULT_VALUE ) !== false ) || ( strpos ( $ variable , self :: SYMBOL_ASSIGN_DEFAULT_VALUE ) !== false ) ) { return true ; } return false ; }

Checks to see if the variable has a parameter expansion

@param string $variable The variable to check

@return bool Does the variable have a parameter expansion


private function fetchParameterExpansion($variable_name)
    {
        $parameter_type = $this->fetchParameterExpansionType($variable_name);

        list($parameter_symbol, $empty_flag) = $this->fetchParameterExpansionSymbol($variable_name, $parameter_type);
        list($variable, $default) = $this->splitVariableDefault($variable_name, $parameter_symbol);

        $value = $this->getVariable($variable);

        return $this->parseVariableParameter(
            $variable,
            $default,
            $this->hasVariable($variable),
            $empty_flag && empty($value),
            $parameter_type
        );
    }

private function fetchParameterExpansion ( $ variable_name ) { $ parameter_type = $ this -> fetchParameterExpansionType ( $ variable_name ) ; list ( $ parameter_symbol , $ empty_flag ) = $ this -> fetchParameterExpansionSymbol ( $ variable_name , $ parameter_type ) ; list ( $ variable , $ default ) = $ this -> splitVariableDefault ( $ variable_name , $ parameter_symbol ) ; $ value = $ this -> getVariable ( $ variable ) ; return $ this -> parseVariableParameter ( $ variable , $ default , $ this -> hasVariable ( $ variable ) , $ empty_flag && empty ( $ value ) , $ parameter_type ) ; }

Fetches and sets the parameter expansion

@param string $variable_name The parameter expansion inside this to fetch

@return string The parsed value


private function fetchParameterExpansionSymbol($variable_name, $type)
    {
        $class = new \ReflectionClass($this);
        $symbol = $class->getConstant('SYMBOL_'.strtoupper($type));
        $pos = strpos($variable_name, $symbol);

        $check_empty = substr($variable_name, ($pos - 1), 1) === ":";

        if ($check_empty) {
            $symbol = sprintf(":%s", $symbol);
        }

        return array($symbol, $check_empty);
    }

private function fetchParameterExpansionSymbol ( $ variable_name , $ type ) { $ class = new \ ReflectionClass ( $ this ) ; $ symbol = $ class -> getConstant ( 'SYMBOL_' . strtoupper ( $ type ) ) ; $ pos = strpos ( $ variable_name , $ symbol ) ; $ check_empty = substr ( $ variable_name , ( $ pos - 1 ) , 1 ) === ":" ; if ( $ check_empty ) { $ symbol = sprintf ( ":%s" , $ symbol ) ; } return array ( $ symbol , $ check_empty ) ; }

Fetches the parameter type symbol

@param string $variable_name The variable
@param string $type          The type of parameter expansion

@return array The symbol and if there is a empty check


private function splitVariableDefault($variable_name, $parameter_symbol)
    {
        $variable_default = explode($parameter_symbol, $variable_name, 2);

        if (count($variable_default) !== 2 || empty($variable_default[1])) {
            throw new ParseException(
                'You must have valid parameter expansion syntax, eg. ${parameter:=word}',
                $variable_name,
                $this->parser->line_num
            );
        }

        return array(trim($variable_default[0]), trim($variable_default[1]));
    }

Splits the parameter expansion into variable and default

@param string $variable_name    The variable name to split
@param string $parameter_symbol The parameter expansion symbol

@throws \M1\Env\Exception\ParseException If the parameter expansion if not valid syntax

@return array The split variable and default value


private function parseVariableParameter($variable, $default, $exists, $empty, $type)
    {
        if ($exists && !$empty) {
            return $this->getVariable($variable);
        }

        return $this->assignVariableParameterDefault($variable, $default, $empty, $type);
    }

private function parseVariableParameter ( $ variable , $ default , $ exists , $ empty , $ type ) { if ( $ exists && ! $ empty ) { return $ this -> getVariable ( $ variable ) ; } return $ this -> assignVariableParameterDefault ( $ variable , $ default , $ empty , $ type ) ; }

Parses and sets the variable and default if needed

@param string $variable The variable to parse
@param string $default  The default value
@param bool   $exists   Does the variable exist
@param bool   $empty    Is there the variable empty if exists and the empty flag is set
@param string $type     The type of parameter expansion

@return string The parsed value


private function assignVariableParameterDefault($variable, $default, $empty, $type)
    {
        $default = $this->parser->value_parser->parse($default);

        if ($type === "assign_default_value" && $empty) {
            $this->parser->lines[$variable] = $default;
        }

        return $default;
    }

private function assignVariableParameterDefault ( $ variable , $ default , $ empty , $ type ) { $ default = $ this -> parser -> value_parser -> parse ( $ default ) ; if ( $ type === "assign_default_value" && $ empty ) { $ this -> parser -> lines [ $ variable ] = $ default ; } return $ default ; }

Parses and sets the variable parameter to default

@param string $variable The variable to parse
@param string $default  The default value
@param bool   $empty    Is there the variable empty if exists and the empty flag is set
@param string $type     The type of parameter expansion

@return string The parsed default value


private function hasVariable($variable)
    {
        if (array_key_exists($variable, $this->parser->lines)) {
            return true;
        }

        if (array_key_exists($variable, $this->context)) {
            return true;
        }

        return false;
    }

private function hasVariable ( $ variable ) { if ( array_key_exists ( $ variable , $ this -> parser -> lines ) ) { return true ; } if ( array_key_exists ( $ variable , $ this -> context ) ) { return true ; } return false ; }

Checks to see if a variable exists

@param string $variable The variable name to get

@return bool


private function getVariable($variable)
    {
        if (array_key_exists($variable, $this->parser->lines)) {
            return $this->parser->lines[$variable];
        }

        if (array_key_exists($variable, $this->context)) {
            return $this->context[$variable];
        }

        return null;
    }

private function getVariable ( $ variable ) { if ( array_key_exists ( $ variable , $ this -> parser -> lines ) ) { return $ this -> parser -> lines [ $ variable ] ; } if ( array_key_exists ( $ variable , $ this -> context ) ) { return $ this -> context [ $ variable ] ; } return null ; }

Get variable value

@param string $variable

@return mixed


public function parse($key)
    {
        $key = trim($key);

        if ($this->parser->string_helper->startsWith('#', $key)) {
            return false;
        }

        if (!ctype_alnum(str_replace('_', '', $key)) || $this->parser->string_helper->startsWithNumber($key)) {
            throw new ParseException(
                sprintf('Key can only contain alphanumeric and underscores and can not start with a number: %s', $key),
                $key,
                $this->parser->line_num
            );
        }

        return $key;
    }

Parses a .env key

@param string $key The key string

@throws \M1\Env\Exception\ParseException If key contains a character that isn't alphanumeric or a _

@return string|false The parsed key, or false if the key is a comment


protected function doParse($content)
    {
        $raw_lines = array_filter($this->makeLines($content), 'strlen');

        if (empty($raw_lines)) {
            return;
        }

        return $this->parseContent($raw_lines);
    }

protected function doParse ( $ content ) { $ raw_lines = array_filter ( $ this -> makeLines ( $ content ) , 'strlen' ) ; if ( empty ( $ raw_lines ) ) { return ; } return $ this -> parseContent ( $ raw_lines ) ; }

Opens the .env, parses it then returns the contents

@param string $content The content to parse

@return array The .env contents

Opens the . env parses it then returns the contents


private function parseContent(array $raw_lines)
    {
        $this->lines = array();
        $this->line_num = 0;

        foreach ($raw_lines as $raw_line) {
            $this->line_num++;

            if ($this->string_helper->startsWith('#', $raw_line) || !$raw_line) {
                continue;
            }

            $this->parseLine($raw_line);
        }

        return $this->lines;
    }

private function parseContent ( array $ raw_lines ) { $ this -> lines = array ( ) ; $ this -> line_num = 0 ; foreach ( $ raw_lines as $ raw_line ) { $ this -> line_num ++ ; if ( $ this -> string_helper -> startsWith ( '#' , $ raw_line ) || ! $ raw_line ) { continue ; } $ this -> parseLine ( $ raw_line ) ; } return $ this -> lines ; }

Parses the .env line by line

@param array $raw_lines The raw content of the file

@throws \M1\Env\Exception\ParseException If the file does not have a key=value structure

@return array The .env contents


private function parseLine($raw_line)
    {
        $raw_line = $this->parseExport($raw_line);

        list($key, $value) = $this->parseKeyValue($raw_line);

        $key = $this->key_parser->parse($key);

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

        $this->lines[$key] = $this->value_parser->parse($value);
    }

private function parseLine ( $ raw_line ) { $ raw_line = $ this -> parseExport ( $ raw_line ) ; list ( $ key , $ value ) = $ this -> parseKeyValue ( $ raw_line ) ; $ key = $ this -> key_parser -> parse ( $ key ) ; if ( ! is_string ( $ key ) ) { return ; } $ this -> lines [ $ key ] = $ this -> value_parser -> parse ( $ value ) ; }

Parses a line of the .env

@param string $raw_line The raw content of the line

@return array The parsed lines


private function parseExport($raw_line)
    {
        $line = trim($raw_line);

        if ($this->string_helper->startsWith("export", $line)) {
            $export_line = explode("export", $raw_line, 2);

            if (count($export_line) !== 2 || empty($export_line[1])) {
                throw new ParseException(
                    'You must have a export key = value',
                    $raw_line,
                    $this->line_num
                );
            }

            $line = trim($export_line[1]);
        }

        return $line;
    }

private
function
parseExport
(
$
raw_line
)
{
$
line
=
trim
(
$
raw_line
)
;
if
(
$
this
->
string_helper
->
startsWith
(
"export"
,
$
line
)
)
{
$
export_line
=
explode
(
"export"
,
$
raw_line
,
2
)
;
if
(
count
(
$
export_line
)
!==
2
||
empty
(
$
export_line
[
1
]
)
)
{
throw
new
ParseException
(
'You must have a export key = value'
,
$
raw_line
,
$
this
->
line_num
)
;
}
$
line
=
trim
(
$
export_line
[
1
]
)
;
}
return
$
line
;
}

Parses a export line of the .env

@param string $raw_line The raw content of the line

@throws \M1\Env\Exception\ParseException If the file does not have a key=value structure

@return string The parsed line


private function parseKeyValue($raw_line)
    {
        $key_value = explode("=", $raw_line, 2);

        if (count($key_value) !== 2) {
            throw new ParseException(
                'You must have a key = value',
                $raw_line,
                $this->line_num
            );
        }

        return $key_value;
    }

private
function
parseKeyValue
(
$
raw_line
)
{
$
key_value
=
explode
(
"="
,
$
raw_line
,
2
)
;
if
(
count
(
$
key_value
)
!==
2
)
{
throw
new
ParseException
(
'You must have a key = value'
,
$
raw_line
,
$
this
->
line_num
)
;
}
return
$
key_value
;
}

Gets the key = value items from the line

@param string $raw_line The raw content of the line

@throws \M1\Env\Exception\ParseException If the line does not have a key=value structure

@return array The parsed lines


public function getContent($keyName = null)
    {
		if (!is_null($keyName)) {
			return (array_key_exists($keyName, $this->lines)) ? $this->lines[$keyName] : null;
		}
        return $this->lines;
    }

public function getContent ( $ keyName = null ) { if ( ! is_null ( $ keyName ) ) { return ( array_key_exists ( $ keyName , $ this -> lines ) ) ? $ this -> lines [ $ keyName ] : null ; } return $ this -> lines ; }

Returns the contents of the .env

@return array The .env contents


public function startTask(TaskInterface $task)
    {
        $response = $this->http->post($this->getTaskWorkerUrl(), [
            self::ATTR_PROG => self::PROG,
            self::ATTR_NAME => get_class($task),
            self::ATTR_DATA => $this->serializer->encode($this->properties->getPropertiesFromObject($task)),
            self::ATTR_MAX_PROCESSING_TIME => method_exists($task, 'getMaxProcessingTime') ? $task->getMaxProcessingTime() : null,
        ]);

        if ($response->hasErrors()) {
            if (strpos($response->body->error, 'Your worker does not listen') !== false) {
                throw new AgentNotListeningException($this->appId, $this->appEnv);
            }

            if (strpos($response->body->error, 'Unknown version') !== false) {
                throw new AgentUpdateRequiredException('>=0.6.0');
            }

            throw new AgentException($response->body->error);
        }
    }

public
function
startTask
(
TaskInterface
$
task
)
{
$
response
=
$
this
->
http
->
post
(
$
this
->
getTaskWorkerUrl
(
)
,
[
self
::
ATTR_PROG
=>
self
::
PROG
,
self
::
ATTR_NAME
=>
get_class
(
$
task
)
,
self
::
ATTR_DATA
=>
$
this
->
serializer
->
encode
(
$
this
->
properties
->
getPropertiesFromObject
(
$
task
)
)
,
self
::
ATTR_MAX_PROCESSING_TIME
=>
method_exists
(
$
task
,
'getMaxProcessingTime'
)
$
task
->
getMaxProcessingTime
(
)
:
,
]
)
;
if
(
$
response
->
hasErrors
(
)
)
{
if
(
strpos
(
$
response
->
body
->
error
,
'Your worker does not listen'
)
!==
false
)
{
throw
new
AgentNotListeningException
(
$
this
->
appId
,
$
this
->
appEnv
)
;
}
if
(
strpos
(
$
response
->
body
->
error
,
'Unknown version'
)
!==
false
)
{
throw
new
AgentUpdateRequiredException
(
'>=0.6.0'
)
;
}
throw
new
AgentException
(
$
response
->
body
->
error
)
;
}
}

Start a single task.

@throws AgentNotListeningException   If the agent is not listening to the application
@throws AgentUpdateRequiredException If the agent does not have the minimum required version
@throws AgentException               For any other error coming from the agent


public function startWorkflow(WorkflowInterface $flow)
    {
        $canonical = null;
        // if $flow is a versionned workflow
        if ($flow instanceof VersionedWorkflow) {
            // store canonical name
            $canonical = get_class($flow);
            // replace by true current implementation
            $flow = $flow->getCurrentImplementation();
        }

        // custom id management
        $customId = null;
        if (method_exists($flow, 'getId')) {
            $customId = $flow->getId();
            if (!is_string($customId) && !is_int($customId)) {
                throw new InvalidArgumentException('Provided Id must be a string or an integer');
            }
            // at the end, it's a string
            $customId = (string) $customId;
            // should be not more than 256 bytes;
            if (strlen($customId) > self::MAX_ID_SIZE) {
                throw new InvalidArgumentException('Provided Id must not exceed '.self::MAX_ID_SIZE.' bytes');
            }
        }

        // start workflow
        $this->http->post($this->getInstanceWorkerUrl(), [
            self::ATTR_PROG => self::PROG,
            self::ATTR_CANONICAL => $canonical,
            self::ATTR_NAME => get_class($flow),
            self::ATTR_DATA => $this->serializer->encode($this->properties->getPropertiesFromObject($flow)),
            self::ATTR_ID => $customId,
        ]);
    }

Start a workflow instance.

@param WorkflowInterface $flow Workflow to start


public function findWorkflow($workflowName, $customId)
    {
        $params = [
            static::ATTR_ID => $customId,
            static::ATTR_NAME => $workflowName,
            static::ATTR_PROG => static::PROG,
        ];

        $response = $this->http->get($this->getInstanceWebsiteUrl($params));
        if ($response->code === 404) {
            return null;
        }

        if ($response->hasErrors()) {
            throw ApiException::unexpectedStatusCode($response->code);
        }

        return $this->properties->getObjectFromNameAndProperties($response->body->data->name, $this->serializer->decode($response->body->data->properties));
    }

public function findWorkflow ( $ workflowName , $ customId ) { $ params = [ static :: ATTR_ID => $ customId , static :: ATTR_NAME => $ workflowName , static :: ATTR_PROG => static :: PROG , ] ; $ response = $ this -> http -> get ( $ this -> getInstanceWebsiteUrl ( $ params ) ) ; if ( $ response -> code === 404 ) { return null ; } if ( $ response -> hasErrors ( ) ) { throw ApiException :: unexpectedStatusCode ( $ response -> code ) ; } return $ this -> properties -> getObjectFromNameAndProperties ( $ response -> body -> data -> name , $ this -> serializer -> decode ( $ response -> body -> data -> properties ) ) ; }

Find a workflow instance.

@param string $workflowName Workflow class name
@param string $customId     Provided custom id

@return null|WorkflowInterface


public function _getTimestampOrDuration()
    {
        if (null === $this->_buffer) {
            return [null, null];
        }

        list($now, $then) = $this->_initNowThen();

        $this->_mode = null;
        // apply buffered methods
        foreach ($this->_buffer as $call) {
            $then = $this->_apply($call[0], $call[1], $now, $then);
        }
        // has user used a method by timestamp?
        $isTimestamp = null !== $this->_mode;
        //return
        if ($isTimestamp) {
            return [$then->timestamp, null];
        }

        return [null, $now->diffInSeconds($then)];
    }

public
function
_getTimestampOrDuration
(
)
{
if
(
===
$
this
->
_buffer
)
{
return
[
,
]
;
}
list
(
$
now
,
$
then
)
=
$
this
->
_initNowThen
(
)
;
$
this
->
_mode
=
;
// apply buffered methods
foreach
(
$
this
->
_buffer
as
$
call
)
{
$
then
=
$
this
->
_apply
(
$
call
[
0
]
,
$
call
[
1
]
,
$
now
,
$
then
)
;
}
// has user used a method by timestamp?
$
isTimestamp
=
!==
$
this
->
_mode
;
//return
if
(
$
isTimestamp
)
{
return
[
$
then
->
timestamp
,
]
;
}
return
[
,
$
now
->
diffInSeconds
(
$
then
)
]
;
}

Return Wait timestamp or duration depending on methods used.

@return array [null, duration] or [timestamp, null] or [null, null]

Return Wait timestamp or duration depending on methods used .


private function getClassProperties($argument, $filter = null)
    {
        if (null === $filter) {
            $filter = \ReflectionProperty::IS_STATIC | \ReflectionProperty::IS_PUBLIC | \ReflectionProperty::IS_PROTECTED | \ReflectionProperty::IS_PRIVATE;
        }

        $reflectionClass = new \ReflectionClass($argument);

        if ($parentClass = $reflectionClass->getParentClass()) {
            return array_merge($this->getClassProperties($parentClass->getName(), $filter), $reflectionClass->getProperties($filter));
        }

        return $reflectionClass->getProperties($filter);
    }

private function getClassProperties ( $ argument , $ filter = null ) { if ( null === $ filter ) { $ filter = \ ReflectionProperty :: IS_STATIC | \ ReflectionProperty :: IS_PUBLIC | \ ReflectionProperty :: IS_PROTECTED | \ ReflectionProperty :: IS_PRIVATE ; } $ reflectionClass = new \ ReflectionClass ( $ argument ) ; if ( $ parentClass = $ reflectionClass -> getParentClass ( ) ) { return array_merge ( $ this -> getClassProperties ( $ parentClass -> getName ( ) , $ filter ) , $ reflectionClass -> getProperties ( $ filter ) ) ; } return $ reflectionClass -> getProperties ( $ filter ) ; }

Return properties of a class and all its inheritance hierarchy.

@param object|string $argument Object or class name to get properties from
@param null|int      $filter   Optional filter, for filtering desired property types. It's configured using the `\ReflectionProperty` constants, and defaults to all property types.

@throws \ReflectionException if the class to reflect does not exist

@return \ReflectionProperty[]

Return properties of a class and all its inheritance hierarchy .


protected function configureSitemap(array $config, ContainerBuilder $container)
    {
        $source = $container->getDefinition('sonata.seo.sitemap.manager');

        if (method_exists($source, 'setShared')) { // Symfony 2.8+
            $source->setShared(false);
        } else {
            // For Symfony <2.8 compatibility
            $source->setScope(ContainerInterface::SCOPE_PROTOTYPE);
        }

        foreach ($config['doctrine_orm'] as $pos => $sitemap) {
            // define the connectionIterator
            $connectionIteratorId = 'sonata.seo.source.doctrine_connection_iterator_'.$pos;

            $connectionIterator = new Definition('%sonata.seo.exporter.database_source_iterator.class%', [
                new Reference($sitemap['connection']),
                $sitemap['query'],
            ]);

            $connectionIterator->setPublic(false);
            $container->setDefinition($connectionIteratorId, $connectionIterator);

            // define the sitemap proxy iterator
            $sitemapIteratorId = 'sonata.seo.source.doctrine_sitemap_iterator_'.$pos;

            $sitemapIterator = new Definition('%sonata.seo.exporter.sitemap_source_iterator.class%', [
                new Reference($connectionIteratorId),
                new Reference('router'),
                $sitemap['route'],
                $sitemap['parameters'],
            ]);

            $sitemapIterator->setPublic(false);

            $container->setDefinition($sitemapIteratorId, $sitemapIterator);

            $source->addMethodCall('addSource', [$sitemap['group'], new Reference($sitemapIteratorId), $sitemap['types']]);
        }

        foreach ($config['services'] as $service) {
            $source->addMethodCall('addSource', [$service['group'], new Reference($service['id']), $service['types']]);
        }
    }

Configure the sitemap source manager.

@param array            $config
@param ContainerBuilder $container


protected function fixConfiguration(array $config)
    {
        foreach ($config['sitemap']['doctrine_orm'] as $pos => $sitemap) {
            $sitemap['group'] = $sitemap['group'] ?? false;
            $sitemap['types'] = $sitemap['types'] ?? [];
            $sitemap['connection'] = $sitemap['connection'] ?? 'doctrine.dbal.default_connection';
            $sitemap['route'] = $sitemap['route'] ?? false;
            $sitemap['parameters'] = $sitemap['parameters'] ?? false;
            $sitemap['query'] = $sitemap['query'] ?? false;

            if (false === $sitemap['route']) {
                throw new \RuntimeException('Route cannot be empty, please review the sonata_seo.sitemap configuration');
            }

            if (false === $sitemap['query']) {
                throw new \RuntimeException('Query cannot be empty, please review the sonata_seo.sitemap configuration');
            }

            if (false === $sitemap['parameters']) {
                throw new \RuntimeException('Route\'s parameters cannot be empty, please review the sonata_seo.sitemap configuration');
            }

            $config['sitemap']['doctrine_orm'][$pos] = $sitemap;
        }

        foreach ($config['sitemap']['services'] as $pos => $sitemap) {
            if (!\is_array($sitemap)) {
                $sitemap = [
                    'group' => false,
                    'types' => [],
                    'id' => $sitemap,
                ];
            } else {
                $sitemap['group'] = $sitemap['group'] ?? false;
                $sitemap['types'] = $sitemap['types'] ?? [];

                if (!isset($sitemap['id'])) {
                    throw new \RuntimeException('Service id must to be defined, please review the sonata_seo.sitemap configuration');
                }
            }

            $config['sitemap']['services'][$pos] = $sitemap;
        }

        return $config;
    }

Fix the sitemap configuration.

@param array $config

@return array


public function addSource($group, SourceIteratorInterface $source, array $types = [])
    {
        if (!isset($this->sources[$group])) {
            $this->sources[$group] = new \stdClass();

            $this->sources[$group]->sources = new ChainSourceIterator();
            $this->sources[$group]->types = [];
        }

        $this->sources[$group]->sources->addSource($source);

        if ($types) {
            $this->sources[$group]->types += array_diff($types, $this->sources[$group]->types);
        }
    }

public function addSource ( $ group , SourceIteratorInterface $ source , array $ types = [ ] ) { if ( ! isset ( $ this -> sources [ $ group ] ) ) { $ this -> sources [ $ group ] = new \ stdClass ( ) ; $ this -> sources [ $ group ] -> sources = new ChainSourceIterator ( ) ; $ this -> sources [ $ group ] -> types = [ ] ; } $ this -> sources [ $ group ] -> sources -> addSource ( $ source ) ; if ( $ types ) { $ this -> sources [ $ group ] -> types += array_diff ( $ types , $ this -> sources [ $ group ] -> types ) ; } }

Adding source with his group.

@param string                  $group
@param SourceIteratorInterface $source
@param array                   $types


public function onBlock(BlockEvent $event)
    {
        $context = $event->getSetting('context', null);

        if (null === $context) {
            return;
        }

        foreach ($this->blockServices as $type => $blockService) {
            if ($blockService->handleContext($context)) {
                $block = new Block();
                $block->setId(uniqid());
                $block->setSettings($event->getSettings());
                $block->setType($type);

                $event->addBlock($block);

                return;
            }
        }
    }

public function onBlock ( BlockEvent $ event ) { $ context = $ event -> getSetting ( 'context' , null ) ; if ( null === $ context ) { return ; } foreach ( $ this -> blockServices as $ type => $ blockService ) { if ( $ blockService -> handleContext ( $ context ) ) { $ block = new Block ( ) ; $ block -> setId ( uniqid ( ) ) ; $ block -> setSettings ( $ event -> getSettings ( ) ) ; $ block -> setType ( $ type ) ; $ event -> addBlock ( $ block ) ; return ; } } }

Add context related BlockService, if found.

@param BlockEvent $event

Add context related BlockService if found .


protected function getRootMenu(BlockContextInterface $blockContext)
    {
        $settings = $blockContext->getSettings();
        /*
         * @todo : Use the router to get the homepage URI
         */

        $menu = $this->factory->createItem('breadcrumb');

        $menu->setChildrenAttribute('class', 'breadcrumb');

        if (method_exists($menu, 'setCurrentUri')) {
            $menu->setCurrentUri($settings['current_uri']);
        }

        if (method_exists($menu, 'setCurrent')) {
            $menu->setCurrent($settings['current_uri']);
        }

        if ($settings['include_homepage_link']) {
            $menu->addChild('sonata_seo_homepage_breadcrumb', ['uri' => '/']);
        }

        return $menu;
    }

Initialize breadcrumb menu.

@param BlockContextInterface $blockContext

@return ItemInterface


private function getFonts()
    {
        if (empty($this->fonts)) {
            $files = FileHelper::findFiles(Craft::getAlias(self::FONT_DIR), ['only' => self::FONT_EXT]);
            $filenames = [];
            $fonts = [];

            foreach ($files as $file) {
                $pathInfo = pathinfo($file);
                $safename = in_array($pathInfo['filename'], $filenames) ? $pathInfo['basename'] : $pathInfo['filename'];
                $safename = $this->safeName($safename);
                $fonts[$safename] = ArrayHelper::merge(
                    [
                        'path' => $file,
                        'safename' => $safename
                    ],
                    $pathInfo
                );

                $filenames[] = $pathInfo['filename'];
            }

            $this->fonts = $fonts;
        }

        return $this->fonts;
    }

private function getFonts ( ) { if ( empty ( $ this -> fonts ) ) { $ files = FileHelper :: findFiles ( Craft :: getAlias ( self :: FONT_DIR ) , [ 'only' => self :: FONT_EXT ] ) ; $ filenames = [ ] ; $ fonts = [ ] ; foreach ( $ files as $ file ) { $ pathInfo = pathinfo ( $ file ) ; $ safename = in_array ( $ pathInfo [ 'filename' ] , $ filenames ) ? $ pathInfo [ 'basename' ] : $ pathInfo [ 'filename' ] ; $ safename = $ this -> safeName ( $ safename ) ; $ fonts [ $ safename ] = ArrayHelper :: merge ( [ 'path' => $ file , 'safename' => $ safename ] , $ pathInfo ) ; $ filenames [ ] = $ pathInfo [ 'filename' ] ; } $ this -> fonts = $ fonts ; } return $ this -> fonts ; }

Get all the fonts that are residing in the fonts directory and have the right extention.
Index them by path as key and pathinfo array as value

@return array

Get all the fonts that are residing in the fonts directory and have the right extention . Index them by path as key and pathinfo array as value


private function getIcons()
    {
        if (!empty($this->iconFont)) {
            $fonts = $this->getFonts();
            if (!empty($fonts) && isset($fonts[$this->iconFont])) {
                $font = Font::load($fonts[$this->iconFont]['path']);
                $font->parse();

                if ($font !== null) {
                    return $font->getUnicodeCharMap();
                }
            }
        }

        return null;
    }

private function getIcons ( ) { if ( ! empty ( $ this -> iconFont ) ) { $ fonts = $ this -> getFonts ( ) ; if ( ! empty ( $ fonts ) && isset ( $ fonts [ $ this -> iconFont ] ) ) { $ font = Font :: load ( $ fonts [ $ this -> iconFont ] [ 'path' ] ) ; $ font -> parse ( ) ; if ( $ font !== null ) { return $ font -> getUnicodeCharMap ( ) ; } } } return null ; }

Load a font and get all unicode characters available in that font.

@return array|null

Load a font and get all unicode characters available in that font .


public function getFontCss()
    {
        $sharedAsset = new sharedAsset();
        $scss = "";

        foreach ($this->getFonts() as $safeName => $pathInfo) {
            $fontFile = $pathInfo['path'];
            $font = Font::load($fontFile);
            $font->parse();

            if (!empty($font)) {
                $iconFontName = $safeName;

                if (!empty($iconFontName)) {
                    $scss .= "
@font-face {
    font-family: 'dq-iconpicker-".$iconFontName."';
    src: url('../fonts/".$pathInfo['basename']."');
    font-weight: 100;
    font-style: normal;
}\n\n";

                    $scss .= '
[class*="dq-icon-'.$iconFontName.'"] {
  /* use !important to prevent issues with browser extensions that change fonts */
  font-family: dq-iconpicker-'.$iconFontName.' !important;
  speak: none;
  font-style: normal;
  font-weight: normal;
  font-variant: normal;
  text-transform: none;
  line-height: 1;
  display: inline-block;
  vertical-align: baseline;

  /* Better Font Rendering =========== */
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;

}'."\n\n";
                }
            }
        }

        file_put_contents(Craft::getAlias($sharedAsset->sourcePath . '/css/fonts.css'), $scss);

        // Register the assetbundle that loads the generated css
        Craft::$app->view->registerAssetBundle(sharedAsset::className());
    }

Generate a css file that creates font families for each font file in the font directory


public static function hashAndEncrypt(string $password, Key $aesKey): string
    {
        /** @var string $hash */
        $hash = \password_hash(
            Base64::encode(
                \hash('sha384', $password, true)
            ),
            PASSWORD_DEFAULT
        );
        if (!\is_string($hash)) {
            throw new \Exception("Unknown hashing error.");
        }
        return Crypto::encrypt($hash, $aesKey);
    }

public
static
function
hashAndEncrypt
(
string
$
password
,
Key
$
aesKey
)
:
string
{
/** @var string $hash */
$
hash
=
\
password_hash
(
Base64
::
encode
(
\
hash
(
'sha384'
,
$
password
,
true
)
)
,
PASSWORD_DEFAULT
)
;
if
(
!
\
is_string
(
$
hash
)
)
{
throw
new
\
Exception
(
"Unknown hashing error."
)
;
}
return
Crypto
::
encrypt
(
$
hash
,
$
aesKey
)
;
}

1. Hash password using bcrypt-base64-SHA256
2. Encrypt-then-MAC the hash

@param string $password
@param Key $aesKey
@return string
@throws \Exception
@throws \InvalidArgumentException

1 . Hash password using bcrypt - base64 - SHA256 2 . Encrypt - then - MAC the hash


public static function upgradeFromVersion1(
        string $password,
        string $ciphertext,
        string $oldKey,
        Key $newKey
    ): string {
        if (!self::decryptAndVerifyLegacy($password, $ciphertext, $oldKey)) {
            throw new \Exception(
                'The correct password is necessary for legacy migration.'
            );
        }
        $plaintext = Crypto::legacyDecrypt($ciphertext, $oldKey);
        return self::hashAndEncrypt($plaintext, $newKey);
    }

For migrating from an older version of the library

@param string $password
@param string $ciphertext
@param string $oldKey
@param Key $newKey
@return string
@throws \Exception


protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->init($input, $output);

        $config = $this->initConfiguration($input->getOption('config_file'));

        $rules = $config->getRules();

        foreach ($rules as $name => $rule) {
            $info = Init::getInitInformationByClass(get_class($rule));
            $output->writeln('  ' . $name . ':');
            $output->writeln('    class: ' . get_class($rule));
            $output->writeln('    description: ' . str_replace("\n", "\n                 ", $info['documentation']));

            if (count($info['parameters']) > 0) {
                $output->writeln('    parameter:');

                foreach ($info['parameters'] as $parameter) {
                    $output->writeln('      ' . $parameter['name'] . ': ' . $parameter['description'] . ' (default: ' . $parameter['default'] . ')');
                }
            }

            $output->writeln('');
        }
    }

protected
function
execute
(
InputInterface
$
input
,
OutputInterface
$
output
)
{
$
this
->
init
(
$
input
,
$
output
)
;
$
config
=
$
this
->
initConfiguration
(
$
input
->
getOption
(
'config_file'
)
)
;
$
rules
=
$
config
->
getRules
(
)
;
foreach
(
$
rules
as
$
name
=>
$
rule
)
{
$
info
=
Init
::
getInitInformationByClass
(
get_class
(
$
rule
)
)
;
$
output
->
writeln
(
'  '
.
$
name
.
':'
)
;
$
output
->
writeln
(
'    class: '
.
get_class
(
$
rule
)
)
;
$
output
->
writeln
(
'    description: '
.
str_replace
(
"\n"
,
"\n                 "
,
$
info
[
'documentation'
]
)
)
;
if
(
count
(
$
info
[
'parameters'
]
)
>
0
)
{
$
output
->
writeln
(
'    parameter:'
)
;
foreach
(
$
info
[
'parameters'
]
as
$
parameter
)
{
$
output
->
writeln
(
'      '
.
$
parameter
[
'name'
]
.
': '
.
$
parameter
[
'description'
]
.
' (default: '
.
$
parameter
[
'default'
]
.
')'
)
;
}
}
$
output
->
writeln
(
''
)
;
}
}

Runs the analysis of the given website with all given parameters.

@param InputInterface  $input
@param OutputInterface $output

Runs the analysis of the given website with all given parameters .


protected function writeSmokeCredentials($url = null)
    {
        if (defined('SMOKE_CREDENTIALS')) {
            $this->output->writeln("\n " . SMOKE_CREDENTIALS . "\n");
        } else {
            $this->output->writeln("\n Smoke " . SMOKE_VERSION . " by Nils Langner\n");
        }

        if ($url) {
            $this->output->writeln(' <info>Scanning ' . $url . "</info>\n");
        }
    }

protected
function
writeSmokeCredentials
(
$
url
=
)
{
if
(
defined
(
'SMOKE_CREDENTIALS'
)
)
{
$
this
->
output
->
writeln
(
"\n "
.
SMOKE_CREDENTIALS
.
"\n"
)
;
}
else
{
$
this
->
output
->
writeln
(
"\n Smoke "
.
SMOKE_VERSION
.
" by Nils Langner\n"
)
;
}
if
(
$
url
)
{
$
this
->
output
->
writeln
(
' <info>Scanning '
.
$
url
.
"</info>\n"
)
;
}
}

This function creates the credentials header for the command line.

@param null $url

This function creates the credentials header for the command line .


protected function getConfigArray($configFile, $mandatory = false)
    {
        $configArray = array();

        if ($configFile) {
            if (strpos($configFile, 'http://') === 0 || strpos($configFile, 'https://') === 0) {
                $curlClient = new Client();
                $fileContent = (string)$curlClient->get($configFile)->getBody();
            } else {
                if (file_exists($configFile)) {
                    $fileContent = file_get_contents($configFile);
                } else {
                    throw new \RuntimeException("Config file was not found ('" . $configFile . "').");
                }
            }
            $configArray = EnvAwareYaml::parse($fileContent);
        } else {
            if ($mandatory) {
                throw new \RuntimeException('Config file was not defined.');
            }
        }

        return $configArray;
    }

protected
function
getConfigArray
(
$
configFile
,
$
mandatory
=
false
)
{
$
configArray
=
array
(
)
;
if
(
$
configFile
)
{
if
(
strpos
(
$
configFile
,
'http://'
)
===
0
||
strpos
(
$
configFile
,
'https://'
)
===
0
)
{
$
curlClient
=
new
Client
(
)
;
$
fileContent
=
(
string
)
$
curlClient
->
get
(
$
configFile
)
->
getBody
(
)
;
}
else
{
if
(
file_exists
(
$
configFile
)
)
{
$
fileContent
=
file_get_contents
(
$
configFile
)
;
}
else
{
throw
new
\
RuntimeException
(
"Config file was not found ('"
.
$
configFile
.
"')."
)
;
}
}
$
configArray
=
EnvAwareYaml
::
parse
(
$
fileContent
)
;
}
else
{
if
(
$
mandatory
)
{
throw
new
\
RuntimeException
(
'Config file was not defined.'
)
;
}
}
return
$
configArray
;
}

Returns an array representing the configuration.

@param $configFile

@return array

Returns an array representing the configuration .


public function isFiltered(UriInterface $currentUri, UriInterface $startUri)
    {
        /* @var $currentUri Uri */
        /* @var $startUri Uri */

        $startDomainElements = explode('.', $startUri->getHost());
        $currentDomainElements = explode('.', $currentUri->getHost());

        $startDomainLength = count($startDomainElements);
        $currentDomainLength = count($currentDomainElements);

        if ($currentDomainLength < $startDomainLength) {
            return true;
        }

        return $currentUri->getHost($startDomainLength) !== $startUri->getHost($startDomainLength);
    }

public
function
isFiltered
(
UriInterface
$
currentUri
,
UriInterface
$
startUri
)
{
/* @var $currentUri Uri */
/* @var $startUri Uri */
$
startDomainElements
=
explode
(
'.'
,
$
startUri
->
getHost
(
)
)
;
$
currentDomainElements
=
explode
(
'.'
,
$
currentUri
->
getHost
(
)
)
;
$
startDomainLength
=
count
(
$
startDomainElements
)
;
$
currentDomainLength
=
count
(
$
currentDomainElements
)
;
if
(
$
currentDomainLength
<
$
startDomainLength
)
{
return
true
;
}
return
$
currentUri
->
getHost
(
$
startDomainLength
)
!==
$
startUri
->
getHost
(
$
startDomainLength
)
;
}

Filter foreign domains before request is fired

@param UriInterface $currentUri
@param UriInterface $startUri
@return bool


private function registerCommands()
    {
        $this->add(new ScanCommand());
        $this->add(new ExplainCommand());
        $this->add(new WarmUpCommand());
        $this->add(new CustomCommand());
    }

private function registerCommands ( ) { $ this -> add ( new ScanCommand ( ) ) ; $ this -> add ( new ExplainCommand ( ) ) ; $ this -> add ( new WarmUpCommand ( ) ) ; $ this -> add ( new CustomCommand ( ) ) ; }


public function findAllTemplates()
    {
        if (null !== $this->templates) {
            return $this->templates;
        }
        //All themes
        $this->themes = $this->themeManager->getThemes();

        $templates = array();

        foreach ($this->kernel->getBundles() as $bundle) {
            $templates = array_merge($templates, $this->findTemplatesInBundle($bundle));
        }

        $templates = array_merge($templates, $this->findTemplatesInFolder($this->rootDir.'/views'));

        return $this->templates = $templates;
    }

public
function
findAllTemplates
(
)
{
if
(
!==
$
this
->
templates
)
{
return
$
this
->
templates
;
}
//All themes
$
this
->
themes
=
$
this
->
themeManager
->
getThemes
(
)
;
$
templates
=
array
(
)
;
foreach
(
$
this
->
kernel
->
getBundles
(
)
as
$
bundle
)
{
$
templates
=
array_merge
(
$
templates
,
$
this
->
findTemplatesInBundle
(
$
bundle
)
)
;
}
$
templates
=
array_merge
(
$
templates
,
$
this
->
findTemplatesInFolder
(
$
this
->
rootDir
.
'/views'
)
)
;
return
$
this
->
templates
=
$
templates
;
}

Find all the templates in the bundle and in the kernel Resources folder.

@return TemplateReferenceInterface[]

Find all the templates in the bundle and in the kernel Resources folder .


private function findTemplatesInBundle(BundleInterface $bundle)
    {
        $name = $bundle->getName();
        $templates = array_merge(
            $this->findTemplatesInFolder($bundle->getPath().'/Resources/views'),
            $this->findTemplatesInFolder($this->rootDir.'/'.$name.'/views')
        );
        //追踪主题下的模板
        foreach ($this->themes as $theme) {
            $templates = array_merge($templates,
                $this->findTemplatesInFolder($this->themeDir.'/'.$name.'/views')
            );
        }
        $templates = array_unique($templates);

        foreach ($templates as $i => $template) {
            $templates[$i] = $template->set('bundle', $name);
        }

        return $templates;
    }

private function findTemplatesInBundle ( BundleInterface $ bundle ) { $ name = $ bundle -> getName ( ) ; $ templates = array_merge ( $ this -> findTemplatesInFolder ( $ bundle -> getPath ( ) . '/Resources/views' ) , $ this -> findTemplatesInFolder ( $ this -> rootDir . '/' . $ name . '/views' ) ) ; //追踪主题下的模板 foreach ( $ this -> themes as $ theme ) { $ templates = array_merge ( $ templates , $ this -> findTemplatesInFolder ( $ this -> themeDir . '/' . $ name . '/views' ) ) ; } $ templates = array_unique ( $ templates ) ; foreach ( $ templates as $ i => $ template ) { $ templates [ $ i ] = $ template -> set ( 'bundle' , $ name ) ; } return $ templates ; }

Find templates in the given bundle.

@param BundleInterface $bundle The bundle where to look for templates

@return TemplateReferenceInterface[]


protected function executeCommand($command, OutputInterface $output = null, array $options = [])
    {
        if (is_null($output)) {
            $output = new NullOutput();
        }

        $options = array_merge($options, [
            'command' => $command,
        ]);

        $this
            ->getApplication()
            ->run(new ArrayInput($options), $output);

        return $this;
    }

protected function executeCommand ( $ command , OutputInterface $ output = null , array $ options = [ ] ) { if ( is_null ( $ output ) ) { $ output = new NullOutput ( ) ; } $ options = array_merge ( $ options , [ 'command' => $ command , ] ) ; $ this -> getApplication ( ) -> run ( new ArrayInput ( $ options ) , $ output ) ; return $ this ; }

Execute a command.

@param string          $command
@param OutputInterface $output
@param array           $options Command options

@return $this Self object


public function between($start, $end)
    {
        if ($start == '' && $end == '') {
            return $this;
        }

        if ($start != '' && strpos($this->string, $start) === false) {
            return new static();
        }

        if ($end != '' && strpos($this->string, $end) === false) {
            return new static();
        }

        if ($start == '') {
            return new static(substr($this->string, 0, strpos($this->string, $end)));
        }

        if ($end == '') {
            return new static(substr($this->string, strpos($this->string, $start) + strlen($start)));
        }

        $stringWithoutStart = explode($start, $this->string)[1];

        $middle = explode($end, $stringWithoutStart)[0];

        return new static($middle);
    }

public function between ( $ start , $ end ) { if ( $ start == '' && $ end == '' ) { return $ this ; } if ( $ start != '' && strpos ( $ this -> string , $ start ) === false ) { return new static ( ) ; } if ( $ end != '' && strpos ( $ this -> string , $ end ) === false ) { return new static ( ) ; } if ( $ start == '' ) { return new static ( substr ( $ this -> string , 0 , strpos ( $ this -> string , $ end ) ) ) ; } if ( $ end == '' ) { return new static ( substr ( $ this -> string , strpos ( $ this -> string , $ start ) + strlen ( $ start ) ) ) ; } $ stringWithoutStart = explode ( $ start , $ this -> string ) [ 1 ] ; $ middle = explode ( $ end , $ stringWithoutStart ) [ 0 ] ; return new static ( $ middle ) ; }

Get the string between the given start and end.

@param $start
@param $end

@return \Spatie\String\Str

Get the string between the given start and end .


private function sanitizeForTease($string)
    {
        $string = trim($string);

        //remove html
        $string = strip_tags($string);

        //replace multiple spaces
        $string = preg_replace("/\s+/", ' ', $string);

        return $string;
    }

private
function
sanitizeForTease
(
$
string
)
{
$
string
=
trim
(
$
string
)
;
//remove html
$
string
=
strip_tags
(
$
string
)
;
//replace multiple spaces
$
string
=
preg_replace
(
"/\s+/"
,
' '
,
$
string
)
;
return
$
string
;
}

Sanitize the string for teasing.

@param $string

@return string


public function replaceFirst($search, $replace)
    {
        if ($search == '') {
            return $this;
        }

        $position = strpos($this->string, $search);

        if ($position === false) {
            return $this;
        }

        $resultString = substr_replace($this->string, $replace, $position, strlen($search));

        return new static($resultString);
    }

public function replaceFirst ( $ search , $ replace ) { if ( $ search == '' ) { return $ this ; } $ position = strpos ( $ this -> string , $ search ) ; if ( $ position === false ) { return $ this ; } $ resultString = substr_replace ( $ this -> string , $ replace , $ position , strlen ( $ search ) ) ; return new static ( $ resultString ) ; }

Replace the first occurrence of a string.

@param $search
@param $replace

@return \Spatie\String\Str

Replace the first occurrence of a string .


public function replaceLast($search, $replace)
    {
        if ($search == '') {
            return $this;
        }

        $position = strrpos($this->string, $search);

        if ($position === false) {
            return $this;
        }

        $resultString = substr_replace($this->string, $replace, $position, strlen($search));

        return new static($resultString);
    }

public function replaceLast ( $ search , $ replace ) { if ( $ search == '' ) { return $ this ; } $ position = strrpos ( $ this -> string , $ search ) ; if ( $ position === false ) { return $ this ; } $ resultString = substr_replace ( $ this -> string , $ replace , $ position , strlen ( $ search ) ) ; return new static ( $ resultString ) ; }

Replace the last occurrence of a string.

@param $search
@param $replace

@return \Spatie\String\Str

Replace the last occurrence of a string .


public function possessive()
    {
        if ($this->string == '') {
            return new static();
        }

        $noApostropheEdgeCases = ['it'];

        if (in_array($this->string, $noApostropheEdgeCases)) {
            return new static($this->string.'s');
        }

        return new static($this->string.'\''.($this->string[strlen($this->string) - 1] != 's' ? 's' : ''));
    }

public function possessive ( ) { if ( $ this -> string == '' ) { return new static ( ) ; } $ noApostropheEdgeCases = [ 'it' ] ; if ( in_array ( $ this -> string , $ noApostropheEdgeCases ) ) { return new static ( $ this -> string . 's' ) ; } return new static ( $ this -> string . '\'' . ( $ this -> string [ strlen ( $ this -> string ) - 1 ] != 's' ? 's' : '' ) ) ; }

Get the possessive version of a string.

@return \Spatie\String\Str

Get the possessive version of a string .


public function segment($delimiter, $index)
    {
        $segments = explode($delimiter, $this->string);

        if ($index < 0) {
            $segments = array_reverse($segments);
            $index = abs($index) - 1;
        }

        $segment = isset($segments[$index]) ? $segments[$index] : '';

        return new static($segment);
    }

public function segment ( $ delimiter , $ index ) { $ segments = explode ( $ delimiter , $ this -> string ) ; if ( $ index < 0 ) { $ segments = array_reverse ( $ segments ) ; $ index = abs ( $ index ) - 1 ; } $ segment = isset ( $ segments [ $ index ] ) ? $ segments [ $ index ] : '' ; return new static ( $ segment ) ; }

Get a segment from a string based on a delimiter.
Returns an empty string when the offset doesn't exist.
Use a negative index to start counting from the last element.

@param string $delimiter
@param int    $index

@return \Spatie\String\Str

Get a segment from a string based on a delimiter . Returns an empty string when the offset doesn t exist . Use a negative index to start counting from the last element .


public function contains($needle, $caseSensitive = false, $absolute = false)
    {
        return $this->find($needle, $caseSensitive, $absolute);
    }

public function contains ( $ needle , $ caseSensitive = false , $ absolute = false ) { return $ this -> find ( $ needle , $ caseSensitive , $ absolute ) ; }

Alias for find.

@param array|string $needle
@param bool         $caseSensitive
@param bool         $absolute

@return bool


protected function encrypt()
    {
        $this->hash = '';
        $hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10";
        $hashVarsSeq = explode('|', $hashSequence);
        $hash_string = '';

        foreach($hashVarsSeq as $hash_var) {
            $hash_string .= isset($this->parameters[$hash_var]) ? $this->parameters[$hash_var] : '';
            $hash_string .= '|';
        }

        $hash_string .= $this->salt;
        $this->hash = strtolower(hash('sha512', $hash_string));
    }


protected function decrypt($response)
    {

        $hashSequence = "status||||||udf5|udf4|udf3|udf2|udf1|email|firstname|productinfo|amount|txnid|key";
        $hashVarsSeq = explode('|', $hashSequence);
        $hash_string = $this->salt."|";

        foreach($hashVarsSeq as $hash_var) {
            $hash_string .= isset($response[$hash_var]) ? $response[$hash_var] : '';
            $hash_string .= '|';
        }

        $hash_string = trim($hash_string,'|');

        return strtolower(hash('sha512', $hash_string));
    }

PayUMoney Decrypt Function

@param $plainText
@param $key
@return string


protected function encrypt($plainText,$key)
    {
        $secretKey = $this->hextobin(md5($key));
        $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
        $openMode = @mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
        $blockSize = @mcrypt_get_block_size(MCRYPT_RIJNDAEL_128, 'cbc');
        $plainPad = $this->pkcs5_pad($plainText, $blockSize);
        if (@mcrypt_generic_init($openMode, $secretKey, $initVector) != -1)
        {
            $encryptedText = @mcrypt_generic($openMode, $plainPad);
            @mcrypt_generic_deinit($openMode);

        }
        return bin2hex($encryptedText);
    }

protected function encrypt ( $ plainText , $ key ) { $ secretKey = $ this -> hextobin ( md5 ( $ key ) ) ; $ initVector = pack ( "C*" , 0x00 , 0x01 , 0x02 , 0x03 , 0x04 , 0x05 , 0x06 , 0x07 , 0x08 , 0x09 , 0x0a , 0x0b , 0x0c , 0x0d , 0x0e , 0x0f ) ; $ openMode = @ mcrypt_module_open ( MCRYPT_RIJNDAEL_128 , '' , 'cbc' , '' ) ; $ blockSize = @ mcrypt_get_block_size ( MCRYPT_RIJNDAEL_128 , 'cbc' ) ; $ plainPad = $ this -> pkcs5_pad ( $ plainText , $ blockSize ) ; if ( @ mcrypt_generic_init ( $ openMode , $ secretKey , $ initVector ) != - 1 ) { $ encryptedText = @ mcrypt_generic ( $ openMode , $ plainPad ) ; @ mcrypt_generic_deinit ( $ openMode ) ; } return bin2hex ( $ encryptedText ) ; }

CCAvenue Encrypt Function

@param $plainText
@param $key
@return string


protected function decrypt($encryptedText,$key)
    {
        $secretKey = $this->hextobin(md5($key));
        $initVector = pack("C*", 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f);
        $encryptedText=$this->hextobin($encryptedText);
        $openMode = @mcrypt_module_open(MCRYPT_RIJNDAEL_128, '','cbc', '');
        @mcrypt_generic_init($openMode, $secretKey, $initVector);
        $decryptedText = @mdecrypt_generic($openMode, $encryptedText);
        $decryptedText = rtrim($decryptedText, "\0");
        @mcrypt_generic_deinit($openMode);
        return $decryptedText;

    }

protected function decrypt ( $ encryptedText , $ key ) { $ secretKey = $ this -> hextobin ( md5 ( $ key ) ) ; $ initVector = pack ( "C*" , 0x00 , 0x01 , 0x02 , 0x03 , 0x04 , 0x05 , 0x06 , 0x07 , 0x08 , 0x09 , 0x0a , 0x0b , 0x0c , 0x0d , 0x0e , 0x0f ) ; $ encryptedText = $ this -> hextobin ( $ encryptedText ) ; $ openMode = @ mcrypt_module_open ( MCRYPT_RIJNDAEL_128 , '' , 'cbc' , '' ) ; @ mcrypt_generic_init ( $ openMode , $ secretKey , $ initVector ) ; $ decryptedText = @ mdecrypt_generic ( $ openMode , $ encryptedText ) ; $ decryptedText = rtrim ( $ decryptedText , "\0" ) ; @ mcrypt_generic_deinit ( $ openMode ) ; return $ decryptedText ; }

CCAvenue Decrypt Function

@param $encryptedText
@param $key
@return string


protected function encrypt()
    {

        $hash_string = $this->vanityUrl.$this->parameters['orderAmount'].$this->parameters['merchantTxnId'].$this->parameters['currency'];

        $this->hash = hash_hmac('sha1', $hash_string, $this->secretKey);

    }

protected function encrypt ( ) { $ hash_string = $ this -> vanityUrl . $ this -> parameters [ 'orderAmount' ] . $ this -> parameters [ 'merchantTxnId' ] . $ this -> parameters [ 'currency' ] ; $ this -> hash = hash_hmac ( 'sha1' , $ hash_string , $ this -> secretKey ) ; }


protected function decrypt($response)
    {
        $hash_string = '';
        $hash_string .= $response['TxId'];
        $hash_string .= $response['TxStatus'];
        $hash_string .= $response['amount'];
        $hash_string .= $response['pgTxnNo'];
        $hash_string .= $response['issuerRefNo'];
        $hash_string .= $response['authIdCode'];
        $hash_string .= $response['firstName'];
        $hash_string .= $response['lastName'];
        $hash_string .= $response['pgRespCode'];
        $hash_string .= $response['addressZip'];

        return hash_hmac('sha1', $hash_string, $this->secretKey);

    }

protected function decrypt ( $ response ) { $ hash_string = '' ; $ hash_string .= $ response [ 'TxId' ] ; $ hash_string .= $ response [ 'TxStatus' ] ; $ hash_string .= $ response [ 'amount' ] ; $ hash_string .= $ response [ 'pgTxnNo' ] ; $ hash_string .= $ response [ 'issuerRefNo' ] ; $ hash_string .= $ response [ 'authIdCode' ] ; $ hash_string .= $ response [ 'firstName' ] ; $ hash_string .= $ response [ 'lastName' ] ; $ hash_string .= $ response [ 'pgRespCode' ] ; $ hash_string .= $ response [ 'addressZip' ] ; return hash_hmac ( 'sha1' , $ hash_string , $ this -> secretKey ) ; }

Citrus Decrypt Function

@param $response
@return string


protected function encrypt()
    {
        $this->hash = '';
        $hash_string = $this->secretKey."|".urlencode($this->parameters['account_id'])."|".urlencode($this->parameters['amount'])."|".urlencode($this->parameters['reference_no'])."|".$this->parameters['return_url']."|".urlencode($this->parameters['mode']);
        $this->hash = md5($hash_string);
    }

protected function encrypt ( ) { $ this -> hash = '' ; $ hash_string = $ this -> secretKey . "|" . urlencode ( $ this -> parameters [ 'account_id' ] ) . "|" . urlencode ( $ this -> parameters [ 'amount' ] ) . "|" . urlencode ( $ this -> parameters [ 'reference_no' ] ) . "|" . $ this -> parameters [ 'return_url' ] . "|" . urlencode ( $ this -> parameters [ 'mode' ] ) ; $ this -> hash = md5 ( $ hash_string ) ; }


public function range()
    {
        $args = func_get_args();
        $arg_num = count($args);

        if ($arg_num%2 != 0) {
            throw new \InvalidArgumentException('Number of args must be even', 1);
        }

        $value = '[';

        for ($i = 0; $i < $arg_num;) {
            $value .= self::sanitize($args[$i++]) . '-' . self::sanitize($args[$i++]);
        }

        $value .= ']';

        return $this->add($value);
    }

public
function
range
(
)
{
$
args
=
func_get_args
(
)
;
$
arg_num
=
count
(
$
args
)
;
if
(
$
arg_num
%
2
!=
0
)
{
throw
new
\
InvalidArgumentException
(
'Number of args must be even'
,
1
)
;
}
$
value
=
'['
;
for
(
$
i
=
0
;
$
i
<
$
arg_num
;
)
{
$
value
.=
self
::
sanitize
(
$
args
[
$
i
++
]
)
.
'-'
.
self
::
sanitize
(
$
args
[
$
i
++
]
)
;
}
$
value
.=
']'
;
return
$
this
->
add
(
$
value
)
;
}

Add a range

Adds a range to our expression ex: range(a,z) => a-z, range(a,z,0,9) => a-z0-9

@access public
@return VerbalExpressions
@throws \InvalidArgumentException


public function addModifier($modifier)
    {
        if (strpos($this->modifiers, $modifier) === false) {
            $this->modifiers .= $modifier;
        }

        return $this;
    }

public function addModifier ( $ modifier ) { if ( strpos ( $ this -> modifiers , $ modifier ) === false ) { $ this -> modifiers .= $ modifier ; } return $ this ; }

Add a modifier

Adds a modifier

@access public
@param  string $modifier
@return VerbalExpressions


public function addRange(int $start, int $end): void
    {
        $this->pages = array_merge($this->pages, range($start, $end));
    }

public function addRange ( int $ start , int $ end ) : void { $ this -> pages = array_merge ( $ this -> pages , range ( $ start , $ end ) ) ; }


public function addRaw(string $content, PagesInterface $pages = null): void
    {
        $this->sources[] = new RawSource($content, $pages);
    }

public function addRaw ( string $ content , PagesInterface $ pages = null ) : void { $ this -> sources [ ] = new RawSource ( $ content , $ pages ) ; }


public function addFile(string $filename, PagesInterface $pages = null): void
    {
        $this->sources[] = new FileSource($filename, $pages);
    }

public function addFile ( string $ filename , PagesInterface $ pages = null ) : void { $ this -> sources [ ] = new FileSource ( $ filename , $ pages ) ; }


public function addIterator(iterable $iterator, PagesInterface $pages = null): void
    {
        foreach ($iterator as $filename) {
            $this->addFile($filename, $pages);
        }
    }

public function addIterator ( iterable $ iterator , PagesInterface $ pages = null ) : void { foreach ( $ iterator as $ filename ) { $ this -> addFile ( $ filename , $ pages ) ; } }

Add files using iterator

Note that optional pages constraint is used for every added pdf


protected static function jsonUnserializeFromProperties($properties)
    {
        if ( ! is_array($properties) && ! is_object($properties)) {
            throw UnserializationException::invalidProperty('Linked CRS', 'properties', $properties, 'array or object');
        }

        $properties = new \ArrayObject($properties);

        if ( ! $properties->offsetExists('href')) {
            throw UnserializationException::missingProperty('Linked CRS', 'properties.href', 'string');
        }

        $href = (string) $properties['href'];
        $type = isset($properties['type']) ? (string) $properties['type'] : null;

        return new self($href, $type);
    }

protected
static
function
jsonUnserializeFromProperties
(
$
properties
)
{
if
(
!
is_array
(
$
properties
)
&&
!
is_object
(
$
properties
)
)
{
throw
UnserializationException
::
invalidProperty
(
'Linked CRS'
,
'properties'
,
$
properties
,
'array or object'
)
;
}
$
properties
=
new
\
ArrayObject
(
$
properties
)
;
if
(
!
$
properties
->
offsetExists
(
'href'
)
)
{
throw
UnserializationException
::
missingProperty
(
'Linked CRS'
,
'properties.href'
,
'string'
)
;
}
$
href
=
(
string
)
$
properties
[
'href'
]
;
$
type
=
isset
(
$
properties
[
'type'
]
)
(
string
)
$
properties
[
'type'
]
:
;
return
new
self
(
$
href
,
$
type
)
;
}

Factory method for creating a Linked CRS object from properties.

@see CoordinateReferenceSystem::jsonUnserialize()
@param array|object $properties
@return Linked
@throws UnserializationException

Factory method for creating a Linked CRS object from properties .


protected function setOptionalConstructorArgs(array $args)
    {
        foreach ($args as $arg) {
            if ($arg instanceof CoordinateReferenceSystem) {
                $this->crs = $arg;
            }

            if ($arg instanceof BoundingBox) {
                $this->boundingBox = $arg;
            }
        }
    }

protected function setOptionalConstructorArgs ( array $ args ) { foreach ( $ args as $ arg ) { if ( $ arg instanceof CoordinateReferenceSystem ) { $ this -> crs = $ arg ; } if ( $ arg instanceof BoundingBox ) { $ this -> boundingBox = $ arg ; } } }

Set optional CRS and BoundingBox arguments passed to a constructor.

@todo Decide if multiple CRS or BoundingBox instances should override a
previous value or be ignored

Set optional CRS and BoundingBox arguments passed to a constructor .


public static function invalidValue($context, $value, $expectedType)
    {
        return new self(sprintf(
            '%s expected value of type %s, %s given',
            $context,
            $expectedType,
            is_object($value) ? get_class($value) : gettype($value)
        ));
    }

Creates an UnserializationException for a value with an invalid type.

@param string $context
@param mixed $value
@param string $expectedType
@return UnserializationException

Creates an UnserializationException for a value with an invalid type .


public static function invalidProperty($context, $property, $value, $expectedType)
    {
        return new self(sprintf(
            '%s expected "%s" property of type %s, %s given',
            $context,
            $property,
            $expectedType,
            is_object($value) ? get_class($value) : gettype($value)
        ));
    }

Creates an UnserializationException for a property with an invalid type.

@param string $context
@param string $property
@param mixed $value
@param string $expectedType
@return UnserializationException

Creates an UnserializationException for a property with an invalid type .


protected static function jsonUnserializeFromProperties($properties)
    {
        if ( ! is_array($properties) && ! is_object($properties)) {
            throw UnserializationException::invalidProperty('Named CRS', 'properties', $properties, 'array or object');
        }

        $properties = new \ArrayObject($properties);

        if ( ! $properties->offsetExists('name')) {
            throw UnserializationException::missingProperty('Named CRS', 'properties.name', 'string');
        }

        $name = (string) $properties['name'];

        return new self($name);
    }

protected
static
function
jsonUnserializeFromProperties
(
$
properties
)
{
if
(
!
is_array
(
$
properties
)
&&
!
is_object
(
$
properties
)
)
{
throw
UnserializationException
::
invalidProperty
(
'Named CRS'
,
'properties'
,
$
properties
,
'array or object'
)
;
}
$
properties
=
new
\
ArrayObject
(
$
properties
)
;
if
(
!
$
properties
->
offsetExists
(
'name'
)
)
{
throw
UnserializationException
::
missingProperty
(
'Named CRS'
,
'properties.name'
,
'string'
)
;
}
$
name
=
(
string
)
$
properties
[
'name'
]
;
return
new
self
(
$
name
)
;
}

Factory method for creating a Named CRS object from properties.

@see CoordinateReferenceSystem::jsonUnserialize()
@param array|object $properties
@return Named
@throws UnserializationException

Factory method for creating a Named CRS object from properties .


public function configPath($path = '')
    {
        return $this->basePath.DIRECTORY_SEPARATOR.'vendor'.DIRECTORY_SEPARATOR.'matthewbdaly'.DIRECTORY_SEPARATOR.'artisan-standalone'.DIRECTORY_SEPARATOR.'config'.($path ? DIRECTORY_SEPARATOR.$path : $path);
    }

public function configPath ( $ path = '' ) { return $ this -> basePath . DIRECTORY_SEPARATOR . 'vendor' . DIRECTORY_SEPARATOR . 'matthewbdaly' . DIRECTORY_SEPARATOR . 'artisan-standalone' . DIRECTORY_SEPARATOR . 'config' . ( $ path ? DIRECTORY_SEPARATOR . $ path : $ path ) ; }

Get the path to the application configuration files.

@param  string $path Optionally, a path to append to the config path
@return string

Get the path to the application configuration files .


public function getNamespace()
    {
        if (! is_null($this->namespace)) {
            return $this->namespace;
        }
        $path = $this->basePath;
        $composer = json_decode(file_get_contents($path.DIRECTORY_SEPARATOR.'composer.json'), true);

        foreach ((array) data_get($composer, 'autoload.psr-4') as $namespace => $path) {
            return $this->namespace = $namespace;
        }

        throw new RuntimeException('Unable to detect application namespace.');
    }

Get the application namespace.

@return string

@throws \RuntimeException


public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
        $loader->load('services.yml');

        // Configure client services
        $first = isset($config['providers']['default']) ? 'default' : null;
        foreach ($config['providers'] as $name => $arguments) {
            if (null === $first) {
                $first = $name;
            }

            $factoryClass = $container->getDefinition($arguments['factory'])->getClass();
            $factoryClass::validate($arguments['options'], $name);

            // See if any option has a service reference
            $arguments['options'] = $this->findReferences($arguments['options']);

            $def = $container->register('cache.provider.'.$name, DummyAdapter::class);
            $def->setFactory([new Reference($arguments['factory']), 'createAdapter'])
                ->addArgument($arguments['options'])
                ->setPublic(true);

            $def->addTag('cache.provider');
            foreach ($arguments['aliases'] as $alias) {
                $container->setAlias($alias, new Alias('cache.provider.'.$name, true));
            }
        }

        if (null !== $first) {
            $container->setAlias('cache', 'cache.provider.'.$first);
            $container->setAlias('php_cache', 'cache.provider.'.$first);
        }
    }

Loads the configs for Cache and puts data into the container.

@param array            $configs   Array of configs
@param ContainerBuilder $container Container Object

Loads the configs for Cache and puts data into the container .


public static function newMasterNode($entropy)
    {
        $hmac = hash_hmac('sha512', $entropy, 'ed25519 seed', true);

        return new HdNode(
            substr($hmac, 0, 32),
            substr($hmac, 32, 32)
        );
    }

public
static
function
newMasterNode
(
$
entropy
)
{
$
hmac
=
hash_hmac
(
'sha512'
,
$
entropy
,
'ed25519 seed'
,
true
)
;
return
new
HdNode
(
substr
(
$
hmac
,
0
,
32
)
,
substr
(
$
hmac
,
32
,
32
)
)
;
}

Returns a new master node that can be used to derive subnodes

@param $entropy
@return HdNode


public function getNativeBalance()
    {
        MathSafety::require64Bit();

        foreach ($this->getBalances() as $balance) {
            if ($balance->isNativeAsset()) return $balance->getBalance();
        }

        return 0;
    }

public function getNativeBalance ( ) { MathSafety :: require64Bit ( ) ; foreach ( $ this -> getBalances ( ) as $ balance ) { if ( $ balance -> isNativeAsset ( ) ) return $ balance -> getBalance ( ) ; } return 0 ; }

Returns a string representing the native balance

@return string
@throws \ErrorException


public function getNativeBalanceStroops()
    {
        MathSafety::require64Bit();

        foreach ($this->getBalances() as $balance) {
            if ($balance->isNativeAsset()) return $balance->getUnscaledBalance();
        }

        return "0";
    }

public function getNativeBalanceStroops ( ) { MathSafety :: require64Bit ( ) ; foreach ( $ this -> getBalances ( ) as $ balance ) { if ( $ balance -> isNativeAsset ( ) ) return $ balance -> getUnscaledBalance ( ) ; } return "0" ; }

Returns the balance in stroops

@return string
@throws \ErrorException


public function getCustomAssetBalanceValue(Asset $asset)
    {
        foreach ($this->getBalances() as $balance) {
            if ($balance->getAssetCode() !== $asset->getAssetCode()) continue;
            if ($balance->getAssetIssuerAccountId() != $asset->getIssuer()->getAccountIdString()) continue;

            return $balance->getBalance();
        }

        return null;
    }

public function getCustomAssetBalanceValue ( Asset $ asset ) { foreach ( $ this -> getBalances ( ) as $ balance ) { if ( $ balance -> getAssetCode ( ) !== $ asset -> getAssetCode ( ) ) continue ; if ( $ balance -> getAssetIssuerAccountId ( ) != $ asset -> getIssuer ( ) -> getAccountIdString ( ) ) continue ; return $ balance -> getBalance ( ) ; } return null ; }

Returns the numeric balance of the given asset

@param Asset $asset
@return null|string


public function getCustomAssetBalance(Asset $asset)
    {
        foreach ($this->getBalances() as $balance) {
            if ($balance->getAssetCode() !== $asset->getAssetCode()) continue;
            if ($balance->getAssetIssuerAccountId() != $asset->getIssuer()->getAccountIdString()) continue;

            return $balance;
        }

        return null;
    }

public function getCustomAssetBalance ( Asset $ asset ) { foreach ( $ this -> getBalances ( ) as $ balance ) { if ( $ balance -> getAssetCode ( ) !== $ asset -> getAssetCode ( ) ) continue ; if ( $ balance -> getAssetIssuerAccountId ( ) != $ asset -> getIssuer ( ) -> getAccountIdString ( ) ) continue ; return $ balance ; } return null ; }

Returns an AssetAmount representing the balance of this asset

@param Asset $asset
@return null|AssetAmount


public function getCustomAssetBalanceStroops(Asset $asset)
    {
        MathSafety::require64Bit();

        foreach ($this->getBalances() as $balance) {
            if ($balance->getAssetCode() !== $asset->getAssetCode()) continue;
            if ($balance->getAssetIssuerAccountId() != $asset->getIssuer()->getAccountIdString()) continue;

            return $balance->getUnscaledBalance();
        }

        return null;
    }

public function getCustomAssetBalanceStroops ( Asset $ asset ) { MathSafety :: require64Bit ( ) ; foreach ( $ this -> getBalances ( ) as $ balance ) { if ( $ balance -> getAssetCode ( ) !== $ asset -> getAssetCode ( ) ) continue ; if ( $ balance -> getAssetIssuerAccountId ( ) != $ asset -> getIssuer ( ) -> getAccountIdString ( ) ) continue ; return $ balance -> getUnscaledBalance ( ) ; } return null ; }

Returns the balance of a custom asset in stroops

@param Asset $asset
@return null|string
@throws \ErrorException


public static function getEntropyChecksumHex($entropyBytes)
    {
        $checksumLengthBits = (strlen($entropyBytes)*8) / 32;
        $hashBytes = hash('sha256', $entropyBytes, true);

        // base_convert can only handle up to 64 bits, so we have to reduce the
        // length of data that gets sent to it
        $checksumLengthBytes = ceil($checksumLengthBits / 8);
        $reducedBytesToChecksum = substr($hashBytes, 0, $checksumLengthBytes);

        $reducedChecksumHex = bin2hex($reducedBytesToChecksum);
        $reducedChecksumBits = str_pad(base_convert($reducedChecksumHex, 16, 2), $checksumLengthBytes * 8, '0', STR_PAD_LEFT);

        $checksumBitstring = substr($reducedChecksumBits, 0, $checksumLengthBits);
        $checksumHex = static::bitstringToHex($checksumBitstring);

        return $checksumHex;
    }

Returns the hex-encoded checksum for the raw bytes in the entropy

@param $entropyBytes
@return string

Returns the hex - encoded checksum for the raw bytes in the entropy


public static function bitstringToHex($bitstring)
    {
        $chunkSizeBits = 8;

        // If the string is shorter than the chunk size it can be 0-padded
        if (strlen($bitstring) < $chunkSizeBits) {
            $bitstring = str_pad($bitstring, $chunkSizeBits, '0', STR_PAD_LEFT);
        }

        if (strlen($bitstring) % $chunkSizeBits !== 0) throw new \InvalidArgumentException(sprintf('Got bitstring of length %s, but it must be divisible by %s', strlen($bitstring), $chunkSizeBits));

        $finalHex = '';
        for ($i=0; $i < strlen($bitstring); $i += $chunkSizeBits) {
            $bitstringPart = substr($bitstring, $i, $chunkSizeBits);
            $hex = base_convert($bitstringPart, 2, 16);
            // Ensure hex is always two characters
            $hex = str_pad($hex, 2, '0', STR_PAD_LEFT);

            $finalHex .= $hex;
        }

        return $finalHex;
    }

Utility method to convert a bitstring to hex.

Primarily a workaround to avoid requiring a real math library

@param $bitstring
@return string

Utility method to convert a bitstring to hex .


public function mnemonicToEntropy($mnenomic)
    {
        $bitstring = $this->parseMnemonic($mnenomic);

        // Calculate expected lengths
        $numChecksumBits = strlen($bitstring) / 33;
        $numEntropyBits = strlen($bitstring) - $numChecksumBits;

        // Get checksum bits from the end of the string
        $checksumBits = substr($bitstring, -1 * $numChecksumBits);
        $checksumHex = static::bitstringToHex($checksumBits);

        // Remaining bits are the entropy
        $entropyBits = substr($bitstring, 0, $numEntropyBits);
        $entropyHex = static::bitstringToHex($entropyBits);

        $entropyBytes = hex2bin($entropyHex);

        if ($checksumHex !== static::getEntropyChecksumHex($entropyBytes)) {
            throw new \InvalidArgumentException('Invalid checksum');
        }

        return $entropyBytes;
    }

Converts a mnemonic to raw bytes

NOTE: this is NOT the raw bytes used for a Stellar key! See mnemonicToSeedBytes

@param $mnenomic
@return bool|string


public function authorizeTrustline(Asset $asset, $trustorId, $sourceAccountId = null)
    {
        if ($trustorId instanceof Keypair) {
            $trustorId = $trustorId->getPublicKey();
        }

        $op = new AllowTrustOp($asset, new AccountId($trustorId), $sourceAccountId);
        $op->setIsAuthorized(true);

        return $this->addOperation($op);
    }

public function authorizeTrustline ( Asset $ asset , $ trustorId , $ sourceAccountId = null ) { if ( $ trustorId instanceof Keypair ) { $ trustorId = $ trustorId -> getPublicKey ( ) ; } $ op = new AllowTrustOp ( $ asset , new AccountId ( $ trustorId ) , $ sourceAccountId ) ; $ op -> setIsAuthorized ( true ) ; return $ this -> addOperation ( $ op ) ; }

This is called by asset issuers to authorize a trustline established by
a client account

@param Asset $asset
@param       $trustorId
@param null  $sourceAccountId
@return TransactionBuilder


public function revokeTrustline(Asset $asset, $trustorId, $sourceAccountId = null)
    {
        if ($trustorId instanceof Keypair) {
            $trustorId = $trustorId->getPublicKey();
        }

        $op = new AllowTrustOp($asset, new AccountId($trustorId), $sourceAccountId);
        $op->setIsAuthorized(false);

        return $this->addOperation($op);
    }

public function revokeTrustline ( Asset $ asset , $ trustorId , $ sourceAccountId = null ) { if ( $ trustorId instanceof Keypair ) { $ trustorId = $ trustorId -> getPublicKey ( ) ; } $ op = new AllowTrustOp ( $ asset , new AccountId ( $ trustorId ) , $ sourceAccountId ) ; $ op -> setIsAuthorized ( false ) ; return $ this -> addOperation ( $ op ) ; }

This is called by asset issuers to revoke a trustline established by
a client account

@param Asset $asset
@param       $trustorId
@param null  $sourceAccountId
@return TransactionBuilder


public function toXdr()
    {
        $bytes = '';

        // Source Account
        $bytes .= XdrEncoder::optional($this->sourceAccount);

        // Type
        $bytes .= XdrEncoder::unsignedInteger($this->type);

        return $bytes;
    }

public
function
toXdr
(
)
{
$
bytes
=
''
;
// Source Account
$
bytes
.=
XdrEncoder
::
optional
(
$
this
->
sourceAccount
)
;
// Type
$
bytes
.=
XdrEncoder
::
unsignedInteger
(
$
this
->
type
)
;
return
$
bytes
;
}

Child classes MUST call this method to get the header for the operation
and then append their body

@return string


public static function opaqueVariable($value)
    {
        $maxLength = pow(2, 32) - 1;
        if (strlen($value) > $maxLength) throw new \InvalidArgumentException(sprintf('Value of length %s is greater than the maximum allowed length of %s', strlen($value), $maxLength));

        $bytes = '';

        $bytes .= self::unsignedInteger(strlen($value));
        $bytes .= self::applyPadding($value);

        return $bytes;
    }

Variable-length opaque data

Maximum length is 2^32 - 1

@param $value
@return string


public static function optional(XdrEncodableInterface $value = null)
    {
        $bytes = '';

        if ($value !== null) {
            $bytes .= self::boolean(true);
            $bytes .= $value->toXdr();
        }
        else {
            $bytes .= self::boolean(false);
        }

        return $bytes;
    }

public static function optional ( XdrEncodableInterface $ value = null ) { $ bytes = '' ; if ( $ value !== null ) { $ bytes .= self :: boolean ( true ) ; $ bytes .= $ value -> toXdr ( ) ; } else { $ bytes .= self :: boolean ( false ) ; } return $ bytes ; }

Encodes an optional data value as XDR.

Any non-null $value will be encoded and returned

@param XdrEncodableInterface $value
@return string


public function getUniqueBucketHashes()
    {
        $hashes = [];

        if ($this->curr != self::HASH_EMPTY) $hashes[] = $this->curr;
        if ($this->snap != self::HASH_EMPTY) $hashes[] = $this->snap;

        return array_values(array_unique($hashes));
    }

public function getUniqueBucketHashes ( ) { $ hashes = [ ] ; if ( $ this -> curr != self :: HASH_EMPTY ) $ hashes [ ] = $ this -> curr ; if ( $ this -> snap != self :: HASH_EMPTY ) $ hashes [ ] = $ this -> snap ; return array_values ( array_unique ( $ hashes ) ) ; }

Returns an array of unique sha256 hashes in this bucket level

@return array


public function accountExists($accountId)
    {
        // Handle basic errors such as malformed account IDs
        try {
            $account = $this->getAccount($accountId);
        } catch (\InvalidArgumentException $e) {
            return false;
        }

        // Account ID may be valid but hasn't been funded yet
        if (!$account) return false;

        return $account->getNativeBalanceStroops() != '0';
    }

Returns true if the account exists on this server and has been funded

@param $accountId
@return bool
@throws HorizonException
@throws \ErrorException


public function setAuthRequired($isRequired)
    {
        if ($isRequired) {
            $this->setFlags   = $this->setFlags | static::FLAG_AUTH_REQUIRED;
            $this->clearFlags = $this->clearFlags & ~(static::FLAG_AUTH_REQUIRED);
        }
        else {
            $this->setFlags   = $this->setFlags & ~(static::FLAG_AUTH_REQUIRED);
            $this->clearFlags = $this->clearFlags | static::FLAG_AUTH_REQUIRED;
        }

        return $this;
    }

public function setAuthRequired ( $ isRequired ) { if ( $ isRequired ) { $ this -> setFlags = $ this -> setFlags | static :: FLAG_AUTH_REQUIRED ; $ this -> clearFlags = $ this -> clearFlags & ~ ( static :: FLAG_AUTH_REQUIRED ) ; } else { $ this -> setFlags = $ this -> setFlags & ~ ( static :: FLAG_AUTH_REQUIRED ) ; $ this -> clearFlags = $ this -> clearFlags | static :: FLAG_AUTH_REQUIRED ; } return $ this ; }

If set, TrustLines are created with authorized set to false requiring the issuer to set it for each TrustLine

@param $isRequired
@return SetOptionsOp

If set TrustLines are created with authorized set to false requiring the issuer to set it for each TrustLine


public function setAuthRevocable($isRevocable)
    {
        if ($isRevocable) {
            $this->setFlags   = $this->setFlags | static::FLAG_AUTH_REVOCABLE;
            $this->clearFlags = $this->clearFlags & ~(static::FLAG_AUTH_REVOCABLE);
        }
        else {
            $this->setFlags   = $this->setFlags & ~(static::FLAG_AUTH_REVOCABLE);
            $this->clearFlags = $this->clearFlags | static::FLAG_AUTH_REVOCABLE;
        }

        return $this;
    }

public function setAuthRevocable ( $ isRevocable ) { if ( $ isRevocable ) { $ this -> setFlags = $ this -> setFlags | static :: FLAG_AUTH_REVOCABLE ; $ this -> clearFlags = $ this -> clearFlags & ~ ( static :: FLAG_AUTH_REVOCABLE ) ; } else { $ this -> setFlags = $ this -> setFlags & ~ ( static :: FLAG_AUTH_REVOCABLE ) ; $ this -> clearFlags = $ this -> clearFlags | static :: FLAG_AUTH_REVOCABLE ; } return $ this ; }

If set, the authorized flag in TrustLines can be cleared. Otherwise, authorization cannot be revoked

@param $isRevocable
@return SetOptionsOp

If set the authorized flag in TrustLines can be cleared . Otherwise authorization cannot be revoked


public function getPublicKeyChecksum()
    {
        $checksumBytes = substr($this->getPublicKeyBytes(), -2);

        $unpacked = unpack('v', $checksumBytes);

        return array_shift($unpacked);
    }

public function getPublicKeyChecksum ( ) { $ checksumBytes = substr ( $ this -> getPublicKeyBytes ( ) , - 2 ) ; $ unpacked = unpack ( 'v' , $ checksumBytes ) ; return array_shift ( $ unpacked ) ; }

Returns the raw bytes of the checksum for the public key

@return string


public static function opaqueFixedString($xdr, $length)
    {
        $bytes = static::opaqueFixed($xdr, $length);

        // remove trailing nulls
        return strval(rtrim($bytes, "\0x00"));
    }

public
static
function
opaqueFixedString
(
$
xdr
,
$
length
)
{
$
bytes
=
static
::
opaqueFixed
(
$
xdr
,
$
length
)
;
// remove trailing nulls
return
strval
(
rtrim
(
$
bytes
,
"\0x00"
)
)
;
}

Reads a fixed opaque value and returns it as a string

@param $xdr
@param $length
@return string


protected function parseRawData($rawData)
    {
        if (!$rawData) return;

        if (!empty($rawData['result_xdr'])) {
            $xdr = new XdrBuffer(base64_decode($rawData['result_xdr']));
            $this->result = TransactionResult::fromXdr($xdr);
        }
    }

protected function parseRawData ( $ rawData ) { if ( ! $ rawData ) return ; if ( ! empty ( $ rawData [ 'result_xdr' ] ) ) { $ xdr = new XdrBuffer ( base64_decode ( $ rawData [ 'result_xdr' ] ) ) ; $ this -> result = TransactionResult :: fromXdr ( $ xdr ) ; } }

Parses the raw response data and populates this object

@param $rawData
@throws \ErrorException


public function sign($keypairsOrsecretKeyStrings, Server $server = null)
    {
        if (!is_array($keypairsOrsecretKeyStrings)) $keypairsOrsecretKeyStrings = [$keypairsOrsecretKeyStrings];

        $transactionHash = null;
        if ($server) {
            $transactionHash = $server->getApiClient()->hash($this->transactionBuilder);
        }
        else {
            $transactionHash = $this->transactionBuilder->hash();
        }

        foreach ($keypairsOrsecretKeyStrings as $keypairOrSecretKeyString) {
            if (is_string($keypairOrSecretKeyString)) {
                $keypairOrSecretKeyString = Keypair::newFromSeed($keypairOrSecretKeyString);
            }

            $decorated = $keypairOrSecretKeyString->signDecorated($transactionHash);
            $this->signatures->append($decorated);
        }

        return $this;
    }

public function sign ( $ keypairsOrsecretKeyStrings , Server $ server = null ) { if ( ! is_array ( $ keypairsOrsecretKeyStrings ) ) $ keypairsOrsecretKeyStrings = [ $ keypairsOrsecretKeyStrings ] ; $ transactionHash = null ; if ( $ server ) { $ transactionHash = $ server -> getApiClient ( ) -> hash ( $ this -> transactionBuilder ) ; } else { $ transactionHash = $ this -> transactionBuilder -> hash ( ) ; } foreach ( $ keypairsOrsecretKeyStrings as $ keypairOrSecretKeyString ) { if ( is_string ( $ keypairOrSecretKeyString ) ) { $ keypairOrSecretKeyString = Keypair :: newFromSeed ( $ keypairOrSecretKeyString ) ; } $ decorated = $ keypairOrSecretKeyString -> signDecorated ( $ transactionHash ) ; $ this -> signatures -> append ( $ decorated ) ; } return $ this ; }

Adds signatures using the given keypairs or secret key strings

@param Keypair[]|string[] $keypairsOrsecretKeyStrings
@return $this


public function submitTransaction(TransactionBuilder $transactionBuilder, $signingAccountSeedString)
    {
        $transactionEnvelope = $transactionBuilder->sign($signingAccountSeedString);

        return $this->submitB64Transaction(base64_encode($transactionEnvelope->toXdr()));
    }

public function submitTransaction ( TransactionBuilder $ transactionBuilder , $ signingAccountSeedString ) { $ transactionEnvelope = $ transactionBuilder -> sign ( $ signingAccountSeedString ) ; return $ this -> submitB64Transaction ( base64_encode ( $ transactionEnvelope -> toXdr ( ) ) ) ; }

Submits the transaction contained in the TransactionBuilder to the network

@param TransactionBuilder $transactionBuilder
@param                    $signingAccountSeedString
@return PostTransactionResponse


public function fromText($patchText){
        $patches = array();
        if (!$patchText) {
            return $patches;
        }

        $lines = explode("\n", $patchText);
        while (count($lines)) {
            $line = $lines[0];
            if (!preg_match("/^@@ -(\d+),?(\d*) \+(\d+),?(\d*) @@$/", $line, $m)) {
                throw new \InvalidArgumentException("Invalid patch string: " . $line);
            }
            $patch = new PatchObject();
            $patch->setStart1($m[1]);
            if ($m[2] == '') {
                $patch->setStart1($patch->getStart1() - 1);
                $patch->setLength1(1);
            } elseif ($m[2] == '0') {
                $patch->setLength1(0);
            } else {
                $patch->setStart1($patch->getStart1() - 1);
                $patch->setLength1($m[2]);
            }
            $patch->setStart2($m[3]);
            if ($m[4] == '') {
                $patch->setStart2($patch->getStart2() - 1);
                $patch->setLength2(1);
            } elseif ($m[4] == '0') {
                $patch->setLength2(0);
            } else {
                $patch->setStart2($patch->getStart2() - 1);
                $patch->setLength2($m[4]);
            }
            $patches[] = $patch;
            array_shift($lines);

            while (count($lines)) {
                $line = $lines[0];
                if ($line) {
                    $sign = mb_substr($line, 0, 1);
                } else {
                    $sign = '';
                }
                $text = Utils::unescapeString(mb_substr($line, 1));
                switch ($sign) {
                    case '+':
                        // Insertion.
                        $patch->appendChanges(array(Diff::INSERT, $text));
                        break;
                    case '-':
                        // Deletion.
                        $patch->appendChanges(array(Diff::DELETE, $text));
                        break;
                    case ' ':
                        // Minor equality.
                        $patch->appendChanges(array(Diff::EQUAL, $text));
                        break;
                    case '@':
                        // Start of next patch.
                        break 2;
                    case '':
                        // Blank line?  Whatever.
                        break;
                    default:
                        // WTF?
                        throw new \UnexpectedValueException("Invalid patch mode: " .  $sign . PHP_EOL . $text);
                }
                array_shift($lines);
            }
        }

        return $patches;
    }

Parse a textual representation of patches and return a list of patch objects.

@param string $patchText Text representation of patches.

@throws \InvalidArgumentException If invalid input.
@throws \UnexpectedValueException If text has bad syntax.
@return PatchObject[] Array of PatchObjects.

Parse a textual representation of patches and return a list of patch objects .


public function toText($patches)
    {
        $text = '';
        foreach ($patches as $patch) {
            $text .= (string)$patch;
        }

        return $text;
    }

public function toText ( $ patches ) { $ text = '' ; foreach ( $ patches as $ patch ) { $ text .= ( string ) $ patch ; } return $ text ; }

Take a list of patches and return a textual representation.

@param PatchObject[] $patches Array of PatchObjects.

@return string Text representation of patches.

Take a list of patches and return a textual representation .


public function addContext(PatchObject $patch, $text)
    {
        if (!mb_strlen($text)) {
            return;
        }
        $padding = 0;
        $pattern = mb_substr($text, $patch->getStart1(), $patch->getLength1());

        // Look for the first and last matches of pattern in text.
        // If two different matches are found, increase the pattern length.
        $match = $this->getMatch();
        while (
            (!$pattern || mb_strpos($text, $pattern) !== mb_strrpos($text, $pattern)) &&
            ($match->getMaxBits() == 0 || mb_strlen($pattern) < $match->getMaxBits() - 2 * $this->getMargin())
        ) {
            $padding += $this->getMargin();
            $pattern = mb_substr(
                $text,
                max(0, $patch->getStart2() - $padding),
                $patch->getStart2() + $patch->getLength1() + $padding - max(0, $patch->getStart2() - $padding)
            );
        }
        // Add one chunk for good luck.
        $padding += $this->getMargin();

        // Add the prefix.
        $prefix = mb_substr($text, max(0, $patch->getStart2() - $padding), min($patch->getStart2(), $padding));
        if ($prefix != '') {
            $patch->prependChanges(array(Diff::EQUAL, $prefix));
        }
        // Add the suffix.
        $suffix = mb_substr($text, $patch->getStart2() + $patch->getLength1(), $padding);
        if ($suffix != '') {
            $patch->appendChanges(array(Diff::EQUAL, $suffix));
        }

        // Roll back the start points.
        $prefixLen = mb_strlen($prefix);
        $patch->setStart1($patch->getStart1() - $prefixLen);
        $patch->setStart2($patch->getStart2() - $prefixLen);
        // Extend lengths.
        $suffixLen = mb_strlen($suffix);
        $patch->setLength1($patch->getLength1() + $prefixLen + $suffixLen);
        $patch->setLength2($patch->getLength2() + $prefixLen + $suffixLen);
    }

Increase the context until it is unique, but don't let the pattern expand beyond Match->maxBits.

@param PatchObject $patch The patch to grow.
@param string      $text Source text.

Increase the context until it is unique but don t let the pattern expand beyond Match - > maxBits .