public function value($select, $values = array())
    {
        return ($row = $this->row($select, $values, 'row')) ? array_shift($row) : false;
    }

public function value ( $ select , $ values = array ( ) ) { return ( $ row = $ this -> row ( $ select , $ values , 'row' ) ) ? array_shift ( $ row ) : false ; }

Get only the first value of the first row from your query.

@param string|array $select A SELECT statement.
@param mixed        $values The query parameters.

@return bool|string Either ``false`` if there was no row, or the ``$value`` you are looking for.

```php
echo $db->value('SELECT COUNT(*) FROM employees'); // 7
```

Get only the first value of the first row from your query .


public function prepare($query, $fetch = null)
    {
        $query = (is_array($query)) ? trim(implode("\n", $query)) : trim($query);
        $stmt = count(static::$logs[$this->id]) + 1;
        $start = microtime(true);
        $this->prepared[$stmt]['obj'] = $this->dbPrepare($query);
        static::$logs[$this->id][$stmt] = array(
            'sql' => $query,
            'count' => 0,
            'prepared' => microtime(true) - $start,
            'executed' => 0,
        );
        $this->prepared[$stmt]['params'] = substr_count($query, '?');
        $this->prepared[$stmt]['type'] = strtoupper(strtok($query, " \r\n\t"));
        if ($this->prepared[$stmt]['type'] == 'SELECT') {
            $this->prepared[$stmt]['style'] = $this->dbStyle(strtolower((string) $fetch));
        }
        if ($this->prepared[$stmt]['obj'] === false) {
            unset($this->prepared[$stmt]);
            if ($error = $this->dbPrepareError()) {
                static::$logs[$this->id][$stmt]['errors'][] = $error;
            }

            return false;
        }

        return $stmt;
    }

public
function
prepare
(
$
query
,
$
fetch
=
)
{
$
query
=
(
is_array
(
$
query
)
)
trim
(
implode
(
"\n"
,
$
query
)
)
:
trim
(
$
query
)
;
$
stmt
=
count
(
static
::
$
logs
[
$
this
->
id
]
)
+
1
;
$
start
=
microtime
(
true
)
;
$
this
->
prepared
[
$
stmt
]
[
'obj'
]
=
$
this
->
dbPrepare
(
$
query
)
;
static
::
$
logs
[
$
this
->
id
]
[
$
stmt
]
=
array
(
'sql'
=>
$
query
,
'count'
=>
0
,
'prepared'
=>
microtime
(
true
)
$
start
,
'executed'
=>
0
,
)
;
$
this
->
prepared
[
$
stmt
]
[
'params'
]
=
substr_count
(
$
query
,
'?'
)
;
$
this
->
prepared
[
$
stmt
]
[
'type'
]
=
strtoupper
(
strtok
(
$
query
,
" \r\n\t"
)
)
;
if
(
$
this
->
prepared
[
$
stmt
]
[
'type'
]
==
'SELECT'
)
{
$
this
->
prepared
[
$
stmt
]
[
'style'
]
=
$
this
->
dbStyle
(
strtolower
(
(
string
)
$
fetch
)
)
;
}
if
(
$
this
->
prepared
[
$
stmt
]
[
'obj'
]
===
false
)
{
unset
(
$
this
->
prepared
[
$
stmt
]
)
;
if
(
$
error
=
$
this
->
dbPrepareError
(
)
)
{
static
::
$
logs
[
$
this
->
id
]
[
$
stmt
]
[
'errors'
]
[
]
=
$
error
;
}
return
false
;
}
return
$
stmt
;
}

Prepare a query to be executed.

@param string|array $query An SQL statement.
@param string       $fetch How you would like the SELECT rows returned.  Either '**obj**', '**assoc**', '**named**', '**both**', or '**num**' (the default).

@return bool|int Either ``false`` if there was an error, or a ``$stmt`` id that can be``$db->execute()``d or ``$db->fetch()``ed.  Don't forget to ``$db->close($stmt)``.


public function execute($stmt, $values = null)
    {
        if (isset($this->prepared[$stmt])) {
            if (!is_array($values)) {
                $values = ($this->prepared[$stmt]['params'] == 1) ? array($values) : array();
            }
            $start = microtime(true);
            if ($this->dbExecute($this->prepared[$stmt]['obj'], array_values($values), $stmt)) {
                static::$logs[$this->id][$stmt]['executed'] += microtime(true) - $start;
                static::$logs[$this->id][$stmt]['count']++;
                switch ($this->prepared[$stmt]['type']) {
                    case 'SELECT':
                        return true;
                    break;
                    case 'INSERT':
                        return $this->dbInserted();
                    default:
                        return $this->dbAffected($this->prepared[$stmt]['obj']);
                }
            } elseif ($error = $this->dbExecuteError($this->prepared[$stmt]['obj'])) {
                static::$logs[$this->id][$stmt]['errors'][] = $error;
            }
        }

        return false;
    }

public function execute ( $ stmt , $ values = null ) { if ( isset ( $ this -> prepared [ $ stmt ] ) ) { if ( ! is_array ( $ values ) ) { $ values = ( $ this -> prepared [ $ stmt ] [ 'params' ] == 1 ) ? array ( $ values ) : array ( ) ; } $ start = microtime ( true ) ; if ( $ this -> dbExecute ( $ this -> prepared [ $ stmt ] [ 'obj' ] , array_values ( $ values ) , $ stmt ) ) { static :: $ logs [ $ this -> id ] [ $ stmt ] [ 'executed' ] += microtime ( true ) - $ start ; static :: $ logs [ $ this -> id ] [ $ stmt ] [ 'count' ] ++ ; switch ( $ this -> prepared [ $ stmt ] [ 'type' ] ) { case 'SELECT' : return true ; break ; case 'INSERT' : return $ this -> dbInserted ( ) ; default : return $ this -> dbAffected ( $ this -> prepared [ $ stmt ] [ 'obj' ] ) ; } } elseif ( $ error = $ this -> dbExecuteError ( $ this -> prepared [ $ stmt ] [ 'obj' ] ) ) { static :: $ logs [ $ this -> id ] [ $ stmt ] [ 'errors' ] [ ] = $ error ; } } return false ; }

Execute a prepared statement.

@param int          $stmt   A ``$db->prepare(...)``d statement's return value.
@param string|array $values The query parameters.  If there is only one or none, then this can be a string.

@return mixed Either ``false`` if there was an error, ``true`` for a SELECT query, the inserted ``$id`` for an INSERT query, or the ``$num`` of affected rows for everything else.


public function fetch($stmt)
    {
        if (isset($this->prepared[$stmt]) && $this->prepared[$stmt]['type'] == 'SELECT') {
            return $this->dbFetch($this->prepared[$stmt]['obj'], $this->prepared[$stmt]['style'], $stmt);
        }

        return false;
    }

public function fetch ( $ stmt ) { if ( isset ( $ this -> prepared [ $ stmt ] ) && $ this -> prepared [ $ stmt ] [ 'type' ] == 'SELECT' ) { return $ this -> dbFetch ( $ this -> prepared [ $ stmt ] [ 'obj' ] , $ this -> prepared [ $ stmt ] [ 'style' ] , $ stmt ) ; } return false ; }

Get the next row from an executed SELECT statement.

@param int $stmt A ``$db->prepare(...)``d statement's return value.

@return mixed

Get the next row from an executed SELECT statement .


public function log($value = null)
    {
        $log = (is_numeric($value)) ? static::$logs[$this->id][$value] : end(static::$logs[$this->id]);
        if (isset($log['errors'])) {
            $log['errors'] = array_count_values($log['errors']);
        }
        $log['average'] = ($log['count'] > 0) ? $log['executed'] / $log['count'] : 0;
        $log['total'] = $log['prepared'] + $log['executed'];
        $log['time'] = round($log['total'] * 1000).' ms';
        if ($log['count'] > 1) {
            $log['time'] .= ' (~'.round($log['average'] * 1000).' ea)';
        }
        if (is_null($value) || is_numeric($value)) {
            return $log;
        }

        return (isset($log[$value])) ? $log[$value] : null;
    }

public
function
log
(
$
value
=
)
{
$
log
=
(
is_numeric
(
$
value
)
)
static
::
$
logs
[
$
this
->
id
]
[
$
value
]
:
end
(
static
::
$
logs
[
$
this
->
id
]
)
;
if
(
isset
(
$
log
[
'errors'
]
)
)
{
$
log
[
'errors'
]
=
array_count_values
(
$
log
[
'errors'
]
)
;
}
$
log
[
'average'
]
=
(
$
log
[
'count'
]
>
0
)
$
log
[
'executed'
]
/
$
log
[
'count'
]
:
0
;
$
log
[
'total'
]
=
$
log
[
'prepared'
]
+
$
log
[
'executed'
]
;
$
log
[
'time'
]
=
round
(
$
log
[
'total'
]
*
1000
)
.
' ms'
;
if
(
$
log
[
'count'
]
>
1
)
{
$
log
[
'time'
]
.=
' (~'
.
round
(
$
log
[
'average'
]
*
1000
)
.
' ea)'
;
}
if
(
is_null
(
$
value
)
||
is_numeric
(
$
value
)
)
{
return
$
log
;
}
return
(
isset
(
$
log
[
$
value
]
)
)
$
log
[
$
value
]
:
;
}

Returns information about the previously executed query.

@param string $value If you don't want the whole array, then you can specify the specific value you do want.  Either '**sql**', '**count**', '**prepared**', '**executed**', '**errors**', '**average**', '**total**', or '**time**'.

@return mixed

Returns information about the previously executed query .


public function parseValue($value)
    {
        foreach ($this->mappings as $mapping => $replace) {
            if (is_callable($replace)) {
                $value = preg_replace_callback($mapping, $replace, $value);
            } else {
                $value = preg_replace($mapping, $replace, $value);
            }
        }

        return $value;
    }

public function parseValue ( $ value ) { foreach ( $ this -> mappings as $ mapping => $ replace ) { if ( is_callable ( $ replace ) ) { $ value = preg_replace_callback ( $ mapping , $ replace , $ value ) ; } else { $ value = preg_replace ( $ mapping , $ replace , $ value ) ; } } return $ value ; }

Parse the supplied value and return the interpreted value

@param mixed $value

@return mixed


public function filter($value)
    {
        if ($this->_matchPattern == null) {

            throw new Zend_Filter_Exception(get_class($this) . ' does not have a valid MatchPattern set.');
        }

        return preg_replace($this->_matchPattern, $this->_replacement, $value);
    }

Perform regexp replacement as filter

@param  string $value
@return string


protected function dispatchRouter(Request $request): Response
    {
        // Set the request object in the container
        $this->app->container()->singleton(Request::class, $request);

        // Dispatch the before request handled middleware
        $middlewareReturn = $this->requestMiddleware($request);

        // If the middleware returned a response
        if ($middlewareReturn instanceof Response) {
            // Return the response
            return $middlewareReturn;
        }

        return $this->router->dispatch($request);
    }

Dispatch the request via the router.

@param Request $request The request

@return \Valkyrja\Http\Response


protected function terminateRouteMiddleware(Request $request, Response $response): void
    {
        // Ensure a route exists
        if (! $this->app->container()->isSingleton(Route::class)) {
            return;
        }

        /* @var Route $route */
        $route = $this->app->container()->getSingleton(Route::class);

        // If the dispatched route has middleware
        if (null !== $route->getMiddleware()) {
            // Terminate each middleware
            $this->terminableMiddleware(
                $request,
                $response,
                $route->getMiddleware()
            );
        }
    }

Terminate the found route's middleware.

@param Request  $request  The request
@param Response $response The response

@return void

Terminate the found route s middleware .


function startHandler($parser, $element, $attribs)
    {
        $this->_depth++;
        $this->_dataStack[$this->_depth] = null;

        $val = array(
            'name'         => $element,
            'value'        => null,
            'type'         => 'string',
            'childrenKeys' => array(),
            'aggregKeys'   => array()
       );

        if (count($attribs) > 0) {
            $val['children'] = array();
            $val['type'] = 'array';
            $val['children']['attribs'] = $attribs;
        }

        array_push($this->_valStack, $val);
    }

function startHandler ( $ parser , $ element , $ attribs ) { $ this -> _depth ++ ; $ this -> _dataStack [ $ this -> _depth ] = null ; $ val = array ( 'name' => $ element , 'value' => null , 'type' => 'string' , 'childrenKeys' => array ( ) , 'aggregKeys' => array ( ) ) ; if ( count ( $ attribs ) > 0 ) { $ val [ 'children' ] = array ( ) ; $ val [ 'type' ] = 'array' ; $ val [ 'children' ] [ 'attribs' ] = $ attribs ; } array_push ( $ this -> _valStack , $ val ) ; }

Start element handler for XML parser

@access private
@param  object $parser  XML parser object
@param  string $element XML element
@param  array  $attribs attributes of XML tag
@return void


function endHandler($parser, $element)
    {
        $value = array_pop($this->_valStack);
        $data  = $this->postProcess($this->_dataStack[$this->_depth], $element);

        // adjust type of the value
        switch (strtolower($value['type'])) {
            // unserialize an array
            case 'array':
                if ($data !== '') {
                    $value['children']['_content'] = $data;
                }

                $value['value'] = isset($value['children']) ? $value['children'] : array();
                break;

            /*
             * unserialize a null value
             */
            case 'null':
                $data = null;
                break;

            /*
             * unserialize any scalar value
             */
            default:
                settype($data, $value['type']);
                $value['value'] = $data;
                break;
        }

        $parent = array_pop($this->_valStack);
        if ($parent === null) {
            $this->_unserializedData = &$value['value'];
            $this->_root = &$value['name'];
            return true;
        }

        // parent has to be an array
        if (!isset($parent['children']) || !is_array($parent['children'])) {
            $parent['children'] = array();
            if ($parent['type'] != 'array') {
                $parent['type'] = 'array';
            }
        }

        if (!empty($value['name'])) {
            // there already has been a tag with this name
            if (in_array($value['name'], $parent['childrenKeys'])) {
                // no aggregate has been created for this tag
                if (!in_array($value['name'], $parent['aggregKeys'])) {
                    if (isset($parent['children'][$value['name']])) {
                        $parent['children'][$value['name']] = array($parent['children'][$value['name']]);
                    } else {
                        $parent['children'][$value['name']] = array();
                    }
                    array_push($parent['aggregKeys'], $value['name']);
                }
                array_push($parent['children'][$value['name']], $value['value']);
            } else {
                $parent['children'][$value['name']] = &$value['value'];
                array_push($parent['childrenKeys'], $value['name']);
            }
        } else {
            array_push($parent['children'],$value['value']);
        }
        array_push($this->_valStack, $parent);

        $this->_depth--;
    }

/*
             * unserialize a null value
             */

/*
             * unserialize any scalar value
             */

End element handler for XML parser

@access private
@param  object XML parser object
@param  string
@return void


protected function runCommand($command, $basePath, $asset, $result)
    {
        $command = Reaction::$app->getAlias($command);

        $command = strtr($command, [
            '{from}' => escapeshellarg("$basePath/$asset"),
            '{to}' => escapeshellarg("$basePath/$result"),
        ]);
        $descriptor = [
            1 => ['pipe', 'w'],
            2 => ['pipe', 'w'],
        ];
        $pipes = [];
        $proc = proc_open($command, $descriptor, $pipes, $basePath);
        $stdout = stream_get_contents($pipes[1]);
        $stderr = stream_get_contents($pipes[2]);
        foreach ($pipes as $pipe) {
            fclose($pipe);
        }
        $status = proc_close($proc);

        if ($status === 0) {
            Reaction::$app->logger->debug("Converted $asset into $result:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr");
        } elseif (Reaction::isDev()) {
            throw new Exception("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr");
        } else {
            Reaction::error("AssetConverter command '$command' failed with exit code $status:\nSTDOUT:\n$stdout\nSTDERR:\n$stderr");
        }

        return $status === 0;
    }

Runs a command to convert asset files.
@param string $command the command to run. If prefixed with an `@` it will be treated as a [path alias](guide:concept-aliases).
@param string $basePath asset base path and command working directory
@param string $asset the name of the asset file
@param string $result the name of the file to be generated by the converter command
@return bool true on success, false on failure. Failures will be logged.
@throws \Reaction\Exceptions\Exception when the command fails and YII_DEBUG is true.
In production mode the error will be logged.


public function process()
    {
        // $this->channel evaluates to blank in the following if, so store it as a variable
        $channel = $this->channel;

        $client = new Client($this->webhookURL);
        if (empty($channel)) {
            $client->send($this->message);
        } else {
            #Send to designated channel
            $client->to($this->channel)->send($this->message);
        }

        // required to terminate the job
        $this->isComplete = true;
        $this->currentStep = 1;
    }


protected function modifyUploadableBehavior()
    {
        $table = $this->getTable();

        if ($table->hasBehavior('uploadable')) {
            $uploadable = $table->getBehavior('uploadable');
            $parameters = $uploadable->getParameters();
            $up_columns = explode(',', $parameters['columns']);

            foreach (array_keys($this->getColumns()) as $column) {
                foreach ($up_columns as $up_column) {
                    if (trim($up_column) == $column) {
                        continue 2;
                    }
                }

                $up_columns[] = $column;
            }

            $parameters['columns'] = implode(',', $up_columns);
            $uploadable->setParameters($parameters);
        } else {
            $uploadable = new UploadableBehavior();
            $uploadable->setName('uploadable');
            $uploadable->setParameters(array(
                'columns' => implode(',', array_keys($this->getColumns()))
            ));

            $table->addBehavior($uploadable);
        }
    }

protected function modifyUploadableBehavior ( ) { $ table = $ this -> getTable ( ) ; if ( $ table -> hasBehavior ( 'uploadable' ) ) { $ uploadable = $ table -> getBehavior ( 'uploadable' ) ; $ parameters = $ uploadable -> getParameters ( ) ; $ up_columns = explode ( ',' , $ parameters [ 'columns' ] ) ; foreach ( array_keys ( $ this -> getColumns ( ) ) as $ column ) { foreach ( $ up_columns as $ up_column ) { if ( trim ( $ up_column ) == $ column ) { continue 2 ; } } $ up_columns [ ] = $ column ; } $ parameters [ 'columns' ] = implode ( ',' , $ up_columns ) ; $ uploadable -> setParameters ( $ parameters ) ; } else { $ uploadable = new UploadableBehavior ( ) ; $ uploadable -> setName ( 'uploadable' ) ; $ uploadable -> setParameters ( array ( 'columns' => implode ( ',' , array_keys ( $ this -> getColumns ( ) ) ) ) ) ; $ table -> addBehavior ( $ uploadable ) ; } }

Adds or modifies the uploadable behavior


public static function fromJSON($json)
    {
        $request = new static();
        print_r($json);
        $data = json_decode($json, true);
print_r($data);
        if (!$data) {
            throw new UnexpectedValueException(sprintf(
                'Unexpected message, invalid JSON from nginx: "%s"', $json
            ));
        }

        if (isset($data['id'])) {
            $request->setId($data['id']);
        }

        if (isset($data['method'])) {
            $request->setMethod($data['method']);
        }

        if (isset($data['params'])) {
            $request->setPrams($data['params']);
        }

        return $request;
    }

Configure the request based on a JSON

@param  string  $json
@return boolean


public function open($savePath, $name)
    {
        $this->sessionSavePath = $savePath;
        $this->sessionName     = $name;

        return true;
    }

public function open ( $ savePath , $ name ) { $ this -> sessionSavePath = $ savePath ; $ this -> sessionName = $ name ; return true ; }

Open Session - retrieve resources.

@param string $savePath
@param string $name

@return bool


public function read($id)
    {
        $idColumn   = $this->options->getIdColumn();
        $nameColumn = $this->options->getNameColumn();
        $adapter    = $this->getAdapter();

        $sessionData = [
            $idColumn   => $id,
            $nameColumn => $this->sessionName
        ];

        $session = $adapter->select($sessionData);

        if ($session) {
            if ($adapter->isValid($session)) {
                return $this->sanitizeDataRead($id, $adapter->getDataValue($session));
            }

            $this->destroy($id);
        }

        return '';
    }

public function read ( $ id ) { $ idColumn = $ this -> options -> getIdColumn ( ) ; $ nameColumn = $ this -> options -> getNameColumn ( ) ; $ adapter = $ this -> getAdapter ( ) ; $ sessionData = [ $ idColumn => $ id , $ nameColumn => $ this -> sessionName ] ; $ session = $ adapter -> select ( $ sessionData ) ; if ( $ session ) { if ( $ adapter -> isValid ( $ session ) ) { return $ this -> sanitizeDataRead ( $ id , $ adapter -> getDataValue ( $ session ) ) ; } $ this -> destroy ( $ id ) ; } return '' ; }

Read session data.

@param string $id

@return mixed
@throws \Zend\Json\Exception\RuntimeException


public function destroy($id)
    {
        $idColumn    = $this->options->getIdColumn();
        $nameColumn  = $this->options->getNameColumn();
        $adapter     = $this->getAdapter();
        $sessionData = [
            $idColumn   => $id,
            $nameColumn => $this->sessionName
        ];
        $session     = $adapter->select($sessionData);

        if ($session) {
            return (bool) $this->getAdapter()->delete($session);
        }

        return false;
    }

public function destroy ( $ id ) { $ idColumn = $ this -> options -> getIdColumn ( ) ; $ nameColumn = $ this -> options -> getNameColumn ( ) ; $ adapter = $ this -> getAdapter ( ) ; $ sessionData = [ $ idColumn => $ id , $ nameColumn => $ this -> sessionName ] ; $ session = $ adapter -> select ( $ sessionData ) ; if ( $ session ) { return ( bool ) $ this -> getAdapter ( ) -> delete ( $ session ) ; } return false ; }

Destroy Session - remove data from resource for given session id.

@param string $id

@return bool

Destroy Session - remove data from resource for given session id .


public function write($id, $data)
    {
        $idColumn       = $this->options->getIdColumn();
        $nameColumn     = $this->options->getNameColumn();
        $dataColumn     = $this->options->getDataColumn();
        $modifiedColumn = $this->options->getModifiedColumn();
        $createdColumn  = $this->options->getCreatedColumn();
        $lifetimeColumn = $this->options->getLifetimeColumn();
        $adapter        = $this->getAdapter();

        $sessionData = [
            $idColumn   => $id,
            $nameColumn => $this->sessionName
        ];

        $session = $adapter->select($sessionData);

        $sessionData[$dataColumn]     = $this->sanitizeDataWrite($id, $data);
        $sessionData[$modifiedColumn] = new DateTime();

        if ($session) {
            return (bool) $adapter->update($session, $sessionData);
        }

        $sessionData[$lifetimeColumn] = $this->lifetime;
        $sessionData[$createdColumn]  = new DateTime();

        /** @noinspection PhpUndefinedMethodInspection */
        return (bool) $adapter->insert($sessionData);
    }

Write Session - commit data to resource.

@param string $id
@param mixed  $data

@return bool
@throws \InvalidArgumentException

Write Session - commit data to resource .


public static function widget($config = [])
    {
        ob_start();
        ob_implicit_flush(false);
        try {
            /* @var $widget Widget */
            $config['class'] = get_called_class();
            $widget = Reaction::create($config);
            $out = '';
            if ($widget->beforeRun()) {
                $result = $widget->run();
                $out = $widget->afterRun($result);
            }
        } catch (\Exception $e) {
            // close the output buffer opened above if it has not been closed already
            if (ob_get_level() > 0) {
                ob_end_clean();
            }
            throw $e;
        }

        return ob_get_clean() . $out;
    }

Creates a widget instance and runs it.
The widget rendering result is returned by this method.
@param array $config name-value pairs that will be used to initialize the object properties
@return string the rendering result of the widget.

Creates a widget instance and runs it . The widget rendering result is returned by this method .


public function getId($autoGenerate = true)
    {
        if ($autoGenerate && $this->_id === null) {
            $this->_id = static::$autoIdPrefix . $this->htmlHlp->counter++;
        }

        return $this->_id;
    }

public function getId ( $ autoGenerate = true ) { if ( $ autoGenerate && $ this -> _id === null ) { $ this -> _id = static :: $ autoIdPrefix . $ this -> htmlHlp -> counter ++ ; } return $ this -> _id ; }

Returns the ID of the widget.
@param bool $autoGenerate whether to generate an ID if it is not set previously
@return string ID of the widget.


public function beforeRun()
    {
        $isValid = true;
        $this->emit(self::EVENT_BEFORE_RUN, [$this, &$isValid]);
        return $isValid;
    }

public function beforeRun ( ) { $ isValid = true ; $ this -> emit ( self :: EVENT_BEFORE_RUN , [ $ this , & $ isValid ] ) ; return $ isValid ; }

This method is invoked right before the widget is executed.

The method will trigger the [[EVENT_BEFORE_RUN]] event. The return value of the method
will determine whether the widget should continue to run.

When overriding this method, make sure you call the parent implementation like the following:

```php
public function beforeRun()
{
if (!parent::beforeRun()) {
return false;
}

// your custom code here

return true; // or false to not run the widget
}
```
@return bool

This method is invoked right before the widget is executed .


protected function checkAppPersistence()
    {
        if (!isset($this->app) || !$this->app instanceof Reaction\RequestApplicationInterface) {
            $message = sprintf("You must specify \$app (RequestApplicationInterface) parameter for widget '%s'", get_called_class());
            throw new Reaction\Exceptions\InvalidConfigException($message);
        }
    }

Check that RequestApplicationInterface is set
@throws Reaction\Exceptions\InvalidConfigException


public static function where($field, $value, $dbConn = NULL)
    {
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

        try {
			$query = $dbConn->prepare('SELECT * FROM ' . $table . ' WHERE ' . $field . ' = ?');
			$query->execute([$value]);
        } catch (PDOException $e) {
            return $e->getMessage();
        } finally {
            $dbConn = null;
        }

        if ($query->rowCount()) {
            $found = new static;
            $found->dbData = $query->fetch(DbConn::FETCH_ASSOC);

            return $found;
        } else {
            throw new RecordNotFoundException;
        }
    }

public
static
function
where
(
$
field
,
$
value
,
$
dbConn
=
)
{
$
table
=
Backbone
::
getTable
(
get_called_class
(
)
,
$
dbConn
)
;
if
(
is_null
(
$
dbConn
)
)
{
$
dbConn
=
Backbone
::
makeDbConn
(
)
;
}
try
{
$
query
=
$
dbConn
->
prepare
(
'SELECT * FROM '
.
$
table
.
' WHERE '
.
$
field
.
' = ?'
)
;
$
query
->
execute
(
[
$
value
]
)
;
}
catch
(
PDOException
$
e
)
{
return
$
e
->
getMessage
(
)
;
}
finally
{
$
dbConn
=
;
}
if
(
$
query
->
rowCount
(
)
)
{
$
found
=
new
static
;
$
found
->
dbData
=
$
query
->
fetch
(
DbConn
::
FETCH_ASSOC
)
;
return
$
found
;
}
else
{
throw
new
RecordNotFoundException
;
}
}

Get a record in the database

@param string $field Field name to search under
@param string $value Field value to search for
@return string|object


public static function destroy($record, $dbConn = NULL)
	{
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

		try {
			$query = $dbConn->prepare('DELETE FROM ' . $table . ' WHERE id= ' . $record);
			$query->execute();
		} catch (PDOException $e) {
			return $e->getMessage();
		} finally {
			$dbConn = null;
		}

		$check = $query->rowCount();

		if ($check) {
			return $check;
		} else {
			throw new RecordNotFoundException;
		}
	}

public
static
function
destroy
(
$
record
,
$
dbConn
=
)
{
$
table
=
Backbone
::
getTable
(
get_called_class
(
)
,
$
dbConn
)
;
if
(
is_null
(
$
dbConn
)
)
{
$
dbConn
=
Backbone
::
makeDbConn
(
)
;
}
try
{
$
query
=
$
dbConn
->
prepare
(
'DELETE FROM '
.
$
table
.
' WHERE id= '
.
$
record
)
;
$
query
->
execute
(
)
;
}
catch
(
PDOException
$
e
)
{
return
$
e
->
getMessage
(
)
;
}
finally
{
$
dbConn
=
;
}
$
check
=
$
query
->
rowCount
(
)
;
if
(
$
check
)
{
return
$
check
;
}
else
{
throw
new
RecordNotFoundException
;
}
}

Delete a record from the database table

@param int $record Index of record to be deleted
@return bool|string


public static function getAll($dbConn = NULL)
	{
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

		try {
			$query = $dbConn->prepare('SELECT * FROM ' . $table);
			$query->execute();
		} catch (PDOException $e) {
			return $e->getMessage();
		} finally {
			$dbConn = null;
		}

		if ($query->rowCount()) {
			return $query->fetchAll(DbConn::FETCH_ASSOC);
		} else {
			throw new EmptyTableException;
		}
	}

public
static
function
getAll
(
$
dbConn
=
)
{
$
table
=
Backbone
::
getTable
(
get_called_class
(
)
,
$
dbConn
)
;
if
(
is_null
(
$
dbConn
)
)
{
$
dbConn
=
Backbone
::
makeDbConn
(
)
;
}
try
{
$
query
=
$
dbConn
->
prepare
(
'SELECT * FROM '
.
$
table
)
;
$
query
->
execute
(
)
;
}
catch
(
PDOException
$
e
)
{
return
$
e
->
getMessage
(
)
;
}
finally
{
$
dbConn
=
;
}
if
(
$
query
->
rowCount
(
)
)
{
return
$
query
->
fetchAll
(
DbConn
::
FETCH_ASSOC
)
;
}
else
{
throw
new
EmptyTableException
;
}
}

Get all the records in a database table

@return string|object


public function save($dbConn = NULL)
    {
		$table = Backbone::getTable(get_called_class(), $dbConn);

		if (is_null($dbConn)) {
			$dbConn = Backbone::makeDbConn();
		}

        try {
            if (isset($this->record['dbData']) && is_array($this->record['dbData'])) {
                $sql = 'UPDATE ' . $table . ' SET ' . Backbone::tokenize(implode(',', Backbone::joinKeysAndValuesOfArray($this->record)), ',') . ' WHERE id=' . $this->record['dbData']['id'];
                $query = $dbConn->prepare($sql);
                $query->execute();
            } else {
                $sql = 'INSERT INTO ' . $table . ' (' . Backbone::tokenize(implode(',', array_keys($this->record)), ',') . ')' . ' VALUES ' . '(' . Backbone::tokenize(implode(',', Backbone::generateUnnamedPlaceholders($this->record)), ',') . ')';
                $query = $dbConn->prepare($sql);
                $query->execute(array_values($this->record));
            }
        } catch (PDOException $e) {
            return $e->getMessage();
        } finally {
            $dbConn = null;
        }

        return $query->rowCount();
    }

public
function
save
(
$
dbConn
=
)
{
$
table
=
Backbone
::
getTable
(
get_called_class
(
)
,
$
dbConn
)
;
if
(
is_null
(
$
dbConn
)
)
{
$
dbConn
=
Backbone
::
makeDbConn
(
)
;
}
try
{
if
(
isset
(
$
this
->
record
[
'dbData'
]
)
&&
is_array
(
$
this
->
record
[
'dbData'
]
)
)
{
$
sql
=
'UPDATE '
.
$
table
.
' SET '
.
Backbone
::
tokenize
(
implode
(
','
,
Backbone
::
joinKeysAndValuesOfArray
(
$
this
->
record
)
)
,
','
)
.
' WHERE id='
.
$
this
->
record
[
'dbData'
]
[
'id'
]
;
$
query
=
$
dbConn
->
prepare
(
$
sql
)
;
$
query
->
execute
(
)
;
}
else
{
$
sql
=
'INSERT INTO '
.
$
table
.
' ('
.
Backbone
::
tokenize
(
implode
(
','
,
array_keys
(
$
this
->
record
)
)
,
','
)
.
')'
.
' VALUES '
.
'('
.
Backbone
::
tokenize
(
implode
(
','
,
Backbone
::
generateUnnamedPlaceholders
(
$
this
->
record
)
)
,
','
)
.
')'
;
$
query
=
$
dbConn
->
prepare
(
$
sql
)
;
$
query
->
execute
(
array_values
(
$
this
->
record
)
)
;
}
}
catch
(
PDOException
$
e
)
{
return
$
e
->
getMessage
(
)
;
}
finally
{
$
dbConn
=
;
}
return
$
query
->
rowCount
(
)
;
}

Insert or Update a record in a database table

@return bool|string


public function index()
    {
        //~ Breadcrumb
        $this->breadcrumb->add((new BreadcrumbItem('List'))->setIcon('list')->setIsActive(true));

        $get    = Get::getInstance();
        $params = $this->route->getParameterCollection();

        $account = null;
        $date    = new \DateTimeImmutable(date('Y-m-01'));

        if ($params->hasByName('id')) {

            $account = $this->verifyAccount((int) $params->getByName('id')->getValue());

            if ($get->has('date_start')) {
                $date = new \DateTimeImmutable($get->get('date_start'));
                $date = $date->setDate($date->format('Y'), $date->format('m'), 1);
            }

            $this->checkMonth($account->getId(), $date);
        }

        //~ Content
        $this->dataCollection->add('title',   'Budgets');
        $this->dataCollection->add('date',    $date);
        $this->dataCollection->add('account', $account);

        return $this->getResponse('Budgets');
    }

public
function
index
(
)
{
//~ Breadcrumb
$
this
->
breadcrumb
->
add
(
(
new
BreadcrumbItem
(
'List'
)
)
->
setIcon
(
'list'
)
->
setIsActive
(
true
)
)
;
$
get
=
Get
::
getInstance
(
)
;
$
params
=
$
this
->
route
->
getParameterCollection
(
)
;
$
account
=
;
$
date
=
new
\
DateTimeImmutable
(
date
(
'Y-m-01'
)
)
;
if
(
$
params
->
hasByName
(
'id'
)
)
{
$
account
=
$
this
->
verifyAccount
(
(
int
)
$
params
->
getByName
(
'id'
)
->
getValue
(
)
)
;
if
(
$
get
->
has
(
'date_start'
)
)
{
$
date
=
new
\
DateTimeImmutable
(
$
get
->
get
(
'date_start'
)
)
;
$
date
=
$
date
->
setDate
(
$
date
->
format
(
'Y'
)
,
$
date
->
format
(
'm'
)
,
1
)
;
}
$
this
->
checkMonth
(
$
account
->
getId
(
)
,
$
date
)
;
}
//~ Content
$
this
->
dataCollection
->
add
(
'title'
,
'Budgets'
)
;
$
this
->
dataCollection
->
add
(
'date'
,
$
date
)
;
$
this
->
dataCollection
->
add
(
'account'
,
$
account
)
;
return
$
this
->
getResponse
(
'Budgets'
)
;
}

Main controller action. OK

@return ResponseInterface


public function ajaxList()
    {
        if (!Server::getInstance()->isAjax()) {
            throw new \RuntimeException();
        }

        $get = Get::getInstance();

        $accountId = (int) $this->route->getParameterCollection()->getByName('id')->getValue();

        //~ Retrieve user account / account
        $account = $this->verifyAccount($accountId);

        if ($get->has('date_start')) {
            $dateStart = new \DateTimeImmutable($get->get('date_start'));
        } else {
            $dateStart = new \DateTimeImmutable(date('Y-m-01'));
        }

        $budgetMapper = new BudgetMapper(Database::get('money'));
        $budgets = $budgetMapper->findAllByDate($account, $dateStart);

        $this->dataCollection->add('account', $account);
        $this->dataCollection->add('budgets', $budgets);
        $this->dataCollection->add('isMain',  true);
        $this->dataCollection->add('date',    $dateStart);
        $this->dataCollection->add('total',   array('planned' => 0.0, 'transactions' => 0.0, 'diff' => 0.0));

        return $this->getResponse('Partial/Budget', true);
    }

public
function
ajaxList
(
)
{
if
(
!
Server
::
getInstance
(
)
->
isAjax
(
)
)
{
throw
new
\
RuntimeException
(
)
;
}
$
get
=
Get
::
getInstance
(
)
;
$
accountId
=
(
int
)
$
this
->
route
->
getParameterCollection
(
)
->
getByName
(
'id'
)
->
getValue
(
)
;
//~ Retrieve user account / account
$
account
=
$
this
->
verifyAccount
(
$
accountId
)
;
if
(
$
get
->
has
(
'date_start'
)
)
{
$
dateStart
=
new
\
DateTimeImmutable
(
$
get
->
get
(
'date_start'
)
)
;
}
else
{
$
dateStart
=
new
\
DateTimeImmutable
(
date
(
'Y-m-01'
)
)
;
}
$
budgetMapper
=
new
BudgetMapper
(
Database
::
get
(
'money'
)
)
;
$
budgets
=
$
budgetMapper
->
findAllByDate
(
$
account
,
$
dateStart
)
;
$
this
->
dataCollection
->
add
(
'account'
,
$
account
)
;
$
this
->
dataCollection
->
add
(
'budgets'
,
$
budgets
)
;
$
this
->
dataCollection
->
add
(
'isMain'
,
true
)
;
$
this
->
dataCollection
->
add
(
'date'
,
$
dateStart
)
;
$
this
->
dataCollection
->
add
(
'total'
,
array
(
'planned'
=>
0.0
,
'transactions'
=>
0.0
,
'diff'
=>
0.0
)
)
;
return
$
this
->
getResponse
(
'Partial/Budget'
,
true
)
;
}

Load items.

@return ResponseInterface
@throws \Exception


protected function verifyAccount($accountId)
    {
        //~ Verify if account is for current user, else throw error 500
        $mapper      = new AccountUserMapper(Database::get('money'));
        $accountUser = $mapper->findByKeys(array('user_id' => Session::getInstance()->get('id'), 'account_id' => $accountId));
        return $accountUser->getAccount();
    }

Verify if account is really owned by current user and return account object.

@param  integer $accountId
@return Account

Verify if account is really owned by current user and return account object .


protected function loadNavBar()
    {
        $this->breadcrumb->add((new BreadcrumbItem('Budget'))
            ->setIcon('money')
            ->setUri('#'));

        $bankMapper = new BankMapper(Database::get('money'));
        $banks      = $bankMapper->select();

        $accountUserMapper = new AccountUserMapper(Database::get('money'));
        $userAccounts      = $accountUserMapper->findByUserId((int) Session::getInstance()->get('id'));

        $accounts = array();
        foreach ($userAccounts as $userAccount) {
            $account = $userAccount->getAccount();

            if ($account->isVirtual()) {
                continue;
            }

            if (!isset($accounts[$account->getBankId()])) {
                $accounts[$account->getBankId()] = array();
            }

            $accounts[$account->getBankId()][] = $account;
        }

        $this->dataCollection->add('banks', $banks);
        $this->dataCollection->add('accounts', $accounts);

        $params = $this->route->getParameterCollection();
        $get    = Get::getInstance();

        try {
            $dateStart = new \DateTimeImmutable($get->get('date_start', date('Y-m-01')));
        } catch(\Exception $exception) {
            $dateStart = new \DateTimeImmutable();
        }

        $this->navForm->setParams(array(
            'banks'            => $banks,
            'accounts'         => $accounts,
            'currentAccountId' => ($params->hasByName('id') ? (int) $params->getByName('id')->getValue() : 0),
            'dateStart'        => $dateStart,
            'date'             => new \DateTimeImmutable(date('Y-m-01')),
        ));

        $this->navForm->setTemplate($this->appTplPath . '/Partial/NavbarForm');
    }

protected function loadNavBar ( ) { $ this -> breadcrumb -> add ( ( new BreadcrumbItem ( 'Budget' ) ) -> setIcon ( 'money' ) -> setUri ( '#' ) ) ; $ bankMapper = new BankMapper ( Database :: get ( 'money' ) ) ; $ banks = $ bankMapper -> select ( ) ; $ accountUserMapper = new AccountUserMapper ( Database :: get ( 'money' ) ) ; $ userAccounts = $ accountUserMapper -> findByUserId ( ( int ) Session :: getInstance ( ) -> get ( 'id' ) ) ; $ accounts = array ( ) ; foreach ( $ userAccounts as $ userAccount ) { $ account = $ userAccount -> getAccount ( ) ; if ( $ account -> isVirtual ( ) ) { continue ; } if ( ! isset ( $ accounts [ $ account -> getBankId ( ) ] ) ) { $ accounts [ $ account -> getBankId ( ) ] = array ( ) ; } $ accounts [ $ account -> getBankId ( ) ] [ ] = $ account ; } $ this -> dataCollection -> add ( 'banks' , $ banks ) ; $ this -> dataCollection -> add ( 'accounts' , $ accounts ) ; $ params = $ this -> route -> getParameterCollection ( ) ; $ get = Get :: getInstance ( ) ; try { $ dateStart = new \ DateTimeImmutable ( $ get -> get ( 'date_start' , date ( 'Y-m-01' ) ) ) ; } catch ( \ Exception $ exception ) { $ dateStart = new \ DateTimeImmutable ( ) ; } $ this -> navForm -> setParams ( array ( 'banks' => $ banks , 'accounts' => $ accounts , 'currentAccountId' => ( $ params -> hasByName ( 'id' ) ? ( int ) $ params -> getByName ( 'id' ) -> getValue ( ) : 0 ) , 'dateStart' => $ dateStart , 'date' => new \ DateTimeImmutable ( date ( 'Y-m-01' ) ) , ) ) ; $ this -> navForm -> setTemplate ( $ this -> appTplPath . '/Partial/NavbarForm' ) ; }

Load navbar for budgets pages
@return void
@throws \Exception


protected function checkMonth($accountId, \DateTimeImmutable $date)
    {
        $mapper = new BudgetMapper(Database::get('money'));
        $budgetMonthMapper = new BudgetMonthMapper(Database::get('money'));

        $budgetMonthMapper->check($mapper->findAllByAccountId($accountId), $date);
    }

protected function checkMonth ( $ accountId , \ DateTimeImmutable $ date ) { $ mapper = new BudgetMapper ( Database :: get ( 'money' ) ) ; $ budgetMonthMapper = new BudgetMonthMapper ( Database :: get ( 'money' ) ) ; $ budgetMonthMapper -> check ( $ mapper -> findAllByAccountId ( $ accountId ) , $ date ) ; }

Check for budget month.

@param  int $accountId
@param  \DateTimeImmutable $date
@return void


function setup(&$installer, $pkg, $atts, $file)
    {
        $this->installer = &$installer;
        $reg = &$this->installer->config->getRegistry();
        $package = $reg->getPackage($pkg->getPackage(), $pkg->getChannel());
        if ($package) {
            $filelist = $package->getFilelist();
            if (isset($filelist[$file]) && isset($filelist[$file]['md5sum'])) {
                $this->md5 = $filelist[$file]['md5sum'];
            }
        }
    }

function setup ( & $ installer , $ pkg , $ atts , $ file ) { $ this -> installer = & $ installer ; $ reg = & $ this -> installer -> config -> getRegistry ( ) ; $ package = $ reg -> getPackage ( $ pkg -> getPackage ( ) , $ pkg -> getChannel ( ) ) ; if ( $ package ) { $ filelist = $ package -> getFilelist ( ) ; if ( isset ( $ filelist [ $ file ] ) && isset ( $ filelist [ $ file ] [ 'md5sum' ] ) ) { $ this -> md5 = $ filelist [ $ file ] [ 'md5sum' ] ; } } }

Do any unusual setup here
@param PEAR_Installer
@param PEAR_PackageFile_v2
@param array file attributes
@param string file name


public function execute(...$constructParameters)
    {
        $class      = $this->class;
        $method     = $this->method;
        $parameters = array_values($this->parameters);

        $instance = new $class(...$constructParameters);
        return $instance->$method(...$parameters);
    }

public function execute ( ... $ constructParameters ) { $ class = $ this -> class ; $ method = $ this -> method ; $ parameters = array_values ( $ this -> parameters ) ; $ instance = new $ class ( ... $ constructParameters ) ; return $ instance -> $ method ( ... $ parameters ) ; }

Instantiates the route's class and calls the route's methods using the parameters found in the url

@return mixed

Instantiates the route s class and calls the route s methods using the parameters found in the url


public function name()
    {
        if(isset($this->first_name) && isset($this->surname))
            return $this->first_name . ' ' . $this->surname;
        elseif(isset($this->first_name))
            return $this->first_name;
        else
            return $this->user;
    }

public
function
name
(
)
{
if
(
isset
(
$
this
->
first_name
)
&&
isset
(
$
this
->
surname
)
)
return
$
this
->
first_name
.
' '
.
$
this
->
surname
;
elseif
(
isset
(
$
this
->
first_name
)
)
return
$
this
->
first_name
;
else
return
$
this
->
user
;
}

Outputs a human readable name, base on firstname and surname, if they exist for the user,
but falling back on username, otherwise

Outputs a human readable name base on firstname and surname if they exist for the user but falling back on username otherwise


public function save()
    {
        $reflection = new \ReflectionObject($this);
        $properties = $reflection->getProperties(\ReflectionProperty::IS_PUBLIC);
        foreach($properties as $prop)
            $info[$prop->name] = $this->{$prop->name};
        return $this->auth->db->update($this->auth->prefix.'users', $info, ['id' => $this->id]);
    }

public function save ( ) { $ reflection = new \ ReflectionObject ( $ this ) ; $ properties = $ reflection -> getProperties ( \ ReflectionProperty :: IS_PUBLIC ) ; foreach ( $ properties as $ prop ) $ info [ $ prop -> name ] = $ this -> { $ prop -> name } ; return $ this -> auth -> db -> update ( $ this -> auth -> prefix . 'users' , $ info , [ 'id' => $ this -> id ] ) ; }

Save any changes to user properties that may have been made to the database


public function changePass($old, $new1, $new2)
    {
        if(!$this->auth->authUser($this->user, $old))
            return False;
        elseif($new1 != $new2)
            return False;
        else
            $hash = password_hash($new1, PASSWORD_BCRYPT);
            return $this->auth->db->update($this->auth->prefix.'users', ['pass' => $hash] , ['id' => $this->id]);
    }

public function changePass ( $ old , $ new1 , $ new2 ) { if ( ! $ this -> auth -> authUser ( $ this -> user , $ old ) ) return False ; elseif ( $ new1 != $ new2 ) return False ; else $ hash = password_hash ( $ new1 , PASSWORD_BCRYPT ) ; return $ this -> auth -> db -> update ( $ this -> auth -> prefix . 'users' , [ 'pass' => $ hash ] , [ 'id' => $ this -> id ] ) ; }

Changes the password for the current user
takes current password, then the new password twice as inputs

Changes the password for the current user takes current password then the new password twice as inputs


public function give( $implementation )
    {
        $this->container->addContextualBindings( $this->concrete, $this->needs, $implementation );
    }

public function give ( $ implementation ) { $ this -> container -> addContextualBindings ( $ this -> concrete , $ this -> needs , $ implementation ) ; }

Define the implementation for the contextual binding.

@param  Closure|string $implementation

Define the implementation for the contextual binding .


protected function getWriter(ServiceLocatorInterface $serviceLocator, string $name, array $options): object
    {
        return $serviceLocator->getService($name, $options);
    }

protected function getWriter ( ServiceLocatorInterface $ serviceLocator , string $ name , array $ options ) : object { return $ serviceLocator -> getService ( $ name , $ options ) ; }

Get writer for name with options.

@param ServiceLocatorInterface $serviceLocator
@param string                  $name
@param array                   $options
@return WriterInterface
@throws ServiceLocatorException


private function parseVersion()
    {
        if (StaticStringy::startsWith($this->versionString, 'v')) {
            $this->versionString = StaticStringy::substr($this->versionString, 1);
        }
        if (strstr($this->versionString, '-')) {
            if (sscanf(
                $this->versionString,
                '%d.%d.%d-%s',
                $this->major,
                $this->minor,
                $this->release,
                $this->suffix
            ) != 4
            ) {
                throw new InvalidArgumentException('Invalid version format ' . $this->versionString);
            }
        } else {
            if (sscanf($this->versionString, '%d.%d.%d', $this->major, $this->minor, $this->release) != 3) {
                throw new InvalidArgumentException('Invalid version format ' . $this->versionString);
            }
        }
    }

private
function
parseVersion
(
)
{
if
(
StaticStringy
::
startsWith
(
$
this
->
versionString
,
'v'
)
)
{
$
this
->
versionString
=
StaticStringy
::
substr
(
$
this
->
versionString
,
1
)
;
}
if
(
strstr
(
$
this
->
versionString
,
'-'
)
)
{
if
(
sscanf
(
$
this
->
versionString
,
'%d.%d.%d-%s'
,
$
this
->
major
,
$
this
->
minor
,
$
this
->
release
,
$
this
->
suffix
)
!=
4
)
{
throw
new
InvalidArgumentException
(
'Invalid version format '
.
$
this
->
versionString
)
;
}
}
else
{
if
(
sscanf
(
$
this
->
versionString
,
'%d.%d.%d'
,
$
this
->
major
,
$
this
->
minor
,
$
this
->
release
)
!=
3
)
{
throw
new
InvalidArgumentException
(
'Invalid version format '
.
$
this
->
versionString
)
;
}
}
}

Parse version string

@throws \ThinFrame\Foundation\Exception\InvalidArgumentException


public function compare(VersionInterface $version)
    {
        if ($this->getMajorVersion() < $version->getMajorVersion()) {
            return -1;
        } elseif ($this->getMajorVersion() > $version->getMajorVersion()) {
            return 1;
        } else {
            if ($this->getMinorVersion() < $version->getMinorVersion()) {
                return -1;
            } elseif ($this->getMinorVersion() > $version->getMinorVersion()) {
                return 1;
            } else {
                if ($this->getReleaseVersion() < $version->getReleaseVersion()) {
                    return -1;
                } elseif ($this->getReleaseVersion() > $version->getReleaseVersion()) {
                    return 1;
                } else {
                    return 0;
                }
            }
        }
    }

public function compare ( VersionInterface $ version ) { if ( $ this -> getMajorVersion ( ) < $ version -> getMajorVersion ( ) ) { return - 1 ; } elseif ( $ this -> getMajorVersion ( ) > $ version -> getMajorVersion ( ) ) { return 1 ; } else { if ( $ this -> getMinorVersion ( ) < $ version -> getMinorVersion ( ) ) { return - 1 ; } elseif ( $ this -> getMinorVersion ( ) > $ version -> getMinorVersion ( ) ) { return 1 ; } else { if ( $ this -> getReleaseVersion ( ) < $ version -> getReleaseVersion ( ) ) { return - 1 ; } elseif ( $ this -> getReleaseVersion ( ) > $ version -> getReleaseVersion ( ) ) { return 1 ; } else { return 0 ; } } } }

Compare with another version

@param VersionInterface $version

@return int (-1,0,1)


public function getBranch($parentId)
    {
        $criteria = new CDbCriteria();
        $criteria->index = 'descendantId';
        $criteria->addCondition('ancestorId=:parentId AND depth=1');
        $criteria->params[':parentId'] = $parentId;
        $root = CActiveRecord::model($this->treeClass)->findAll($criteria);
        $children = $this->owner->findAllByPk(array_keys($root));
        return $children;
    }

public
function
getBranch
(
$
parentId
)
{
$
criteria
=
new
CDbCriteria
(
)
;
$
criteria
->
index
=
'descendantId'
;
$
criteria
->
addCondition
(
'ancestorId=:parentId AND depth=1'
)
;
$
criteria
->
params
[
':parentId'
]
=
$
parentId
;
$
root
=
CActiveRecord
::
model
(
$
this
->
treeClass
)
->
findAll
(
$
criteria
)
;
$
children
=
$
this
->
owner
->
findAllByPk
(
array_keys
(
$
root
)
)
;
return
$
children
;
}

Returns the direct children for the model with the given parent id.
@param int $parentId the parent id.
@return CActiveRecord[] the children.

Returns the direct children for the model with the given parent id .


public function getParent()
    {
        // Load the "current" level from the tree
        $currentLevel = CActiveRecord::model($this->treeClass)->findByAttributes(
            array('descendantId' => $this->owner->{$this->idAttribute}, 'depth' => 1)
        );

        if ($currentLevel->ancestorId > 0) {
            return CActiveRecord::model(get_class($this->owner))->findByPk($currentLevel->ancestorId);
        } else {
            return null;
        }
    }

Get the parent of a model.
@return CActiveRecord


public function getParents($includeSelf = true)
    {
        $parents = array();

        if ($includeSelf) {
            $parents[$this->owner->{$this->idAttribute}] = $this->owner;
        }

        // Try and find a parent
        $parent = $this->getParent();
        if ($parent instanceof CActiveRecord) {
            $parents[$parent->{$this->idAttribute}] = $parent;

            // Fetch any additional ancestry levels
            while ($nextParent = $parent->getParent()) {
                $parents[$nextParent->{$this->idAttribute}] = $nextParent;
                $parent = $nextParent;
            }
        }

        return array_reverse($parents, true);
    }

public
function
getParents
(
$
includeSelf
=
true
)
{
$
parents
=
array
(
)
;
if
(
$
includeSelf
)
{
$
parents
[
$
this
->
owner
->
{
$
this
->
idAttribute
}
]
=
$
this
->
owner
;
}
// Try and find a parent
$
parent
=
$
this
->
getParent
(
)
;
if
(
$
parent
instanceof
CActiveRecord
)
{
$
parents
[
$
parent
->
{
$
this
->
idAttribute
}
]
=
$
parent
;
// Fetch any additional ancestry levels
while
(
$
nextParent
=
$
parent
->
getParent
(
)
)
{
$
parents
[
$
nextParent
->
{
$
this
->
idAttribute
}
]
=
$
nextParent
;
$
parent
=
$
nextParent
;
}
}
return
array_reverse
(
$
parents
,
true
)
;
}

Returns the parents for this node.
@param bool $includeSelf
@return CActiveRecord[] the parents.


protected function arrayify(Container $o) {
		$a = [];

		foreach ($o->props as $k => $v) {
			if ($v instanceof Container) {
				$a[$k] = $this->arrayify($v);
			} else {
				$a[$k] = $v;
			}
		}

		return $a;
	}

protected function arrayify ( Container $ o ) { $ a = [ ] ; foreach ( $ o -> props as $ k => $ v ) { if ( $ v instanceof Container ) { $ a [ $ k ] = $ this -> arrayify ( $ v ) ; } else { $ a [ $ k ] = $ v ; } } return $ a ; }

Recursively turn a container and its childs into an array
@param \merry\Container $o the Container instance to convert to an array
@return array


public function apply($modifier) {
		if (is_callable($modifier)) {
			foreach ($this->props as $prop => $value) {
				$this->__set($prop, $modifier($value, $prop));
			}
		} else {
			foreach ($modifier as $key => $mod) {
				if (is_callable($mod)) {
					$this->props->$key = $mod(isset($this->props->$key) ? $this->props->$key : null, $key);
				} elseif (is_array($mod)) {
					$this->props->$key->apply($mod);
				} else {
					/* */
				}
			}
		}
		return $this;
	}

public
function
apply
(
$
modifier
)
{
if
(
is_callable
(
$
modifier
)
)
{
foreach
(
$
this
->
props
as
$
prop
=>
$
value
)
{
$
this
->
__set
(
$
prop
,
$
modifier
(
$
value
,
$
prop
)
)
;
}
}
else
{
foreach
(
$
modifier
as
$
key
=>
$
mod
)
{
if
(
is_callable
(
$
mod
)
)
{
$
this
->
props
->
$
key
=
$
mod
(
isset
(
$
this
->
props
->
$
key
)
$
this
->
props
->
$
key
:
,
$
key
)
;
}
elseif
(
is_array
(
$
mod
)
)
{
$
this
->
props
->
$
key
->
apply
(
$
mod
)
;
}
else
{
/* */
}
}
}
return
$
this
;
}

Apply one or mor modifier callbacks
@param mixed $modifier
@return \merry\Container


public static function fromUrl($cssUrl, $baseUrl, $mediaType = 'all')
    {
        // Match URL.
        if (strpos($cssUrl, $baseUrl) === false) {
            throw new \InvalidArgumentException('The CSS URL does not begin with the base URL');
        }

        // Create.
        $baseLength = strlen(rtrim($baseUrl, '/')) + 1;
        $path = substr($cssUrl, $baseLength);
        return new CssResource($path, $mediaType);
    }


public function getAddressBook()
    {
        $acquaintances = Auth::user()->getAcquaintances();

        return view('mustard::messages.address-book', [
            'acquaintances' => new Paginator($acquaintances, $acquaintances->count(), config('per_page', 25)),
        ]);
    }

public function getAddressBook ( ) { $ acquaintances = Auth :: user ( ) -> getAcquaintances ( ) ; return view ( 'mustard::messages.address-book' , [ 'acquaintances' => new Paginator ( $ acquaintances , $ acquaintances -> count ( ) , config ( 'per_page' , 25 ) ) , ] ) ; }

Return the messaging address book view.

@return \Illuminate\View\View

Return the messaging address book view .


public function getCompose()
    {
        $acquaintances = Auth::user()->getAcquaintances();

        if ($acquaintances->isEmpty()) {
            return redirect()->to('/account/contacts')->withStatus('Your contacts list is empty.');
        }

        return view('mustard::messages.compose', [
            'acquaintances' => $acquaintances->sortBy('username', SORT_NATURAL | SORT_FLAG_CASE),
            'message'       => new Message(),
        ]);
    }

public
function
getCompose
(
)
{
$
acquaintances
=
Auth
::
user
(
)
->
getAcquaintances
(
)
;
if
(
$
acquaintances
->
isEmpty
(
)
)
{
return
redirect
(
)
->
to
(
'/account/contacts'
)
->
withStatus
(
'Your contacts list is empty.'
)
;
}
return
view
(
'mustard::messages.compose'
,
[
'acquaintances'
=>
$
acquaintances
->
sortBy
(
'username'
,
SORT_NATURAL
|
SORT_FLAG_CASE
)
,
'message'
=>
new
Message
(
)
,
]
)
;
}

Return the messaging compose view.

@return \Illuminate\View\View


public function getView($messageId)
    {
        $message = Message::find($messageId);

        $message->read = true;

        $message->save();

        return view('mustard::messages.view', [
            'message' => $message,
        ]);
    }

public function getView ( $ messageId ) { $ message = Message :: find ( $ messageId ) ; $ message -> read = true ; $ message -> save ( ) ; return view ( 'mustard::messages.view' , [ 'message' => $ message , ] ) ; }

Return the messaging message view.

@param int $messageId

@return \Illuminate\View\View


public function postManage(Request $request)
    {
        foreach ($request->input('messages') as $message_id) {
            $message = Message::find($message_id);

            if (is_null($message) || !$request->has('action')) {
                continue;
            }

            switch ($request->input('action')) {
                case 'mark_read':
                    if ($message->read == false) {
                        $message->read = true;

                        $message->save();
                    }

                    break;
                case 'mark_unread':
                    if ($message->read == true) {
                        $message->read = false;

                        $message->save();
                    }

                    break;
                case 'delete':
                    $message->delete();

                    break;
            }
        }

        return redirect()->back();
    }

public function postManage ( Request $ request ) { foreach ( $ request -> input ( 'messages' ) as $ message_id ) { $ message = Message :: find ( $ message_id ) ; if ( is_null ( $ message ) || ! $ request -> has ( 'action' ) ) { continue ; } switch ( $ request -> input ( 'action' ) ) { case 'mark_read' : if ( $ message -> read == false ) { $ message -> read = true ; $ message -> save ( ) ; } break ; case 'mark_unread' : if ( $ message -> read == true ) { $ message -> read = false ; $ message -> save ( ) ; } break ; case 'delete' : $ message -> delete ( ) ; break ; } } return redirect ( ) -> back ( ) ; }

Manage message flags.

@param \Illuminate\Http\Request $request

@return \Illuminate\Http\RedirectResponse


protected function _appendExtensionsToPaths(array $paths, array $extensions)
    {
        $getPathsWithExtensions = function($path) use($extensions) {
            if ($this->_hasExtension($path)) {
                return [$path];
            }

            $addExtension = function($extension) use($path) {
                return $this->_addExtension($path, $extension);
            };

            return array_map($addExtension, $extensions);
        };

        return call_user_func_array('array_merge', array_map($getPathsWithExtensions, $paths));
    }

protected function _appendExtensionsToPaths ( array $ paths , array $ extensions ) { $ getPathsWithExtensions = function ( $ path ) use ( $ extensions ) { if ( $ this -> _hasExtension ( $ path ) ) { return [ $ path ] ; } $ addExtension = function ( $ extension ) use ( $ path ) { return $ this -> _addExtension ( $ path , $ extension ) ; } ; return array_map ( $ addExtension , $ extensions ) ; } ; return call_user_func_array ( 'array_merge' , array_map ( $ getPathsWithExtensions , $ paths ) ) ; }

Append the extensions to the paths.

@param array $paths The file paths to append to.
@param array $extensions The extensions.
@return array The full combination of every path with every extension.


public function destroy(): void {

		// see example here http://goo.gl/nBVl0

		$this->logout();
		$p = session_get_cookie_params();
		setcookie(session_name(), "", time() - 42000, $p["path"],
			$p["domain"], $p["secure"], $p["httponly"]);

		session_destroy();
	}

public
function
destroy
(
)
:
void
{
// see example here http://goo.gl/nBVl0
$
this
->
logout
(
)
;
$
p
=
session_get_cookie_params
(
)
;
setcookie
(
session_name
(
)
,
""
,
time
(
)
42000
,
$
p
[
"path"
]
,
$
p
[
"domain"
]
,
$
p
[
"secure"
]
,
$
p
[
"httponly"
]
)
;
session_destroy
(
)
;
}


function addAutoload($method, $classname = null)
    {
        if (is_array($method)) {
            array_walk($method, create_function('$a,&$b', '$b = strtolower($b);'));
            $this->_autoload_map = array_merge($this->_autoload_map, $method);
        } else {
            $this->_autoload_map[strtolower($method)] = $classname;
        }
    }

function
addAutoload
(
$
method
,
$
classname
=
)
{
if
(
is_array
(
$
method
)
)
{
array_walk
(
$
method
,
create_function
(
'$a,&$b'
,
'$b = strtolower($b);'
)
)
;
$
this
->
_autoload_map
=
array_merge
(
$
this
->
_autoload_map
,
$
method
)
;
}
else
{
$
this
->
_autoload_map
[
strtolower
(
$
method
)
]
=
$
classname
;
}
}

Add one or more autoload entries.

@param string $method     which method to autoload

@param string $classname  (optional) which class to find the method in.
If the $method parameter is an array, this
parameter may be omitted (and will be ignored
if not), and the $method parameter will be
treated as an associative array with method
names as keys and class names as values.

@return void

@access public


function removeAutoload($method)
    {
        $method = strtolower($method);
        $ok = isset($this->_autoload_map[$method]);
        unset($this->_autoload_map[$method]);
        return $ok;
    }

function removeAutoload ( $ method ) { $ method = strtolower ( $ method ) ; $ ok = isset ( $ this -> _autoload_map [ $ method ] ) ; unset ( $ this -> _autoload_map [ $ method ] ) ; return $ ok ; }

Remove an autoload entry.

@param string $method  which method to remove the autoload entry for

@return bool TRUE if an entry was removed, FALSE if not

@access public


function removeAggregateObject($classname)
    {
        $ok = false;
        $classname = strtolower($classname);
        reset($this->_method_map);
        while (list($method, $obj) = each($this->_method_map)) {
            if (is_a($obj, $classname)) {
                unset($this->_method_map[$method]);
                $ok = true;
            }
        }
        return $ok;
    }

function removeAggregateObject ( $ classname ) { $ ok = false ; $ classname = strtolower ( $ classname ) ; reset ( $ this -> _method_map ) ; while ( list ( $ method , $ obj ) = each ( $ this -> _method_map ) ) { if ( is_a ( $ obj , $ classname ) ) { unset ( $ this -> _method_map [ $ method ] ) ; $ ok = true ; } } return $ ok ; }

Remove an aggregate object.

@param string $classname  the class of the object to remove

@return bool  TRUE if an object was removed, FALSE if not

@access public


function getopt2($args, $short_options, $long_options = null, $skip_unknown = false)
    {
        return Console_Getopt::doGetopt(2, $args, $short_options, $long_options, $skip_unknown);
    }

function getopt2 ( $ args , $ short_options , $ long_options = null , $ skip_unknown = false ) { return Console_Getopt :: doGetopt ( 2 , $ args , $ short_options , $ long_options , $ skip_unknown ) ; }

Parses the command-line options.

The first parameter to this function should be the list of command-line
arguments without the leading reference to the running program.

The second parameter is a string of allowed short options. Each of the
option letters can be followed by a colon ':' to specify that the option
requires an argument, or a double colon '::' to specify that the option
takes an optional argument.

The third argument is an optional array of allowed long options. The
leading '--' should not be included in the option name. Options that
require an argument should be followed by '=', and options that take an
option argument should be followed by '=='.

The return value is an array of two elements: the list of parsed
options and the list of non-option command-line arguments. Each entry in
the list of parsed options is a pair of elements - the first one
specifies the option, and the second one specifies the option argument,
if there was one.

Long and short options can be mixed.

Most of the semantics of this function are based on GNU getopt_long().

@param array  $args          an array of command-line arguments
@param string $short_options specifies the list of allowed short options
@param array  $long_options  specifies the list of allowed long options
@param boolean $skip_unknown suppresses Console_Getopt: unrecognized option

@return array two-element array containing the list of parsed options and
the non-option arguments
@access public


function doGetopt($version, $args, $short_options, $long_options = null, $skip_unknown = false)
    {
        // in case you pass directly readPHPArgv() as the first arg
        if (PEAR::isError($args)) {
            return $args;
        }

        if (empty($args)) {
            return array(array(), array());
        }

        $non_opts = $opts = array();

        settype($args, 'array');

        if ($long_options) {
            sort($long_options);
        }

        /*
         * Preserve backwards compatibility with callers that relied on
         * erroneous POSIX fix.
         */
        if ($version < 2) {
            if (isset($args[0]{0}) && $args[0]{0} != '-') {
                array_shift($args);
            }
        }

        reset($args);
        while (list($i, $arg) = each($args)) {
            /* The special element '--' means explicit end of
               options. Treat the rest of the arguments as non-options
               and end the loop. */
            if ($arg == '--') {
                $non_opts = array_merge($non_opts, array_slice($args, $i + 1));
                break;
            }

            if ($arg{0} != '-' || (strlen($arg) > 1 && $arg{1} == '-' && !$long_options)) {
                $non_opts = array_merge($non_opts, array_slice($args, $i));
                break;
            } elseif (strlen($arg) > 1 && $arg{1} == '-') {
                $error = Console_Getopt::_parseLongOption(substr($arg, 2),
                                                          $long_options,
                                                          $opts,
                                                          $args,
                                                          $skip_unknown);
                if (PEAR::isError($error)) {
                    return $error;
                }
            } elseif ($arg == '-') {
                // - is stdin
                $non_opts = array_merge($non_opts, array_slice($args, $i));
                break;
            } else {
                $error = Console_Getopt::_parseShortOption(substr($arg, 1),
                                                           $short_options,
                                                           $opts,
                                                           $args,
                                                           $skip_unknown);
                if (PEAR::isError($error)) {
                    return $error;
                }
            }
        }

        return array($opts, $non_opts);
    }

The actual implementation of the argument parsing code.

@param int    $version       Version to use
@param array  $args          an array of command-line arguments
@param string $short_options specifies the list of allowed short options
@param array  $long_options  specifies the list of allowed long options
@param boolean $skip_unknown suppresses Console_Getopt: unrecognized option

@return array

The actual implementation of the argument parsing code .


function _parseShortOption($arg, $short_options, &$opts, &$args, $skip_unknown)
    {
        for ($i = 0; $i < strlen($arg); $i++) {
            $opt     = $arg{$i};
            $opt_arg = null;

            /* Try to find the short option in the specifier string. */
            if (($spec = strstr($short_options, $opt)) === false || $arg{$i} == ':') {
                if ($skip_unknown === true) {
                    break;
                }

                $msg = "Console_Getopt: unrecognized option -- $opt";
                return PEAR::raiseError($msg);
            }

            if (strlen($spec) > 1 && $spec{1} == ':') {
                if (strlen($spec) > 2 && $spec{2} == ':') {
                    if ($i + 1 < strlen($arg)) {
                        /* Option takes an optional argument. Use the remainder of
                           the arg string if there is anything left. */
                        $opts[] = array($opt, substr($arg, $i + 1));
                        break;
                    }
                } else {
                    /* Option requires an argument. Use the remainder of the arg
                       string if there is anything left. */
                    if ($i + 1 < strlen($arg)) {
                        $opts[] = array($opt,  substr($arg, $i + 1));
                        break;
                    } else if (list(, $opt_arg) = each($args)) {
                        /* Else use the next argument. */;
                        if (Console_Getopt::_isShortOpt($opt_arg)
                            || Console_Getopt::_isLongOpt($opt_arg)) {
                            $msg = "option requires an argument --$opt";
                            return PEAR::raiseError("Console_Getopt:" . $msg);
                        }
                    } else {
                        $msg = "option requires an argument --$opt";
                        return PEAR::raiseError("Console_Getopt:" . $msg);
                    }
                }
            }

            $opts[] = array($opt, $opt_arg);
        }
    }

Parse short option

@param string     $arg           Argument
@param string[]   $short_options Available short options
@param string[][] &$opts
@param string[]   &$args
@param boolean    $skip_unknown suppresses Console_Getopt: unrecognized option

@access private
@return void


function _parseArgs($argv, $short_options, $long_options = null)
    {
        if (!is_array($argv) && $argv !== null) {
            // Find all items, quoted or otherwise
            preg_match_all("/(?:[\"'])(.*?)(?:['\"])|([^\s]+)/", $argv, $av);
            $argv = $av[1];
            foreach ($av[2] as $k => $a) {
                if (empty($a)) {
                    continue;
                }
                $argv[$k] = trim($a) ;
            }
        }
        return Console_Getopt::getopt2($argv, $short_options, $long_options);
    }

function
_parseArgs
(
$
argv
,
$
short_options
,
$
long_options
=
)
{
if
(
!
is_array
(
$
argv
)
&&
$
argv
!==
)
{
// Find all items, quoted or otherwise
preg_match_all
(
"/(?:[\"'])(.*?)(?:['\"])|([^\s]+)/"
,
$
argv
,
$
av
)
;
$
argv
=
$
av
[
1
]
;
foreach
(
$
av
[
2
]
as
$
k
=>
$
a
)
{
if
(
empty
(
$
a
)
)
{
continue
;
}
$
argv
[
$
k
]
=
trim
(
$
a
)
;
}
}
return
Console_Getopt
::
getopt2
(
$
argv
,
$
short_options
,
$
long_options
)
;
}

returns the commandline arguments of a function

@param    string  $argv           the commandline
@param    string  $short_options  the allowed option short-tags
@param    string  $long_options   the allowed option long-tags
@return   array   the given options and there values
@static
@access private


function _dirToStruct($sPath, $maxinst, $aktinst = 0, $silent = false)
    {
        $struct = array('dirs' => array(), 'files' => array());
        if (($dir = @opendir($sPath)) === false) {
            if (!$silent) {
                System::raiseError("Could not open dir $sPath");
            }
            return $struct; // XXX could not open error
        }

        $struct['dirs'][] = $sPath = realpath($sPath); // XXX don't add if '.' or '..' ?
        $list = array();
        while (false !== ($file = readdir($dir))) {
            if ($file != '.' && $file != '..') {
                $list[] = $file;
            }
        }

        closedir($dir);
        natsort($list);
        if ($aktinst < $maxinst || $maxinst == 0) {
            foreach ($list as $val) {
                $path = $sPath . DIRECTORY_SEPARATOR . $val;
                if (is_dir($path) && !is_link($path)) {
                    $tmp    = System::_dirToStruct($path, $maxinst, $aktinst+1, $silent);
                    $struct = array_merge_recursive($struct, $tmp);
                } else {
                    $struct['files'][] = $path;
                }
            }
        }

        return $struct;
    }

function
_dirToStruct
(
$
sPath
,
$
maxinst
,
$
aktinst
=
0
,
$
silent
=
false
)
{
$
struct
=
array
(
'dirs'
=>
array
(
)
,
'files'
=>
array
(
)
)
;
if
(
(
$
dir
=
@
opendir
(
$
sPath
)
)
===
false
)
{
if
(
!
$
silent
)
{
System
::
raiseError
(
"Could not open dir $sPath"
)
;
}
return
$
struct
;
// XXX could not open error
}
$
struct
[
'dirs'
]
[
]
=
$
sPath
=
realpath
(
$
sPath
)
;
// XXX don't add if '.' or '..' ?
$
list
=
array
(
)
;
while
(
false
!==
(
$
file
=
readdir
(
$
dir
)
)
)
{
if
(
$
file
!=
'.'
&&
$
file
!=
'..'
)
{
$
list
[
]
=
$
file
;
}
}
closedir
(
$
dir
)
;
natsort
(
$
list
)
;
if
(
$
aktinst
<
$
maxinst
||
$
maxinst
==
0
)
{
foreach
(
$
list
as
$
val
)
{
$
path
=
$
sPath
.
DIRECTORY_SEPARATOR
.
$
val
;
if
(
is_dir
(
$
path
)
&&
!
is_link
(
$
path
)
)
{
$
tmp
=
System
::
_dirToStruct
(
$
path
,
$
maxinst
,
$
aktinst
+
1
,
$
silent
)
;
$
struct
=
array_merge_recursive
(
$
struct
,
$
tmp
)
;
}
else
{
$
struct
[
'files'
]
[
]
=
$
path
;
}
}
}
return
$
struct
;
}

Creates a nested array representing the structure of a directory

System::_dirToStruct('dir1', 0) =>
Array
(
[dirs] => Array
(
[0] => dir1
)

[files] => Array
(
[0] => dir1/file2
[1] => dir1/file3
)
)
@param    string  $sPath      Name of the directory
@param    integer $maxinst    max. deep of the lookup
@param    integer $aktinst    starting deep of the lookup
@param    bool    $silent     if true, do not emit errors.
@return   array   the structure of the dir
@static
@access   private


function _multipleToStruct($files)
    {
        $struct = array('dirs' => array(), 'files' => array());
        settype($files, 'array');
        foreach ($files as $file) {
            if (is_dir($file) && !is_link($file)) {
                $tmp    = System::_dirToStruct($file, 0);
                $struct = array_merge_recursive($tmp, $struct);
            } else {
                if (!in_array($file, $struct['files'])) {
                    $struct['files'][] = $file;
                }
            }
        }
        return $struct;
    }

function _multipleToStruct ( $ files ) { $ struct = array ( 'dirs' => array ( ) , 'files' => array ( ) ) ; settype ( $ files , 'array' ) ; foreach ( $ files as $ file ) { if ( is_dir ( $ file ) && ! is_link ( $ file ) ) { $ tmp = System :: _dirToStruct ( $ file , 0 ) ; $ struct = array_merge_recursive ( $ tmp , $ struct ) ; } else { if ( ! in_array ( $ file , $ struct [ 'files' ] ) ) { $ struct [ 'files' ] [ ] = $ file ; } } } return $ struct ; }

Creates a nested array representing the structure of a directory and files

@param    array $files Array listing files and dirs
@return   array
@static
@see System::_dirToStruct()


function rm($args)
    {
        $opts = System::_parseArgs($args, 'rf'); // "f" does nothing but I like it :-)
        if (PEAR::isError($opts)) {
            return System::raiseError($opts);
        }
        foreach ($opts[0] as $opt) {
            if ($opt[0] == 'r') {
                $do_recursive = true;
            }
        }
        $ret = true;
        if (isset($do_recursive)) {
            $struct = System::_multipleToStruct($opts[1]);
            foreach ($struct['files'] as $file) {
                if (!@unlink($file)) {
                    $ret = false;
                }
            }

            rsort($struct['dirs']);
            foreach ($struct['dirs'] as $dir) {
                if (!@rmdir($dir)) {
                    $ret = false;
                }
            }
        } else {
            foreach ($opts[1] as $file) {
                $delete = (is_dir($file)) ? 'rmdir' : 'unlink';
                if (!@$delete($file)) {
                    $ret = false;
                }
            }
        }
        return $ret;
    }

function
rm
(
$
args
)
{
$
opts
=
System
::
_parseArgs
(
$
args
,
'rf'
)
;
// "f" does nothing but I like it :-)
if
(
PEAR
::
isError
(
$
opts
)
)
{
return
System
::
raiseError
(
$
opts
)
;
}
foreach
(
$
opts
[
0
]
as
$
opt
)
{
if
(
$
opt
[
0
]
==
'r'
)
{
$
do_recursive
=
true
;
}
}
$
ret
=
true
;
if
(
isset
(
$
do_recursive
)
)
{
$
struct
=
System
::
_multipleToStruct
(
$
opts
[
1
]
)
;
foreach
(
$
struct
[
'files'
]
as
$
file
)
{
if
(
!
@
unlink
(
$
file
)
)
{
$
ret
=
false
;
}
}
rsort
(
$
struct
[
'dirs'
]
)
;
foreach
(
$
struct
[
'dirs'
]
as
$
dir
)
{
if
(
!
@
rmdir
(
$
dir
)
)
{
$
ret
=
false
;
}
}
}
else
{
foreach
(
$
opts
[
1
]
as
$
file
)
{
$
delete
=
(
is_dir
(
$
file
)
)
'rmdir'
:
'unlink'
;
if
(
!
@
$
delete
(
$
file
)
)
{
$
ret
=
false
;
}
}
}
return
$
ret
;
}

The rm command for removing files.
Supports multiple files and dirs and also recursive deletes

@param    string  $args   the arguments for rm
@return   mixed   PEAR_Error or true for success
@static
@access   public

The rm command for removing files . Supports multiple files and dirs and also recursive deletes


function mkDir($args)
    {
        $opts = System::_parseArgs($args, 'pm:');
        if (PEAR::isError($opts)) {
            return System::raiseError($opts);
        }

        $mode = 0777; // default mode
        foreach ($opts[0] as $opt) {
            if ($opt[0] == 'p') {
                $create_parents = true;
            } elseif ($opt[0] == 'm') {
                // if the mode is clearly an octal number (starts with 0)
                // convert it to decimal
                if (strlen($opt[1]) && $opt[1]{0} == '0') {
                    $opt[1] = octdec($opt[1]);
                } else {
                    // convert to int
                    $opt[1] += 0;
                }
                $mode = $opt[1];
            }
        }

        $ret = true;
        if (isset($create_parents)) {
            foreach ($opts[1] as $dir) {
                $dirstack = array();
                while ((!file_exists($dir) || !is_dir($dir)) &&
                        $dir != DIRECTORY_SEPARATOR) {
                    array_unshift($dirstack, $dir);
                    $dir = dirname($dir);
                }

                while ($newdir = array_shift($dirstack)) {
                    if (!is_writeable(dirname($newdir))) {
                        $ret = false;
                        break;
                    }

                    if (!mkdir($newdir, $mode)) {
                        $ret = false;
                    }
                }
            }
        } else {
            foreach($opts[1] as $dir) {
                if ((@file_exists($dir) || !is_dir($dir)) && !mkdir($dir, $mode)) {
                    $ret = false;
                }
            }
        }

        return $ret;
    }

Make directories.

The -p option will create parent directories
@param    string  $args    the name of the director(y|ies) to create
@return   bool    True for success
@static
@access   public


function mktemp($args = null)
    {
        static $first_time = true;
        $opts = System::_parseArgs($args, 't:d');
        if (PEAR::isError($opts)) {
            return System::raiseError($opts);
        }

        foreach ($opts[0] as $opt) {
            if ($opt[0] == 'd') {
                $tmp_is_dir = true;
            } elseif ($opt[0] == 't') {
                $tmpdir = $opt[1];
            }
        }

        $prefix = (isset($opts[1][0])) ? $opts[1][0] : 'tmp';
        if (!isset($tmpdir)) {
            $tmpdir = System::tmpdir();
        }

        if (!System::mkDir(array('-p', $tmpdir))) {
            return false;
        }

        $tmp = tempnam($tmpdir, $prefix);
        if (isset($tmp_is_dir)) {
            unlink($tmp); // be careful possible race condition here
            if (!mkdir($tmp, 0700)) {
                return System::raiseError("Unable to create temporary directory $tmpdir");
            }
        }

        $GLOBALS['_System_temp_files'][] = $tmp;
        if (isset($tmp_is_dir)) {
            //$GLOBALS['_System_temp_files'][] = dirname($tmp);
        }

        if ($first_time) {
            PEAR::registerShutdownFunc(array('System', '_removeTmpFiles'));
            $first_time = false;
        }

        return $tmp;
    }

Creates temporary files or directories. This function will remove
the created files when the scripts finish its execution.

Usage:
1) $tempfile = System::mktemp("prefix");
2) $tempdir  = System::mktemp("-d prefix");
3) $tempfile = System::mktemp();
4) $tempfile = System::mktemp("-t /var/tmp prefix");

prefix -> The string that will be prepended to the temp name
(defaults to "tmp").
-d     -> A temporary dir will be created instead of a file.
-t     -> The target dir where the temporary (file|dir) will be created. If
this param is missing by default the env vars TMP on Windows or
TMPDIR in Unix will be used. If these vars are also missing
c:\windows\temp or /tmp will be used.

@param   string  $args  The arguments
@return  mixed   the full path of the created (file|dir) or false
@see System::tmpdir()
@static
@access  public

Creates temporary files or directories . This function will remove the created files when the scripts finish its execution .


function _removeTmpFiles()
    {
        if (count($GLOBALS['_System_temp_files'])) {
            $delete = $GLOBALS['_System_temp_files'];
            array_unshift($delete, '-r');
            System::rm($delete);
            $GLOBALS['_System_temp_files'] = array();
        }
    }

function _removeTmpFiles ( ) { if ( count ( $ GLOBALS [ '_System_temp_files' ] ) ) { $ delete = $ GLOBALS [ '_System_temp_files' ] ; array_unshift ( $ delete , '-r' ) ; System :: rm ( $ delete ) ; $ GLOBALS [ '_System_temp_files' ] = array ( ) ; } }

Remove temporary files created my mkTemp. This function is executed
at script shutdown time

@static
@access private

Remove temporary files created my mkTemp . This function is executed at script shutdown time


function find($args)
    {
        if (!is_array($args)) {
            $args = preg_split('/\s+/', $args, -1, PREG_SPLIT_NO_EMPTY);
        }
        $dir = realpath(array_shift($args));
        if (!$dir) {
            return array();
        }
        $patterns = array();
        $depth = 0;
        $do_files = $do_dirs = true;
        $args_count = count($args);
        for ($i = 0; $i < $args_count; $i++) {
            switch ($args[$i]) {
                case '-type':
                    if (in_array($args[$i+1], array('d', 'f'))) {
                        if ($args[$i+1] == 'd') {
                            $do_files = false;
                        } else {
                            $do_dirs = false;
                        }
                    }
                    $i++;
                    break;
                case '-name':
                    $name = preg_quote($args[$i+1], '#');
                    // our magic characters ? and * have just been escaped,
                    // so now we change the escaped versions to PCRE operators
                    $name = strtr($name, array('\?' => '.', '\*' => '.*'));
                    $patterns[] = '('.$name.')';
                    $i++;
                    break;
                case '-maxdepth':
                    $depth = $args[$i+1];
                    break;
            }
        }
        $path = System::_dirToStruct($dir, $depth, 0, true);
        if ($do_files && $do_dirs) {
            $files = array_merge($path['files'], $path['dirs']);
        } elseif ($do_dirs) {
            $files = $path['dirs'];
        } else {
            $files = $path['files'];
        }
        if (count($patterns)) {
            $dsq = preg_quote(DIRECTORY_SEPARATOR, '#');
            $pattern = '#(^|'.$dsq.')'.implode('|', $patterns).'($|'.$dsq.')#';
            $ret = array();
            $files_count = count($files);
            for ($i = 0; $i < $files_count; $i++) {
                // only search in the part of the file below the current directory
                $filepart = basename($files[$i]);
                if (preg_match($pattern, $filepart)) {
                    $ret[] = $files[$i];
                }
            }
            return $ret;
        }
        return $files;
    }

The "find" command

Usage:

System::find($dir);
System::find("$dir -type d");
System::find("$dir -type f");
System::find("$dir -name *.php");
System::find("$dir -name *.php -name *.htm*");
System::find("$dir -maxdepth 1");

Params implmented:
$dir            -> Start the search at this directory
-type d         -> return only directories
-type f         -> return only files
-maxdepth <n>   -> max depth of recursion
-name <pattern> -> search pattern (bash style). Multiple -name param allowed

@param  mixed Either array or string with the command line
@return array Array of found files
@static


protected function getLog(string $message, PriorityInterface $priority = null, array $metaData = null): LogInterface
    {
        return new Log($message, $priority ?? null, null, $metaData ?? null);
    }

protected function getLog ( string $ message , PriorityInterface $ priority = null , array $ metaData = null ) : LogInterface { return new Log ( $ message , $ priority ?? null , null , $ metaData ?? null ) ; }

Get new log.

@param string                 $message
@param PriorityInterface|null $priority
@param array|null             $metaData
@return LogInterface


public function setBudgetId($budgetId)
    {
        $budgetId = (int) $budgetId;

        if ($this->budgetId < 0) {
            throw new \UnderflowException('Value of "budgetId" must be greater than 0');
        }

        if ($this->exists() && $this->budgetId !== $budgetId) {
            $this->updated['budgetId'] = true;
        }

        $this->budgetId = $budgetId;

        return $this;
    }

Set value for field "budget_id"

@param  int $budgetId
@return $this
@throws \UnderflowException


public function getBudget($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinOneCacheBudget) {
            $mapper = new BudgetMapper($this->dependencyContainer->getDatabase('money'));
            $this->joinOneCacheBudget = $mapper->findByKeys(array(
                'budget_id' => $this->getBudgetId(),
            ));
        }

        return $this->joinOneCacheBudget;
    }

public function getBudget ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinOneCacheBudget ) { $ mapper = new BudgetMapper ( $ this -> dependencyContainer -> getDatabase ( 'money' ) ) ; $ this -> joinOneCacheBudget = $ mapper -> findByKeys ( array ( 'budget_id' => $ this -> getBudgetId ( ) , ) ) ; } return $ this -> joinOneCacheBudget ; }

Get Budget data object.

@param  bool $isForceReload
@return Budget


public function getAllTransaction($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinManyCacheTransaction) {
            $mapper = new TransactionMapper($this->dependencyContainer->getDatabase('money'));
            $mapper->addWhere('category_id', $this->getCategoryId());

            $this->joinManyCacheTransaction = $mapper->select();
        }

        return $this->joinManyCacheTransaction;
    }

public function getAllTransaction ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinManyCacheTransaction ) { $ mapper = new TransactionMapper ( $ this -> dependencyContainer -> getDatabase ( 'money' ) ) ; $ mapper -> addWhere ( 'category_id' , $ this -> getCategoryId ( ) ) ; $ this -> joinManyCacheTransaction = $ mapper -> select ( ) ; } return $ this -> joinManyCacheTransaction ; }

Get list of Transaction data objects.

@param  bool $isForceReload
@return Transaction[]


protected function _prepareValue($value)
    {
        if (is_integer($value) || is_float($value)) {
            return $value;
        } elseif (is_bool($value)) {
            return ($value ? 'true' : 'false');
        } elseif (strpos($value, '"') === false) {
            return '"' . $value .  '"';
        } else {
            /** @see Zend_Config_Exception */

            throw new Zend_Config_Exception('Value can not contain double quotes "');
        }
    }

protected
function
_prepareValue
(
$
value
)
{
if
(
is_integer
(
$
value
)
||
is_float
(
$
value
)
)
{
return
$
value
;
}
elseif
(
is_bool
(
$
value
)
)
{
return
(
$
value
'true'
:
'false'
)
;
}
elseif
(
strpos
(
$
value
,
'"'
)
===
false
)
{
return
'"'
.
$
value
.
'"'
;
}
else
{
/** @see Zend_Config_Exception */
throw
new
Zend_Config_Exception
(
'Value can not contain double quotes "'
)
;
}
}

Prepare a value for INI

@param  mixed $value
@return string


public function setUrl($url)
    {
        if (is_string($url)) {
            $url = new Net_URL2(
                $url, array(Net_URL2::OPTION_USE_BRACKETS => $this->config['use_brackets'])
            );
        }
        if (!$url instanceof Net_URL2) {
            throw new HTTP_Request2_LogicException(
                'Parameter is not a valid HTTP URL',
                HTTP_Request2_Exception::INVALID_ARGUMENT
            );
        }
        // URL contains username / password?
        if ($url->getUserinfo()) {
            $username = $url->getUser();
            $password = $url->getPassword();
            $this->setAuth(rawurldecode($username), $password? rawurldecode($password): '');
            $url->setUserinfo('');
        }
        if ('' == $url->getPath()) {
            $url->setPath('/');
        }
        $this->url = $url;

        return $this;
    }

public
function
setUrl
(
$
url
)
{
if
(
is_string
(
$
url
)
)
{
$
url
=
new
Net_URL2
(
$
url
,
array
(
Net_URL2
::
OPTION_USE_BRACKETS
=>
$
this
->
config
[
'use_brackets'
]
)
)
;
}
if
(
!
$
url
instanceof
Net_URL2
)
{
throw
new
HTTP_Request2_LogicException
(
'Parameter is not a valid HTTP URL'
,
HTTP_Request2_Exception
::
INVALID_ARGUMENT
)
;
}
// URL contains username / password?
if
(
$
url
->
getUserinfo
(
)
)
{
$
username
=
$
url
->
getUser
(
)
;
$
password
=
$
url
->
getPassword
(
)
;
$
this
->
setAuth
(
rawurldecode
(
$
username
)
,
$
password
rawurldecode
(
$
password
)
:
''
)
;
$
url
->
setUserinfo
(
''
)
;
}
if
(
''
==
$
url
->
getPath
(
)
)
{
$
url
->
setPath
(
'/'
)
;
}
$
this
->
url
=
$
url
;
return
$
this
;
}

Sets the URL for this request

If the URL has userinfo part (username & password) these will be removed
and converted to auth data. If the URL does not have a path component,
that will be set to '/'.

@param string|Net_URL2 $url Request URL

@return   HTTP_Request2
@throws   HTTP_Request2_LogicException


public function setMethod($method)
    {
        // Method name should be a token: http://tools.ietf.org/html/rfc2616#section-5.1.1
        if (preg_match(self::REGEXP_INVALID_TOKEN, $method)) {
            throw new HTTP_Request2_LogicException(
                "Invalid request method '{$method}'",
                HTTP_Request2_Exception::INVALID_ARGUMENT
            );
        }
        $this->method = $method;

        return $this;
    }

Sets the request method

@param string $method one of the methods defined in RFC 2616

@return   HTTP_Request2
@throws   HTTP_Request2_LogicException if the method name is invalid


public function setAuth($user, $password = '', $scheme = self::AUTH_BASIC)
    {
        if (empty($user)) {
            $this->auth = null;
        } else {
            $this->auth = array(
                'user'     => (string)$user,
                'password' => (string)$password,
                'scheme'   => $scheme
            );
        }

        return $this;
    }

public function setAuth ( $ user , $ password = '' , $ scheme = self :: AUTH_BASIC ) { if ( empty ( $ user ) ) { $ this -> auth = null ; } else { $ this -> auth = array ( 'user' => ( string ) $ user , 'password' => ( string ) $ password , 'scheme' => $ scheme ) ; } return $ this ; }

Sets the autentification data

@param string $user     user name
@param string $password password
@param string $scheme   authentication scheme

@return   HTTP_Request2


public function addCookie($name, $value)
    {
        if (!empty($this->cookieJar)) {
            $this->cookieJar->store(
                array('name' => $name, 'value' => $value), $this->url
            );

        } else {
            $cookie = $name . '=' . $value;
            if (preg_match(self::REGEXP_INVALID_COOKIE, $cookie)) {
                throw new HTTP_Request2_LogicException(
                    "Invalid cookie: '{$cookie}'",
                    HTTP_Request2_Exception::INVALID_ARGUMENT
                );
            }
            $cookies = empty($this->headers['cookie'])? '': $this->headers['cookie'] . '; ';
            $this->setHeader('cookie', $cookies . $cookie);
        }

        return $this;
    }

public
function
addCookie
(
$
name
,
$
value
)
{
if
(
!
empty
(
$
this
->
cookieJar
)
)
{
$
this
->
cookieJar
->
store
(
array
(
'name'
=>
$
name
,
'value'
=>
$
value
)
,
$
this
->
url
)
;
}
else
{
$
cookie
=
$
name
.
'='
.
$
value
;
if
(
preg_match
(
self
::
REGEXP_INVALID_COOKIE
,
$
cookie
)
)
{
throw
new
HTTP_Request2_LogicException
(
"Invalid cookie: '{$cookie}'"
,
HTTP_Request2_Exception
::
INVALID_ARGUMENT
)
;
}
$
cookies
=
empty
(
$
this
->
headers
[
'cookie'
]
)
''
:
$
this
->
headers
[
'cookie'
]
.
'; '
;
$
this
->
setHeader
(
'cookie'
,
$
cookies
.
$
cookie
)
;
}
return
$
this
;
}

Adds a cookie to the request

If the request does not have a CookieJar object set, this method simply
appends a cookie to "Cookie:" header.

If a CookieJar object is available, the cookie is stored in that object.
Data from request URL will be used for setting its 'domain' and 'path'
parameters, 'expires' and 'secure' will be set to null and false,
respectively. If you need further control, use CookieJar's methods.

@param string $name  cookie name
@param string $value cookie value

@return   HTTP_Request2
@throws   HTTP_Request2_LogicException
@see      setCookieJar()


public function setBody($body, $isFilename = false)
    {
        if (!$isFilename && !is_resource($body)) {
            if (!$body instanceof HTTP_Request2_MultipartBody) {
                $this->body = (string)$body;
            } else {
                $this->body = $body;
            }
        } else {
            $fileData = $this->fopenWrapper($body, empty($this->headers['content-type']));
            $this->body = $fileData['fp'];
            if (empty($this->headers['content-type'])) {
                $this->setHeader('content-type', $fileData['type']);
            }
        }
        $this->postParams = $this->uploads = array();

        return $this;
    }

public function setBody ( $ body , $ isFilename = false ) { if ( ! $ isFilename && ! is_resource ( $ body ) ) { if ( ! $ body instanceof HTTP_Request2_MultipartBody ) { $ this -> body = ( string ) $ body ; } else { $ this -> body = $ body ; } } else { $ fileData = $ this -> fopenWrapper ( $ body , empty ( $ this -> headers [ 'content-type' ] ) ) ; $ this -> body = $ fileData [ 'fp' ] ; if ( empty ( $ this -> headers [ 'content-type' ] ) ) { $ this -> setHeader ( 'content-type' , $ fileData [ 'type' ] ) ; } } $ this -> postParams = $ this -> uploads = array ( ) ; return $ this ; }

Sets the request body

If you provide file pointer rather than file name, it should support
fstat() and rewind() operations.

@param string|resource|HTTP_Request2_MultipartBody $body       Either a
string with the body or filename containing body or
pointer to an open file or object with multipart body data
@param bool                                        $isFilename Whether
first parameter is a filename

@return   HTTP_Request2
@throws   HTTP_Request2_LogicException


public function getBody()
    {
        if (self::METHOD_POST == $this->method
            && (!empty($this->postParams) || !empty($this->uploads))
        ) {
            if (0 === strpos($this->headers['content-type'], 'application/x-www-form-urlencoded')) {
                $body = http_build_query($this->postParams, '', '&');
                if (!$this->getConfig('use_brackets')) {
                    $body = preg_replace('/%5B\d+%5D=/', '=', $body);
                }
                // support RFC 3986 by not encoding '~' symbol (request #15368)
                return str_replace('%7E', '~', $body);

            } elseif (0 === strpos($this->headers['content-type'], 'multipart/form-data')) {
                require_once 'HTTP/Request2/MultipartBody.php';
                return new HTTP_Request2_MultipartBody(
                    $this->postParams, $this->uploads, $this->getConfig('use_brackets')
                );
            }
        }
        return $this->body;
    }

Returns the request body

@return   string|resource|HTTP_Request2_MultipartBody