public function callClassAndMethodWithInputArguments(
        $class,
        $method,
        \Mmf\IO\RequestInterface $request
    ) {
        $params = $this->getFunctionArguments($class, $method);

        $listOfParams = [];
        foreach ($params as $param) {
            $paramValue = $request->input($param['name']);
            if ($paramValue === null && $param['isOptional'] === false) {
                throw new ControllerException('The param ' . $param['name'] . ' is mandatory', 1501);
            } elseif ($paramValue === null && $param['isOptional'] === true) {
                $paramValue = $param['initialValue'];
            }
            $listOfParams[] = $paramValue;
        }
        if (!is_object($class)) {
            $class = new $class();
        }
        $returnOfAction = call_user_func_array(array($class, $method), $listOfParams);
        if ($returnOfAction !== false) {
            return $returnOfAction;
        } else {
            throw new \Mmf\Core\CoreException('FrontController::callClassAndMethodWithInputArguments'
            . ', Is not unable to call the action (' . $method . ') with '
            . 'the parameters(' . print_r($listOfParams, true) . '), the expected name of parameters are'
            . '(' . print_r($params, true) . ')');
        }
    }

Call a class and a method trying to pass the method recive in the request.
If the request doesn't have the parameters, it is set to false.

@param string | object      $class to call the method
@param string               $method to be call
@param \RequestInterface $request

@return mixed

@throws \ControllerException
@throws \CoreException

Call a class and a method trying to pass the method recive in the request . If the request doesn t have the parameters it is set to false .


public function getFunctionArguments($class, $method) {

        $ReflectionMethod = new \ReflectionMethod($class, $method);

        $paramsArray = array();
        foreach ($ReflectionMethod->getParameters() as $param) {
            $auxParam = array('name' => $param->getName(), 'isOptional' => false, 'initialValue' => null);
            if ($param->isOptional()) {
                $auxParam['isOptional'] = true;
                $auxParam['initialValue'] = $param->getDefaultValue();
            }
            $paramsArray[] = $auxParam;
        }
        return $paramsArray;
    }

public function getFunctionArguments ( $ class , $ method ) { $ ReflectionMethod = new \ ReflectionMethod ( $ class , $ method ) ; $ paramsArray = array ( ) ; foreach ( $ ReflectionMethod -> getParameters ( ) as $ param ) { $ auxParam = array ( 'name' => $ param -> getName ( ) , 'isOptional' => false , 'initialValue' => null ) ; if ( $ param -> isOptional ( ) ) { $ auxParam [ 'isOptional' ] = true ; $ auxParam [ 'initialValue' ] = $ param -> getDefaultValue ( ) ; } $ paramsArray [ ] = $ auxParam ; } return $ paramsArray ; }

This function returns the arguments of the method in class send it in the
parameters.

@param string | object $class
@param string $method
@return array of parameters <'name', 'isOptional', 'initialValue'>

This function returns the arguments of the method in class send it in the parameters .


public function getRoleAndUserFromToken($token) {
        $sql = 'SELECT
                    user.username,
                    user.id_user,
                    role.name,
                    role.id_role,
                    role.id_parent,
                    NOW() AS db_date,
                    token.expire
                FROM
                    role
                        INNER JOIN
                    user ON user.id_role = role.id_role
                        INNER JOIN
                    token ON user.id_user = token.id_user
                WHERE token.token="'.$token.'"
                 ';
        $role = $this->select($sql);
        if(is_array($role) && count($role)>0) {
            return $role[0];
        } else {
            return false;
        }
    }

Return the role and user attributes from the given token.

@param string $token
@return boolean

Return the role and user attributes from the given token .


public function getRoleAndUserFromIdUser($userId) {
        $sql = 'SELECT
                    user.username,
                    user.id_user,
                    role.name,
                    role.id_role,
                    role.id_parent,
                    NOW() AS db_date
                FROM
                    role
                        INNER JOIN
                    user ON user.id_role = role.id_role
                WHERE user.id_user="'.$userId.'"
                 ';
        $role = $this->select($sql);
        if(is_array($role) && count($role)>0) {
            return $role[0];
        } else {
            return false;
        }
    }

Return user information given id user.

@param int $userId

@return array


protected function getCurrentOptions()
    {
        $value = Html::getAttributeValue($this->model, $this->attribute);

        if (!isset($value) || empty($value)) {
            return [];
        }

        if (!empty($this->current)) {
            return $this->current;
        }

        if ($this->getHasId()) {
            if (!is_scalar($value)) {
                Yii::error('When Combo has ID, property $current must be set manually, or attribute value must be a scalar. Value ' . var_export($value, true) . ' is not a scalar.', __METHOD__);
                return [];
            }

            return [$value => $value];
        } else {
            if (is_array($value)) {
                return array_combine(array_values($value), array_values($value));
            }

            return [$value => $value];
        }
    }

Method collects list of options that will be rendered inside the `select` tag.
@return array

Method collects list of options that will be rendered inside the select tag .


protected function setBulkOfInputGivenArray($arrayOfParameters) {
        if(is_array($arrayOfParameters)) {
            foreach ($arrayOfParameters as $nameOfParameter => $valueOfParameter) {
                $this->setInput($nameOfParameter, $valueOfParameter);
            }
        }
    }

protected function setBulkOfInputGivenArray ( $ arrayOfParameters ) { if ( is_array ( $ arrayOfParameters ) ) { foreach ( $ arrayOfParameters as $ nameOfParameter => $ valueOfParameter ) { $ this -> setInput ( $ nameOfParameter , $ valueOfParameter ) ; } } }

Set a bulk of input parameters from and array.

@param array $arrayOfParameters

Set a bulk of input parameters from and array .


public function input($varName) {
        if (isset($this->parameters[$varName])) {
            return $this->filterVar($this->parameters[$varName]);
        } else {
            return null;
        }
    }

public function input ( $ varName ) { if ( isset ( $ this -> parameters [ $ varName ] ) ) { return $ this -> filterVar ( $ this -> parameters [ $ varName ] ) ; } else { return null ; } }

Get the input var.

@param string $varName name of the var to retrive the value.
@return mixed input


public function filterVar($var) {
        $response = NULL;
        if (is_bool($var)) {
            $response = $var;
        } elseif(is_int($var)) {
            $response = $var;
        } elseif(is_float($var)) {
            $response = $var;
        }
        if($var != 'null') {
            if(is_string($var)) {
                $response = filter_var($var, FILTER_SANITIZE_SPECIAL_CHARS);
            } elseif(is_array($var)) {
                $response = array();
                foreach ($var as $key => $value) {
                    if(is_array($value)) {
                        $response[$key] = $this->filterVar($value);
                    } else {
                        $response[$key] = filter_var($value, FILTER_SANITIZE_SPECIAL_CHARS);
                    }
                }
            }
        }
        return $response;

    }

public function filterVar ( $ var ) { $ response = NULL ; if ( is_bool ( $ var ) ) { $ response = $ var ; } elseif ( is_int ( $ var ) ) { $ response = $ var ; } elseif ( is_float ( $ var ) ) { $ response = $ var ; } if ( $ var != 'null' ) { if ( is_string ( $ var ) ) { $ response = filter_var ( $ var , FILTER_SANITIZE_SPECIAL_CHARS ) ; } elseif ( is_array ( $ var ) ) { $ response = array ( ) ; foreach ( $ var as $ key => $ value ) { if ( is_array ( $ value ) ) { $ response [ $ key ] = $ this -> filterVar ( $ value ) ; } else { $ response [ $ key ] = filter_var ( $ value , FILTER_SANITIZE_SPECIAL_CHARS ) ; } } } } return $ response ; }

Function to filter the input var. Is it define as public to replicate
the logic for every var that you want.

@param string $var
@return mixed sanitize var

Function to filter the input var . Is it define as public to replicate the logic for every var that you want .


public function openConnection($name='db_default') {
        foreach ($this->connections as $connection) {
            if($connection['name'] == $name) {
                return $connection['lynk'];
            }
        }
        //Open new connection
        try {
            //Get the configuration of the connection.
            $dbConfig = $this->config->get($name);
            //Create the new connection.
            $connection = new \PDO('mysql:host=' . $dbConfig['host'] .
                                       ';port=' . $dbConfig['port'] .
                                       ';dbname=' . $dbConfig['name'],
                                   $dbConfig['user'],
                                   $dbConfig['pass'],
                                   array(\PDO::MYSQL_ATTR_FOUND_ROWS => true, \PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));

            $connection->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);

            $this->connections[] = array('name'=>$name,'lynk'=>$connection);

            return $connection;

        } catch (\Exception $e) {
            throw new ModelException('Error trying to connect to db');
        }
    }

Open connection if is not already open.

@param string $name optional parameter if nothing is send it gets
the default connection.

@return \PDO
@throws \ModelException

Open connection if is not already open .


public function closeConnection($name='db_default') {
        foreach ($this->connections as $key => $connection) {
            if($connection['name'] == $name) {
                $this->connections[$key]['lynk'] = null; //closing the connection
                array_splice($this->connections, $key, 1);
                return true;
            }
        }
        return false;
    }

public
function
closeConnection
(
$
name
=
'db_default'
)
{
foreach
(
$
this
->
connections
as
$
key
=>
$
connection
)
{
if
(
$
connection
[
'name'
]
==
$
name
)
{
$
this
->
connections
[
$
key
]
[
'lynk'
]
=
;
//closing the connection
array_splice
(
$
this
->
connections
,
$
key
,
1
)
;
return
true
;
}
}
return
false
;
}

Close connection if is still open.

@param string $name optional parameter if nothing is send it gets
the default connection.

@return bool


private function executeSQL($SQL, $parameters = null) {
        try {
            $queryPrepare = $this->connection->prepare($SQL);
            if (is_array($parameters)) {
                $queryPrepare->execute($parameters);
            } else {
                $queryPrepare->execute();
            }
        } catch (\PDOException $e) {
            throw new ModelException('Error in the Select QUERY ('.$SQL.') '
                    . 'and error message('.$e->getMessage().')');
        }
        return $queryPrepare;
    }

private
function
executeSQL
(
$
SQL
,
$
parameters
=
)
{
try
{
$
queryPrepare
=
$
this
->
connection
->
prepare
(
$
SQL
)
;
if
(
is_array
(
$
parameters
)
)
{
$
queryPrepare
->
execute
(
$
parameters
)
;
}
else
{
$
queryPrepare
->
execute
(
)
;
}
}
catch
(
\
PDOException
$
e
)
{
throw
new
ModelException
(
'Error in the Select QUERY ('
.
$
SQL
.
') '
.
'and error message('
.
$
e
->
getMessage
(
)
.
')'
)
;
}
return
$
queryPrepare
;
}

Execute SQL and return the object.

@param string $SQL
@throws ModelException


public function select($SQL, $parameters = null) {
        $queryResult = $this->executeSQL($SQL, $parameters);
        return $queryResult->fetchAll(\PDO::FETCH_ASSOC);
    }

public function select ( $ SQL , $ parameters = null ) { $ queryResult = $ this -> executeSQL ( $ SQL , $ parameters ) ; return $ queryResult -> fetchAll ( \ PDO :: FETCH_ASSOC ) ; }

Do a select query to Database and return the result in a array type.

@param string $SQL
@return array selected rows.
@throws ModelException

Do a select query to Database and return the result in a array type .


public function insert($SQL, $parameters = null) {
        $this->executeSQL($SQL, $parameters);
        return $this->connection->lastInsertId();
    }

public function insert ( $ SQL , $ parameters = null ) { $ this -> executeSQL ( $ SQL , $ parameters ) ; return $ this -> connection -> lastInsertId ( ) ; }

Do a insert query to Database and return the id of the row inserted.

@param string $SQL
@return int id of inserted row.
@throws ModelException

Do a insert query to Database and return the id of the row inserted .


public function delete($SQL, $parameters = null) {
        $queryResult = $this->executeSQL($SQL, $parameters);
        return $queryResult->rowCount();
    }

public function delete ( $ SQL , $ parameters = null ) { $ queryResult = $ this -> executeSQL ( $ SQL , $ parameters ) ; return $ queryResult -> rowCount ( ) ; }

Do a delete query to Database and return the number of deleted rows.

@param string $SQL
@return int number of deleted rows.
@throws ModelException

Do a delete query to Database and return the number of deleted rows .


public function update($SQL, $parameters = null) {
        $queryResult = $this->executeSQL($SQL, $parameters);
        return $queryResult->rowCount();
    }

public function update ( $ SQL , $ parameters = null ) { $ queryResult = $ this -> executeSQL ( $ SQL , $ parameters ) ; return $ queryResult -> rowCount ( ) ; }

Do a update query to Database and return the number of updated rows

@param string $SQL
@return int number of update rows.
@throws ModelException


public function logout() {
        $this->setUserId($this->guestUserId);
        $this->setUsername($this->guestUsername);
        $this->setRoleId($this->guestRoleId);
        $this->setRoleName($this->guestRoleName);
    }

public function logout ( ) { $ this -> setUserId ( $ this -> guestUserId ) ; $ this -> setUsername ( $ this -> guestUsername ) ; $ this -> setRoleId ( $ this -> guestRoleId ) ; $ this -> setRoleName ( $ this -> guestRoleName ) ; }


public function setUserId($userId) {
        $this->userId = $userId;
        if ($this->session !== null) {
            $this->session->set('userId', $userId);
        }
    }

public function setUserId ( $ userId ) { $ this -> userId = $ userId ; if ( $ this -> session !== null ) { $ this -> session -> set ( 'userId' , $ userId ) ; } }


public function setUsername($username) {
        $this->username = $username;
        if ($this->session !== null) {
            $this->session->set('username', $username);
        }
    }

public function setUsername ( $ username ) { $ this -> username = $ username ; if ( $ this -> session !== null ) { $ this -> session -> set ( 'username' , $ username ) ; } }

Set the username.

@param string $username


public function setRoleId($roleId) {
        $this->roleId = $roleId;
        if ($this->session !== null) {
            $this->session->set('roleId', $roleId);
        }
    }

public function setRoleId ( $ roleId ) { $ this -> roleId = $ roleId ; if ( $ this -> session !== null ) { $ this -> session -> set ( 'roleId' , $ roleId ) ; } }


public function setRoleName($roleName) {
        $this->roleName = $roleName;
        if ($this->session !== null) {
            $this->session->set('roleName', $roleName);
        }
    }

public function setRoleName ( $ roleName ) { $ this -> roleName = $ roleName ; if ( $ this -> session !== null ) { $ this -> session -> set ( 'roleName' , $ roleName ) ; } }

Set the role name

@param string $roleName


public function validate($value, Constraint $constraint)
    {
        $method = $constraint->method;
        if (!$this->getManager()->$method($value, $constraint)) {
            $this->setMessage($constraint->message, array(
                '%property%' => $constraint->property
            ));
            return false;
        }

        return true;
    }

public function validate ( $ value , Constraint $ constraint ) { $ method = $ constraint -> method ; if ( ! $ this -> getManager ( ) -> $ method ( $ value , $ constraint ) ) { $ this -> setMessage ( $ constraint -> message , array ( '%property%' => $ constraint -> property ) ) ; return false ; } return true ; }

Indicates whether the constraint is valid

@param Entity     $value
@param Constraint $constraint


public function getInstalledPlugins($path) {
        $searchPluginDirectories = $this->searchPluginDirectories($path);
        $validPluginDirectories  = array();
        $factoryPluginClasses    = array();
        foreach ($searchPluginDirectories as $pluginDirectory) {
            if (is_file($pluginDirectory. '/enable.php')) {
                $validPluginClass = $this->searchPluginFactoryClass($pluginDirectory);
                if ($validPluginClass) {
                    $validPluginDirectories[] = $pluginDirectory;
                    $factoryPluginClasses[] = $validPluginClass;
                }
            }
        }
        return array('pluginClasses'    => $factoryPluginClasses,
                     'pluginDirectories'=> $validPluginDirectories,
                     'pluginEnabled'    => true
                     );
    }

public function getInstalledPlugins ( $ path ) { $ searchPluginDirectories = $ this -> searchPluginDirectories ( $ path ) ; $ validPluginDirectories = array ( ) ; $ factoryPluginClasses = array ( ) ; foreach ( $ searchPluginDirectories as $ pluginDirectory ) { if ( is_file ( $ pluginDirectory . '/enable.php' ) ) { $ validPluginClass = $ this -> searchPluginFactoryClass ( $ pluginDirectory ) ; if ( $ validPluginClass ) { $ validPluginDirectories [ ] = $ pluginDirectory ; $ factoryPluginClasses [ ] = $ validPluginClass ; } } } return array ( 'pluginClasses' => $ factoryPluginClasses , 'pluginDirectories' => $ validPluginDirectories , 'pluginEnabled' => true ) ; }

Return all the plugin installed classes found in the concrete path.

@param string $path
@return array('pluginClasses'=>$factoryPluginClasses,'pluginDirectories'=>$validPluginDirectories)

Return all the plugin installed classes found in the concrete path .


protected function searchPluginDirectories($path) {
        $pluginDirectories = array();
        if ( ($directoryHandle = opendir($path)) == true ) {
            while (($fileOrDir = readdir( $directoryHandle )) !== false) {
                if (is_dir($path. $fileOrDir ) && $fileOrDir !== '.' && $fileOrDir !=='..') {
                    $pluginDirectories[] = $path. $fileOrDir;
                }
            }
        } else {
            throw new PluginException('Invalid plugin path, check the main config.ini file');
        }
        return $pluginDirectories;
    }

Given a path it give the directories.

@param string $path

@return array pluginDirectories
@throws \PluginException


protected function searchPluginFactoryClass($pluginDirectory) {
        foreach ($this->internalPluginStructure as $pluginStructure) {
            $path = $pluginDirectory.'/'.$pluginStructure.'/';
            if ( ($directoryHandle = opendir($path)) == true ) {
                while (($fileOrDir = readdir( $directoryHandle )) !== false) {
                    if (is_file($path. $fileOrDir) && $this->isPhpFile($path.$fileOrDir)) {
                        $classImplementation = $this->haveTheFileImplementationOf($path. $fileOrDir);
                        if ($classImplementation) {
                            return $classImplementation;
                        }
                    }
                }
            } else {
                throw new PluginException('Invalid plugin structure path, check the main config.ini file');
            }
        }

        return null;

    }

Given the plugin directory it search, based on plugin structure, if
exists a pluginFactoryClass to call to get ready the plugin.

@param string $pluginDirectory

@return PluginInterface|null
@throws \PluginException

Given the plugin directory it search based on plugin structure if exists a pluginFactoryClass to call to get ready the plugin .


public function haveTheFileImplementationOf($file, $implementation = 'PluginInterface') {
        $matches = array();
        $fp = fopen($file, 'r');
        while (!feof($fp)) {
            $line = stream_get_line($fp, 1000000, "\n");
            if (preg_match('/class\s+(\w+)(.*)\simplements\s+(\w+)(.*)?\{/', $line, $matches)) {
                if ($matches[3] === $implementation) {
                    return $matches[1]; //Return the class name
                }
            }
        }
        return false;
    }

Open the given path file and search for a plugin implementation. It returns
the class name in a positive case.

@param string $file
@param string $implementation
@return boolean|string

Open the given path file and search for a plugin implementation . It returns the class name in a positive case .


public static function toString(Closure $closure)
    {
        $functionStringValue = '';
        $functionReflection = new ReflectionFunction($closure);

        $file = file($functionReflection->getFileName());

        $lastLine = ($functionReflection->getEndLine() - 1);

        for ($codeline = $functionReflection->getStartLine(); $codeline < $lastLine; $codeline++) {
            $functionStringValue .= $file[$codeline];
        }

        return $functionStringValue;
    }

public static function toString ( Closure $ closure ) { $ functionStringValue = '' ; $ functionReflection = new ReflectionFunction ( $ closure ) ; $ file = file ( $ functionReflection -> getFileName ( ) ) ; $ lastLine = ( $ functionReflection -> getEndLine ( ) - 1 ) ; for ( $ codeline = $ functionReflection -> getStartLine ( ) ; $ codeline < $ lastLine ; $ codeline ++ ) { $ functionStringValue .= $ file [ $ codeline ] ; } return $ functionStringValue ; }

Get the string representation of the anonymous function.

@param Closre $closure The anonymous function.

@return string

Get the string representation of the anonymous function .


public function execute(Closure $closure)
    {
        $temporaryFile = tempnam(sys_get_temp_dir(), 'covert');

        $temporaryContent = '<?php'.PHP_EOL.PHP_EOL;

        if ($this->autoload !== false) {
            $temporaryContent .= "require('$this->autoload');".PHP_EOL.PHP_EOL;
        }

        $temporaryContent .= FunctionReflection::toString($closure).PHP_EOL.PHP_EOL;
        $temporaryContent .= 'unlink(__FILE__);'.PHP_EOL.PHP_EOL;
        $temporaryContent .= 'exit;';

        file_put_contents($temporaryFile, $temporaryContent);

        $this->processId = $this->executeFile($temporaryFile);

        return $this;
    }

public function execute ( Closure $ closure ) { $ temporaryFile = tempnam ( sys_get_temp_dir ( ) , 'covert' ) ; $ temporaryContent = '<?php' . PHP_EOL . PHP_EOL ; if ( $ this -> autoload !== false ) { $ temporaryContent .= "require('$this->autoload');" . PHP_EOL . PHP_EOL ; } $ temporaryContent .= FunctionReflection :: toString ( $ closure ) . PHP_EOL . PHP_EOL ; $ temporaryContent .= 'unlink(__FILE__);' . PHP_EOL . PHP_EOL ; $ temporaryContent .= 'exit;' ; file_put_contents ( $ temporaryFile , $ temporaryContent ) ; $ this -> processId = $ this -> executeFile ( $ temporaryFile ) ; return $ this ; }

Execute the process.

@param \Closure $closure The anonyouse function to execute.

@return void


private function executeFile($file)
    {
        if (OperatingSystem::isWindows()) {
            return $this->runCommandForWindows($file);
        }

        return $this->runCommandForNix($file);
    }

private function executeFile ( $ file ) { if ( OperatingSystem :: isWindows ( ) ) { return $ this -> runCommandForWindows ( $ file ) ; } return $ this -> runCommandForNix ( $ file ) ; }

Check the operating system call appropriate execution method.

@param string $file The absolute path to the executing file.

@return void

Check the operating system call appropriate execution method .


private function runCommandForWindows($file)
    {
        if ($this->logging) {
            $stdoutPipe = ['file', $this->logging, 'w'];
            $stderrPipe = ['file', $this->logging, 'w'];
        } else {
            $stdoutPipe = fopen('NUL', 'c');
            $stderrPipe = fopen('NUL', 'c');
        }

        $desc = [
            ['pipe', 'r'],
            $stdoutPipe,
            $stderrPipe,
        ];

        $cmd = "START /b php {$file}";

        $handle = proc_open(
            $cmd,
            $desc,
            $pipes,
            getcwd()
        );

        if (!is_resource($handle)) {
            throw new Exception('Could not create a background resource. Try using a better operating system.');
        }

        $pid = proc_get_status($handle)['pid'];

        try {
            proc_close($handle);
            $resource = array_filter(explode(' ', shell_exec("wmic process get parentprocessid, processid | find \"$pid\"")));
            array_pop($resource);
            $pid = end($resource);
        } catch (Exception $e) {
        }

        return $pid;
    }

Execute the shell process for the Windows platform.

@param string $file The absolute path to the executing file.

@return void

Execute the shell process for the Windows platform .


public function setAutoloadFile($autoload)
    {
        if ($autoload !== false && !file_exists($autoload)) {
            throw new Exception("The autoload path '{$autoload}' doesn't exist.");
        }

        $this->autoload = $autoload;

        return $this;
    }

Set a custom path to the autoload.php file.

@param string $file The absolute path to the autoload.php file.

@return void

Set a custom path to the autoload . php file .


public function isRunning()
    {
        $processId = $this->getProcessId();

        if (OperatingSystem::isWindows()) {
            $pids = shell_exec("wmic process get processid | find \"{$processId}\"");
            $resource = array_filter(explode(' ', $pids));

            $isRunning = count($resource) > 0 && $processId == reset($resource);
        } else {
            $isRunning = (bool) posix_getsid($processId);
        }

        return $isRunning;
    }

Returns true if the process ID is still active.

@return bool

Returns true if the process ID is still active .


public function kill()
    {
        if ($this->isRunning()) {
            $processId = $this->getProcessId();

            if (OperatingSystem::isWindows()) {
                $cmd = "taskkill /pid {$processId} -t -f";
            } else {
                $cmd = "kill -9 {$processId}";
            }

            shell_exec($cmd);
        }

        return $this;
    }

public
function
kill
(
)
{
if
(
$
this
->
isRunning
(
)
)
{
$
processId
=
$
this
->
getProcessId
(
)
;
if
(
OperatingSystem
::
isWindows
(
)
)
{
$
cmd
=
"taskkill /pid {$processId} -t -f"
;
}
else
{
$
cmd
=
"kill -9 {$processId}"
;
}
shell_exec
(
$
cmd
)
;
}
return
$
this
;
}

Kill the current operation process if it is running.

@return self

Kill the current operation process if it is running .


protected function reset()
    {
        $this->log_sections = [];
        $this->max_memory_usage = null;
        $this->start_time = null;
        $this->end_time = null;
    }

protected function reset ( ) { $ this -> log_sections = [ ] ; $ this -> max_memory_usage = null ; $ this -> start_time = null ; $ this -> end_time = null ; }


public static function createFromString(string $str): self
    {
        $parsedUrl = parse_url($str);

        return new self($parsedUrl['scheme'] ?? '',
                        $parsedUrl['host'] ?? null,
                        $parsedUrl['port'] ?? null,
                        $parsedUrl['path'] ?? '/',
                        $parsedUrl['query'] ?? '',
                        $parsedUrl['fragment'] ?? '',
                        $parsedUrl['user'] ?? '',
                        $parsedUrl['pass'] ?? '');
    }

public static function createFromString ( string $ str ) : self { $ parsedUrl = parse_url ( $ str ) ; return new self ( $ parsedUrl [ 'scheme' ] ?? '' , $ parsedUrl [ 'host' ] ?? null , $ parsedUrl [ 'port' ] ?? null , $ parsedUrl [ 'path' ] ?? '/' , $ parsedUrl [ 'query' ] ?? '' , $ parsedUrl [ 'fragment' ] ?? '' , $ parsedUrl [ 'user' ] ?? '' , $ parsedUrl [ 'pass' ] ?? '' ) ; }

Create Uri object with string

@param string $str

@return \Berlioz\Http\Message\Uri


final static function getDriver(array $drivers=array('gd')) {
        foreach ($drivers as $driver) {
            if (!preg_match('/^[a-z0-9\_]+$/i', $driver))
                continue;
            $class = __NAMESPACE__ . "\\image_$driver";
            if (class_exists($class) && method_exists($class, "available")) {
                eval("\$avail = $class::available();");
                if ($avail) return $driver;
            }
        }
        return false;
    }

final
static
function
getDriver
(
array
$
drivers
=
array
(
'gd'
)
)
{
foreach
(
$
drivers
as
$
driver
)
{
if
(
!
preg_match
(
'/^[a-z0-9\_]+$/i'
,
$
driver
)
)
continue
;
$
class
=
__NAMESPACE__
.
"\\image_$driver"
;
if
(
class_exists
(
$
class
)
&&
method_exists
(
$
class
,
"available"
)
)
{
eval
(
"\$avail = $class::available();"
)
;
if
(
$
avail
)
return
$
driver
;
}
}
return
false
;
}

Checks if the drivers in the array parameter could be used. Returns first
found one
@param array $drivers
@return string

Checks if the drivers in the array parameter could be used . Returns first found one


final protected function buildImage($image) {
        $class = get_class($this);

        if ($image instanceof $class) {
            $width = $image->width;
            $height = $image->height;
            $img = $image->image;

        } elseif (is_array($image)) {
            list($key, $width) = each($image);
            list($key, $height) = each($image);
            $img = $this->getBlankImage($width, $height);

        } else
            $img = $this->getImage($image, $width, $height);

        return ($img !== false)
            ? array($img, $width, $height)
            : false;
    }

final protected function buildImage ( $ image ) { $ class = get_class ( $ this ) ; if ( $ image instanceof $ class ) { $ width = $ image -> width ; $ height = $ image -> height ; $ img = $ image -> image ; } elseif ( is_array ( $ image ) ) { list ( $ key , $ width ) = each ( $ image ) ; list ( $ key , $ height ) = each ( $ image ) ; $ img = $ this -> getBlankImage ( $ width , $ height ) ; } else $ img = $ this -> getImage ( $ image , $ width , $ height ) ; return ( $ img !== false ) ? array ( $ img , $ width , $ height ) : false ; }

Returns an array. Element 0 - image resource. Element 1 - width. Element 2 - height.
Returns FALSE on failure.
@param mixed $image
@return array

Returns an array . Element 0 - image resource . Element 1 - width . Element 2 - height . Returns FALSE on failure .


final public function getPropWidth($resizedHeight) {
        $width = round(($this->width * $resizedHeight) / $this->height);
        if (!$width) $width = 1;
        return $width;
    }

final public function getPropWidth ( $ resizedHeight ) { $ width = round ( ( $ this -> width * $ resizedHeight ) / $ this -> height ) ; if ( ! $ width ) $ width = 1 ; return $ width ; }

Returns calculated proportional width from the given height
@param integer $resizedHeight
@return integer


final public function getPropHeight($resizedWidth) {
        $height = round(($this->height * $resizedWidth) / $this->width);
        if (!$height) $height = 1;
        return $height;
    }

final public function getPropHeight ( $ resizedWidth ) { $ height = round ( ( $ this -> height * $ resizedWidth ) / $ this -> width ) ; if ( ! $ height ) $ height = 1 ; return $ height ; }

Returns calculated proportional height from the given width
@param integer $resizedWidth
@return integer


public static function formatBinary($bytes, $precision = null)
    {
        static $formatter = null;
        if (!$formatter) {
            $formatter = new Formatter\Binary();
        }

        return $formatter->format($bytes, $precision);
    }

public static function formatBinary ( $ bytes , $ precision = null ) { static $ formatter = null ; if ( ! $ formatter ) { $ formatter = new Formatter \ Binary ( ) ; } return $ formatter -> format ( $ bytes , $ precision ) ; }

Binary formatter static proxy

@staticvar Formatter\Binary $formatter
@uses Formatter\Binary::format()

@param  integer|string $bytes Integer or string representing the number
of bytes.
@param  integer $precision Number of significant digits to include in the
formatted output.
@return string Returns a human-friendly formatted string.


public static function formatMetric($bytes, $precision = null)
    {
        static $formatter = null;
        if (!$formatter) {
            $formatter = new Formatter\Metric();
        }

        return $formatter->format($bytes, $precision);
    }

public static function formatMetric ( $ bytes , $ precision = null ) { static $ formatter = null ; if ( ! $ formatter ) { $ formatter = new Formatter \ Metric ( ) ; } return $ formatter -> format ( $ bytes , $ precision ) ; }

Metric formatter static proxy

@staticvar Formatter\Metric $formatter
@uses Formatter\Metric::format()

@param  integer|string $bytes Integer or string representing the number
of bytes.
@param  integer $precision Number of significant digits to include in the
formatted output.
@return string Returns a human-friendly formatted string.


public static function create($driverClass = self::DRIVER_SERVER, array $options = [])
    {
        $session = new Session($driverClass, $options);
        return $session->initialize();
    }

public static function create ( $ driverClass = self :: DRIVER_SERVER , array $ options = [ ] ) { $ session = new Session ( $ driverClass , $ options ) ; return $ session -> initialize ( ) ; }

Creates the session driver with provided options

@param string $driverClass
@param array  $options

@return SessionDriverInterface

@throws ClassNotFoundException if class does not exists
@throws InvalidDriverClassException if class does not implement the SessionDriverInterface


public function initialize()
    {
        $this->checkClassExistence();

        $this->checkClassType();

        $className = $this->driverClass;
        return new $className($this->options);
    }

public function initialize ( ) { $ this -> checkClassExistence ( ) ; $ this -> checkClassType ( ) ; $ className = $ this -> driverClass ; return new $ className ( $ this -> options ) ; }

Initializes a new session driver

@return SessionDriverInterface

@throws ClassNotFoundException if class does not exists
@throws InvalidDriverClassException if class does not implement the SessionDriverInterface


public function parse()
    {
        $this->stream->rewind();
        parse_str($this->stream->getContents(), $parsed);
        return array_merge($_POST, $parsed);
    }

public function parse ( ) { $ this -> stream -> rewind ( ) ; parse_str ( $ this -> stream -> getContents ( ) , $ parsed ) ; return array_merge ( $ _POST , $ parsed ) ; }

Parses the URL encoded body.

@return array


private function generateUrl()
    {
        $hostHeader = $this->request->getHeaderLine('host');
        $defaultHost = strlen($hostHeader) > 0 ? $hostHeader : 'unknown-host';
        $host = $this->getServerParam('SERVER_NAME', $defaultHost);
        $scheme = $this->getServerParam('REQUEST_SCHEME', 'http');
        $uri = $this->getServerParam('REQUEST_URI', '/');
        $port = $this->getServerParam('SERVER_PORT', '80');

        $port = in_array($port, ['80', '443']) ? '' : ":{$port}";

        return "{$scheme}://{$host}{$port}{$uri}";
    }

private function generateUrl ( ) { $ hostHeader = $ this -> request -> getHeaderLine ( 'host' ) ; $ defaultHost = strlen ( $ hostHeader ) > 0 ? $ hostHeader : 'unknown-host' ; $ host = $ this -> getServerParam ( 'SERVER_NAME' , $ defaultHost ) ; $ scheme = $ this -> getServerParam ( 'REQUEST_SCHEME' , 'http' ) ; $ uri = $ this -> getServerParam ( 'REQUEST_URI' , '/' ) ; $ port = $ this -> getServerParam ( 'SERVER_PORT' , '80' ) ; $ port = in_array ( $ port , [ '80' , '443' ] ) ? '' : ":{$port}" ; return "{$scheme}://{$host}{$port}{$uri}" ; }

Generates an URL from current request data

@return string


private function getServerParam($name, $default = null)
    {
        $data = $this->request->getServerParams();
        if (array_key_exists($name, $data)) {
            $default = trim($data[$name]);
        }
        return $default;
    }

private function getServerParam ( $ name , $ default = null ) { $ data = $ this -> request -> getServerParams ( ) ; if ( array_key_exists ( $ name , $ data ) ) { $ default = trim ( $ data [ $ name ] ) ; } return $ default ; }

Retrieve an request server parameter stored with provided name

If no match is found the default value is returned instead

@param string $name    $_SERVER super-global key name
@param null   $default

@return null|string


protected function getDefaultInputDefinition()
    {
        return new InputDefinition(
            [
                new InputArgument('command', InputArgument::REQUIRED, 'The command to execute'),
                new InputOption(
                    '--env',
                    '-e',
                    InputOption::VALUE_REQUIRED,
                    'The environment to be used',
                    getenv('BLUZ_ENV') ?: 'dev'
                ),
                new InputOption('--help', '-h', InputOption::VALUE_NONE, 'Display this help message'),
                new InputOption('--quiet', '-q', InputOption::VALUE_NONE, 'Do not output any message'),
                new InputOption('--verbose', '-v', InputOption::VALUE_NONE, 'Increase verbosity of messages'),
                new InputOption('--version', '-V', InputOption::VALUE_NONE, 'Display this application version')
            ]
        );
    }

protected
function
getDefaultInputDefinition
(
)
{
return
new
InputDefinition
(
[
new
InputArgument
(
'command'
,
InputArgument
::
REQUIRED
,
'The command to execute'
)
,
new
InputOption
(
'--env'
,
'-e'
,
InputOption
::
VALUE_REQUIRED
,
'The environment to be used'
,
getenv
(
'BLUZ_ENV'
)
:
'dev'
)
,
new
InputOption
(
'--help'
,
'-h'
,
InputOption
::
VALUE_NONE
,
'Display this help message'
)
,
new
InputOption
(
'--quiet'
,
'-q'
,
InputOption
::
VALUE_NONE
,
'Do not output any message'
)
,
new
InputOption
(
'--verbose'
,
'-v'
,
InputOption
::
VALUE_NONE
,
'Increase verbosity of messages'
)
,
new
InputOption
(
'--version'
,
'-V'
,
InputOption
::
VALUE_NONE
,
'Display this application version'
)
]
)
;
}

Removed some commands from default input definition.

@return InputDefinition An InputDefinition instance

Removed some commands from default input definition .


protected function registerCommands()
    {
        $this->addCommands(
            [
                new Command\MagicCommand,
                new Command\RunCommand,
                new Command\TestCommand,
                new Command\Db\CreateCommand,
                new Command\Db\MigrateCommand,
                new Command\Db\RollbackCommand,
                new Command\Db\StatusCommand,
                new Command\Db\SeedCreateCommand,
                new Command\Db\SeedRunCommand,
                new Command\Generate\ModuleCommand,
                new Command\Generate\ControllerCommand,
                new Command\Generate\ModelCommand,
                new Command\Generate\CrudCommand,
                new Command\Generate\GridCommand,
                new Command\Generate\RestCommand,
                new Command\Generate\ScaffoldCommand,
                new Command\Module\InstallCommand,
                new Command\Module\ListCommand,
                new Command\Module\RemoveCommand,
                new Command\Server\StartCommand,
                new Command\Server\StopCommand,
                new Command\Server\StatusCommand,
            ]
        );
    }

protected function registerCommands ( ) { $ this -> addCommands ( [ new Command \ MagicCommand , new Command \ RunCommand , new Command \ TestCommand , new Command \ Db \ CreateCommand , new Command \ Db \ MigrateCommand , new Command \ Db \ RollbackCommand , new Command \ Db \ StatusCommand , new Command \ Db \ SeedCreateCommand , new Command \ Db \ SeedRunCommand , new Command \ Generate \ ModuleCommand , new Command \ Generate \ ControllerCommand , new Command \ Generate \ ModelCommand , new Command \ Generate \ CrudCommand , new Command \ Generate \ GridCommand , new Command \ Generate \ RestCommand , new Command \ Generate \ ScaffoldCommand , new Command \ Module \ InstallCommand , new Command \ Module \ ListCommand , new Command \ Module \ RemoveCommand , new Command \ Server \ StartCommand , new Command \ Server \ StopCommand , new Command \ Server \ StatusCommand , ] ) ; }

Register Bluzman commands

@todo Find a way to do this automatically or move it to /bin/bluzman


public function getModelPath($name) : string
    {
        return $this->getWorkingPath() . DIRECTORY_SEPARATOR
            . 'application' . DIRECTORY_SEPARATOR
            . 'models' . DIRECTORY_SEPARATOR
            . ucfirst(strtolower($name));
    }

public function getModelPath ( $ name ) : string { return $ this -> getWorkingPath ( ) . DIRECTORY_SEPARATOR . 'application' . DIRECTORY_SEPARATOR . 'models' . DIRECTORY_SEPARATOR . ucfirst ( strtolower ( $ name ) ) ; }

Get Model path

@param  string $name
@return string


protected function addForceOption() : void
    {
        $force = new InputOption('--force', '-f', InputOption::VALUE_NONE, 'Rewrite previously generated files');
        $this->getDefinition()->addOption($force);
    }

protected
function
addForceOption
(
)
:
void
{
$
force
=
new
InputOption
(
'--force'
,
'-f'
,
InputOption
::
VALUE_NONE
,
'Rewrite previously generated files'
)
;
$
this
->
getDefinition
(
)
->
addOption
(
$
force
)
;
}


protected function addModelArgument() : void
    {
        $model = new InputArgument('model', InputArgument::REQUIRED, 'Model name is required');
        $this->getDefinition()->addArgument($model);
    }

protected
function
addModelArgument
(
)
:
void
{
$
model
=
new
InputArgument
(
'model'
,
InputArgument
::
REQUIRED
,
'Model name is required'
)
;
$
this
->
getDefinition
(
)
->
addArgument
(
$
model
)
;
}


protected function validateModelArgument() : void
    {
        $model = $this->getInput()->getArgument('model');

        $validator = Validator::create()
            ->string()
            ->alphaNumeric()
            ->noWhitespace();

        if ($this->getDefinition()->getArgument('model')->isRequired()
            && !$validator->validate($model)) {
            throw new InputException($validator->getError());
        }
    }

protected function validateModelArgument ( ) : void { $ model = $ this -> getInput ( ) -> getArgument ( 'model' ) ; $ validator = Validator :: create ( ) -> string ( ) -> alphaNumeric ( ) -> noWhitespace ( ) ; if ( $ this -> getDefinition ( ) -> getArgument ( 'model' ) -> isRequired ( ) && ! $ validator -> validate ( $ model ) ) { throw new InputException ( $ validator -> getError ( ) ) ; } }

Validate Model Argument

@return void
@throws \Bluzman\Input\InputException


protected function addTableArgument() : void
    {
        $table = new InputArgument('table', InputArgument::REQUIRED, 'Table name is required');
        $this->getDefinition()->addArgument($table);
    }

protected
function
addTableArgument
(
)
:
void
{
$
table
=
new
InputArgument
(
'table'
,
InputArgument
::
REQUIRED
,
'Table name is required'
)
;
$
this
->
getDefinition
(
)
->
addArgument
(
$
table
)
;
}


protected function validateTableArgument() : void
    {
        $table = $this->getInput()->getArgument('table');

        $validator = Validator::create()
            ->string()
            ->alphaNumeric('_')
            ->noWhitespace();

        if ($this->getDefinition()->getArgument('table')->isRequired()
            && !$validator->validate($table)) {
            throw new InputException($validator->getError());
        }
    }

protected function validateTableArgument ( ) : void { $ table = $ this -> getInput ( ) -> getArgument ( 'table' ) ; $ validator = Validator :: create ( ) -> string ( ) -> alphaNumeric ( '_' ) -> noWhitespace ( ) ; if ( $ this -> getDefinition ( ) -> getArgument ( 'table' ) -> isRequired ( ) && ! $ validator -> validate ( $ table ) ) { throw new InputException ( $ validator -> getError ( ) ) ; } }

Validate Table Argument

@return void
@throws \Bluzman\Input\InputException


protected function getTableInstance($model) : Table
    {
        $file = $this->getApplication()->getModelPath($model) . DS . 'Table.php';
        if (!file_exists($file)) {
            throw new GeneratorException(
                "Model $model is not exist, run command `bluzman generate:model $model` before"
            );
        }
        include_once $file;
        $class = '\\Application\\' . ucfirst($model) . '\\Table';
        if (!class_exists($class)) {
            throw new GeneratorException("Bluzman can't found `Table` class for model `$model`");
        }
        return $class::getInstance();
    }

Get Table instance

@param  string $model

@return Table
@throws \Bluzman\Generator\GeneratorException


protected function generateFile($class, $file, array $data = []) : void
    {
        if (file_exists($file) && !$this->getInput()->getOption('force')) {
            $this->comment(" |> File <info>$file</info> already exists");
            return;
        }

        $template = $this->getTemplate($class);
        $template->setFilePath($file);
        $template->setTemplateData($data);

        $generator = new Generator($template);
        $generator->make();
    }

Small wrapper for simplify code

@param  string $class
@param  string $file
@param  array  $data

@return void


public function handle(ServerRequestInterface $request): ResponseInterface
    {
        $response = call_user_func($this->callback, $request);
        return $response;
    }

public function handle ( ServerRequestInterface $ request ) : ResponseInterface { $ response = call_user_func ( $ this -> callback , $ request ) ; return $ response ; }

Handle the request and return a response.

@param ServerRequestInterface $request

@return ResponseInterface

Handle the request and return a response .


public function isSeekable()
    {
        $seekable = false;
        if ($this->stream) {
            $meta = stream_get_meta_data($this->stream);
            $seekable = $meta['seekable'];
        }
        return $seekable;
    }

public function isSeekable ( ) { $ seekable = false ; if ( $ this -> stream ) { $ meta = stream_get_meta_data ( $ this -> stream ) ; $ seekable = $ meta [ 'seekable' ] ; } return $ seekable ; }

Returns whether or not the stream is seekable.

@return bool

Returns whether or not the stream is seekable .


private function createParserWith(StreamInterface $body)
    {
        $class = NullParser::class;
        foreach (self::$parsers as $parser => $contentTypes) {
            foreach ($contentTypes as $contentType) {
                if (stripos($this->contentType, $contentType) !== false) {
                    $class = $parser;
                }
            }
        }
        return new $class($body);
    }

private function createParserWith ( StreamInterface $ body ) { $ class = NullParser :: class ; foreach ( self :: $ parsers as $ parser => $ contentTypes ) { foreach ( $ contentTypes as $ contentType ) { if ( stripos ( $ this -> contentType , $ contentType ) !== false ) { $ class = $ parser ; } } } return new $ class ( $ body ) ; }

Creates the parser based on the parsers map with provided stream

@param StreamInterface $body

@return BodyParserInterface


public static function addParser($className, array $contentTypes)
    {
        if (! is_a($className, BodyParserInterface::class)) {
            throw new InvalidArgumentException(
                "Parser objects MUST implement the BodyParserInterface interface."
            );
        }

        $existing = isset(self::$parsers[$className])
            ? self::$parsers[$className]
            : [];
        array_unshift(
            self::$parsers[$className],
            array_merge($existing, $contentTypes)
        );
    }

Adds a body parser to parsers map

@param string $className
@param array  $contentTypes

@throws InvalidArgumentException if provided class does not implement BodyParserInterface


protected function addModuleArgument($required = InputArgument::REQUIRED) : void
    {
        $module = new InputArgument('module', $required, 'Module name is required');
        $this->getDefinition()->addArgument($module);
    }

protected
function
addModuleArgument
(
$
required
=
InputArgument
::
REQUIRED
)
:
void
{
$
module
=
new
InputArgument
(
'module'
,
$
required
,
'Module name is required'
)
;
$
this
->
getDefinition
(
)
->
addArgument
(
$
module
)
;
}

Add Module Argument

@param int $required
@return void


protected function addControllerArgument($required = InputArgument::REQUIRED) : void
    {
        $controller = new InputArgument('controller', $required, 'Controller name is required');
        $this->getDefinition()->addArgument($controller);
    }

protected
function
addControllerArgument
(
$
required
=
InputArgument
::
REQUIRED
)
:
void
{
$
controller
=
new
InputArgument
(
'controller'
,
$
required
,
'Controller name is required'
)
;
$
this
->
getDefinition
(
)
->
addArgument
(
$
controller
)
;
}

Add Controller Argument

@param int $required
@return void


public function createRequest(string $method,
                                  $uri,
                                  array $headers = [],
                                  $body = null,
                                  $protocolVersion = '1.1'): RequestInterface
    {
        $request = new Request($method, $this->createUri($uri));

        // Headers ?
        if (!empty($headers)) {
            $request = $request->withHeaders($headers);
        }

        // Body ?
        if (!is_null($body)) {
            if ($body instanceof StreamInterface) {
                $request = $request->withBody($body);
            }

            if (is_resource($body)) {
                $request = $request->withBody($this->createStreamFromResource($body));
            }

            if (is_string($body)) {
                $request = $request->withBody($this->createStream($body));
            }
        }

        // Protocol version ?
        if ($protocolVersion != $request->getProtocolVersion()) {
            $request = $request->withProtocolVersion($protocolVersion);
        }

        return $request;
    }

public
function
createRequest
(
string
$
method
,
$
uri
,
array
$
headers
=
[
]
,
$
body
=
,
$
protocolVersion
=
'1.1'
)
:
RequestInterface
{
$
request
=
new
Request
(
$
method
,
$
this
->
createUri
(
$
uri
)
)
;
// Headers ?
if
(
!
empty
(
$
headers
)
)
{
$
request
=
$
request
->
withHeaders
(
$
headers
)
;
}
// Body ?
if
(
!
is_null
(
$
body
)
)
{
if
(
$
body
instanceof
StreamInterface
)
{
$
request
=
$
request
->
withBody
(
$
body
)
;
}
if
(
is_resource
(
$
body
)
)
{
$
request
=
$
request
->
withBody
(
$
this
->
createStreamFromResource
(
$
body
)
)
;
}
if
(
is_string
(
$
body
)
)
{
$
request
=
$
request
->
withBody
(
$
this
->
createStream
(
$
body
)
)
;
}
}
// Protocol version ?
if
(
$
protocolVersion
!=
$
request
->
getProtocolVersion
(
)
)
{
$
request
=
$
request
->
withProtocolVersion
(
$
protocolVersion
)
;
}
return
$
request
;
}

Create a new request.

@param string                               $method The HTTP method associated with the request.
@param UriInterface|string                  $uri    The URI associated with the request.
@param array                                $headers
@param resource|string|StreamInterface|null $body
@param string                               $protocolVersion

@return \Psr\Http\Message\RequestInterface


public function createServerRequest(string $method, $uri, array $serverParams = []): ServerRequestInterface
    {
        if (is_string($uri)) {
            $uri = Uri::createFromString($uri);
        }

        return new ServerRequest($method, $uri, [], [], $serverParams, new Stream());
    }

public function createServerRequest ( string $ method , $ uri , array $ serverParams = [ ] ) : ServerRequestInterface { if ( is_string ( $ uri ) ) { $ uri = Uri :: createFromString ( $ uri ) ; } return new ServerRequest ( $ method , $ uri , [ ] , [ ] , $ serverParams , new Stream ( ) ) ; }

Create a new server request.

Note that server parameters are taken precisely as given - no parsing/processing
of the given values is performed. In particular, no attempt is made to
determine the HTTP method or URI, which must be provided explicitly.

@param string              $method       The HTTP method associated with the request.
@param UriInterface|string $uri          The URI associated with the request.
@param array               $serverParams An array of Server API (SAPI) parameters with
which to seed the generated request instance.

@return \Psr\Http\Message\ServerRequestInterface


public function createStream(string $content = ''): StreamInterface
    {
        $stream = new Stream();
        $stream->write($content);

        return $stream;
    }

public function createStream ( string $ content = '' ) : StreamInterface { $ stream = new Stream ( ) ; $ stream -> write ( $ content ) ; return $ stream ; }

Create a new stream from a string.

The stream SHOULD be created with a temporary resource.

@param string $content String content with which to populate the stream.

@return \Psr\Http\Message\StreamInterface


public function createStreamFromFile(string $filename, string $mode = 'r'): StreamInterface
    {
        if (!in_array($mode, ['r', 'r+', 'w+', 'a+', 'c+'])) {
            throw new \InvalidArgumentException(sprintf('Invalid mode "%s" to read file "%s"', $mode));
        }

        if (($resource = @fopen($filename, $mode)) === false) {
            throw new \RuntimeException(sprintf('Unable to open file "%s" with mode "%s"', $filename, $mode));
        }

        // Read file
        rewind($resource);
        $content = fread($resource, filesize($filename));
        fclose($resource);

        return $this->createStream($content);
    }

Create a stream from an existing file.

The file MUST be opened using the given mode, which may be any mode
supported by the `fopen` function.

The `$filename` MAY be any string supported by `fopen()`.

@param string $filename The filename or stream URI to use as basis of stream.
@param string $mode     The mode with which to open the underlying filename/stream.

@return \Psr\Http\Message\StreamInterface
@throws \RuntimeException If the file cannot be opened.
@throws \InvalidArgumentException If the mode is invalid.


public function createUploadedFile(
        StreamInterface $stream,
        int $size = null,
        int $error = \UPLOAD_ERR_OK,
        string $clientFilename = null,
        string $clientMediaType = null,
        string $filename = ''
    ): UploadedFileInterface {
        if (is_null($size)) {
            $size = $stream->getSize();
        }

        $uploadedFile = new UploadedFile($filename, $clientFilename, $clientMediaType, $size, $error);
        $uploadedFile->setStream($stream);

        return $uploadedFile;
    }

public function createUploadedFile ( StreamInterface $ stream , int $ size = null , int $ error = \ UPLOAD_ERR_OK , string $ clientFilename = null , string $ clientMediaType = null , string $ filename = '' ) : UploadedFileInterface { if ( is_null ( $ size ) ) { $ size = $ stream -> getSize ( ) ; } $ uploadedFile = new UploadedFile ( $ filename , $ clientFilename , $ clientMediaType , $ size , $ error ) ; $ uploadedFile -> setStream ( $ stream ) ; return $ uploadedFile ; }

Create a new uploaded file.

If a size is not provided it will be determined by checking the size of
the stream.

@link http://php.net/manual/features.file-upload.post-method.php
@link http://php.net/manual/features.file-upload.errors.php

@param StreamInterface $stream          The underlying stream representing the
uploaded file content.
@param int             $size            The size of the file in bytes.
@param int             $error           The PHP file upload error.
@param string          $clientFilename  The filename as provided by the client, if any.
@param string          $clientMediaType The media type as provided by the client, if any.
@param string          $filename        Filename

@return \Psr\Http\Message\UploadedFileInterface
@throws \InvalidArgumentException If the file resource is not readable.


public function createUri(string $uri = ''): UriInterface
    {
        if (is_string($uri)) {
            return Uri::createFromString($uri);
        } else {
            throw new \InvalidArgumentException('Not valid URI given');
        }
    }

public
function
createUri
(
string
$
uri
=
''
)
:
UriInterface
{
if
(
is_string
(
$
uri
)
)
{
return
Uri
::
createFromString
(
$
uri
)
;
}
else
{
throw
new
\
InvalidArgumentException
(
'Not valid URI given'
)
;
}
}

Create a new URI.

@param string $uri The URI to parse.

@return \Psr\Http\Message\UriInterface
@throws \InvalidArgumentException If the given URI cannot be parsed.


public function format($bytes, $precision = null)
    {
        $bytes = $this->normalizeBytes($bytes);
        $out = $bytes . 'B';

        foreach ($this->suffixes as $power => $suffix) {
            if (bccomp($calc = $this->divPow($bytes, $this->base, $power), 1) >= 0) {
                $out = $this->formatNumber($calc, $suffix, $precision);
                break;
            }
        }

        return $out;
    }

public function format ( $ bytes , $ precision = null ) { $ bytes = $ this -> normalizeBytes ( $ bytes ) ; $ out = $ bytes . 'B' ; foreach ( $ this -> suffixes as $ power => $ suffix ) { if ( bccomp ( $ calc = $ this -> divPow ( $ bytes , $ this -> base , $ power ) , 1 ) >= 0 ) { $ out = $ this -> formatNumber ( $ calc , $ suffix , $ precision ) ; break ; } } return $ out ; }

Format input into a human-friendly string for display

@uses \bccomp()
@uses AbstractFormatter::divPow()
@uses AbstractFormatter::formatNumber()
@uses AbstractFormatter::normalizeBytes()

@param  integer|string $bytes Integer or string representing the number
of bytes.
@param  integer $precision Number of significant digits to include in the
formatted output. Defaults to 2.
@return string Returns a human-friendly formatted string.

Format input into a human - friendly string for display


protected function formatNumber($float, $suffix, $precision = null)
    {
        if ($precision === null) {
            $precision = $this->precision;
        }
        $precision = $this->normalizePrecision($precision);

        return sprintf("%.{$precision}f%s", $float, $suffix);
    }

protected function formatNumber ( $ float , $ suffix , $ precision = null ) { if ( $ precision === null ) { $ precision = $ this -> precision ; } $ precision = $ this -> normalizePrecision ( $ precision ) ; return sprintf ( "%.{$precision}f%s" , $ float , $ suffix ) ; }

Format a float value with given suffix

@uses AbstractFormatter::normalizePrecision()

@param  integer|float $float The number to format.
@param  string $suffix The suffix to attach.
@param  integer $precision The number of significant digits to include.
@return string Returns the formatted string.


protected function normalizeBytes($bytes)
    {
        $filteredBytes = filter_var($bytes, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION);
        list ($bytes, $part) = explode('.', $filteredBytes . '.0');
        if (bccomp($part, 0) == 1) {
            $bytes = bcadd($bytes, 1);
        }

        return $bytes;
    }

protected function normalizeBytes ( $ bytes ) { $ filteredBytes = filter_var ( $ bytes , FILTER_SANITIZE_NUMBER_FLOAT , FILTER_FLAG_ALLOW_FRACTION ) ; list ( $ bytes , $ part ) = explode ( '.' , $ filteredBytes . '.0' ) ; if ( bccomp ( $ part , 0 ) == 1 ) { $ bytes = bcadd ( $ bytes , 1 ) ; } return $ bytes ; }

Normalize bytes value

The resulting value is a string representation of the bytes value. This
is done by the BCMath library so we can work with very large integer
values.

@uses \bcadd()
@uses \bccomp()
@uses \filter_var()

@param  integer|float|string $bytes The bytes value.
@return string Returns the normalized value.


protected function normalizePrecision($precision)
    {
        $precisionFiltered = filter_var($precision, FILTER_SANITIZE_NUMBER_INT);

        return (int) min(10, max(0, $precisionFiltered));
    }

protected function normalizePrecision ( $ precision ) { $ precisionFiltered = filter_var ( $ precision , FILTER_SANITIZE_NUMBER_INT ) ; return ( int ) min ( 10 , max ( 0 , $ precisionFiltered ) ) ; }

Normalize precision value

The resulting value is an integer value between 0 and 10.

@uses \filter_var()

@param  integer $precision The precision value.
@return integer Returns the normalized value.


public function withMethod($method)
    {
        $method = strtoupper($method);
        $knownMethods = [
            'HEAD', 'OPTIONS', 'GET', 'POST', 'PUT',
            'DELETE', 'CONNECT', 'TRACE', 'PATCH', 'PURGE'
        ];

        if (! in_array($method, $knownMethods)) {
            throw new InvalidArgumentException(
                "Invalid or unknown method name."
            );
        }

        $message = clone $this;
        $message->method = $method;
        return $message;
    }

public
function
withMethod
(
$
method
)
{
$
method
=
strtoupper
(
$
method
)
;
$
knownMethods
=
[
'HEAD'
,
'OPTIONS'
,
'GET'
,
'POST'
,
'PUT'
,
'DELETE'
,
'CONNECT'
,
'TRACE'
,
'PATCH'
,
'PURGE'
]
;
if
(
!
in_array
(
$
method
,
$
knownMethods
)
)
{
throw
new
InvalidArgumentException
(
"Invalid or unknown method name."
)
;
}
$
message
=
clone
$
this
;
$
message
->
method
=
$
method
;
return
$
message
;
}

Return an instance with the provided HTTP method.

@param string $method Case-sensitive method.
@return static
@throws InvalidArgumentException for invalid HTTP methods.

Return an instance with the provided HTTP method .


protected function setUri(UriInterface $uri, $preserveHost = false)
    {
        if (! $preserveHost && $uri->getHost() !== '') {
            $key = $this->headerKey('Host');
            $this->headers[$key] = [$uri->getHost()];
        }

        $this->uri = $uri;
    }

protected function setUri ( UriInterface $ uri , $ preserveHost = false ) { if ( ! $ preserveHost && $ uri -> getHost ( ) !== '' ) { $ key = $ this -> headerKey ( 'Host' ) ; $ this -> headers [ $ key ] = [ $ uri -> getHost ( ) ] ; } $ this -> uri = $ uri ; }

Sets the request URI

@param UriInterface $uri
@param bool $preserveHost


private function getTargetFromUri()
    {
        $target  = "/{$this->uri->getPath()}";
        $target .= $this->uri->getQuery() !== ''
            ? "?{$this->uri->getQuery()}"
            : '';
        $target .= $this->uri->getFragment() !== ''
            ? "#{$this->uri->getFragment()}"
            : '';
        return str_replace('//', '/', $target);
    }

private function getTargetFromUri ( ) { $ target = "/{$this->uri->getPath()}" ; $ target .= $ this -> uri -> getQuery ( ) !== '' ? "?{$this->uri->getQuery()}" : '' ; $ target .= $ this -> uri -> getFragment ( ) !== '' ? "#{$this->uri->getFragment()}" : '' ; return str_replace ( '//' , '/' , $ target ) ; }

Get the target from the uri

@return string


public function push($middleware)
    {
        if (! $middleware instanceof MiddlewareInterface &&
            ! is_callable($middleware)
        ) {
            throw new InvalidArgumentException(
                "Middleware stack accepts only MiddlewareInterface object or callable"
            );
        }

        array_push($this->middlewareStack, $middleware);
        return $this;
    }

Pushes a middleware to the stack

@param MiddlewareInterface|callable $middleware

@return MiddlewareStack


public static function reasonPhraseFor($code)
    {
        $status = '';
        if (array_key_exists($code, self::$codes)) {
            $status = self::$codes[$code];
        }
        return $status;
    }

public static function reasonPhraseFor ( $ code ) { $ status = '' ; if ( array_key_exists ( $ code , self :: $ codes ) ) { $ status = self :: $ codes [ $ code ] ; } return $ status ; }

Get the Reason Phrase for provide code

@param int $code

@return string


public function getMessages()
    {
        return [
            new IncomingMessage($this->event->get('message')['message'], $this->event->get('message')['from']['id'],
                $this->event->get('room')['id'], $this->event),
        ];
    }

public function getMessages ( ) { return [ new IncomingMessage ( $ this -> event -> get ( 'message' ) [ 'message' ] , $ this -> event -> get ( 'message' ) [ 'from' ] [ 'id' ] , $ this -> event -> get ( 'room' ) [ 'id' ] , $ this -> event ) , ] ; }

Retrieve the chat message.

@return array


public function getUser(IncomingMessage $matchingMessage)
    {
        $payload = $matchingMessage->getPayload();

        return new User($payload->get('message')['from']['id'], $payload->get('message')['from']['name'], null,
            $payload->get('message')['from']['mention_name']);
    }

public function getUser ( IncomingMessage $ matchingMessage ) { $ payload = $ matchingMessage -> getPayload ( ) ; return new User ( $ payload -> get ( 'message' ) [ 'from' ] [ 'id' ] , $ payload -> get ( 'message' ) [ 'from' ] [ 'name' ] , null , $ payload -> get ( 'message' ) [ 'from' ] [ 'mention_name' ] ) ; }

Retrieve User information.
@param \BotMan\BotMan\Messages\Incoming\IncomingMessage $matchingMessage
@return User


static function getExtension($filename, $toLower=true) {
        return preg_match('/^.*\.([^\.]*)$/s', $filename, $patt)
            ? ($toLower ? strtolower($patt[1]) : $patt[1]) : "";
    }

static function getExtension ( $ filename , $ toLower = true ) { return preg_match ( '/^.*\.([^\.]*)$/s' , $ filename , $ patt ) ? ( $ toLower ? strtolower ( $ patt [ 1 ] ) : $ patt [ 1 ] ) : "" ; }

Get the extension from filename
@param string $filename
@param bool $toLower
@return string


static function normalizeFilename($filename) {
        $string = htmlentities($filename, ENT_QUOTES, 'UTF-8');
        if (strpos($string, '&') !== false)
            $filename = html_entity_decode(preg_replace('~&([a-z]{1,2})(?:acute|cedil|circ|grave|lig|orn|ring|slash|tilde|uml);~i', '$1', $string), ENT_QUOTES, 'UTF-8');
        $filename = trim(preg_replace('~[^0-9a-z\.\- ]~i', "_", $filename));
        return $filename;
    }

Normalize given filename. Accented characters becomes non-accented and
removes any other special characters. Usable for non-unicode filesystems
@param $filename
@return string

Normalize given filename . Accented characters becomes non - accented and removes any other special characters . Usable for non - unicode filesystems


public function getContents()
    {
        if (!$this->isReadable() || ($contents = stream_get_contents($this->fp, -1, 0)) === false) {
            throw new \RuntimeException('Unable to get contents of stream');
        }

        return $contents;
    }

public
function
getContents
(
)
{
if
(
!
$
this
->
isReadable
(
)
||
(
$
contents
=
stream_get_contents
(
$
this
->
fp
,
1
,
0
)
)
===
false
)
{
throw
new
\
RuntimeException
(
'Unable to get contents of stream'
)
;
}
return
$
contents
;
}

Returns the remaining contents in a string

@return string
@throws \RuntimeException if unable to read or an error occurs while
reading.


public function fixSiteUrlFilter($url, $path, $scheme)
    {
        if (strpos($url, $this->wpDirectoryPath)) {
            return $url;
        }

        $wordpressUrl = ['/(wp-login\.php)/', '/(wp-admin)/'];
        $multiSiteUrl = [trim($this->wpDirectoryPath, '/').'/wp-login.php', trim($this->wpDirectoryPath, '/').'/wp-admin'];

        return preg_replace($wordpressUrl, $multiSiteUrl, $url, 1);
    }

public function fixSiteUrlFilter ( $ url , $ path , $ scheme ) { if ( strpos ( $ url , $ this -> wpDirectoryPath ) ) { return $ url ; } $ wordpressUrl = [ '/(wp-login\.php)/' , '/(wp-admin)/' ] ; $ multiSiteUrl = [ trim ( $ this -> wpDirectoryPath , '/' ) . '/wp-login.php' , trim ( $ this -> wpDirectoryPath , '/' ) . '/wp-admin' ] ; return preg_replace ( $ wordpressUrl , $ multiSiteUrl , $ url , 1 ) ; }

Set the right path for wp-login and wp-admin.

@param string      $url
@param string      $path
@param string|null $scheme

@return string

Set the right path for wp - login and wp - admin .


public function fixWpIncludeFolder($url, $path)
    {
        if (strpos($url, $this->wpDirectoryPath)) {
            return $url;
        }

        $wordpressUrl = ['/(wp-includes)/'];
        $multiSiteUrl = [trim($this->wpDirectoryPath, '/').'/wp-includes'];

        return preg_replace($wordpressUrl, $multiSiteUrl, $url, 1);
    }

public function fixWpIncludeFolder ( $ url , $ path ) { if ( strpos ( $ url , $ this -> wpDirectoryPath ) ) { return $ url ; } $ wordpressUrl = [ '/(wp-includes)/' ] ; $ multiSiteUrl = [ trim ( $ this -> wpDirectoryPath , '/' ) . '/wp-includes' ] ; return preg_replace ( $ wordpressUrl , $ multiSiteUrl , $ url , 1 ) ; }

Add subfolder path to wp-includes path.

@param string $url
@param string $path

@return string

Add subfolder path to wp - includes path .


public function fixNetworkAdminUrlFilter($path = '', $scheme = 'admin')
    {
        if (strpos($path, $this->wpDirectoryPath)) {
            return $path;
        }

        $wordpressUrl = [
            '/(wp-admin)/',
            '/(wp-login\.php)/',
            '/(wp-activate\.php)/',
            '/(wp-signup\.php)/',
        ];

        $multiSiteUrl = [
            $this->wpFolderName.'/wp-admin',
            $this->wpFolderName.'/wp-login.php',
            $this->wpFolderName.'/wp-activate.php',
            $this->wpFolderName.'/wp-signup.php',
        ];

        return preg_replace($wordpressUrl, $multiSiteUrl, $path, 1);
    }

public function fixNetworkAdminUrlFilter ( $ path = '' , $ scheme = 'admin' ) { if ( strpos ( $ path , $ this -> wpDirectoryPath ) ) { return $ path ; } $ wordpressUrl = [ '/(wp-admin)/' , '/(wp-login\.php)/' , '/(wp-activate\.php)/' , '/(wp-signup\.php)/' , ] ; $ multiSiteUrl = [ $ this -> wpFolderName . '/wp-admin' , $ this -> wpFolderName . '/wp-login.php' , $ this -> wpFolderName . '/wp-activate.php' , $ this -> wpFolderName . '/wp-signup.php' , ] ; return preg_replace ( $ wordpressUrl , $ multiSiteUrl , $ path , 1 ) ; }

Set the right links in Adminbar.

@param string $path
@param string $scheme

@return string


public function fixWpDoubleSlashFilter($urls)
    {
        foreach ($urls as &$url) {
            if ($url) {
                $url = str_replace('//app', '/app', $url);
            }
        }

        return $urls;
    }

public function fixWpDoubleSlashFilter ( $ urls ) { foreach ( $ urls as & $ url ) { if ( $ url ) { $ url = str_replace ( '//app' , '/app' , $ url ) ; } } return $ urls ; }

Fix double backslashes in app folder.

@param string


public function init()
    {
        $this->getWpBridge()->addFilter('network_admin_url', [$this, 'fixNetworkAdminUrlFilter'], 10, 2);

        $this->getWpBridge()->addFilter('script_loader_src', [$this, 'fixStyleScriptPathFilter'], 10, 2);
        $this->getWpBridge()->addFilter('style_loader_src', [$this, 'fixStyleScriptPathFilter'], 10, 2);

        $this->getWpBridge()->addFilter('upload_dir', [$this, 'fixWpDoubleSlashFilter'], 10, 1);
        $this->getWpBridge()->addFilter('upload_dir', [$this, 'fixWpProtocolFilter'], 10, 1);
    }

public function init ( ) { $ this -> getWpBridge ( ) -> addFilter ( 'network_admin_url' , [ $ this , 'fixNetworkAdminUrlFilter' ] , 10 , 2 ) ; $ this -> getWpBridge ( ) -> addFilter ( 'script_loader_src' , [ $ this , 'fixStyleScriptPathFilter' ] , 10 , 2 ) ; $ this -> getWpBridge ( ) -> addFilter ( 'style_loader_src' , [ $ this , 'fixStyleScriptPathFilter' ] , 10 , 2 ) ; $ this -> getWpBridge ( ) -> addFilter ( 'upload_dir' , [ $ this , 'fixWpDoubleSlashFilter' ] , 10 , 1 ) ; $ this -> getWpBridge ( ) -> addFilter ( 'upload_dir' , [ $ this , 'fixWpProtocolFilter' ] , 10 , 1 ) ; }


protected function setWpFolderName()
    {
        $dirs = explode('/', $this->wpDirectoryPath);

        $this->wpFolderName = $dirs[count($dirs) - 2];
    }

protected function setWpFolderName ( ) { $ dirs = explode ( '/' , $ this -> wpDirectoryPath ) ; $ this -> wpFolderName = $ dirs [ count ( $ dirs ) - 2 ] ; }

Set wordpress folder name.

@param string


static function url2fullPath($url) {
        $url = self::normalize($url);

        $uri = isset($_SERVER['SCRIPT_NAME'])
            ? $_SERVER['SCRIPT_NAME'] : (isset($_SERVER['PHP_SELF'])
            ? $_SERVER['PHP_SELF']
            : false);

        $uri = self::normalize($uri);

        if (substr($url, 0, 1) !== "/") {
            if ($uri === false) return false;
            $url = dirname($uri) . "/$url";
        }

        if (isset($_SERVER['DOCUMENT_ROOT'])) {
            return self::normalize($_SERVER['DOCUMENT_ROOT'] . "/$url");

        } else {
            if ($uri === false) return false;

            if (isset($_SERVER['SCRIPT_FILENAME'])) {
                $scr_filename = self::normalize($_SERVER['SCRIPT_FILENAME']);
                return self::normalize(substr($scr_filename, 0, -strlen($uri)) . "/$url");
            }

            $count = count(explode('/', $uri)) - 1;
            for ($i = 0, $chdir = ""; $i < $count; $i++)
                $chdir .= "../";
            $chdir = self::normalize($chdir);

            $dir = getcwd();
            if (($dir === false) || !@chdir($chdir))
                return false;
            $rdir = getcwd();
            chdir($dir);
            return ($rdir !== false) ? self::normalize($rdir . "/$url") : false;
        }
    }

static function url2fullPath ( $ url ) { $ url = self :: normalize ( $ url ) ; $ uri = isset ( $ _SERVER [ 'SCRIPT_NAME' ] ) ? $ _SERVER [ 'SCRIPT_NAME' ] : ( isset ( $ _SERVER [ 'PHP_SELF' ] ) ? $ _SERVER [ 'PHP_SELF' ] : false ) ; $ uri = self :: normalize ( $ uri ) ; if ( substr ( $ url , 0 , 1 ) !== "/" ) { if ( $ uri === false ) return false ; $ url = dirname ( $ uri ) . "/$url" ; } if ( isset ( $ _SERVER [ 'DOCUMENT_ROOT' ] ) ) { return self :: normalize ( $ _SERVER [ 'DOCUMENT_ROOT' ] . "/$url" ) ; } else { if ( $ uri === false ) return false ; if ( isset ( $ _SERVER [ 'SCRIPT_FILENAME' ] ) ) { $ scr_filename = self :: normalize ( $ _SERVER [ 'SCRIPT_FILENAME' ] ) ; return self :: normalize ( substr ( $ scr_filename , 0 , - strlen ( $ uri ) ) . "/$url" ) ; } $ count = count ( explode ( '/' , $ uri ) ) - 1 ; for ( $ i = 0 , $ chdir = "" ; $ i < $ count ; $ i ++ ) $ chdir .= "../" ; $ chdir = self :: normalize ( $ chdir ) ; $ dir = getcwd ( ) ; if ( ( $ dir === false ) || ! @ chdir ( $ chdir ) ) return false ; $ rdir = getcwd ( ) ; chdir ( $ dir ) ; return ( $ rdir !== false ) ? self :: normalize ( $ rdir . "/$url" ) : false ; } }

Resolve full filesystem path of given URL. Returns FALSE if the URL
cannot be resolved
@param string $url
@return string

Resolve full filesystem path of given URL . Returns FALSE if the URL cannot be resolved


static function urlPathEncode($path) {
        $path = self::normalize($path);
        $encoded = "";
        foreach (explode("/", $path) as $dir)
            $encoded .= rawurlencode($dir) . "/";
        $encoded = substr($encoded, 0, -1);
        return $encoded;
    }

static function urlPathEncode ( $ path ) { $ path = self :: normalize ( $ path ) ; $ encoded = "" ; foreach ( explode ( "/" , $ path ) as $ dir ) $ encoded .= rawurlencode ( $ dir ) . "/" ; $ encoded = substr ( $ encoded , 0 , - 1 ) ; return $ encoded ; }

Encode URL Path
@param string $path
@return string


static function urlPathDecode($path) {
        $path = self::normalize($path);
        $decoded = "";
        foreach (explode("/", $path) as $dir)
            $decoded .= rawurldecode($dir) . "/";
        $decoded = substr($decoded, 0, -1);
        return $decoded;
    }

static function urlPathDecode ( $ path ) { $ path = self :: normalize ( $ path ) ; $ decoded = "" ; foreach ( explode ( "/" , $ path ) as $ dir ) $ decoded .= rawurldecode ( $ dir ) . "/" ; $ decoded = substr ( $ decoded , 0 , - 1 ) ; return $ decoded ; }

Decode URL Path
@param string $path
@return string


static function content($dir, array $options=null) {

        $defaultOptions = array(
            'types' => "all",   // Allowed: "all" or possible return values
                                // of filetype(), or an array with them
            'addPath' => true,  // Whether to add directory path to filenames
            'pattern' => '/./', // Regular expression pattern for filename
            'followLinks' => true
        );

        if (!is_dir($dir) || !is_readable($dir))
            return false;

        if (strtoupper(substr(PHP_OS, 0, 3)) == "WIN")
            $dir = str_replace("\\", "/", $dir);
        $dir = rtrim($dir, "/");

        $dh = @opendir($dir);
        if ($dh === false)
            return false;

        if ($options === null)
            $options = $defaultOptions;

        foreach ($defaultOptions as $key => $val)
            if (!isset($options[$key]))
                $options[$key] = $val;

        $files = array();
        while (($file = @readdir($dh)) !== false) {

            if (($file == '.') || ($file == '..') ||
                !preg_match($options['pattern'], $file)
            )
                continue;

            $fullpath = "$dir/$file";
            $type = filetype($fullpath);

            // If file is a symlink, get the true type of its destination
            if ($options['followLinks'] && ($type == "link"))
                $type = filetype(realpath($fullpath));

            if (($options['types'] === "all") || ($type === $options['types']) ||
                (is_array($options['types']) && in_array($type, $options['types']))
            )
                $files[] = $options['addPath'] ? $fullpath : $file;
        }
        closedir($dh);
        usort($files, array(__NAMESPACE__ . "\\dir", "fileSort"));
        return $files;
    }

Get the content of the given directory. Returns an array with filenames
or FALSE on failure
@param string $dir
@param array $options
@return mixed

Get the content of the given directory . Returns an array with filenames or FALSE on failure


public function database($data, $time_start, $memory_start = null)
    {
        if (!array_key_exists('Database', $this->Profiler->log_sections)) {
            return ;
        }

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

        if (!is_float($time_start)) {
            $time_start = $this->Profiler->getMicrotime();
        }

        if ($memory_start === null) {
            // is dev still not using memory start? trigger error.
            trigger_error('You did not enter $memory_start argument for \Rundiz\Profiler\Console->database() method. Please set the $memory_start to memory_get_usage() in your code.', E_USER_NOTICE);
        }
        if (!is_int($memory_start)) {
            $memory_start = memory_get_usage();
        }

        $backtrace = debug_backtrace();
        $trace_items = [];
        if (is_array($backtrace)) {
            foreach ($backtrace as $items) {
                if (is_array($items) && array_key_exists('file', $items) && array_key_exists('line', $items)) {
                    $trace_items[] = ['file' => $items['file'], 'line' => $items['line']];
                }
            }
        }
        unset($backtrace, $items);

        $section_database = $this->Profiler->log_sections['Database'];
        $section_database_data = [];
        $section_database_data[] = [
            'data' => $data,
            'memory_start' => $memory_start,
            'memory' => memory_get_usage(),// @deprecated [rundizprofiler] and will be removed in the future
            'memory_end' => memory_get_usage(),
            'time_start' => $time_start,
            'time_end' => $this->Profiler->getMicrotime(),
            'call_trace' => $trace_items,
        ];
        $section_database = array_merge($section_database, $section_database_data);

        $this->Profiler->log_sections['Database'] = $section_database;
        unset($section_database, $section_database_data, $trace_items);

        //$this->writeLogSections('Database', $data, $file, $line);
    }

Database profiling log.

@param string $data SQL query statement. for example: SELECT id FROM people;.
@param double $time_start `microtime(true)` at before start the query.
@param integer $memory_start `memory_get_usage()` at before start the query. If this was not set then it will not be showing the real memory start. (Required).
@todo [rundizprofiler] the "memory" in array key for Database will be remove in future version.


public function log($logtype, $data, $file = '', $line = '')
    {
        $data = [
            'logtype' => $logtype,
            'data' => $data,
        ];

        $this->writeLogSections('Logs', $data, $file, $line);
    }

public function log ( $ logtype , $ data , $ file = '' , $ line = '' ) { $ data = [ 'logtype' => $ logtype , 'data' => $ data , ] ; $ this -> writeLogSections ( 'Logs' , $ data , $ file , $ line ) ; }

write normal logs.

@param string $logtype accept debug, info, notice, warning, error, critical, alert, emergency. referrer: http://www.php-fig.org/psr/psr-3/
@param mixed $data log data.
@param string $file path to file where it calls logger. (optional).
@param integer $line number of line in that file that calls logger. (optional).


public function memoryUsage($data, $file = '', $line = '', $matchKey = null)
    {
        $this->writeLogSections('Memory Usage', $data, $file, $line, $matchKey);
    }

public
function
memoryUsage
(
$
data
,
$
file
=
''
,
$
line
=
''
,
$
matchKey
=
)
{
$
this
->
writeLogSections
(
'Memory Usage'
,
$
data
,
$
file
,
$
line
,
$
matchKey
)
;
}

write memory usage logs.

@param mixed $data log data.
@param string $file path to file where it calls logger. (optional).
@param integer $line number of line in that file that calls logger. (optional).
@param string|null $matchKey The key to be match at the beginning and end for calculate total time or memory only for this key. (optional). The key must be unique in this section.


public function timeload($data, $file = '', $line = '', $matchKey = null)
    {
        $this->writeLogSections('Time Load', $data, $file, $line, $matchKey);
    }

public
function
timeload
(
$
data
,
$
file
=
''
,
$
line
=
''
,
$
matchKey
=
)
{
$
this
->
writeLogSections
(
'Time Load'
,
$
data
,
$
file
,
$
line
,
$
matchKey
)
;
}

Write time load logs.

To calculate total time load only for specification functional, use `$matchKey`.

Example:

$Profiler->Console->timeload('Before run sleep.', '', '', 'run_sleep');
sleep(3);
$Profiler->Console->timeload('After run sleep.', '', '', 'run_sleep');

The `$matchKey` must be unique from others.

@param mixed $data Log data.
@param string $file Path to file where it calls logger. (optional).
@param integer $line Number of line in that file that calls logger. (optional).
@param string|null $matchKey The key to be match at the beginning and end for calculate total time or memory only for this key. (optional). The key must be unique in this section.


public function writeLogSections($section, $data, $file = '', $line = '', $matchKey = null)
    {
        if (!is_array($this->Profiler->log_sections)) {
            $this->Profiler->log_sections = [];
        }

        if (!array_key_exists($section, $this->Profiler->log_sections)) {
            // if section is not exists in the key means it was not registered, get out of this function.
            return ;
        }

        if (!is_string($matchKey)) {
            $matchKey = null;
        }

        if ($section == 'Logs') {
            if (is_array($data) && array_key_exists('logtype', $data) && array_key_exists('data', $data)) {
                $logtype = $data['logtype'];
                $data = $data['data'];
            }
        }

        $section_data_array = [
            'data' => $data,
            'file' => $file,
            'line' => $line,
        ];
        if ($matchKey !== null) {
            $section_data_array['matchKey'] = $matchKey;
        }
        if ($section == 'Time Load') {
            $section_data_array['time'] = $this->Profiler->getMicrotime();
        }
        if ($section == 'Memory Usage') {
            $section_data_array['memory'] = memory_get_usage();
        }

        if (isset($logtype)) {
            $section_data_array['logtype'] = $logtype;
        }

        $this->Profiler->log_sections[$section][] = $section_data_array;
        unset($section_data_array);
    }

Write other sections logs.

@param string $section The section name.
@param mixed $data Log data. This can be any type.
@param string $file Path to file where it calls logger. (optional).
@param integer $line Number of line in that file that calls logger. (optional).
@param string|null $matchKey The key to be match at the beginning and end for calculate total time or memory only for this key. (optional). The key must be unique (for start and end) in each section.


public static function filesFlip(&$result, $keys, $value)
    {
        if (is_array($value)) {
            foreach ($value as $k => $v) {
                $newKeys = $keys;
                array_push($newKeys, $k);
                self::filesFlip($result, $newKeys, $v);
            }
        } else {
            $res = $value;
            // Move the innermost key to the outer spot
            $first = array_shift($keys);
            array_push($keys, $first);
            foreach (array_reverse($keys) as $k) {
                // You might think we'd say $res[$k] = $res, but $res starts out not as an array
                $res = [$k => $res];
            }

            $result = array_replace_recursive($result, $res);
        }
    }

Flips the file's array keys.

@param array $result
@param array $keys
@param mixed $value

@return void

@author Bart Kelsey <http://www.opengameart.org>
@see    https://stackoverflow.com/questions/5444827/how-do-you-loop-through-files-array/29664753#29664753


public function setStream(StreamInterface $stream): UploadedFile
    {
        if ($this->hasMoved()) {
            throw new \RuntimeException(sprintf('Uploaded file "%s" has already moved', $this->file));
        }

        $this->stream = $stream;

        return $this;
    }

public
function
setStream
(
StreamInterface
$
stream
)
:
UploadedFile
{
if
(
$
this
->
hasMoved
(
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'Uploaded file "%s" has already moved'
,
$
this
->
file
)
)
;
}
$
this
->
stream
=
$
stream
;
return
$
this
;
}

Set stream of uploaded file.

@param \Psr\Http\Message\StreamInterface $stream

@return \Berlioz\Http\Message\UploadedFile


public function getHash($algo = 'sha1')
    {
        if ($this->hasMoved()) {
            throw new \RuntimeException(sprintf('Uploaded file "%s" has already moved', $this->file));
        }

        return hash_file($algo, $this->file);
    }

public
function
getHash
(
$
algo
=
'sha1'
)
{
if
(
$
this
->
hasMoved
(
)
)
{
throw
new
\
RuntimeException
(
sprintf
(
'Uploaded file "%s" has already moved'
,
$
this
->
file
)
)
;
}
return
hash_file
(
$
algo
,
$
this
->
file
)
;
}

Retrieve the hash value using the contents of file.

@param string $algo Name of selected hashing algorithm (i.e. "md5", "sha256", "haval160,4", etc..)

@return string
@throws \RuntimeException on any error during the hash operation.

@see \hash_file()

Retrieve the hash value using the contents of file .


public function getMediaType()
    {
        if ($this->hasMoved()) {
            throw new \RuntimeException(sprintf('Uploaded file "%s" has already moved', $this->file));
        }

        if (extension_loaded('fileinfo')) {
            $finfo = finfo_open(FILEINFO_MIME);
            $mime = finfo_file($finfo, $this->file);
            finfo_close($finfo);

            $mime = explode(";", $mime);
            $mime = trim($mime[0]);

            return $mime;
        } else {
            throw new \RuntimeException(sprintf('You must install fileinfo extension to determine the real type of uploaded file "%s"', $this->file));
        }
    }

Retrieve the media type of file.

@return string|null The media type or null if unavailable
@throws \RuntimeException on any error during the mime extraction operation.


public function getQueryParams()
    {
        if (!is_null($this->queryParams)) {
            return $this->queryParams;
        } else {
            if (!is_null($this->getUri())) {
                parse_str($this->getUri()->getQuery(), $this->queryParams);

                return $this->queryParams;
            } else {
                return [];
            }
        }
    }

public function getQueryParams ( ) { if ( ! is_null ( $ this -> queryParams ) ) { return $ this -> queryParams ; } else { if ( ! is_null ( $ this -> getUri ( ) ) ) { parse_str ( $ this -> getUri ( ) -> getQuery ( ) , $ this -> queryParams ) ; return $ this -> queryParams ; } else { return [ ] ; } } }

Retrieve query string arguments.

Retrieves the deserialized query string arguments, if any.

Note: the query params might not be in sync with the URI or server
params. If you need to ensure you are only getting the original
values, you may need to parse the query string from `getUri()->getQuery()`
or from the `QUERY_STRING` server param.

@return array


public function isAjaxRequest()
    {
        // Check if ajax request
        {
            $ajaxRequest = $this->hasHeader('AjaxRequest');

            $serverParams = $this->getServerParams();
            if (!$ajaxRequest && !empty($serverParams['HTTP_X_REQUESTED_WITH']) && strtolower($serverParams['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
                $ajaxRequest = true;
            }
        }

        return $ajaxRequest;
    }

public
function
isAjaxRequest
(
)
{
// Check if ajax request
{
$
ajaxRequest
=
$
this
->
hasHeader
(
'AjaxRequest'
)
;
$
serverParams
=
$
this
->
getServerParams
(
)
;
if
(
!
$
ajaxRequest
&&
!
empty
(
$
serverParams
[
'HTTP_X_REQUESTED_WITH'
]
)
&&
strtolower
(
$
serverParams
[
'HTTP_X_REQUESTED_WITH'
]
)
==
'xmlhttprequest'
)
{
$
ajaxRequest
=
true
;
}
}
return
$
ajaxRequest
;
}


public function toDocument($json)
    {
        $data = json_decode($json, true);

        $document = new Document();

        if (isset($data['class']) && is_array($data['class'])) {
            $document->setClass($data['class']);
        }

        if (isset($data['properties']) && is_array($data['properties'])) {
            $document->setProperties($data['properties']);
        }

        if (isset($data['entities']) && is_array($data['entities'])) {
            $entities = $this->getEntitiesFromDataArray($data['entities']);
            $document->setEntities($entities);
        }

        if (isset($data['actions']) && is_array($data['actions'])) {
            $actions = $this->getActionsFromDataArray($data['actions']);
            $document->setActions($actions);
        }

        if (isset($data['links']) && is_array($data['links'])) {
            $links = $this->getLinksFromDataArray($data['links']);
            $document->setLinks($links);
        }

        return $document;
    }

public function toDocument ( $ json ) { $ data = json_decode ( $ json , true ) ; $ document = new Document ( ) ; if ( isset ( $ data [ 'class' ] ) && is_array ( $ data [ 'class' ] ) ) { $ document -> setClass ( $ data [ 'class' ] ) ; } if ( isset ( $ data [ 'properties' ] ) && is_array ( $ data [ 'properties' ] ) ) { $ document -> setProperties ( $ data [ 'properties' ] ) ; } if ( isset ( $ data [ 'entities' ] ) && is_array ( $ data [ 'entities' ] ) ) { $ entities = $ this -> getEntitiesFromDataArray ( $ data [ 'entities' ] ) ; $ document -> setEntities ( $ entities ) ; } if ( isset ( $ data [ 'actions' ] ) && is_array ( $ data [ 'actions' ] ) ) { $ actions = $ this -> getActionsFromDataArray ( $ data [ 'actions' ] ) ; $ document -> setActions ( $ actions ) ; } if ( isset ( $ data [ 'links' ] ) && is_array ( $ data [ 'links' ] ) ) { $ links = $ this -> getLinksFromDataArray ( $ data [ 'links' ] ) ; $ document -> setLinks ( $ links ) ; } return $ document ; }

Method to convert a siren JSON string into a Siren document object

@param string $json
@return Document


protected function getEntitiesFromDataArray(array $entitiesArray)
    {
        $entities = array();
        foreach ($entitiesArray as $entityArray) {
            $entity = new Entity();

            if (isset($entityArray['class']) && is_array($entityArray['class'])) {
                $entity->setClass($entityArray['class']);
            }

            if (isset($entityArray['rel']) && is_array($entityArray['rel'])) {
                $entity->setRel($entityArray['rel']);
            }

            if (isset($entityArray['href']) && is_string($entityArray['href'])) {
                $entity->setHref($entityArray['href']);
            }

            if (isset($entityArray['properties']) && is_array($entityArray['properties'])) {
                $entity->setProperties($entityArray['properties']);
            }

            if (isset($entityArray['links']) && is_array($entityArray['links'])) {
                $links = $this->getLinksFromDataArray($entityArray['links']);
                $entity->setLinks($links);
            }

            $entities[] = $entity;
        }

        return $entities;
    }

protected function getEntitiesFromDataArray ( array $ entitiesArray ) { $ entities = array ( ) ; foreach ( $ entitiesArray as $ entityArray ) { $ entity = new Entity ( ) ; if ( isset ( $ entityArray [ 'class' ] ) && is_array ( $ entityArray [ 'class' ] ) ) { $ entity -> setClass ( $ entityArray [ 'class' ] ) ; } if ( isset ( $ entityArray [ 'rel' ] ) && is_array ( $ entityArray [ 'rel' ] ) ) { $ entity -> setRel ( $ entityArray [ 'rel' ] ) ; } if ( isset ( $ entityArray [ 'href' ] ) && is_string ( $ entityArray [ 'href' ] ) ) { $ entity -> setHref ( $ entityArray [ 'href' ] ) ; } if ( isset ( $ entityArray [ 'properties' ] ) && is_array ( $ entityArray [ 'properties' ] ) ) { $ entity -> setProperties ( $ entityArray [ 'properties' ] ) ; } if ( isset ( $ entityArray [ 'links' ] ) && is_array ( $ entityArray [ 'links' ] ) ) { $ links = $ this -> getLinksFromDataArray ( $ entityArray [ 'links' ] ) ; $ entity -> setLinks ( $ links ) ; } $ entities [ ] = $ entity ; } return $ entities ; }

Helper method to convert an entities data array to an array of entity objects

@param array $entitiesArray
@return Entity[]


protected function getActionsFromDataArray(array $actionsArray)
    {
        $actions = array();
        foreach ($actionsArray as $actionArray) {
            $action = new Action();

            if (isset($actionArray['name']) && is_string($actionArray['name'])) {
                $action->setName($actionArray['name']);
            }

            if (isset($actionArray['title']) && is_string($actionArray['title'])) {
                $action->setTitle($actionArray['title']);
            }

            if (isset($actionArray['method']) && is_string($actionArray['method'])) {
                $action->setMethod($actionArray['method']);
            }

            if (isset($actionArray['href']) && is_string($actionArray['href'])) {
                $action->setHref($actionArray['href']);
            }

            if (isset($actionArray['type']) && is_string($actionArray['type'])) {
                $action->setType($actionArray['type']);
            }

            if (isset($actionArray['fields']) && is_array($actionArray['fields'])) {
                $fields = $this->getFieldsFromDataArray($actionArray['fields']);
                $action->setFields($fields);
            }

            $actions[] = $action;
        }

        return $actions;
    }

protected function getActionsFromDataArray ( array $ actionsArray ) { $ actions = array ( ) ; foreach ( $ actionsArray as $ actionArray ) { $ action = new Action ( ) ; if ( isset ( $ actionArray [ 'name' ] ) && is_string ( $ actionArray [ 'name' ] ) ) { $ action -> setName ( $ actionArray [ 'name' ] ) ; } if ( isset ( $ actionArray [ 'title' ] ) && is_string ( $ actionArray [ 'title' ] ) ) { $ action -> setTitle ( $ actionArray [ 'title' ] ) ; } if ( isset ( $ actionArray [ 'method' ] ) && is_string ( $ actionArray [ 'method' ] ) ) { $ action -> setMethod ( $ actionArray [ 'method' ] ) ; } if ( isset ( $ actionArray [ 'href' ] ) && is_string ( $ actionArray [ 'href' ] ) ) { $ action -> setHref ( $ actionArray [ 'href' ] ) ; } if ( isset ( $ actionArray [ 'type' ] ) && is_string ( $ actionArray [ 'type' ] ) ) { $ action -> setType ( $ actionArray [ 'type' ] ) ; } if ( isset ( $ actionArray [ 'fields' ] ) && is_array ( $ actionArray [ 'fields' ] ) ) { $ fields = $ this -> getFieldsFromDataArray ( $ actionArray [ 'fields' ] ) ; $ action -> setFields ( $ fields ) ; } $ actions [ ] = $ action ; } return $ actions ; }

Helper method to convert an action data array to an array of action objects

@param array $actionsArray
@return Action[]


protected function getFieldsFromDataArray(array $fieldsArray)
    {
        $fields = array();
        foreach ($fieldsArray as $fieldArray) {
            $field = new Field();

            if (isset($fieldArray['name']) && is_string($fieldArray['name'])) {
                $field->setName($fieldArray['name']);
            }

            if (isset($fieldArray['type']) && is_string($fieldArray['type'])) {
                $field->setType($fieldArray['type']);
            }

            if (isset($fieldArray['value'])) {
                $field->setValue($fieldArray['value']);
            }

            $fields[] = $field;
        }

        return $fields;
    }

protected function getFieldsFromDataArray ( array $ fieldsArray ) { $ fields = array ( ) ; foreach ( $ fieldsArray as $ fieldArray ) { $ field = new Field ( ) ; if ( isset ( $ fieldArray [ 'name' ] ) && is_string ( $ fieldArray [ 'name' ] ) ) { $ field -> setName ( $ fieldArray [ 'name' ] ) ; } if ( isset ( $ fieldArray [ 'type' ] ) && is_string ( $ fieldArray [ 'type' ] ) ) { $ field -> setType ( $ fieldArray [ 'type' ] ) ; } if ( isset ( $ fieldArray [ 'value' ] ) ) { $ field -> setValue ( $ fieldArray [ 'value' ] ) ; } $ fields [ ] = $ field ; } return $ fields ; }

Helper method to convert a fields data array to an array of field objects

@param array $fieldsArray
@return Field[]