private function callAll($args)
    {
        if (isset($this->filters['all'])) {
            reset($this->filters['all']);
            do {
                foreach ((array) current($this->filters['all']) as $fn_arr) {
                    if (!is_null($fn_arr['function'])) {
                        call_user_func_array($fn_arr['function'], $args);
                    }
                }
            } while (next($this->filters['all']) !== false);
        }
    }

private function callAll ( $ args ) { if ( isset ( $ this -> filters [ 'all' ] ) ) { reset ( $ this -> filters [ 'all' ] ) ; do { foreach ( ( array ) current ( $ this -> filters [ 'all' ] ) as $ fn_arr ) { if ( ! is_null ( $ fn_arr [ 'function' ] ) ) { call_user_func_array ( $ fn_arr [ 'function' ] , $ args ) ; } } } while ( next ( $ this -> filters [ 'all' ] ) !== false ) ; } }

Call the 'all' hook, which will process the functions hooked into it.

The 'all' hook passes all of the arguments or parameters that were used for
the hook, which this function was called for.

Inherited docs from WordPress :
-------------------------------
This function is used internally for apply_filters(), do_action(), and
do_action_ref_array() and is not meant to be used from outside those
functions. This function does not check for the existence of the all hook, so
it will fail unless the all hook exists prior to this function call.

@access private
@param array $args The collected parameters from the hook that was called.

Call the all hook which will process the functions hooked into it .


public function append($hookName, $callable, $priority = 10, $accepted_args = 1, $create = true)
    {
        if ($create || ! $this->has($hookName, $callable)) {
            return $this->add($hookName, $callable, $priority, $accepted_args);
        }
        return false;
    }

public function append ( $ hookName , $ callable , $ priority = 10 , $ accepted_args = 1 , $ create = true ) { if ( $ create || ! $ this -> has ( $ hookName , $ callable ) ) { return $ this -> add ( $ hookName , $ callable , $ priority , $ accepted_args ) ; } return false ; }

Appending Hooks Function, if hooks existor just append the hooks

@param  string    $hookName            Hook Name
@param  Callable  $callable            Callable
@param  integer   $priority            priority
@param  integer   $accepted_args       num count of accepted args / parameter
@param  boolean   $create              true if want to create new if not exists

@return boolean

Appending Hooks Function if hooks existor just append the hooks


public function exists($hookName, $function_to_check = false)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName || !isset($this->filters[$hookName])) {
            return false;
        }
        // Don't reset the internal array pointer
        $has    = !empty($this->filters[$hookName]);
        // Make sure at least one priority has a filter callback
        if ($has) {
            $exists = false;
            foreach ($this->filters[$hookName] as $callbacks) {
                if (! empty($callbacks)) {
                    $exists = true;
                    break;
                }
            }

            if (! $exists) {
                $has = false;
            }
        }

        // recheck
        if (false === $function_to_check || false === $has) {
            return $has;
        }

        if (! $id = $this->uniqueId($hookName, $function_to_check, false)) {
            return false;
        }

        foreach (array_keys($this->filters[$hookName]) as $priority) {
            if (isset($this->filters[$hookName][$priority][$id])) {
                return $priority;
            }
        }

        return false;
    }

Check if hook name exists

@param  string      $hookName          Hook name
@param  string|mixed $function_to_check Specially Functions on Hook

@return boolean|int


public function call($hookName, $arg = '')
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName) {
            return false;
        }
        if (! isset($this->actions[$hookName])) {
            $this->actions[$hookName] = 1;
        } else {
            $this->actions[$hookName]++;
        }

        // Do 'all' actions first
        if (isset($this->filters['all'])) {
            $this->current[] = $hookName;
            $all_args = func_get_args();
            $this->callAll($all_args);
        }

        if (!isset($this->filters[$hookName])) {
            if (isset($this->filters['all'])) {
                array_pop($this->current);
            }
            return null;
        }

        if (!isset($this->filters['all'])) {
            $this->current[] = $hookName;
        }

        $args = array();
        if (is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0])) {
            // array(&$this)
            $args[] =& $arg[0];
        } else {
            $args[] = $arg;
        }

        for ($a = 2, $num = func_num_args(); $a < $num; $a++) {
            $args[] = func_get_arg($a);
        }
        // Sort
        if (!isset($this->merged[$hookName])) {
            ksort($this->filters[$hookName]);
            $this->merged[$hookName] = true;
        }
        reset($this->filters[$hookName]);
        do {
            foreach ((array) current($this->filters[$hookName]) as $the_) {
                if (!is_null($the_['function'])) {
                    call_user_func_array(
                        $the_['function'],
                        array_slice($args, 0, (int) $the_['accepted_args'])
                    );
                }
            }
        } while (next($this->filters[$hookName]) !== false);
        array_pop($this->current);

        return true;
    }

public
function
call
(
$
hookName
,
$
arg
=
''
)
{
$
hookName
=
$
this
->
sanitize
(
$
hookName
)
;
if
(
!
$
hookName
)
{
return
false
;
}
if
(
!
isset
(
$
this
->
actions
[
$
hookName
]
)
)
{
$
this
->
actions
[
$
hookName
]
=
1
;
}
else
{
$
this
->
actions
[
$
hookName
]
++
;
}
// Do 'all' actions first
if
(
isset
(
$
this
->
filters
[
'all'
]
)
)
{
$
this
->
current
[
]
=
$
hookName
;
$
all_args
=
func_get_args
(
)
;
$
this
->
callAll
(
$
all_args
)
;
}
if
(
!
isset
(
$
this
->
filters
[
$
hookName
]
)
)
{
if
(
isset
(
$
this
->
filters
[
'all'
]
)
)
{
array_pop
(
$
this
->
current
)
;
}
return
;
}
if
(
!
isset
(
$
this
->
filters
[
'all'
]
)
)
{
$
this
->
current
[
]
=
$
hookName
;
}
$
args
=
array
(
)
;
if
(
is_array
(
$
arg
)
&&
1
==
count
(
$
arg
)
&&
isset
(
$
arg
[
0
]
)
&&
is_object
(
$
arg
[
0
]
)
)
{
// array(&$this)
$
args
[
]
=
&
$
arg
[
0
]
;
}
else
{
$
args
[
]
=
$
arg
;
}
for
(
$
a
=
2
,
$
num
=
func_num_args
(
)
;
$
a
<
$
num
;
$
a
++
)
{
$
args
[
]
=
func_get_arg
(
$
a
)
;
}
// Sort
if
(
!
isset
(
$
this
->
merged
[
$
hookName
]
)
)
{
ksort
(
$
this
->
filters
[
$
hookName
]
)
;
$
this
->
merged
[
$
hookName
]
=
true
;
}
reset
(
$
this
->
filters
[
$
hookName
]
)
;
do
{
foreach
(
(
array
)
current
(
$
this
->
filters
[
$
hookName
]
)
as
$
the_
)
{
if
(
!
is_null
(
$
the_
[
'function'
]
)
)
{
call_user_func_array
(
$
the_
[
'function'
]
,
array_slice
(
$
args
,
0
,
(
int
)
$
the_
[
'accepted_args'
]
)
)
;
}
}
}
while
(
next
(
$
this
->
filters
[
$
hookName
]
)
!==
false
)
;
array_pop
(
$
this
->
current
)
;
return
true
;
}

Call hook from existing declared hook record

@param  string $hookName Hook Name
@param  string $arg      the arguments for next parameter

@return boolean


public function replace(
        $hookName,
        $function_to_replace,
        $callable,
        $priority = 10,
        $accepted_args = 1,
        $create = true
    ) {
        $hookName = $this->sanitize($hookName);
        if (!$hookName) {
            throw new \Exception("Invalid Hook Name Specified", E_ERROR);
        }

        if (!is_callable($callable)) {
            throw new \Exception("Invalid Hook Callable Specified", E_ERROR);
        }

        if (($has = $this->has($hookName, $function_to_replace)) || $create) {
            $has && $this->remove($hookName, $function_to_replace);
            // add hooks first
            return $this->add($hookName, $callable, $priority, $accepted_args);
        }

        return false;
    }

public
function
replace
(
$
hookName
,
$
function_to_replace
,
$
callable
,
$
priority
=
10
,
$
accepted_args
=
1
,
$
create
=
true
)
{
$
hookName
=
$
this
->
sanitize
(
$
hookName
)
;
if
(
!
$
hookName
)
{
throw
new
\
Exception
(
"Invalid Hook Name Specified"
,
E_ERROR
)
;
}
if
(
!
is_callable
(
$
callable
)
)
{
throw
new
\
Exception
(
"Invalid Hook Callable Specified"
,
E_ERROR
)
;
}
if
(
(
$
has
=
$
this
->
has
(
$
hookName
,
$
function_to_replace
)
)
||
$
create
)
{
$
has
&&
$
this
->
remove
(
$
hookName
,
$
function_to_replace
)
;
// add hooks first
return
$
this
->
add
(
$
hookName
,
$
callable
,
$
priority
,
$
accepted_args
)
;
}
return
false
;
}

Replace Hooks Function, this will replace all existing hooks

@param  string    $hookName            Hook Name
@param  string    $function_to_replace Function to replace
@param  Callable  $callable            Callable
@param  integer   $priority            priority
@param  integer   $accepted_args       num count of accepted args / parameter
@param  boolean   $create              true if want to create new if not exists

@return boolean
@throws \Exception

Replace Hooks Function this will replace all existing hooks


public function count($hookName)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName || !isset($this->filters[$hookName])) {
            return false;
        }
        return count((array) $this->filters[$hookName]);
    }

public function count ( $ hookName ) { $ hookName = $ this -> sanitize ( $ hookName ) ; if ( ! $ hookName || ! isset ( $ this -> filters [ $ hookName ] ) ) { return false ; } return count ( ( array ) $ this -> filters [ $ hookName ] ) ; }

Count all existences Hook

@param string $hookName Hook name

@return integer          Hooks Count


public function isDo($hookName = null)
    {
        if (null === $hookName) {
            return ! empty($this->current);
        }

        $hookName = $this->sanitize($hookName);
        return $hookName && in_array($hookName, $this->current);
    }

public function isDo ( $ hookName = null ) { if ( null === $ hookName ) { return ! empty ( $ this -> current ) ; } $ hookName = $ this -> sanitize ( $ hookName ) ; return $ hookName && in_array ( $ hookName , $ this -> current ) ; }

Check if hook has doing

@param string $hookName Hook name

@return boolean           true if has doing


public function isCalled($hookName)
    {
        $hookName = $this->sanitize($hookName);
        if (!$hookName || ! isset($this->actions[$hookName])) {
            return 0;
        }

        return $this->actions[$hookName];
    }

public function isCalled ( $ hookName ) { $ hookName = $ this -> sanitize ( $ hookName ) ; if ( ! $ hookName || ! isset ( $ this -> actions [ $ hookName ] ) ) { return 0 ; } return $ this -> actions [ $ hookName ] ; }

Check if action hook as execute

@param string $hookName Hook Name

@return integer Count of hook action if has did action


public function addRoute(
        $path,
        $middlewares = null,
        string $method = null,
        string $name = null
    ): Route {
        if (!$path instanceof Route && null === $middlewares) {
            throw new \InvalidArgumentException('Invalid route config');
        }

        if ($path instanceof Route) {
            $route = $path;
        }

        if (!isset($route)) {
            $path = $this->groupPath . $path;

            if (count($this->groupMiddleware) > 0) {
                $temp = $middlewares;
                $middlewares = $this->groupMiddleware;

                array_push($middlewares, $temp);
            }

            $middlewares = $this->buildMiddleware($middlewares);
            $route = new Route($path, $middlewares, $method, $name);
        }

        $this->router->addRoute($route);

        $this->log(
            $this->container,
            sprintf(
                'App::addRoute - Add route %s %s (%s)',
                implode(',', $route->getMethod()),
                $route->getPath(),
                null === $route->getName() ? 'no name' : $route->getName()
            )
        );

        return $route;
    }

public
function
addRoute
(
$
path
,
$
middlewares
=
,
string
$
method
=
,
string
$
name
=
)
:
Route
{
if
(
!
$
path
instanceof
Route
&&
===
$
middlewares
)
{
throw
new
\
InvalidArgumentException
(
'Invalid route config'
)
;
}
if
(
$
path
instanceof
Route
)
{
$
route
=
$
path
;
}
if
(
!
isset
(
$
route
)
)
{
$
path
=
$
this
->
groupPath
.
$
path
;
if
(
count
(
$
this
->
groupMiddleware
)
>
0
)
{
$
temp
=
$
middlewares
;
$
middlewares
=
$
this
->
groupMiddleware
;
array_push
(
$
middlewares
,
$
temp
)
;
}
$
middlewares
=
$
this
->
buildMiddleware
(
$
middlewares
)
;
$
route
=
new
Route
(
$
path
,
$
middlewares
,
$
method
,
$
name
)
;
}
$
this
->
router
->
addRoute
(
$
route
)
;
$
this
->
log
(
$
this
->
container
,
sprintf
(
'App::addRoute - Add route %s %s (%s)'
,
implode
(
','
,
$
route
->
getMethod
(
)
)
,
$
route
->
getPath
(
)
,
===
$
route
->
getName
(
)
'no name'
:
$
route
->
getName
(
)
)
)
;
return
$
route
;
}

Add route on router.

@param string      $path
@param null        $middlewares
@param string|null $method
@param string|null $name

@throws \InvalidArgumentException

@return Route


public function pipe($path, $middlewares = null, string $env = null): self
    {
        if (null !== $env && $this->env !== $env) {
            return $this;
        }

        if (null === $middlewares) {
            $middlewares = $this->buildMiddleware($path);
            $path = '*';
        }

        if (!$middlewares instanceof MiddlewareInterface) {
            $middlewares = $this->buildMiddleware($middlewares);
        }

        $route = new Route($path, $middlewares);

        $this->dispatcher->pipe($route);

        $this->log(
            $this->container,
            sprintf(
                'App::pipe - Pipe middleware %s %s - %s',
                implode(',', $route->getMethod()),
                $route->getPath(),
                get_class($middlewares)
            )
        );

        return $this;
    }

Add middleware on pipe.

@param $path
@param null        $middlewares
@param string|null $env

@return App

@internal param bool $first


public function run(?ServerRequestInterface $request = null, bool $returnResponse = false)
    {
        $request = (null !== $request) ? $request : ServerRequest::fromGlobals();
        $request = $request->withAttribute('originalResponse', $this->response);
        $response = $this->dispatcher->handle($request);

        $this->log(
            $this->container,
            sprintf(
                'App::run - Response [%d] %s',
                $response->getStatusCode(),
                $response->getReasonPhrase()
            )
        );

        if (true === $returnResponse) {
            return $response;
        }

        if (PHP_SAPI === 'cli') {
            echo (string) $response->getBody();
        } else {
            \Http\Response\send($response);
        }
    }

public
function
run
(
ServerRequestInterface
$
request
=
,
bool
$
returnResponse
=
false
)
{
$
request
=
(
!==
$
request
)
$
request
:
ServerRequest
::
fromGlobals
(
)
;
$
request
=
$
request
->
withAttribute
(
'originalResponse'
,
$
this
->
response
)
;
$
response
=
$
this
->
dispatcher
->
handle
(
$
request
)
;
$
this
->
log
(
$
this
->
container
,
sprintf
(
'App::run - Response [%d] %s'
,
$
response
->
getStatusCode
(
)
,
$
response
->
getReasonPhrase
(
)
)
)
;
if
(
true
===
$
returnResponse
)
{
return
$
response
;
}
if
(
PHP_SAPI
===
'cli'
)
{
echo
(
string
)
$
response
->
getBody
(
)
;
}
else
{
\
Http
\
Response
\
send
(
$
response
)
;
}
}

Start process dispatcher.

@param null|ServerRequestInterface $request
@param bool                        $returnResponse

@return void|\Psr\Http\Message\ResponseInterface


protected function singalExecution(Node $node, Execution $execution, array $vars, array $delegation)
    {
        $behavior = $node->getBehavior();

        if ($behavior instanceof SignalableBehaviorInterface) {
            $behavior->signal($execution, $this->signal, $vars, $delegation);
        }
    }

protected function singalExecution ( Node $ node , Execution $ execution , array $ vars , array $ delegation ) { $ behavior = $ node -> getBehavior ( ) ; if ( $ behavior instanceof SignalableBehaviorInterface ) { $ behavior -> signal ( $ execution , $ this -> signal , $ vars , $ delegation ) ; } }

Perform logic to actually signal the execution.

@param Node $node
@param Execution $execution
@param array $vars
@param array $delegation

Perform logic to actually signal the execution .


public function set($id, $value)
    {
        if (!empty($this->locks[$id])) {
            throw new ContainerException("Cannot override locked key {$id}");
        }
        $this->definitions[$id] = $value;
        $this->calcs[$id] = false;
        // unset on override
        unset($this->objects[$id]);
    }

public
function
set
(
$
id
,
$
value
)
{
if
(
!
empty
(
$
this
->
locks
[
$
id
]
)
)
{
throw
new
ContainerException
(
"Cannot override locked key {$id}"
)
;
}
$
this
->
definitions
[
$
id
]
=
$
value
;
$
this
->
calcs
[
$
id
]
=
false
;
// unset on override
unset
(
$
this
->
objects
[
$
id
]
)
;
}

Sets a parameter defined in an unique key ID.
You can set objects as a closures.

@param string $id    Key Name
@param mixed  $value Value or closure function

@return void

Sets a parameter defined in an unique key ID . You can set objects as a closures .


public function raw($idOrClosure)
    {
        if (is_object($idOrClosure) && method_exists($idOrClosure, "__invoke")) {
            $this->raws->attach($idOrClosure);

            return $idOrClosure;
        }

        if (!isset($this->definitions[$idOrClosure])) {
            return null;
        }

        return $this->definitions[$idOrClosure];
    }

public function raw ( $ idOrClosure ) { if ( is_object ( $ idOrClosure ) && method_exists ( $ idOrClosure , "__invoke" ) ) { $ this -> raws -> attach ( $ idOrClosure ) ; return $ idOrClosure ; } if ( ! isset ( $ this -> definitions [ $ idOrClosure ] ) ) { return null ; } return $ this -> definitions [ $ idOrClosure ] ; }

Returns a raw definition. Used when a closure is set and
you want to get the closure not the result of it.

@param string $idOrClosure

@return mixed Returns whatever it is stored in the key. NULL if
nothing is stored.

Returns a raw definition . Used when a closure is set and you want to get the closure not the result of it .


public function encrypt(string $value, string $key = null): string
    {
        if ($key === null) {
            $key = $this->getDefaultKey();
        }
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->cipher));
        return $iv . openssl_encrypt($value, $this->cipher, $key, 0, $iv);
    }

public function encrypt ( string $ value , string $ key = null ) : string { if ( $ key === null ) { $ key = $ this -> getDefaultKey ( ) ; } $ iv = openssl_random_pseudo_bytes ( openssl_cipher_iv_length ( $ this -> cipher ) ) ; return $ iv . openssl_encrypt ( $ value , $ this -> cipher , $ key , 0 , $ iv ) ; }

Encrypts the value provided. The default key will be used if none specified.

@param string $value
@param string $key
@return string

Encrypts the value provided . The default key will be used if none specified .


public function decrypt(string $value, string $key = null): ?string
    {
        if ($key === null) {
            $key = $this->getDefaultKey();
        }
        $ivLength = openssl_cipher_iv_length($this->cipher);
        $iv = substr($value, 0, $ivLength);
        $result = @openssl_decrypt(substr($value, $ivLength), $this->cipher, $key, 0, $iv);
        if ($result === false) {
            return null;
        }
        return $result;
    }

public function decrypt ( string $ value , string $ key = null ) : ? string { if ( $ key === null ) { $ key = $ this -> getDefaultKey ( ) ; } $ ivLength = openssl_cipher_iv_length ( $ this -> cipher ) ; $ iv = substr ( $ value , 0 , $ ivLength ) ; $ result = @ openssl_decrypt ( substr ( $ value , $ ivLength ) , $ this -> cipher , $ key , 0 , $ iv ) ; if ( $ result === false ) { return null ; } return $ result ; }

Decrypts the value provided. The default key will be used if none specified.

@param string $value
@param string $key
@return string

Decrypts the value provided . The default key will be used if none specified .


private function getDefaultKey()
    {
        if (isset($this->cache['defaultKey'])) {
            return $this->cache['defaultKey'];
        }
        $app = App::get();
        $cacheKey = 'ivopetkov-encryption-default-key';
        $value = $app->cache->getValue($cacheKey);
        if ($value === null) {
            $dataKey = 'encryption/default.key';
            $value = $app->data->getValue($dataKey);
            if ($value === null) {
                $value = md5(openssl_random_pseudo_bytes(openssl_cipher_iv_length($this->cipher)) . uniqid('', true) . rand(0, 999999999));
                $app->data->set($app->data->make($dataKey, $value));
            }
            $app->cache->set($app->cache->make($cacheKey, $value));
        }
        $this->cache['defaultKey'] = $value;
        return $value;
    }

private function getDefaultKey ( ) { if ( isset ( $ this -> cache [ 'defaultKey' ] ) ) { return $ this -> cache [ 'defaultKey' ] ; } $ app = App :: get ( ) ; $ cacheKey = 'ivopetkov-encryption-default-key' ; $ value = $ app -> cache -> getValue ( $ cacheKey ) ; if ( $ value === null ) { $ dataKey = 'encryption/default.key' ; $ value = $ app -> data -> getValue ( $ dataKey ) ; if ( $ value === null ) { $ value = md5 ( openssl_random_pseudo_bytes ( openssl_cipher_iv_length ( $ this -> cipher ) ) . uniqid ( '' , true ) . rand ( 0 , 999999999 ) ) ; $ app -> data -> set ( $ app -> data -> make ( $ dataKey , $ value ) ) ; } $ app -> cache -> set ( $ app -> cache -> make ( $ cacheKey , $ value ) ) ; } $ this -> cache [ 'defaultKey' ] = $ value ; return $ value ; }


private function calculateArguments(array $config): array
    {
        $args = [];

        foreach ($config as $key => $item)
        {
            if (\is_string($item) && $this->base->has($item)) {
                $args[] = $this->base->get($item);
                continue;
            }

            if (\is_string($key) && \is_array($item)) {
                $this->dc->set($key, $item);
                $args[] = $this->dc->get($key);
                continue;
            }

            $args[] = $item;
        }

        return $args;
    }

private function calculateArguments ( array $ config ) : array { $ args = [ ] ; foreach ( $ config as $ key => $ item ) { if ( \ is_string ( $ item ) && $ this -> base -> has ( $ item ) ) { $ args [ ] = $ this -> base -> get ( $ item ) ; continue ; } if ( \ is_string ( $ key ) && \ is_array ( $ item ) ) { $ this -> dc -> set ( $ key , $ item ) ; $ args [ ] = $ this -> dc -> get ( $ key ) ; continue ; } $ args [ ] = $ item ; } return $ args ; }

Calculate the arguments for the enclosed object.

@param array $config
@return array

Calculate the arguments for the enclosed object .


public static function getStrType( $str ) {

		if ( null === $str ) {
			return 's';
		}

		$chrType = substr((string)gettype($str),0,1);
		return (!in_array($chrType,array("i","d","s"))) ? "b" : $chrType;

	}

public static function getStrType ( $ str ) { if ( null === $ str ) { return 's' ; } $ chrType = substr ( ( string ) gettype ( $ str ) , 0 , 1 ) ; return ( ! in_array ( $ chrType , array ( "i" , "d" , "s" ) ) ) ? "b" : $ chrType ; }

Devuelve el tipo para el bind
@param string $str
@return string


public function addApp(string $path, $ext, string $module)
    {
        $ext_key = empty($ext) ? '_' : $ext;
        if (!isset($this->apps[$ext_key]))
        {
            $this->apps[$ext_key] = array(
                'path' => $path,
                'module' => $module,
                'route' => $this->route,
                'ext' => $ext,
                'depth' => $this->depth
            );
        }
        return $this;
    }

public function addApp ( string $ path , $ ext , string $ module ) { $ ext_key = empty ( $ ext ) ? '_' : $ ext ; if ( ! isset ( $ this -> apps [ $ ext_key ] ) ) { $ this -> apps [ $ ext_key ] = array ( 'path' => $ path , 'module' => $ module , 'route' => $ this -> route , 'ext' => $ ext , 'depth' => $ this -> depth ) ; } return $ this ; }

Link an app to this route.
@param string $path The path to the app
@param string $ext The file extension for this app
@param string $module The module this app belongs to
@return Route Provides fluent interface


public function getSubRoute(string $route_part)
    {
        $sub_route = $this->route === '/' ? '/' . $route_part : $this->route . '/' . $route_part;

        if (!isset($this->children[$route_part]))
            $this->children[$route_part] = new Route($sub_route, $this->depth + 1);

        return $this->children[$route_part];
    }

public function getSubRoute ( string $ route_part ) { $ sub_route = $ this -> route === '/' ? '/' . $ route_part : $ this -> route . '/' . $ route_part ; if ( ! isset ( $ this -> children [ $ route_part ] ) ) $ this -> children [ $ route_part ] = new Route ( $ sub_route , $ this -> depth + 1 ) ; return $ this -> children [ $ route_part ] ; }

Get a sub route for the specified route part. If a
child node does not exist yet, it will be created.
@param string $route_part The child route part
@return Route The child node

Get a sub route for the specified route part . If a child node does not exist yet it will be created .


public function serialize()
    {
        return serialize([
            'route' => $this->route,
            'depth' => $this->depth,
            'apps' => $this->apps,
            'children' => $this->children
        ]);
    }

public function serialize ( ) { return serialize ( [ 'route' => $ this -> route , 'depth' => $ this -> depth , 'apps' => $ this -> apps , 'children' => $ this -> children ] ) ; }

Serialize the route.
@return string data The serialized route


public function unserialize($data)
    {
        $data = unserialize($data);
        $this->route = $data['route'];
        $this->depth = $data['depth'];
        $this->apps = $data['apps'];
        $this->children = $data['children'];
    }

public function unserialize ( $ data ) { $ data = unserialize ( $ data ) ; $ this -> route = $ data [ 'route' ] ; $ this -> depth = $ data [ 'depth' ] ; $ this -> apps = $ data [ 'apps' ] ; $ this -> children = $ data [ 'children' ] ; }

Unserialize the route from serialized PHP data
@param string $data The PHP Serialized data


public static function getYearToActual(int $beginYear): string
	{
		$actualYear = strftime('%Y');
		if ($beginYear == $actualYear) {
			return $actualYear;
		} else {
			return $beginYear . ' - ' . $actualYear;
		}
	}

public
static
function
getYearToActual
(
int
$
beginYear
)
:
string
{
$
actualYear
=
strftime
(
'%Y'
)
;
if
(
$
beginYear
==
$
actualYear
)
{
return
$
actualYear
;
}
else
{
return
$
beginYear
.
' - '
.
$
actualYear
;
}
}

Vrati pocatecni rok - aktualni rok. V pripade, ze se shoduji pouze aktualni
@param int $beginYear pocatecni rok
@return string napr: 2012 - 2014 nebo pouze 2014

Vrati pocatecni rok - aktualni rok . V pripade ze se shoduji pouze aktualni


public static function getCurrentTimeStamp(): string
	{
		$t = microtime(true);
		$micro = sprintf('%06d', ($t - floor($t)) * 1000000);
		$d = new DateTime(date('Y-m-d H:i:s.' . $micro, (int) $t));
		return $d->format('Y_m_d_H_i_s_u');
	}

public
static
function
getCurrentTimeStamp
(
)
:
string
{
$
t
=
microtime
(
true
)
;
$
micro
=
sprintf
(
'%06d'
,
(
$
t
floor
(
$
t
)
)
*
1000000
)
;
$
d
=
new
DateTime
(
date
(
'Y-m-d H:i:s.'
.
$
micro
,
(
int
)
$
t
)
)
;
return
$
d
->
format
(
'Y_m_d_H_i_s_u'
)
;
}

Vrati aktualni cas na milivteriny
@return string


public static function getDay($day): string
	{
		if ($day instanceof DateTimeInterface) {
			$day = (int) $day->format('N');
		}
		if (!is_int($day)) {
			throw new InvalidArgumentException;
		}
		return self::$dayNames[self::$locale][$day];
	}

public static function getDay ( $ day ) : string { if ( $ day instanceof DateTimeInterface ) { $ day = ( int ) $ day -> format ( 'N' ) ; } if ( ! is_int ( $ day ) ) { throw new InvalidArgumentException ; } return self :: $ dayNames [ self :: $ locale ] [ $ day ] ; }

Vrati nazev dne
@param int|DateTimeInterface $day
@return string


public static function getShortDay($day): string
	{
		if ($day instanceof DateTimeInterface) {
			$day = (int) $day->format('N');
		}
		if (!is_int($day)) {
			throw new InvalidArgumentException;
		}
		return self::$dayNamesShort[self::$locale][$day];
	}

public static function getShortDay ( $ day ) : string { if ( $ day instanceof DateTimeInterface ) { $ day = ( int ) $ day -> format ( 'N' ) ; } if ( ! is_int ( $ day ) ) { throw new InvalidArgumentException ; } return self :: $ dayNamesShort [ self :: $ locale ] [ $ day ] ; }

Vrati zkraceny nazev dne
@param int|DateTimeInterface $day
@return string


public static function getMonth($month): string
	{
		if ($month instanceof DateTimeInterface) {
			$month = (int) $month->format('n');
		}
		if (!is_int($month)) {
			throw new InvalidArgumentException;
		}
		return self::$monthNames[self::$locale][$month];
	}

public static function getMonth ( $ month ) : string { if ( $ month instanceof DateTimeInterface ) { $ month = ( int ) $ month -> format ( 'n' ) ; } if ( ! is_int ( $ month ) ) { throw new InvalidArgumentException ; } return self :: $ monthNames [ self :: $ locale ] [ $ month ] ; }

Vrati nazev mesice
@param int|DateTimeInterface $month
@return string


public static function getShortMonth($month): string
	{
		if ($month instanceof DateTimeInterface) {
			$month = (int) $month->format('n');
		}
		if (!is_int($month)) {
			throw new InvalidArgumentException;
		}
		return self::$monthNamesShort[self::$locale][$month];
	}

public static function getShortMonth ( $ month ) : string { if ( $ month instanceof DateTimeInterface ) { $ month = ( int ) $ month -> format ( 'n' ) ; } if ( ! is_int ( $ month ) ) { throw new InvalidArgumentException ; } return self :: $ monthNamesShort [ self :: $ locale ] [ $ month ] ; }

Vrati zkraceny nazev mesice
@param int|DateTimeInterface $month
@return string


private static function formatDate($datetime, string $format): ?string
	{
		if (empty($datetime)) {
			return null;
		} elseif ($datetime instanceof DateTimeInterface) {
			$date = $datetime;
		} else {
			$date = DateTime::createFromFormat('U', (string) $datetime);
		}
		return $date->format($format);
	}

private static function formatDate ( $ datetime , string $ format ) : ? string { if ( empty ( $ datetime ) ) { return null ; } elseif ( $ datetime instanceof DateTimeInterface ) { $ date = $ datetime ; } else { $ date = DateTime :: createFromFormat ( 'U' , ( string ) $ datetime ) ; } return $ date -> format ( $ format ) ; }

Vrati lokalizovany format data
@param DateTimeInterface|int $datetime
@param string $format
@return string|null


public static function getDateTime($datetime, bool $withSeconds = false): ?string
	{
		return self::formatDate($datetime, self::getFormat(true, true, $withSeconds));
	}

public static function getDateTime ( $ datetime , bool $ withSeconds = false ) : ? string { return self :: formatDate ( $ datetime , self :: getFormat ( true , true , $ withSeconds ) ) ; }

Lokalizovane datum s casem
@param DateTimeInterface|int $datetime datum nebo timestamp
@param bool $withSeconds
@return null|string


public function registerBaseServices()
    {
        //see example https://github.com/slimphp/Slim/blob/3.x/Slim/DefaultServicesProvider.php
        $container = $this->getContainer();

        // wrapper for Request validation
        if (!isset($container['validator'])) {
            $container['validator'] = new \Amcms\Services\ValidatorService($container);
        }

        // Auth service
        if (!isset($container['auth'])) {
            $container['auth'] = new \Amcms\Services\AuthService($container);
        }

        // Twig View
        if (!isset($container['twig'])) {
            $container['twig'] = function ($c) {
                $isDebug = $c['settings']['debug'] ?: false;
                $twigTemplatesPath = $c['path'] . '/' . (isset($c['settings']['templates']['twig']['template_path']) ? trim($c['settings']['templates']['twig']['template_path'], '/') : 'resources/views/templates');
                $twigCachePath = $c['path'] . '/' . (isset($c['settings']['templates']['twig']['cache_path']) ? trim($c['settings']['templates']['twig']['cache_path'], '/') : 'storage/cache');

                $view = new \Amcms\View\TwigView($twigTemplatesPath, [
                    'cache' => $twigCachePath,
                    'debug' => $isDebug,
                    // 'auto_update' => false,
                ]);

                $view->addExtension(new \Amcms\View\TwigExtension($c));

                return $view;
            };
        }
    }

Register some "internal" services
@return void


public function postSectiontreeAction() {
        $serializer = $this->get("tpg_extjs.phpcr_serializer");
        $entity = $serializer->deserialize(
            $this->getRequest()->getContent(),
            'Application\Togu\ApplicationModelsBundle\Document\Section',
            'json',
            DeserializationContext::create()->setGroups(array("Default", "post"))
        );
		$modelLoader = $this->get('togu.generator.model.config');
		if(! $modelLoader->hasModel($entity->getType())) {
			throw new \InvalidArgumentException(sprintf('The model %s does not exist', $entity->getType()));
		}
        $validator = $this->get('validator');
        $validations = $validator->validate($entity, array('Default', 'post'));
        if ($validations->count() === 0) {
            $manager = $this->get('doctrine_phpcr.odm.default_document_manager');
            $rootData = $manager->find(null, '/data');

            $sectionClassName = $modelLoader->getFullClassName($entity->getType());
            $section = new $sectionClassName(array(
				"sectionConfig" => $entity,
            	"parentDocument" => $rootData
            ));
            $entity->getParentSection()->getSectionConfig()->addNextSection($section);
            $entity->getPage()->setSection($section);
            $manager->persist($entity);
            $manager->persist($section);
            try {
                $manager->flush();
            } catch (DBALException $e) {
                return $this->handleView(
                    View::create(array('errors'=>array($e->getMessage())), 400)
                );
            }
            return $this->handleView(
                View::create(array(
                	"success" => true,
                	"records" => array($entity)
                ), 200)->setSerializationContext($this->getSerializerContext(array('Default', 'post')))
            );
        } else {
            return $this->handleView(
                View::create(array('errors'=>$validations), 400)
            );
        }
    }

Create a new Section record

@return \Symfony\Component\HttpFoundation\Response


public function setOwner($type, $id)
    {
        $this->ownerType = $type;
        $this->ownerId = $id;

        return $this;
    }

public function setOwner ( $ type , $ id ) { $ this -> ownerType = $ type ; $ this -> ownerId = $ id ; return $ this ; }

Set the session owner

@param string $type The type of the owner (e.g. user, app)
@param string $id   The identifier of the owner

@return self


private function removeComments( $input, $proxy = false )
  {
    if ( preg_match_all("/\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\//", $input, $comments) )
    {
      foreach ( $comments[ 0 ] as $comment )
      {
        $lines = explode(PHP_EOL, $comment);
        $newComment = implode(PHP_EOL,preg_grep("/copyright|license|author|preserve|credit|http|\/\*\!/i",$lines));

        if($newComment)
        {
          // Add proper comment encapsulation
          if ( count( $lines ) > 1 )
          {
            $prefix = (substr($newComment,0,3) == '/*!') ? '' : '/*!' . PHP_EOL;
            $newComment = $prefix . $newComment . PHP_EOL . " */";
          }
          else
          {
            $newComment = str_replace( array("/* ","/** "), "/*! ", $newComment );
          }

          if($proxy) { $this->comments[] = $newComment; }

          $input = str_replace( $comment, $newComment, $input );

        }
        else
        {
          $input = str_replace( $comment, "", $input );
        }
      }

    }

    return $input;
  }

Removes comments from a multi line string while preserving any comments that mention licenses, authors, copyrights
or the source URL of the code.  This ensures that minification does not break most open source licenses which
require attribution.

@param  string  $input
@param  bool   $proxy

@return string

Removes comments from a multi line string while preserving any comments that mention licenses authors copyrights or the source URL of the code . This ensures that minification does not break most open source licenses which require attribution .


private function minifyCSS($input)
  {
    $keepComments = null;
    $output = $this->stashComments( $input );

    // Remove Comments, preserving comments marked as important
    $output = preg_replace('!/\*[^*\!]*\*+([^/][^*]*\*+)*/!', '', $output);

    $output = $this->minifySpaceCSS($output);

    $output = $this->shortenHex($output);

    // Replace common units after 0's - they aren't needed
    $output = preg_replace('/((?<!\\\\)\:|\s)\-?0(?:em|cm|mm|in|px|pt|%)/iS', '${1}0', $output);

    // Remove Leading Zeros in Floats
    $output = preg_replace("/0\.([0-9]+)/", '.$1', $output);

    // Extra whitespace
    $output = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $output);

    // Add line breaks around remaining comments
    $output = $this->retrieveComments( $output );

    return $output;
  }

Minify CSS by removing unneeded code.

Regex references from:
http://stackoverflow.com/questions/15195750/minify-compress-css-with-regex
http://stackoverflow.com/questions/2167793/how-to-convert-all-color-code-xxyyzz-to-shorter-3-character-version-xyz-of-who

@param  string $input  The string of CSS code to minify

@return string         The minified CSS code.


public function setGlobal($name, $value, $options = []) {
        if (isset($options['namespace'])) {
            $this->getEnvironment()->addGlobal($options['namespace'], [$name => $value]);
        } else {
            $this->getEnvironment()->addGlobal($name, $value);
        }
    }

public function setGlobal ( $ name , $ value , $ options = [ ] ) { if ( isset ( $ options [ 'namespace' ] ) ) { $ this -> getEnvironment ( ) -> addGlobal ( $ options [ 'namespace' ] , [ $ name => $ value ] ) ; } else { $ this -> getEnvironment ( ) -> addGlobal ( $ name , $ value ) ; } }

Adds global variable to view
@param string $name
@param string $value
@param array  $options


public static function quote($val = "", $q = "\"")
    {
        if (is_string($val)) {
            return $q . $val . $q;
        } elseif (is_numeric($val)) {
            return $val;
        } elseif (is_array($val)) {
            return "StringUtils::quote returned 'array'! ";
        } else {
            return $q . $val . $q;
        }
    }

public
static
function
quote
(
$
val
=
""
,
$
q
=
"\""
)
{
if
(
is_string
(
$
val
)
)
{
return
$
q
.
$
val
.
$
q
;
}
elseif
(
is_numeric
(
$
val
)
)
{
return
$
val
;
}
elseif
(
is_array
(
$
val
)
)
{
return
"StringUtils::quote returned 'array'! "
;
}
else
{
return
$
q
.
$
val
.
$
q
;
}
}

Encloses and input string with double quotes.
@param  string $val
@param  string $q
@return string

Encloses and input string with double quotes .


public static function explodeGeneric($input = '', array $delims = [' '])
    {
        foreach ($delims as $delim) {
            $input = str_replace($delim, ' ', $input);
        }
        $input = preg_replace('/\s\s+/', ' ', $input);
        $input = trim($input);
        $out = explode(' ', $input);
        return $out;
    }

public
static
function
explodeGeneric
(
$
input
=
''
,
array
$
delims
=
[
' '
]
)
{
foreach
(
$
delims
as
$
delim
)
{
$
input
=
str_replace
(
$
delim
,
' '
,
$
input
)
;
}
$
input
=
preg_replace
(
'/\s\s+/'
,
' '
,
$
input
)
;
$
input
=
trim
(
$
input
)
;
$
out
=
explode
(
' '
,
$
input
)
;
return
$
out
;
}

Generic explode function.
@param  string $input
@param  array $delims Array containing delimiter characters.
@return array


public function getRole($role)
    {
        foreach ($this->getRoles() as $roleItem) {
            if ($role == $roleItem->getRole()) {
                return $roleItem;
            }
        }
        return null;
    }

public function getRole ( $ role ) { foreach ( $ this -> getRoles ( ) as $ roleItem ) { if ( $ role == $ roleItem -> getRole ( ) ) { return $ roleItem ; } } return null ; }

Pass a string, get the desired Role object or null.

@param string $role

@return Role|null

Pass a string get the desired Role object or null .


public function addRole($role)
    {
        if (!$role instanceof Role) {
            //throw new \Exception( "addRole takes a Role object as the parameter" );
            $_role = new Role($role);
        } else {
            $_role = $role;
        }

        if (!$this->hasRole($_role->getRole())) {
            $_role->addUser($this);
            $this->roles->add($_role);
        }
    }

Adds a Role OBJECT to the ArrayCollection. Can't type hint due to interface so throws Exception.

@throws \Exception

@param Role $role

@return \FOS\UserBundle\Model\UserInterface|void

Adds a Role OBJECT to the ArrayCollection . Can t type hint due to interface so throws Exception .


public function hasRole($role)
    {
        $roles = $this->getRoles();
        /** @var Role $roleObject */
        foreach ($roles as $roleObject) {
            if ($roleObject->getRole() == strtoupper($role)) {
                return true;
            }
        }
        return false;
    }

public
function
hasRole
(
$
role
)
{
$
roles
=
$
this
->
getRoles
(
)
;
/** @var Role $roleObject */
foreach
(
$
roles
as
$
roleObject
)
{
if
(
$
roleObject
->
getRole
(
)
==
strtoupper
(
$
role
)
)
{
return
true
;
}
}
return
false
;
}

Never use this to check if this user has access to anything!

Use the SecurityContext, or an implementation of AccessDecisionManager
instead, e.g.

$securityContext->isGranted('ROLE_USER');

@param string $role

@return boolean


public static function errorHandler($errNo, $errMsg, $fileName, $lineNum, $vars)
    {
        // don't respond to the error if it
        // was suppressed with a '@'
        if (error_reporting() == 0) {
            return;
        }

        if ($errNo == E_NOTICE || $errNo == E_STRICT) { // || $errno == E_WARNING)
            return; // ignore notice error
        }

        $debug_array = debug_backtrace();
        $back_trace = self::_errorBacktrace($debug_array);
        $err = self::_getOutputErrorMsg($errNo, $errMsg, $fileName, $lineNum, $back_trace);

        Openbizx::$app->getLog()->logError($errNo, "ErrorHandler", $errMsg, null, $back_trace);

        if ((defined('CLI') && CLI) || self::$errorMode == 'text') {
            // echo $err;
        } else {
            Openbizx::$app->getClientProxy()->showErrorMessage($err, true);
        }
        if ($errNo == E_USER_ERROR || $errNo == E_ERROR) {
            Openbizx::$app->getClientProxy()->printOutput();
            exit();
        }
    }

public
static
function
errorHandler
(
$
errNo
,
$
errMsg
,
$
fileName
,
$
lineNum
,
$
vars
)
{
// don't respond to the error if it
// was suppressed with a '@'
if
(
error_reporting
(
)
==
0
)
{
return
;
}
if
(
$
errNo
==
E_NOTICE
||
$
errNo
==
E_STRICT
)
{
// || $errno == E_WARNING)
return
;
// ignore notice error
}
$
debug_array
=
debug_backtrace
(
)
;
$
back_trace
=
self
::
_errorBacktrace
(
$
debug_array
)
;
$
err
=
self
::
_getOutputErrorMsg
(
$
errNo
,
$
errMsg
,
$
fileName
,
$
lineNum
,
$
back_trace
)
;
Openbizx
::
$
app
->
getLog
(
)
->
logError
(
$
errNo
,
"ErrorHandler"
,
$
errMsg
,
,
$
back_trace
)
;
if
(
(
defined
(
'CLI'
)
&&
CLI
)
||
self
::
$
errorMode
==
'text'
)
{
// echo $err;
}
else
{
Openbizx
::
$
app
->
getClientProxy
(
)
->
showErrorMessage
(
$
err
,
true
)
;
}
if
(
$
errNo
==
E_USER_ERROR
||
$
errNo
==
E_ERROR
)
{
Openbizx
::
$
app
->
getClientProxy
(
)
->
printOutput
(
)
;
exit
(
)
;
}
}

User error handler

@param number $errNo error number
@param string $errMsg error message
@param string $fileName file name where the error occurred
@param number $lineNum line number where the error occurred
@param <type> $vars (not yet implemented)
@return void


public static function exceptionHandler($exc)
    {
        $errno = $exc->getCode();
        $errmsg = $exc->getMessage();
        $filename = $exc->getFile();
        $linenum = $exc->getLine();
        $debug_array = $exc->getTrace();
        $back_trace = self::_errorBacktrace($debug_array);
        $err = self::_getOutputErrorMsg($errno, $errmsg, $filename, $linenum, $back_trace);

        Openbizx::$app->getLog()->logError($errno, "ExceptionHandler", $errmsg, null, $back_trace);

        if ((defined('CLI') && CLI) || self::$errorMode == 'text') {
            echo $err;
        } else {
            Openbizx::$app->getClientProxy()->showErrorMessage($err, true);
        }
        if (!$exc->no_exit) {
            Openbizx::$app->getClientProxy()->printOutput();
            exit();
        }
    }

public static function exceptionHandler ( $ exc ) { $ errno = $ exc -> getCode ( ) ; $ errmsg = $ exc -> getMessage ( ) ; $ filename = $ exc -> getFile ( ) ; $ linenum = $ exc -> getLine ( ) ; $ debug_array = $ exc -> getTrace ( ) ; $ back_trace = self :: _errorBacktrace ( $ debug_array ) ; $ err = self :: _getOutputErrorMsg ( $ errno , $ errmsg , $ filename , $ linenum , $ back_trace ) ; Openbizx :: $ app -> getLog ( ) -> logError ( $ errno , "ExceptionHandler" , $ errmsg , null , $ back_trace ) ; if ( ( defined ( 'CLI' ) && CLI ) || self :: $ errorMode == 'text' ) { echo $ err ; } else { Openbizx :: $ app -> getClientProxy ( ) -> showErrorMessage ( $ err , true ) ; } if ( ! $ exc -> no_exit ) { Openbizx :: $ app -> getClientProxy ( ) -> printOutput ( ) ; exit ( ) ; } }

User exception handler

@param  object $exc hold error data
@return void


private static function _getOutputErrorMsg($errno, $errmsg, $filename, $linenum, $back_trace)
    {
        // timestamp for the error entry
        date_default_timezone_set('GMT'); // to avoid error PHP 5.1
        $dt = date("Y-m-d H:i:s (T)");
        // TODO: use CSS class for style
        $err = "
\n";
        $err .= "[$dt] An exception occurred while executing this script:
\n";
        $err .= "Error message:  #$errno, $errmsg
\n";
        $err .= "Script name and line number of error: $filename:$linenum
\n";
        $err .= "
" . $back_trace . "
\n";
        //$err .= "Variable state when error occurred: $vars
";
        $err .= "
";
        $err .= "Please ask system administrator for help...
\n";
        if ((defined('CLI') && CLI) || self::$errorMode == 'text') {
            $err = strip_tags($err);
        }
        return $err;
    }

"<div style='font-size: 12px; color: blue; font-family:Arial; font-weight:bold;'>\n"

"[$dt] An exception occurred while executing this script:<br>\n"

//$err .= "Variable state when error occurred: $vars<br>";

"Please ask system administrator for help...</div>\n"

Get output error message

@param number $errno error number
@param string $errmsg error message
@param string $filename file name where the error occurred
@param number $linenum line number where the error occurred     * @param <type> $filename
@param string $back_trace back trace message (print out call stack of the error)
@return string error message in html


private static function _errorBacktrace($debug_array = NULL)
    {
        if ($debug_array == NULL) {
            $debug_array = debug_backtrace();
        }
        $counter = count($debug_array);
        $msg = "";
        for ($tmp_counter = 0; $tmp_counter != $counter; ++$tmp_counter) {
            $msg .= "
function: ";
            $msg .= $debug_array[$tmp_counter]["function"] . " ( ";
            //count how many args a there
            $args_counter = count($debug_array[$tmp_counter]["args"]);
            //print them
            for ($tmp_args_counter = 0; $tmp_args_counter != $args_counter; ++$tmp_args_counter) {
                $a = $debug_array[$tmp_counter]["args"][$tmp_args_counter];
                switch (gettype($a)) {
                    case 'integer':
                    case 'double':
                        $msg .= $a;
                        break;
                    case 'string':
                        //$a = htmlspecialchars(substr($a, 0, 64)).((strlen($a) > 64) ? '...' : '');
                        //$msg .= "\"$a\"";
                        $a = htmlspecialchars($a);
                        $msg .= "\"$a\"";
                        break;
                    case 'array':
                        $msg .= 'Array(' . count($a) . ')';
                        break;
                    case 'object':
                        $msg .= 'Object(' . get_class($a) . ')';
                        break;
                    case 'resource':
                        $msg .= 'Resource(' . strstr($a, '#') . ')';
                        break;
                    case 'boolean':
                        $msg .= $a ? 'True' : 'False';
                        break;
                    case 'NULL':
                        $msg .= 'Null';
                        break;
                    default:
                        $msg .= 'Unknown';
                }
                if (($tmp_args_counter + 1) != $args_counter) {
                    $msg .= (", ");
                } else {
                    $msg .= (" ");
                }
            }
            $msg .= ") @ ";
            if (isset($debug_array[$tmp_counter]["file"])) {
                $msg .= ($debug_array[$tmp_counter]["file"] . " ");
            }
            if (isset($debug_array[$tmp_counter]["line"])) {
                $msg .= ($debug_array[$tmp_counter]["line"]);
            }
            if (($tmp_counter + 1) != $counter) {
                $msg .= "\n";
            }
        }
        return $msg;
    }

Print out call stack of the error

@param array $debug_array
@return string


public function setName($name = null)
    {
        if (null === $name || !is_string($name)) {
            $this->name = self::getRandomString(8);
        } else {
            $this->name = $name;
        }

        return $this;
    }

public function setName ( $ name = null ) { if ( null === $ name || ! is_string ( $ name ) ) { $ this -> name = self :: getRandomString ( 8 ) ; } else { $ this -> name = $ name ; } return $ this ; }

Sets the name of the check. When null or a non-string value is given a random name is set.

@param string $name name of the check

@return Check this instance for fluent API support

Sets the name of the check . When null or a non - string value is given a random name is set .


protected function addSetting($name, $value, $group = null, $flag = ISetting::NORMAL, $cachable = false)
    {
        if (empty($name)) {
            throw new \InvalidArgumentException('A setting must have a valid name.');
        }

        if (null === $group) {
            $group = $this->getDefaultSettingGroupName();
        }

        $setting = new Setting($name, $value, $group, $flag);

        $this->result->addSetting($setting, $cachable);

        return $this;
    }

protected
function
addSetting
(
$
name
,
$
value
,
$
group
=
,
$
flag
=
ISetting
::
NORMAL
,
$
cachable
=
false
)
{
if
(
empty
(
$
name
)
)
{
throw
new
\
InvalidArgumentException
(
'A setting must have a valid name.'
)
;
}
if
(
===
$
group
)
{
$
group
=
$
this
->
getDefaultSettingGroupName
(
)
;
}
$
setting
=
new
Setting
(
$
name
,
$
value
,
$
group
,
$
flag
)
;
$
this
->
result
->
addSetting
(
$
setting
,
$
cachable
)
;
return
$
this
;
}

Adds the given value under the given key to the settings
of the result. The setting may have a group name to more
easily separate them on export. If no group name is specified
the check's default setting group name is used as the default.

@param string $name key for that setting
@param mixed $value usually a string value
@param string $group name of group this setting belongs to
@param int $flag type of the setting (normal or sensitive)
@param boolean $cachable whether that setting should also be stored in a cache. Default is false (NOT cached!).

@return Check this instance for fluent API support

@throws \InvalidArgumentException if no valid setting key was given

Adds the given value under the given key to the settings of the result . The setting may have a group name to more easily separate them on export . If no group name is specified the check s default setting group name is used as the default .


protected function addCachableSetting($name, $value, $group = null, $flag = ISetting::NORMAL)
    {
        $this->addSetting($name, $value, $group, $flag, true);

        return $this;
    }

protected function addCachableSetting ( $ name , $ value , $ group = null , $ flag = ISetting :: NORMAL ) { $ this -> addSetting ( $ name , $ value , $ group , $ flag , true ) ; return $ this ; }

Adds the given value under the given key to the settings
of the result. The setting may have a group name to more
easily separate them on export. If no group name is specified
the check's default setting group name is used as the default.
This setting may be written to a cache to be available on re-runs
of the check.

@param string $name key for that setting
@param mixed $value usually a string value
@param string $group name of group this setting belongs to
@param int $flag type of the setting (ISetting::NORMAL by default)

@return Check this instance for fluent API support

@throws \InvalidArgumentException if no valid setting key was given

Adds the given value under the given key to the settings of the result . The setting may have a group name to more easily separate them on export . If no group name is specified the check s default setting group name is used as the default . This setting may be written to a cache to be available on re - runs of the check .


public function offsetUnset($offset)
    {
        if (isset($this->map[$offset])) {
            unset($this->map[$offset]);
        }

        if (isset($this->services[$offset])) {
            unset($this->services[$offset]);
        }
    }

public function offsetUnset ( $ offset ) { if ( isset ( $ this -> map [ $ offset ] ) ) { unset ( $ this -> map [ $ offset ] ) ; } if ( isset ( $ this -> services [ $ offset ] ) ) { unset ( $ this -> services [ $ offset ] ) ; } }

Offset to unset

@link  http://php.net/manual/en/arrayaccess.offsetunset.php
@param mixed $offset <p>
The offset to unset.
</p>
@return void
@since 5.0.0


public function setSyncState($state)
    {
        switch ((int) $state) {
            case self::SYNC_STATE_MODIFIED:
            case self::SYNC_STATE_NO_CHANGE:
            case self::SYNC_STATE_REMOVED:
                // OK
                break;
            default:
                throw new \InvalidArgumentException(sprintf('Invalid sync state: %s', $state));
        }

        $this->syncState = (int) $state;
    }

public
function
setSyncState
(
$
state
)
{
switch
(
(
int
)
$
state
)
{
case
self
::
SYNC_STATE_MODIFIED
:
case
self
::
SYNC_STATE_NO_CHANGE
:
case
self
::
SYNC_STATE_REMOVED
:
// OK
break
;
default
:
throw
new
\
InvalidArgumentException
(
sprintf
(
'Invalid sync state: %s'
,
$
state
)
)
;
}
$
this
->
syncState
=
(
int
)
$
state
;
}

Set the current sync state.

@param integer $state One of the Execution::SYNC_STATE_* constants.

@throws \InvalidArgumentException When an invalid sync state value has been given.


public function collectSyncData()
    {
        $data = [
            'id' => $this->id,
            'parentId' => ($this->parentExecution === null) ? null : $this->parentExecution->getId(),
            'processId' => $this->getRootExecution()->getId(),
            'modelId' => $this->model->getId(),
            'state' => $this->state,
            'depth' => $this->getExecutionDepth(),
            'timestamp' => $this->timestamp,
            'variables' => $this->variables,
            'transition' => ($this->transition === null) ? null : (string) $this->transition->getId(),
            'node' => ($this->node === null) ? null : (string) $this->node->getId()
        ];

        return $data;
    }

public function collectSyncData ( ) { $ data = [ 'id' => $ this -> id , 'parentId' => ( $ this -> parentExecution === null ) ? null : $ this -> parentExecution -> getId ( ) , 'processId' => $ this -> getRootExecution ( ) -> getId ( ) , 'modelId' => $ this -> model -> getId ( ) , 'state' => $ this -> state , 'depth' => $ this -> getExecutionDepth ( ) , 'timestamp' => $ this -> timestamp , 'variables' => $ this -> variables , 'transition' => ( $ this -> transition === null ) ? null : ( string ) $ this -> transition -> getId ( ) , 'node' => ( $ this -> node === null ) ? null : ( string ) $ this -> node -> getId ( ) ] ; return $ data ; }

Compute current sync data from execution state.

@return array

Compute current sync data from execution state .


public function getExpressionContext()
    {
        $access = new ExecutionAccess($this);
        $this->engine->notify(new CreateExpressionContextEvent($access));

        return $this->engine->getExpressionContextFactory()->createContext($access);
    }

public function getExpressionContext ( ) { $ access = new ExecutionAccess ( $ this ) ; $ this -> engine -> notify ( new CreateExpressionContextEvent ( $ access ) ) ; return $ this -> engine -> getExpressionContextFactory ( ) -> createContext ( $ access ) ; }

Create an expression context bound to this execution.

@return ExpressionContextInterface

Create an expression context bound to this execution .


public function terminate($triggerExecution = true)
    {
        if ($this->hasState(self::STATE_TERMINATE)) {
            return;
        }

        $this->state |= self::STATE_TERMINATE;
        $this->syncState = self::SYNC_STATE_REMOVED;

        $this->engine->debug('Terminate {execution}', [
            'execution' => (string) $this
        ]);

        foreach ($this->childExecutions as $execution) {
            $execution->terminate(false);
        }

        if ($triggerExecution) {
            $this->timestamp = microtime(true);
        }

        if ($this->parentExecution === null) {
            $this->engine->notify(new EndProcessEvent($this->node, $this));
        } else {
            $this->parentExecution->childExecutionTerminated($this, $triggerExecution);
        }
    }

public
function
terminate
(
$
triggerExecution
=
true
)
{
if
(
$
this
->
hasState
(
self
::
STATE_TERMINATE
)
)
{
return
;
}
$
this
->
state
|=
self
::
STATE_TERMINATE
;
$
this
->
syncState
=
self
::
SYNC_STATE_REMOVED
;
$
this
->
engine
->
debug
(
'Terminate {execution}'
,
[
'execution'
=>
(
string
)
$
this
]
)
;
foreach
(
$
this
->
childExecutions
as
$
execution
)
{
$
execution
->
terminate
(
false
)
;
}
if
(
$
triggerExecution
)
{
$
this
->
timestamp
=
microtime
(
true
)
;
}
if
(
$
this
->
parentExecution
===
)
{
$
this
->
engine
->
notify
(
new
EndProcessEvent
(
$
this
->
node
,
$
this
)
)
;
}
else
{
$
this
->
parentExecution
->
childExecutionTerminated
(
$
this
,
$
triggerExecution
)
;
}
}

Terminate this path of execution, will also terminate all child executions.

@param boolean $triggerExecution Trigger / signal parent execution after termination?

Terminate this path of execution will also terminate all child executions .


public function registerChildExecution(Execution $execution)
    {
        $execution->parentExecution = $this;

        if (!in_array($execution, $this->childExecutions, true)) {
            $this->childExecutions[] = $execution;
        }

        $this->markModified();

        return $execution;
    }

public function registerChildExecution ( Execution $ execution ) { $ execution -> parentExecution = $ this ; if ( ! in_array ( $ execution , $ this -> childExecutions , true ) ) { $ this -> childExecutions [ ] = $ execution ; } $ this -> markModified ( ) ; return $ execution ; }

Register the given child execution with the parent execution.

@param Execution $execution
@return Execution

Register the given child execution with the parent execution .


protected function childExecutionTerminated(Execution $execution, $triggerExecution = true)
    {
        $removed = false;
        $scope = $execution->isScope() || !$execution->isConcurrent();

        foreach ($this->childExecutions as $index => $exec) {
            if ($exec === $execution) {
                unset($this->childExecutions[$index]);
                $removed = true;

                break;
            }
        }

        if (empty($this->childExecutions) && $scope && $removed && $triggerExecution) {
            if ($this->isWaiting()) {
                $this->signal(null, [], [
                    'executionId' => $execution->getId()
                ]);
            } else {
                $this->takeAll(null, [
                    $this
                ]);
            }
        }
    }

protected function childExecutionTerminated ( Execution $ execution , $ triggerExecution = true ) { $ removed = false ; $ scope = $ execution -> isScope ( ) || ! $ execution -> isConcurrent ( ) ; foreach ( $ this -> childExecutions as $ index => $ exec ) { if ( $ exec === $ execution ) { unset ( $ this -> childExecutions [ $ index ] ) ; $ removed = true ; break ; } } if ( empty ( $ this -> childExecutions ) && $ scope && $ removed && $ triggerExecution ) { if ( $ this -> isWaiting ( ) ) { $ this -> signal ( null , [ ] , [ 'executionId' => $ execution -> getId ( ) ] ) ; } else { $ this -> takeAll ( null , [ $ this ] ) ; } } }

Is being used to notify a parent execution whenever a child execution has been terminated.

@param Execution $execution
@param boolean $triggerExecution Trigger / signal this execution?

Is being used to notify a parent execution whenever a child execution has been terminated .


public function setScope($scope)
    {
        $this->setState(self::STATE_SCOPE, $scope);

        if (!$scope) {
            $this->variables = [];
        }

        $this->markModified();
    }

public function setScope ( $ scope ) { $ this -> setState ( self :: STATE_SCOPE , $ scope ) ; if ( ! $ scope ) { $ this -> variables = [ ] ; } $ this -> markModified ( ) ; }

Toggle scope of the execution.

@param boolean $scope


public function createExecution($concurrent = true)
    {
        $execution = new static(UUID::createRandom(), $this->engine, $this->model, $this);
        $execution->setNode($this->node);

        if ($concurrent) {
            $execution->state |= self::STATE_CONCURRENT;
        }

        $this->engine->registerExecution($execution);

        $this->engine->debug(sprintf('Created %s{execution} from {parent}', $concurrent ? 'concurrent ' : ''), [
            'execution' => (string) $execution,
            'parent' => (string) $this
        ]);

        return $execution;
    }

public
function
createExecution
(
$
concurrent
=
true
)
{
$
execution
=
new
static
(
UUID
::
createRandom
(
)
,
$
this
->
engine
,
$
this
->
model
,
$
this
)
;
$
execution
->
setNode
(
$
this
->
node
)
;
if
(
$
concurrent
)
{
$
execution
->
state
|=
self
::
STATE_CONCURRENT
;
}
$
this
->
engine
->
registerExecution
(
$
execution
)
;
$
this
->
engine
->
debug
(
sprintf
(
'Created %s{execution} from {parent}'
,
$
concurrent
'concurrent '
:
''
)
,
[
'execution'
=>
(
string
)
$
execution
,
'parent'
=>
(
string
)
$
this
]
)
;
return
$
execution
;
}

Create a new child execution and register it with the process engine.

Created executions are unscoped by default.

@param boolean $concurrent
@return Execution

Create a new child execution and register it with the process engine .


public function createNestedExecution(ProcessModel $model, Node $startNode, $isScope = true, $isScopeRoot = false)
    {
        $execution = new static(UUID::createRandom(), $this->engine, $model, $this);
        $execution->setNode($startNode);
        $execution->setState(self::STATE_SCOPE, $isScope);
        $execution->setState(self::STATE_SCOPE_ROOT, $isScopeRoot);

        $this->engine->registerExecution($execution);

        $this->engine->debug('Created nested {execution} from {parent}', [
            'execution' => (string) $execution,
            'parent' => (string) $this
        ]);

        return $execution;
    }

Create a nested execution as child execution.

@param ProcessModel $model
@param Node $startNode
@param boolean $isScope
@param boolean $isScopeRoot
@return Execution

Create a nested execution as child execution .


public function findChildExecutions(Node $node = null)
    {
        if ($node === null) {
            return $this->childExecutions;
        }

        return array_filter($this->childExecutions, function (Execution $execution) use ($node) {
            return $execution->getNode() === $node;
        });
    }

public function findChildExecutions ( Node $ node = null ) { if ( $ node === null ) { return $ this -> childExecutions ; } return array_filter ( $ this -> childExecutions , function ( Execution $ execution ) use ( $ node ) { return $ execution -> getNode ( ) === $ node ; } ) ; }

Find all child executions.

@param Node $node Optional filter, return only executions that have arrived at the given node.
@return array<Execution> All matching child executions.


protected function computeVariables()
    {
        if ($this->isScopeRoot()) {
            return $this->variables;
        }

        if ($this->isScope()) {
            return array_merge($this->parentExecution->computeVariables(), $this->variables);
        }

        return $this->parentExecution->computeVariables();
    }

protected function computeVariables ( ) { if ( $ this -> isScopeRoot ( ) ) { return $ this -> variables ; } if ( $ this -> isScope ( ) ) { return array_merge ( $ this -> parentExecution -> computeVariables ( ) , $ this -> variables ) ; } return $ this -> parentExecution -> computeVariables ( ) ; }

Fetch all variables visible to the execution.

@return array<string, mixed>

Fetch all variables visible to the execution .


public function getVariable($name)
    {
        $vars = $this->computeVariables();

        if (array_key_exists($name, $vars)) {
            return $vars[$name];
        }

        if (func_num_args() > 1) {
            return func_get_arg(1);
        }

        throw new \OutOfBoundsException(sprintf('Variable "%s" neighter set nor inherited in scope %s', $name, $this));
    }

Get the value of the given variable eighter from the current scope or inherited.

@param string $name
@param mixed $default
@return mixed

@throws \OutOfBoundsException When the variable is not set and no default value is given.

Get the value of the given variable eighter from the current scope or inherited .


public function getVariableLocal($name)
    {
        $vars = $this->getScope()->variables;

        if (array_key_exists($name, $vars)) {
            return $vars[$name];
        }

        if (func_num_args() > 1) {
            return func_get_arg(1);
        }

        throw new \OutOfBoundsException(sprintf('Variable "%s" not found in scope %s', $name, $this));
    }

public
function
getVariableLocal
(
$
name
)
{
$
vars
=
$
this
->
getScope
(
)
->
variables
;
if
(
array_key_exists
(
$
name
,
$
vars
)
)
{
return
$
vars
[
$
name
]
;
}
if
(
func_num_args
(
)
>
1
)
{
return
func_get_arg
(
1
)
;
}
throw
new
\
OutOfBoundsException
(
sprintf
(
'Variable "%s" not found in scope %s'
,
$
name
,
$
this
)
)
;
}

Get the value of the given variable in the current scope.

@param string $name
@param mixed $default
@return mixed

@throws \OutOfBoundsException When the variable is not set and no default value is given.

Get the value of the given variable in the current scope .


public function setVariable($name, $value)
    {
        if ($value === null) {
            return $this->removeVariable($name);
        }

        return $this->getScopeRoot()->setVariableLocal($name, $value);
    }

public function setVariable ( $ name , $ value ) { if ( $ value === null ) { return $ this -> removeVariable ( $ name ) ; } return $ this -> getScopeRoot ( ) -> setVariableLocal ( $ name , $ value ) ; }

Set the given variable in the scope root, passing a value of null will remove the variable.

@param string $name
@param mixed $value

Set the given variable in the scope root passing a value of null will remove the variable .


public function setVariableLocal($name, $value)
    {
        if (!$this->isScope()) {
            return $this->getScope()->setVariableLocal($name, $value);
        }

        if ($value === null) {
            unset($this->variables[(string) $name]);
        } else {
            $this->variables[(string) $name] = $value;
        }

        $this->markModified();
    }

public function setVariableLocal ( $ name , $ value ) { if ( ! $ this -> isScope ( ) ) { return $ this -> getScope ( ) -> setVariableLocal ( $ name , $ value ) ; } if ( $ value === null ) { unset ( $ this -> variables [ ( string ) $ name ] ) ; } else { $ this -> variables [ ( string ) $ name ] = $ value ; } $ this -> markModified ( ) ; }

Set the given variable in the current scope, setting a variable to a value of null will
remove the variable from the current scope.

@param string $name
@param mixed $value

Set the given variable in the current scope setting a variable to a value of null will remove the variable from the current scope .


public function removeVariable($name)
    {
        $exec = $this;

        while ($exec !== null) {
            if ($exec->isScope()) {
                $exec->removeVariableLocal($name);
            }

            if ($exec->isScopeRoot()) {
                break;
            }

            $exec = $exec->getParentExecution();
        }
    }

public function removeVariable ( $ name ) { $ exec = $ this ; while ( $ exec !== null ) { if ( $ exec -> isScope ( ) ) { $ exec -> removeVariableLocal ( $ name ) ; } if ( $ exec -> isScopeRoot ( ) ) { break ; } $ exec = $ exec -> getParentExecution ( ) ; } }

Remove a variable, will remove the variable from all parent scopes up to the scope root.

@param string $name

Remove a variable will remove the variable from all parent scopes up to the scope root .


public function removeVariableLocal($name)
    {
        if (!$this->isScope()) {
            return $this->getScope()->removeVariableLocal($name);
        }

        unset($this->variables[(string) $name]);

        $this->markModified();
    }

public function removeVariableLocal ( $ name ) { if ( ! $ this -> isScope ( ) ) { return $ this -> getScope ( ) -> removeVariableLocal ( $ name ) ; } unset ( $ this -> variables [ ( string ) $ name ] ) ; $ this -> markModified ( ) ; }

Remove the given variable from the current scope.

@param string $name

Remove the given variable from the current scope .


public function execute(Node $node)
    {
        if ($this->isTerminated()) {
            throw new \RuntimeException(sprintf('%s is terminated', $this));
        }

        $this->engine->pushCommand($this->engine->createExecuteNodeCommand($this, $node));
    }

public
function
execute
(
Node
$
node
)
{
if
(
$
this
->
isTerminated
(
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'%s is terminated'
,
$
this
)
)
;
}
$
this
->
engine
->
pushCommand
(
$
this
->
engine
->
createExecuteNodeCommand
(
$
this
,
$
node
)
)
;
}

Register commands to execute the behavior of the given node.

@param Node $node

@throws \RuntimeException When the execution has been terminated.

Register commands to execute the behavior of the given node .


public function waitForSignal()
    {
        if ($this->isTerminated()) {
            throw new \RuntimeException(sprintf('Terminated %s cannot enter wait state', $this));
        }

        $this->timestamp = microtime(true);
        $this->setState(self::STATE_WAIT, true);

        $this->engine->debug('{execution} entered wait state', [
            'execution' => (string) $this
        ]);

        $this->markModified();
    }

public
function
waitForSignal
(
)
{
if
(
$
this
->
isTerminated
(
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'Terminated %s cannot enter wait state'
,
$
this
)
)
;
}
$
this
->
timestamp
=
microtime
(
true
)
;
$
this
->
setState
(
self
::
STATE_WAIT
,
true
)
;
$
this
->
engine
->
debug
(
'{execution} entered wait state'
,
[
'execution'
=>
(
string
)
$
this
]
)
;
$
this
->
markModified
(
)
;
}

Put the execution into a wait state.

@throws \RuntimeException When the execution has been terminated.


public function signal($signal = null, array $variables = [], array $delegation = [])
    {
        if ($this->isTerminated()) {
            throw new \RuntimeException(sprintf('Cannot signal terminated %s', $this));
        }

        if (!$this->isWaiting()) {
            throw new \RuntimeException(sprintf('%s is not in a wait state', $this));
        }

        $this->engine->pushCommand($this->engine->createSignalExecutionCommand($this, $signal, $variables, $delegation));
    }

public
function
signal
(
$
signal
=
,
array
$
variables
=
[
]
,
array
$
delegation
=
[
]
)
{
if
(
$
this
->
isTerminated
(
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'Cannot signal terminated %s'
,
$
this
)
)
;
}
if
(
!
$
this
->
isWaiting
(
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'%s is not in a wait state'
,
$
this
)
)
;
}
$
this
->
engine
->
pushCommand
(
$
this
->
engine
->
createSignalExecutionCommand
(
$
this
,
$
signal
,
$
variables
,
$
delegation
)
)
;
}

Signal the execution in order to continue from a wait state.

@param string $signal The name of the signal or null when no such name exists.
@param array<string, mixed> $variables Signal data.
@param array<string, mixed> $delegation Signal delegation data.

@throws \RuntimeException When the execution is terminated or not within a wait state.

Signal the execution in order to continue from a wait state .


public function take($transition = null)
    {
        if ($this->isTerminated()) {
            throw new \RuntimeException(sprintf('Cannot take transition in terminated %s', $this));
        }

        if ($transition !== null && !$transition instanceof Transition) {
            $transition = $this->model->findTransition($transition);
        }

        $this->engine->pushCommand($this->engine->createTakeTransitionCommand($this, $transition));
    }

Take a transition from the given node.

@param string $transition ID of the transition, ommitting it will assume a single outgoing transition.

@throws \RuntimeException When the execution has been terminated.


public function introduceConcurrentRoot($active = false)
    {
        $this->engine->debug('Introducing concurrent root into {execution}', [
            'execution' => (string) $this
        ]);

        $parent = $this->parentExecution;

        $root = new static(UUID::createRandom(), $this->engine, $this->model, $parent);
        $root->setActive($active);
        $root->variables = $this->variables;
        $root->setState(self::STATE_SCOPE, $this->isScope());

        if ($parent !== null) {
            foreach ($parent->childExecutions as $index => $exec) {
                if ($exec === $this) {
                    unset($parent->childExecutions[$index]);
                }
            }
        }

        $this->setParentExecution($root);
        $this->setState(self::STATE_CONCURRENT, true);
        $this->setState(self::STATE_SCOPE, false);
        $this->variables = [];

        $this->markModified();

        $this->engine->registerExecution($root);

        return $root;
    }

Introduce a new concurrent root as parent of this execution.

@param boolean $active
@return Execution

Introduce a new concurrent root as parent of this execution .


public static function loadMessage($messageFile, $packageName = "")
    {
        if (isset($messageFile) && $messageFile != "") {

            // message file location order
            // 1. OPENBIZ_APP_MESSAGE_PATH."/".$messageFile
            // 2. OPENBIZ_APP_MODULE_PATH . "/$moduleName/message/" . $messageFile;
            // 3. CORE_OPENBIZ_APP_MODULE_PATH . "/$moduleName/message/" . $messageFile;
            // OPENBIZ_APP_PATH / OPENBIZ_APP_MESSAGE_PATH : OPENBIZ_APP_PATH / messages
            if (is_file(OPENBIZ_APP_MESSAGE_PATH . "/" . $messageFile)) {
                return parse_ini_file(OPENBIZ_APP_MESSAGE_PATH . "/" . $messageFile);
            } else if (is_file(OPENBIZ_APP_MODULE_PATH . "/" . $messageFile)) {
                return parse_ini_file(OPENBIZ_APP_MODULE_PATH . "/" . $messageFile);
            } else {
                if (isset($packageName) && $packageName != "") {
                    $dirs = explode('.', $packageName);
                    $moduleName = $dirs[0];
                    $msgFile = OPENBIZ_APP_MODULE_PATH . "/$moduleName/message/" . $messageFile;
                    if (is_file($msgFile)) {
                        return parse_ini_file($msgFile);
                    } else {
                        $errmsg = self::getMessage("SYS_ERROR_INVALID_MSGFILE", array($msgFile));
                        trigger_error($errmsg, E_USER_ERROR);
                    }
                } else {
                    $errmsg = self::getMessage("SYS_ERROR_INVALID_MSGFILE", array(OPENBIZ_APP_MESSAGE_PATH . "/" . $messageFile));
                    trigger_error($errmsg, E_USER_ERROR);
                }
            }
        }
        return null;
    }

Load message from file

@param string $messageFile
@return mixed


public static function getMessage($msgId, $params = array())
    {
        $message = constant($msgId);
        if (isset($message)) {
            $message = I18n::t($message, $msgId, 'system');
            $result = vsprintf($message, $params);
        }
        return $result;
    }

public static function getMessage ( $ msgId , $ params = array ( ) ) { $ message = constant ( $ msgId ) ; if ( isset ( $ message ) ) { $ message = I18n :: t ( $ message , $ msgId , 'system' ) ; $ result = vsprintf ( $ message , $ params ) ; } return $ result ; }

Get message from CONSTANT, translate and format it
@param string $msgId ID if constant
@param array $params parameter for format (use vsprintf)
@return string

Get message from CONSTANT translate and format it


public static function getZendTemplate()
    {
        $view = new \Zend_View();
        if (defined('SMARTY_TPL_PATH')) {
            $view->setScriptPath(SMARTY_TPL_PATH);
        }

        $theme = Resource::getCurrentTheme();

        // load the config file which has the images and css url defined
        $view->app_url = OPENBIZ_APP_URL;
        $view->app_index = OPENBIZ_APP_INDEX_URL;
        $view->js_url = OPENBIZ_JS_URL;
        $view->css_url = OPENBIZ_THEME_URL . "/" . $theme . "/css";
        $view->resource_url = OPENBIZ_RESOURCE_URL;
        $view->theme_js_url = OPENBIZ_THEME_URL . "/" . $theme . "/js";
        $view->theme_url = OPENBIZ_THEME_URL . "/" . $theme;
        $view->image_url = OPENBIZ_THEME_URL . "/" . $theme . "/images";
        $view->lang = strtolower(I18n::getCurrentLangCode());

        return $view;
    }

Get \Zend Template
@return \Zend_View zend view template object


public static function readableDirectory($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty path given.");
        }

        if (!is_dir($value)) {
            throw new \InvalidArgumentException("Given path is not a regular directory.");
        }

        if (!is_readable($value)) {
            throw new \InvalidArgumentException("Given directory is not readable.");
        }

        return $value;
    }

Validates the given path and throws an exception
if it is not a regular directory or readable.

@param string $value value to check

@return string path to valid directory

@throws \InvalidArgumentException in case of validation errors (empty value, irregular or non-readable directory)

Validates the given path and throws an exception if it is not a regular directory or readable .


public static function writableDirectory($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty path given.");
        }

        if (!is_dir($value)) {
            throw new \InvalidArgumentException("Given path is not a regular directory.");
        }

        if (!is_writable($value)) {
            throw new \InvalidArgumentException("Given directory is not writable.");
        }

        return $value;
    }

Validates the given path and throws an exception
if it is not a regular directory or writable.

@param string $value value to check

@return string path to valid directory

@throws \InvalidArgumentException in case of validation errors (empty value, irregular or non-writable directory)

Validates the given path and throws an exception if it is not a regular directory or writable .


public static function writableFile($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty file path given.");
        }

        if (!is_file($value)) {
            throw new \InvalidArgumentException("Given file path is not a regular file.");
        }

        if (!is_writable($value)) {
            throw new \InvalidArgumentException("Given file is not writable.");
        }

        return $value;
    }

Validates the given file path and throws an exception
if it is not a regular file or writable.

@param string $value value to check

@return string path to valid file

@throws \InvalidArgumentException in case of validation errors (empty value or irregular or non-writable file)

Validates the given file path and throws an exception if it is not a regular file or writable .


public static function readableFile($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty file path given.");
        }

        if (!is_file($value)) {
            throw new \InvalidArgumentException("Given file path is not a regular file.");
        }

        if (!is_readable($value)) {
            throw new \InvalidArgumentException("Given file is not readable.");
        }

        return $value;
    }

Validates the given file path and throws an exception
if it is not a regular file or readable.

@param string $value value to check

@return string path to valid file

@throws \InvalidArgumentException in case of validation errors (empty value or irregular or non-readable file)

Validates the given file path and throws an exception if it is not a regular file or readable .


public static function validEmail($value)
    {
        if (is_object($value) || empty($value)) {
            throw new \InvalidArgumentException("Empty email given.");
        }

        if (!filter_var((string)$value, FILTER_VALIDATE_EMAIL)) {
            throw new \InvalidArgumentException("Invalid email address given.");
        }

        return $value;
    }

public
static
function
validEmail
(
$
value
)
{
if
(
is_object
(
$
value
)
||
empty
(
$
value
)
)
{
throw
new
\
InvalidArgumentException
(
"Empty email given."
)
;
}
if
(
!
filter_var
(
(
string
)
$
value
,
FILTER_VALIDATE_EMAIL
)
)
{
throw
new
\
InvalidArgumentException
(
"Invalid email address given."
)
;
}
return
$
value
;
}

Validates the given value using the PHP filter_var
with FILTER_VALIDATE_EMAIL option.

@param string $value value to check

@return string email

@throws \InvalidArgumentException in case of validation errors (invalid or empty email)

Validates the given value using the PHP filter_var with FILTER_VALIDATE_EMAIL option .


public static function validIp($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty IP address given.");
        }

        if (!filter_var($value, FILTER_VALIDATE_IP)) {
            throw new \InvalidArgumentException("Invalid IP address given.");
        }

        return $value;
    }

public
static
function
validIp
(
$
value
)
{
if
(
empty
(
$
value
)
)
{
throw
new
\
InvalidArgumentException
(
"Empty IP address given."
)
;
}
if
(
!
filter_var
(
$
value
,
FILTER_VALIDATE_IP
)
)
{
throw
new
\
InvalidArgumentException
(
"Invalid IP address given."
)
;
}
return
$
value
;
}

Validates the given value using the PHP filter_var with
FILTER_VALIDATE_IP.

@param string $value IP to validate

@return string ipv4 or ipv6 (may still be in private or reserved range)

@throws \InvalidArgumentException in case of validation errors (invalid or empty ip)

Validates the given value using the PHP filter_var with FILTER_VALIDATE_IP .


public static function validIpv4($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty IPv4 address given.");
        }

        if (!filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
            throw new \InvalidArgumentException("Invalid IPv4 address given.");
        }

        return $value;
    }

public
static
function
validIpv4
(
$
value
)
{
if
(
empty
(
$
value
)
)
{
throw
new
\
InvalidArgumentException
(
"Empty IPv4 address given."
)
;
}
if
(
!
filter_var
(
$
value
,
FILTER_VALIDATE_IP
,
FILTER_FLAG_IPV4
)
)
{
throw
new
\
InvalidArgumentException
(
"Invalid IPv4 address given."
)
;
}
return
$
value
;
}

Validates the given value using the PHP filter_var with
FILTER_VALIDATE_IP and flag FILTER_FLAG_IPV4.

@param string $value IP to validate

@return string ipv4 (may still be in private or reserved range)

@throws \InvalidArgumentException in case of validation errors (invalid or empty ip)

Validates the given value using the PHP filter_var with FILTER_VALIDATE_IP and flag FILTER_FLAG_IPV4 .


public static function validIpv4NotReserved($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty IPv4 address given.");
        }

        if (!filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE)) {
            throw new \InvalidArgumentException(
                "Invalid IPv4 address given. Reserved ranges like 240.0.0.0/4 are disallowed."
            );
        }

        return $value;
    }

Validates the given value using the PHP filter_var with
FILTER_VALIDATE_IP and flag FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE.

@param string $value IP to validate

@return string ipv4 (may still be in private range)

@throws \InvalidArgumentException in case of validation errors (invalid or empty ip)

Validates the given value using the PHP filter_var with FILTER_VALIDATE_IP and flag FILTER_FLAG_IPV4 | FILTER_FLAG_NO_RES_RANGE .


public static function validIpv6($value)
    {
        if (empty($value)) {
            throw new \InvalidArgumentException("Empty IPv6 address given.");
        }

        if (!filter_var($value, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
            throw new \InvalidArgumentException("Invalid IPv6 address given.");
        }

        return $value;
    }

public
static
function
validIpv6
(
$
value
)
{
if
(
empty
(
$
value
)
)
{
throw
new
\
InvalidArgumentException
(
"Empty IPv6 address given."
)
;
}
if
(
!
filter_var
(
$
value
,
FILTER_VALIDATE_IP
,
FILTER_FLAG_IPV6
)
)
{
throw
new
\
InvalidArgumentException
(
"Invalid IPv6 address given."
)
;
}
return
$
value
;
}

Validates the given value using the PHP filter_var with
FILTER_VALIDATE_IP and flag FILTER_FLAG_IPV6

@param string $value IP to validate

@return string ipv6 (may still be in private or reserved range)

@throws \InvalidArgumentException in case of validation errors (invalid or empty ip)


protected function initializeView(ViewInterface $view) {
    $configurationManager = $this->objectManager->get(ConfigurationManager::class);
    $data                 = $configurationManager->getContentObject()->data;

    $this->view->assign('data', $data);
  }

protected function initializeView ( ViewInterface $ view ) { $ configurationManager = $ this -> objectManager -> get ( ConfigurationManager :: class ) ; $ data = $ configurationManager -> getContentObject ( ) -> data ; $ this -> view -> assign ( 'data' , $ data ) ; }

Initialises a view.

@param \TYPO3\CMS\Extbase\Mvc\View\ViewInterface $view The view


public static function hasAttribute(string $className, string $name): bool
    {
        return in_array($name, static::attributes($className));
    }

public static function hasAttribute ( string $ className , string $ name ) : bool { return in_array ( $ name , static :: attributes ( $ className ) ) ; }

Checks to see if the given attribute is in the list of public attributes.

@param string $className
@param string $name
@return bool

Checks to see if the given attribute is in the list of public attributes .


public static function hasMethod(string $className, string $name): bool
    {
        return in_array($name, static::methods($className));
    }

public static function hasMethod ( string $ className , string $ name ) : bool { return in_array ( $ name , static :: methods ( $ className ) ) ; }

Checks to see if the given method is in the list of public class methods.

@param string $className
@param string $name
@return bool

Checks to see if the given method is in the list of public class methods .


public static function getMethodParameters($instance, string $method)
    {
        try {
            if (! is_callable([$instance, $method])) {
                return false;
            }

            $reflection = static::getReflectionMethod($instance, $method);
            if ($reflection instanceof ReflectionMethod === false) {
                return false;
            }

            $params = [];
            foreach ($reflection->getParameters() as $param) {
                $params[$param->getName()] = $param->isDefaultValueAvailable() ? $param->getDefaultValue() : null;
            }
            return $params;

        } catch (ReflectionException $e) {}
    }

public static function getMethodParameters ( $ instance , string $ method ) { try { if ( ! is_callable ( [ $ instance , $ method ] ) ) { return false ; } $ reflection = static :: getReflectionMethod ( $ instance , $ method ) ; if ( $ reflection instanceof ReflectionMethod === false ) { return false ; } $ params = [ ] ; foreach ( $ reflection -> getParameters ( ) as $ param ) { $ params [ $ param -> getName ( ) ] = $ param -> isDefaultValueAvailable ( ) ? $ param -> getDefaultValue ( ) : null ; } return $ params ; } catch ( ReflectionException $ e ) { } }

Returns an array of parameter names for the given method instance.

@param $instance
@param string $method
@return array|bool

Returns an array of parameter names for the given method instance .


public static function getReflectionMethod($object, string $method)
    {
        assert(is_object($object));

        if (method_exists($object, $method)) {
            return new ReflectionMethod($object, $method);
        }

        // if method does not exist, but it is callable, that means it has a magic caller.
        if (! is_callable([$object, $method])) {
            return false;
        }

        // it is not easy to detect each implementation of __call or __callStatic automatically.
        foreach (static::$customReflections as $className => $callback) {
            if (is_a($object, $className)) {
                return $callback($object, $method);
                break;
            }
        }

        return false;
    }

Tries to find the correct reflection method.

@throws \ReflectionException

@param object $object
@param string $method
@return bool|\ReflectionMethod

Tries to find the correct reflection method .


public function toArray(array $fields = [], array $expand = [], $recursive = true)
    {
        $array = [];

        foreach ($this->data as $key => $value) {
            if ($recursive && is_array($value)) {
                $array[$key] = (new ArrayObject($value))->toArray([], [], $recursive);
            } else {
                $array[$key] = $value;
            }
        }

        return $array;
    }

public function toArray ( array $ fields = [ ] , array $ expand = [ ] , $ recursive = true ) { $ array = [ ] ; foreach ( $ this -> data as $ key => $ value ) { if ( $ recursive && is_array ( $ value ) ) { $ array [ $ key ] = ( new ArrayObject ( $ value ) ) -> toArray ( [ ] , [ ] , $ recursive ) ; } else { $ array [ $ key ] = $ value ; } } return $ array ; }

Converts the object into an array.

@param array   $fields    the fields that the output array should contain. Fields not specified
in [[fields()]] will be ignored. If this parameter is empty, all fields as specified
in
[[fields()]] will be returned.
@param array   $expand    the additional fields that the output array should contain.
Fields not specified in [[extraFields()]] will be ignored. If this parameter is empty,
no extra fields will be returned.
@param boolean $recursive whether to recursively return array representation of embedded objects.

@return array the array representation of the object


public function getResponse($recipient, $message)
    {
        $message = json_encode(array(
            'message' => urlencode($message),
            'sms' => array($recipient)
        ));

        $fields = array(
            'clientcode'    => urlencode($this->login),
            'passcode'      => urlencode($this->password),
            'smsData'       => urlencode($message),
        );

        $fieldsString = '';

        foreach($fields as $key => $value) {
            $fieldsString .= $key.'='.$value.'&';
        }

        rtrim($fieldsString, '&');

        $response = $this->httpClient->post('http://api.msinnovations.com/http/sendSms_v8.php', array(
            'body' => $fieldsString
        ));

        return $response->json();
    }

Will perform the message send. Will return anyhow an array with the response

@param string $recipient
@param string $message

@return array

Will perform the message send . Will return anyhow an array with the response


private function getBlankLine(int $count = null):string
    {
        $out = "";
        for ($i = 0; $i < ($count ?: 1); $i++) {
            $out .= $this->getLine('');
        }
        return $out;
    }

private function getBlankLine ( int $ count = null ) : string { $ out = "" ; for ( $ i = 0 ; $ i < ( $ count ? : 1 ) ; $ i ++ ) { $ out .= $ this -> getLine ( '' ) ; } return $ out ; }

Returns a blank line.

@param int $count Number of lines to be returned
@return string


private function countTermCols():int
    {
        if (!$this->termCols) {
            if (!($this->termCols = (int)exec('tput cols'))) {
                $this->termCols = 80;
            }
        }
        return $this->termCols;
    }

private
function
countTermCols
(
)
:
int
{
if
(
!
$
this
->
termCols
)
{
if
(
!
(
$
this
->
termCols
=
(
int
)
exec
(
'tput cols'
)
)
)
{
$
this
->
termCols
=
80
;
}
}
return
$
this
->
termCols
;
}

Returns the number of columns in the terminal windows.

@return int

Returns the number of columns in the terminal windows .


private function getErrorBlock(\Throwable $exception, ?int $linePadding = null):string
    {
        // Renders the message
        $out = $this->getLine(get_class($exception), self::STYLE_BOLD | self::STYLE_ITALIC, $linePadding)
            .$this->getLine($exception->getMessage(), null, $linePadding);

        // Renders the position
        if ($this->options & self::OPT_RENDER_LOCATION) {
            $out .= $this->getLine($exception->getFile().':'.$exception->getLine(),
                    self::STYLE_ITALIC, $linePadding)
                .$this->getBlankLine();
        }

        // Renders the backtrace
        if ($this->options & self::OPT_RENDER_BACKTRACE) {
            $out .= $this->getLine("Backtrace",
                    self::STYLE_BOLD | self::STYLE_ITALIC,$linePadding + 2)
                .$this->getLine($exception->getTraceAsString(),
                    self::STYLE_ITALIC, $linePadding + 2);
        }

        return $out;
    }

private
function
getErrorBlock
(
\
Throwable
$
exception
,
int
$
linePadding
=
)
:
string
{
// Renders the message
$
out
=
$
this
->
getLine
(
get_class
(
$
exception
)
,
self
::
STYLE_BOLD
|
self
::
STYLE_ITALIC
,
$
linePadding
)
.
$
this
->
getLine
(
$
exception
->
getMessage
(
)
,
,
$
linePadding
)
;
// Renders the position
if
(
$
this
->
options
&
self
::
OPT_RENDER_LOCATION
)
{
$
out
.=
$
this
->
getLine
(
$
exception
->
getFile
(
)
.
':'
.
$
exception
->
getLine
(
)
,
self
::
STYLE_ITALIC
,
$
linePadding
)
.
$
this
->
getBlankLine
(
)
;
}
// Renders the backtrace
if
(
$
this
->
options
&
self
::
OPT_RENDER_BACKTRACE
)
{
$
out
.=
$
this
->
getLine
(
"Backtrace"
,
self
::
STYLE_BOLD
|
self
::
STYLE_ITALIC
,
$
linePadding
+
2
)
.
$
this
->
getLine
(
$
exception
->
getTraceAsString
(
)
,
self
::
STYLE_ITALIC
,
$
linePadding
+
2
)
;
}
return
$
out
;
}

Returns an error block.

@param \Throwable $exception
@param int|null $linePadding
@return string