public function addPrimaryKey($name, $table, $columns)
    {
        $description = "add primary key $name on $table (" . (is_array($columns) ? implode(',', $columns) : $columns) . ')';
        $cmdPromise = $this->createCommand()->addPrimaryKey($name, $table, $columns)->execute();
        return $this->execPromise($cmdPromise, $description);
    }

public
function
addPrimaryKey
(
$
name
,
$
table
,
$
columns
)
{
$
description
=
"add primary key $name on $table ("
.
(
is_array
(
$
columns
)
implode
(
','
,
$
columns
)
:
$
columns
)
.
')'
;
$
cmdPromise
=
$
this
->
createCommand
(
)
->
addPrimaryKey
(
$
name
,
$
table
,
$
columns
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
$
description
)
;
}

Builds and executes a SQL statement for creating a primary key.
The method will properly quote the table and column names.
@param string $name the name of the primary key constraint.
@param string $table the table that the primary key constraint will be added to.
@param string|array $columns comma separated string or array of columns that the primary key will consist of.
@return LazyPromiseInterface

Builds and executes a SQL statement for creating a primary key . The method will properly quote the table and column names .


public function dropPrimaryKey($name, $table)
    {
        $cmdPromise = $this->createCommand()->dropPrimaryKey($name, $table)->execute();
        return $this->execPromise($cmdPromise, "drop primary key $name");
    }

public
function
dropPrimaryKey
(
$
name
,
$
table
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
dropPrimaryKey
(
$
name
,
$
table
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"drop primary key $name"
)
;
}

Builds and executes a SQL statement for dropping a primary key.
@param string $name the name of the primary key constraint to be removed.
@param string $table the table that the primary key constraint will be removed from.
@return LazyPromiseInterface

Builds and executes a SQL statement for dropping a primary key .


public function addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete = null, $update = null)
    {
        $description = "add foreign key $name: $table (" . implode(',', (array)$columns) . ") references $refTable (" . implode(',', (array)$refColumns) . ')';
        $cmdPromise = $this->createCommand()->addForeignKey($name, $table, $columns, $refTable, $refColumns, $delete, $update)->execute();
        return $this->execPromise($cmdPromise, $description);
    }

public
function
addForeignKey
(
$
name
,
$
table
,
$
columns
,
$
refTable
,
$
refColumns
,
$
delete
=
,
$
update
=
)
{
$
description
=
"add foreign key $name: $table ("
.
implode
(
','
,
(
array
)
$
columns
)
.
") references $refTable ("
.
implode
(
','
,
(
array
)
$
refColumns
)
.
')'
;
$
cmdPromise
=
$
this
->
createCommand
(
)
->
addForeignKey
(
$
name
,
$
table
,
$
columns
,
$
refTable
,
$
refColumns
,
$
delete
,
$
update
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
$
description
)
;
}

Builds a SQL statement for adding a foreign key constraint to an existing table.
The method will properly quote the table and column names.
@param string $name the name of the foreign key constraint.
@param string $table the table that the foreign key constraint will be added to.
@param string|array $columns the name of the column to that the constraint will be added on. If there are multiple columns, separate them with commas or use an array.
@param string $refTable the table that the foreign key references to.
@param string|array $refColumns the name of the column that the foreign key references to. If there are multiple columns, separate them with commas or use an array.
@param string $delete the ON DELETE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
@param string $update the ON UPDATE option. Most DBMS support these options: RESTRICT, CASCADE, NO ACTION, SET DEFAULT, SET NULL
@return LazyPromiseInterface

Builds a SQL statement for adding a foreign key constraint to an existing table . The method will properly quote the table and column names .


public function dropForeignKey($name, $table)
    {
        $cmdPromise = $this->createCommand()->dropForeignKey($name, $table)->execute();
        return $this->execPromise($cmdPromise, "drop foreign key $name from table $table");
    }

Builds a SQL statement for dropping a foreign key constraint.
@param string $name the name of the foreign key constraint to be dropped. The name will be properly quoted by the method.
@param string $table the table whose foreign is to be dropped. The name will be properly quoted by the method.
@return LazyPromiseInterface

Builds a SQL statement for dropping a foreign key constraint .


public function createIndex($name, $table, $columns, $unique = false)
    {
        $description = 'create' . ($unique ? ' unique' : '') . " index $name on $table (" . implode(',', (array)$columns) . ')';
        $cmdPromise = $this->createCommand()->createIndex($name, $table, $columns, $unique)->execute();
        return $this->execPromise($cmdPromise, $description);
    }

public
function
createIndex
(
$
name
,
$
table
,
$
columns
,
$
unique
=
false
)
{
$
description
=
'create'
.
(
$
unique
' unique'
:
''
)
.
" index $name on $table ("
.
implode
(
','
,
(
array
)
$
columns
)
.
')'
;
$
cmdPromise
=
$
this
->
createCommand
(
)
->
createIndex
(
$
name
,
$
table
,
$
columns
,
$
unique
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
$
description
)
;
}

Builds and executes a SQL statement for creating a new index.
@param string $name the name of the index. The name will be properly quoted by the method.
@param string $table the table that the new index will be created for. The table name will be properly quoted by the method.
@param string|array $columns the column(s) that should be included in the index. If there are multiple columns, please separate them
by commas or use an array. Each column name will be properly quoted by the method. Quoting will be skipped for column names that
include a left parenthesis "(".
@param bool $unique whether to add UNIQUE constraint on the created index.
@return LazyPromiseInterface

Builds and executes a SQL statement for creating a new index .


public function dropIndex($name, $table)
    {
        $cmdPromise = $this->createCommand()->dropIndex($name, $table)->execute();
        return $this->execPromise($cmdPromise, "drop index $name on $table");
    }

public
function
dropIndex
(
$
name
,
$
table
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
dropIndex
(
$
name
,
$
table
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"drop index $name on $table"
)
;
}

Builds and executes a SQL statement for dropping an index.
@param string $name the name of the index to be dropped. The name will be properly quoted by the method.
@param string $table the table whose index is to be dropped. The name will be properly quoted by the method.
@return LazyPromiseInterface

Builds and executes a SQL statement for dropping an index .


public function addCommentOnColumn($table, $column, $comment)
    {
        $cmdPromise = $this->createCommand()->addCommentOnColumn($table, $column, $comment)->execute();
        return $this->execPromise($cmdPromise, "add comment on column $column");
    }

public
function
addCommentOnColumn
(
$
table
,
$
column
,
$
comment
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
addCommentOnColumn
(
$
table
,
$
column
,
$
comment
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"add comment on column $column"
)
;
}

Builds and execute a SQL statement for adding comment to column.

@param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
@param string $column the name of the column to be commented. The column name will be properly quoted by the method.
@param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
@return LazyPromiseInterface

Builds and execute a SQL statement for adding comment to column .


public function addCommentOnTable($table, $comment)
    {
        $cmdPromise = $this->createCommand()->addCommentOnTable($table, $comment)->execute();
        return $this->execPromise($cmdPromise, "add comment on table $table");
    }

public
function
addCommentOnTable
(
$
table
,
$
comment
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
addCommentOnTable
(
$
table
,
$
comment
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"add comment on table $table"
)
;
}

Builds a SQL statement for adding comment to table.

@param string $table the table to be commented. The table name will be properly quoted by the method.
@param string $comment the text of the comment to be added. The comment will be properly quoted by the method.
@return LazyPromiseInterface

Builds a SQL statement for adding comment to table .


public function dropCommentFromColumn($table, $column)
    {
        $cmdPromise = $this->createCommand()->dropCommentFromColumn($table, $column)->execute();
        return $this->execPromise($cmdPromise, "drop comment from column $column");
    }

public
function
dropCommentFromColumn
(
$
table
,
$
column
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
dropCommentFromColumn
(
$
table
,
$
column
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"drop comment from column $column"
)
;
}

Builds and execute a SQL statement for dropping comment from column.

@param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
@param string $column the name of the column to be commented. The column name will be properly quoted by the method.
@return LazyPromiseInterface

Builds and execute a SQL statement for dropping comment from column .


public function dropCommentFromTable($table)
    {
        $cmdPromise = $this->createCommand()->dropCommentFromTable($table)->execute();
        return $this->execPromise($cmdPromise, "drop comment from table $table");
    }

public
function
dropCommentFromTable
(
$
table
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
dropCommentFromTable
(
$
table
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"drop comment from table $table"
)
;
}

Builds a SQL statement for dropping comment from table.

@param string $table the table whose column is to be commented. The table name will be properly quoted by the method.
@return LazyPromiseInterface

Builds a SQL statement for dropping comment from table .


protected function execPromise($cmdPromise, $description)
    {
        return $this->beginCommandLazy($description)->thenLazy(
            function($time) use ($cmdPromise) {
                if (is_array($cmdPromise)) {
                    $cmdPromise = allInOrder($cmdPromise);
                }
                return $cmdPromise->always(function() use ($time) {
                    return $this->endCommand($time);
                });
            }
        );
    }

protected function execPromise ( $ cmdPromise , $ description ) { return $ this -> beginCommandLazy ( $ description ) -> thenLazy ( function ( $ time ) use ( $ cmdPromise ) { if ( is_array ( $ cmdPromise ) ) { $ cmdPromise = allInOrder ( $ cmdPromise ) ; } return $ cmdPromise -> always ( function ( ) use ( $ time ) { return $ this -> endCommand ( $ time ) ; } ) ; } ) ; }

Execute command promise with description printing and time elapsed

@param ExtendedPromiseInterface|ExtendedPromiseInterface[] $cmdPromise
@param string $description
@return LazyPromiseInterface


public static function log(string $message, string $level = self::LEVEL_INFO, ?string $category = null, $dump = null)
    {
        $message = Text::crop($message, 255);
        return static::getAdapter()->log($message, $level, $category, $dump);
    }

public static function log ( string $ message , string $ level = self :: LEVEL_INFO , ? string $ category = null , $ dump = null ) { $ message = Text :: crop ( $ message , 255 ) ; return static :: getAdapter ( ) -> log ( $ message , $ level , $ category , $ dump ) ; }

Save un log
@param string $message
@param string $level
@param string|null $category
@param mixed $dump
@return mixed


private function validate($regex): void {
    if(@preg_match($regex, '') === false) {
      throw new InvalidArgumentException('Expected regex, but got [' . var_export($regex, true) . '] instead');
    }
  }

private
function
validate
(
$
regex
)
:
void
{
if
(
@
preg_match
(
$
regex
,
''
)
===
false
)
{
throw
new
InvalidArgumentException
(
'Expected regex, but got ['
.
var_export
(
$
regex
,
true
)
.
'] instead'
)
;
}
}

Ensures the regex passed in is valid

@throws  InvalidArgumentException  If the value is not a valid regex

@param  string  $regex  The value to validate


public function capture(Text $text): array {
    preg_match_all($this->raw, (string)$text, $matches, PREG_SET_ORDER);

    foreach($matches as &$match) {
      array_shift($match);

      $match = $text->fromArray($match);
    }

    return $matches;
  }

public function capture ( Text $ text ) : array { preg_match_all ( $ this -> raw , ( string ) $ text , $ matches , PREG_SET_ORDER ) ; foreach ( $ matches as & $ match ) { array_shift ( $ match ) ; $ match = $ text -> fromArray ( $ match ) ; } return $ matches ; }

Extracts capture groups from a given Text object

@param  Text  $text  The text to capture from

@return  Text[]  An array of new Text objects based on the capturing groups of this regular expression


public function split(Text $text): array {
    return $text->fromArray(preg_split($this->raw, (string)$text));
  }

public function split ( Text $ text ) : array { return $ text -> fromArray ( preg_split ( $ this -> raw , ( string ) $ text ) ) ; }

Splits a given Text object based on this regular expression

@param  Text  $text  The text to split

@return  Text[]  An array of new Text objects based on the given Text, split by this regular expression


public function replace(Text $text, Text $replace): Text {
    return new Text(preg_replace($this->raw, $replace->raw, $text->raw));
  }

public function replace ( Text $ text , Text $ replace ) : Text { return new Text ( preg_replace ( $ this -> raw , $ replace -> raw , $ text -> raw ) ) ; }

Replaces parts of a Text object based on a search and replace via this regex

@param  Text  $text     The text to replace
@param  Text  $replace  The text with which to replace the found text

@return  Text  A new Text object with all search text replaced


public function configAction()
    {
        $response = new Response(
            json_encode($this->container->getParameter('ekyna_core.form_js'))
        );

        $response
            ->setPublic()
            ->setMaxAge(3600*6)
            ->setSharedMaxAge(3600*6)
            ->headers->add(['Content-Type' => 'application/json'])
        ;

        return $response;
    }

public function configAction ( ) { $ response = new Response ( json_encode ( $ this -> container -> getParameter ( 'ekyna_core.form_js' ) ) ) ; $ response -> setPublic ( ) -> setMaxAge ( 3600 * 6 ) -> setSharedMaxAge ( 3600 * 6 ) -> headers -> add ( [ 'Content-Type' => 'application/json' ] ) ; return $ response ; }

Returns the form plugins configuration.

@return Response

Returns the form plugins configuration .


public function securimageUrl()
  {
    $reflector = new \ReflectionClass('Securimage');
    $securimageUrl = dirname($reflector->getFileName());
    $securimageUrl = preg_replace('#^.*(\\'. DIRECTORY_SEPARATOR .'vendor\\'. DIRECTORY_SEPARATOR .'.+)$#', '$1', $securimageUrl);
    $securimageUrl = str_replace(DIRECTORY_SEPARATOR, '/', $securimageUrl);
    return $securimageUrl . '/securimage_show.php';
  }

public function securimageUrl ( ) { $ reflector = new \ ReflectionClass ( 'Securimage' ) ; $ securimageUrl = dirname ( $ reflector -> getFileName ( ) ) ; $ securimageUrl = preg_replace ( '#^.*(\\' . DIRECTORY_SEPARATOR . 'vendor\\' . DIRECTORY_SEPARATOR . '.+)$#' , '$1' , $ securimageUrl ) ; $ securimageUrl = str_replace ( DIRECTORY_SEPARATOR , '/' , $ securimageUrl ) ; return $ securimageUrl . '/securimage_show.php' ; }

Retourne l'url de Securimage

@return stirng


public function get($id)
    {
        try {
            $model = $this->connection
                ->select()
                ->from($this->dummy->getTableName())
                ->where($this->dummy->getIdField(), '=', $id)
                ->getOneClass($this->getModelClass());
        } catch (QueryBuilderException $e) {
            throw new MappingException($e->getMessage());
        }

        return $model;
    }

public function get ( $ id ) { try { $ model = $ this -> connection -> select ( ) -> from ( $ this -> dummy -> getTableName ( ) ) -> where ( $ this -> dummy -> getIdField ( ) , '=' , $ id ) -> getOneClass ( $ this -> getModelClass ( ) ) ; } catch ( QueryBuilderException $ e ) { throw new MappingException ( $ e -> getMessage ( ) ) ; } return $ model ; }

Return the entity with the ID in the parameter

@param int|string $id

@return Model
@throws MappingException If the object with the given ID is not found


public function getOrNew($id = null)
    {
        try {
            $model = $this->get($id);
        } catch (MappingException $e) {
            $modelClass = $this->getModelClass();
            $model      = new $modelClass();
        }

        return $model;
    }

public function getOrNew ( $ id = null ) { try { $ model = $ this -> get ( $ id ) ; } catch ( MappingException $ e ) { $ modelClass = $ this -> getModelClass ( ) ; $ model = new $ modelClass ( ) ; } return $ model ; }

Return the entity with the ID in the parameter. If it does not exist a new instance is returned.

@param int|string $id

@return Model

Return the entity with the ID in the parameter . If it does not exist a new instance is returned .


public function getList()
    {
        return $this->connection
            ->select()
            ->from($this->dummy->getTableName())
            ->orderBy($this->dummy->getIdField(), static::DEFAULT_ORDER)
            ->getAsClasses($this->getModelClass());
    }

public function getList ( ) { return $ this -> connection -> select ( ) -> from ( $ this -> dummy -> getTableName ( ) ) -> orderBy ( $ this -> dummy -> getIdField ( ) , static :: DEFAULT_ORDER ) -> getAsClasses ( $ this -> getModelClass ( ) ) ; }

Return an array of the model which belongs to the repository

@return Model[]


public function save(Model $model)
    {
        $model->validate();

        if ($model->exists()) {
            if ($model->isModified()) {
                $this->connection
                    ->update($this->dummy->getTableName())
                    ->where($model::getIdField(), '=', $model->getId())
                    ->set($model->getSaveableProperties())
                    ->execute();
            }
        } else {
            $this->connection
                ->insert($model->getSaveableProperties())
                ->into($this->dummy->getTableName())
                ->execute();

            $model->setId($this->connection->getPdo()->lastInsertId());
        }
    }

public function save ( Model $ model ) { $ model -> validate ( ) ; if ( $ model -> exists ( ) ) { if ( $ model -> isModified ( ) ) { $ this -> connection -> update ( $ this -> dummy -> getTableName ( ) ) -> where ( $ model :: getIdField ( ) , '=' , $ model -> getId ( ) ) -> set ( $ model -> getSaveableProperties ( ) ) -> execute ( ) ; } } else { $ this -> connection -> insert ( $ model -> getSaveableProperties ( ) ) -> into ( $ this -> dummy -> getTableName ( ) ) -> execute ( ) ; $ model -> setId ( $ this -> connection -> getPdo ( ) -> lastInsertId ( ) ) ; } }

Save the model into the database

@param Model $model

@return void
@throws \OlajosCs\Repository\Exceptions\ValidationException


public function delete(Model $model)
    {
        $this->connection
            ->delete()
            ->from($this->dummy->getTableName())
            ->where($model::getIdField(), '=', $model->getId())
            ->execute();
    }

public function delete ( Model $ model ) { $ this -> connection -> delete ( ) -> from ( $ this -> dummy -> getTableName ( ) ) -> where ( $ model :: getIdField ( ) , '=' , $ model -> getId ( ) ) -> execute ( ) ; }

Delete the instance from the database

@param Model $model

@return void


public function getWhereIdIn(array $ids)
    {
        return $this->connection
            ->select()
            ->from($this->dummy->getTableName())
            ->whereIn($this->dummy->getIdField(), $ids)
            ->getAsClasses($this->getModelClass());
    }

public function getWhereIdIn ( array $ ids ) { return $ this -> connection -> select ( ) -> from ( $ this -> dummy -> getTableName ( ) ) -> whereIn ( $ this -> dummy -> getIdField ( ) , $ ids ) -> getAsClasses ( $ this -> getModelClass ( ) ) ; }

Return the instances, which have the ID in the parameter array

@param array $ids The IDs which are needed

@return Model[]

Return the instances which have the ID in the parameter array


public function getWhereIdInWithKeys(array $ids)
    {
        $models = $this->getWhereIdIn($ids);

        $returning = [];
        foreach ($models as $model) {
            $returning[$model->getId()] = $model;
        }

        return $returning;
    }

public function getWhereIdInWithKeys ( array $ ids ) { $ models = $ this -> getWhereIdIn ( $ ids ) ; $ returning = [ ] ; foreach ( $ models as $ model ) { $ returning [ $ model -> getId ( ) ] = $ model ; } return $ returning ; }

Return the models, which have the ID in the parameter array.
The keys of the returning array are the IDs of the models.

@param array $ids

@return Model[]

Return the models which have the ID in the parameter array . The keys of the returning array are the IDs of the models .


final public static function setrawcookie(
        $name, $value, $expire = 0, $path = null,
        $domain = null, $secure = false, $httponly = false
    ) {
        $cookie = new http\Cookie();
        $cookie->addCookie($name, $value);
        $cookie->setExpires($expire);
        $cookie->setPath($path);
        $cookie->setDomain($domain);
        $flags = 0;
        if ($secure) {
            $flags = Cookie::SECURE;
        }

        if ($httponly) {
            $flags = $flags | Cookie::HTTPONLY;
        }

        $cookie->setFlags($flags);
        Header::header(sprintf('Set-Cookie: %s', $cookie), false);

        return true;
    }

final
public
static
function
setrawcookie
(
$
name
,
$
value
,
$
expire
=
0
,
$
path
=
,
$
domain
=
,
$
secure
=
false
,
$
httponly
=
false
)
{
$
cookie
=
new
http
\
Cookie
(
)
;
$
cookie
->
addCookie
(
$
name
,
$
value
)
;
$
cookie
->
setExpires
(
$
expire
)
;
$
cookie
->
setPath
(
$
path
)
;
$
cookie
->
setDomain
(
$
domain
)
;
$
flags
=
0
;
if
(
$
secure
)
{
$
flags
=
Cookie
::
SECURE
;
}
if
(
$
httponly
)
{
$
flags
=
$
flags
|
Cookie
::
HTTPONLY
;
}
$
cookie
->
setFlags
(
$
flags
)
;
Header
::
header
(
sprintf
(
'Set-Cookie: %s'
,
$
cookie
)
,
false
)
;
return
true
;
}

Send a cookie without urlencoding the cookie value

@link http://www.php.net/manual/en/function.setrawcookie.php

@param  string  $name   The name of the cookie.
@param  string  $value  (optional) The value of the cookie.
@param  integer $expire (optional) The time the cookie expires. This is a Unix timestamp
@param  string  $path   (optional) The path on the server in which the cookie will be available on.
@param  string  $domain (optional) The domain that the cookie is available to.
@param  boolean $secure (optional) Indicates that the cookie should only be transmitted over a secure HTTPS connection from the client.
@param  boolean $secure (optional) When TRUE the cookie will be made accessible only through the HTTP protocol.
@return boolean


public function connect($remoteHost, $remotePort)
    {
        $request = pack('C5', 0x05, 0x01, 0x00, 0x03, strlen($remoteHost))
                   . $remoteHost . pack('n', $remotePort);

        $this->write($request);
        $response = unpack('Cversion/Creply/Creserved', $this->read(1024));
        if (5 != $response['version'] || 0 != $response['reserved']) {
            throw new HTTP_Request2_MessageException(
                'Invalid response received from SOCKS5 proxy',
                HTTP_Request2_Exception::MALFORMED_RESPONSE
            );
        } elseif (0 != $response['reply']) {
            throw new HTTP_Request2_ConnectionException(
                "Unable to connect to {$remoteHost}:{$remotePort} through SOCKS5 proxy",
                0, $response['reply']
            );
        }
    }

Connects to a remote host via proxy

@param string $remoteHost Remote host
@param int    $remotePort Remote port

@throws HTTP_Request2_ConnectionException
@throws HTTP_Request2_MessageException


public function save($validate_datatype = false)
    {
        $state = $this->getState();
        if ($state == self::STATE_DELETED) {
            throw new Exception\LogicException(__METHOD__ . "Record has already been deleted in database.");
        }

        switch ($state) {
            case self::STATE_NEW:
                // Means insert
                $new_record = $this->getTable()->insert($this->toArray(), $validate_datatype);
                break;
            case self::STATE_CLEAN:
            case self::STATE_DIRTY:
                // Means update
                $predicate = $this->getRecordPrimaryKeyPredicate();
                $this->getTable()->update($this->toArray(), $predicate, $combination = Predicate\PredicateSet::OP_AND, $validate_datatype);
                $new_record = $this->getTable()->findOneBy($predicate);
                break;
                //@codeCoverageIgnoreStart
            default:
                throw new Exception\LogicException(__METHOD__ . ": Record is not on manageable state.");
                //@codeCoverageIgnoreEnd
        }
        /*
        if ($state == self::STATE_NEW) {
            // Means insert
            $new_record = $this->getTable()->insert($data, $validate_datatype);

        } elseif ($state == self::STATE_CLEAN || $state == self::STATE_DIRTY) {
            // Means update
            $predicate = $this->getRecordPrimaryKeyPredicate();
            $this->getTable()->update($data, $predicate, $combination=Predicate\PredicateSet::OP_AND, $validate_datatype);
            $new_record = $this->getTable()->findOneBy($predicate);
        } else {
             //@codeCoverageIgnoreStart

            throw new Exception\LogicException(__METHOD__ . ": Record is not on manageable state.");
             //@codeCoverageIgnoreEnd
        }

         */
        $this->setData($new_record->toArray());
        $this->setState(Record::STATE_CLEAN);
        unset($new_record);
        return $this;
    }

Save a record in database

@throws Exception\LogicException when record has already been deleted

@param boolean $validate_datatype if true will ensure record data correspond to column datatype

@return Record freshly modified record (from database)


public function setData($data)
    {
        $state = $this->getState();
        if ($state == self::STATE_DELETED) {
            throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
        }
        if (is_array($data)) {
            $data = new ArrayObject($data);
        } elseif (! $data instanceof ArrayObject) {
            throw new Exception\InvalidArgumentException(__METHOD__ . ": Data must be an array of an ArrayObject");
        }
        $this->_securedFieldForArrayAccess['data']  = $data;
        $this->setState(self::STATE_DIRTY);
        return $this;
    }

Set record data

@param array|ArrayObject $data
@throws Exception\InvalidArgumentException when the para
@throws Exception\LogicException when the record has been deleted
@return Record


public function toArray()
    {
        if ($this->getState() == self::STATE_DELETED) {
            throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
        }
        return (array) $this->_securedFieldForArrayAccess['data'];
    }

Return an array version of the record

@throws Exception\LogicException when the record has been deleted
@return array


public function offsetGet($field)
    {
        if ($this->getState() == self::STATE_DELETED) {
            throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
        }

        if (!array_key_exists($field, $this->_securedFieldForArrayAccess['data'])) {
            throw new Exception\FieldNotFoundException(__METHOD__ . ": Cannot get field value, field '$field' does not exists in record.");
        }

        return  $this->_securedFieldForArrayAccess['data'][$field];
    }

Get field value
@param string $field
@return mixed
@throws Exception\FieldNotFoundException


public function offsetSet($field, $value)
    {
        $state = $this->getState();
        if ($state == self::STATE_DELETED) {
            throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted");
        }

        $this->_securedFieldForArrayAccess['data'][$field] = $value;
        if ($state != self::STATE_NEW) {
            $this->setState(self::STATE_DIRTY);
        }
        return $this;
    }

Set a field
@param string $field
@param mixed $value
@throws Exception\LogicException when the record has been deleted
@return Record


protected function getRecordPrimaryKeyPredicate()
    {
        // Get table primary keys
        $primary_keys = $this->getTable()->getPrimaryKeys();
        $predicate = [];
        foreach ($primary_keys as $column) {
            $pk_value = $this->offsetGet($column);
            if ($pk_value != '') {
                $predicate[$column] = $pk_value;
            } else {
                throw new Exception\UnexpectedValueException(__METHOD__ . ": Cannot find record primary key values. Record has no primary key value set");
            }
        }
        return $predicate;
    }

Return primary key predicate on record

@throws Exception\PrimaryKeyNotFoundException
@throws Exception\UnexcpectedValueException
@return array predicate


public function parse(string $path): array
    {
        // Validate the path for opening and closing tags
        $this->validatePath($path);

        // Split on [ while skipping placeholders
        $segments = $this->getSegments($path);

        // The current path
        $current = '';

        // Iterate through the segments
        foreach ($segments as $key => $segment) {
            // If this is not the first segment then its an optional group
            if ($key > 0) {
                // Add a non capturing group around this segment
                // NOTE: Since the path was originally split into segments on [
                // it is safe to do this as there SHOULD be a closing bracket
                // before another required group and so there shouldn't
                // be any conflicts in mismatching opening  and closing
                // regex non-capture groups. This assumes the
                // developer did their job correctly in
                // the amount of opening required
                // and optional groups
                $segment = '(?:' . $segment;
            }

            // Check for any non-capturing groups within <> or <*>
            // < > groups are normal non-capturing groups
            // < *> groups are repeatable non-capturing groups
            // NOTE: have to use an alias to avoid breaking @Annotations() usage
            // Replace any end brackets with the appropriate group close
            // NOTE: This will take care of missing end brackets in
            // previous groups because the only way that occurs
            // is when a group is nested within another
            $segment = str_replace(
                [
                    // Opening non-capture required group
                    '<',
                    // Close non-capture repeatable required group
                    '*>',
                    // Close non-capture required group
                    '>',
                    // Close non-capture repeatable optional group
                    '*]',
                    // Close non-capture optional group
                    ']',
                ],
                [
                    // Non-capture required group regex open
                    '(?:',
                    // Non-capture required repeatable group regex close
                    ')*',
                    // Non-capture required group regex close
                    ')',
                    // Non-capture repeatable optional group regex close
                    ')*?',
                    // Non-capture optional group regex close
                    ')?',
                ],
                $segment
            );

            $current .= $segment;
        }

        return $this->parsePath($current, $segments);
    }

Parse a path and get its parts.

@param string $path The path

@throws \InvalidArgumentException

@return array


protected function validatePath(string $path): void
    {
        // The number of opening required non-capture groups <
        $requiredGroupsOpen = substr_count($path, '<');
        // The number of closing required non-capture groups >
        $requiredGroupsClose = substr_count($path, '>');
        // The number of opening optional non-capture groups [
        $optionalGroupsOpen = substr_count($path, '[');
        // The number of closing optional non-capture groups ]
        $optionalGroupsClose = substr_count($path, ']');

        // If the count of required opening and closing tags doesn't match
        if ($requiredGroupsOpen !== $requiredGroupsClose) {
            // Throw an error letting the develop know they made a bad path
            throw new InvalidArgumentException(
                'Mismatch of required groups for path: ' . $path
            );
        }

        // If the count of optional opening and closing tags doesn't match
        if ($optionalGroupsOpen !== $optionalGroupsClose) {
            // Throw an error letting the develop know they made a bad path
            throw new InvalidArgumentException(
                'Mismatch of optional groups for path: ' . $path
            );
        }
    }

Validate a path's opening and closing tags.

@param string $path The path

@throws \InvalidArgumentException

@return void

Validate a path s opening and closing tags .


protected function splitSegments(array $segments, string $deliminator): array
    {
        // The final segments to return
        $returnSegments = [];

        // Iterate through the segments once more
        foreach ($segments as $segment) {
            // If the segment has the deliminator
            if (strpos($segment, $deliminator) !== false) {
                $this->splitSegmentsDeliminator(
                    $returnSegments,
                    $segment,
                    $deliminator
                );

                continue;
            }

            // Otherwise set the segment normally
            $returnSegments[] = $segment;
        }

        return $returnSegments;
    }

Split segments based on ending bracket within the segments.

@param array  $segments    The segments
@param string $deliminator The deliminator

@return array

Split segments based on ending bracket within the segments .


protected function parsePath(string $path, array &$segments): array
    {
        /* @var array[] $params */
        // Get all matches for {paramName} and {paramName:regex} in the path
        preg_match_all(
            '/' . static::VARIABLE_REGEX . '/x',
            $path,
            $params
        );
        $regex        = $path;
        $paramsReturn = [];

        // Run through all matches
        foreach ($params[0] as $key => $param) {
            // Undo replacements made in parse foreach loop (see line 85)
            [$params[0][$key], $params[2][$key]] = str_replace(
                [')*?', ')?'],
                ['*]', ']'],
                [$params[0][$key], $params[2][$key]]
            );
            // Get the regex for this param
            $paramRegex = $this->getParamReplacement($key, $params);
            // Replace the matches with a regex
            $regex = str_replace($param, $paramRegex, $regex);
            // What to replace in the segment for this item
            $replace = '{' . $params[1][$key] . '}';

            // Set the param in the array of params to return
            $paramsReturn[$params[1][$key]] = [
                'replace' => $replace,
                'regex'   => $paramRegex,
            ];

            // Iterate through the segments
            foreach ($segments as $segmentKey => $segment) {
                // Replace this match with the replace text thus removing any regex
                // in the segment this fixes any regex with brackets from being
                // messed up in the splitSegments() method
                $segments[$segmentKey] = str_replace(
                    $params[0][$key],
                    $replace,
                    $segment
                );
            }
        }

        $regex = str_replace('/', '\/', $regex);
        $regex = '/^' . $regex . '$/';

        $segmentsReturn = $this->splitSegments($segments, ']');
        $segmentsReturn = $this->splitSegments($segmentsReturn, '<');
        $segmentsReturn = $this->splitSegments($segmentsReturn, '>');

        return [
            'regex'    => $regex,
            'params'   => $paramsReturn,
            'segments' => $segmentsReturn,
        ];
    }

Parse a path with no optionals.

@param string $path     The path
@param array  $segments The segments

@return array


protected function getParamReplacement(string $key, array $params): string
    {
        return config()['app']['pathRegexMap'][$params[2][$key]]
            ?? '(' . ($params[2][$key] ?: $params[1][$key]) . ')';
    }

protected function getParamReplacement ( string $ key , array $ params ) : string { return config ( ) [ 'app' ] [ 'pathRegexMap' ] [ $ params [ 2 ] [ $ key ] ] ?? '(' . ( $ params [ 2 ] [ $ key ] ? : $ params [ 1 ] [ $ key ] ) . ')' ; }

Get a param's replacement.

@param string $key    The key
@param array  $params The params

@return string


public function cache($key, \Closure $value, $ttl = null)
    {
        // $value可以是callable或是值
        if (static::$cacheManager) {
            if (!static::$cacheManager->getAssistant()) {
                static::$cacheManager = static::$cacheManager->withTags(get_class($this));
            }

            return static::$cacheManager->remember(
                $key,
                $value,
                $ttl ?: $this->ttl
            );
        } else {
            return $value();
        }
    }

public
function
cache
(
$
key
,
\
Closure
$
value
,
$
ttl
=
)
{
// $value可以是callable或是值
if
(
static
::
$
cacheManager
)
{
if
(
!
static
::
$
cacheManager
->
getAssistant
(
)
)
{
static
::
$
cacheManager
=
static
::
$
cacheManager
->
withTags
(
get_class
(
$
this
)
)
;
}
return
static
::
$
cacheManager
->
remember
(
$
key
,
$
value
,
$
ttl
:
$
this
->
ttl
)
;
}
else
{
return
$
value
(
)
;
}
}

Cache a value in the model's cache collection.

@param $key
@param Closure $value
@param $ttl

@return mixed

Cache a value in the model s cache collection .


public static function flushCache()
    {
        // $value可以是callable或是值
        if (static::$cacheManager) {
            if (!static::$cacheManager->getAssistant()) {
                static::$cacheManager = static::$cacheManager->withTags(get_called_class());
            }

            static::$cacheManager->getAssistant()->flushCache();
        }
    }

public
static
function
flushCache
(
)
{
// $value可以是callable或是值
if
(
static
::
$
cacheManager
)
{
if
(
!
static
::
$
cacheManager
->
getAssistant
(
)
)
{
static
::
$
cacheManager
=
static
::
$
cacheManager
->
withTags
(
get_called_class
(
)
)
;
}
static
::
$
cacheManager
->
getAssistant
(
)
->
flushCache
(
)
;
}
}


protected function processResponseData($raw)
    {
        $this->body = $raw->getBody()->__toString();
        $rawHeaders = $raw->getHeaders();

        foreach ($rawHeaders as $key => $value) {
            $this->headers[$key] = implode(', ', $value);
        }

        $this->statusCode = $raw->getStatusCode();

    }

protected
function
processResponseData
(
$
raw
)
{
$
this
->
body
=
$
raw
->
getBody
(
)
->
__toString
(
)
;
$
rawHeaders
=
$
raw
->
getHeaders
(
)
;
foreach
(
$
rawHeaders
as
$
key
=>
$
value
)
{
$
this
->
headers
[
$
key
]
=
implode
(
', '
,
$
value
)
;
}
$
this
->
statusCode
=
$
raw
->
getStatusCode
(
)
;
}

Receives the Http client response, it is processed and stores it into the object properties.

@param  \Guzzle\Http\Client $raw
@return void

Receives the Http client response it is processed and stores it into the object properties .


protected function invokeMethod(array $arguments, $action, $object)
    {
        if (!method_exists($object, $action))
        {
            $message = get_class($object) . " object has no {$action} method.";
            throw new DispatcherException($message);
        }

        $reflection = new ReflectionMethod($object, $action);
        $parameters = [];

        foreach ($reflection->getParameters() as $parameter)
        {
            if (isset($arguments[$parameter->name]))
            {
                $parameters[] = $arguments[$parameter->name];
            }
            elseif ($parameter->isDefaultValueAvailable())
            {
                $parameters[] = $parameter->getDefaultValue();
            }
            else
            {
                $message = "{$parameter->name} argument cannot be resolved.";
                throw new DispatcherException($message, $arguments, $action, $object);
            }
        }

        return $reflection->invokeArgs($object, $parameters);
    }

Invoke object method using arguments.

@param array  $arguments
@param string $action
@param object $object

@throws DispatcherException
@return mixed


public function getContentType(): string
    {
        if (empty($this->content_type) && !empty($this->file)) {
            $this->content_type = $this->getMimeType($this->file);
        }

        return $this->content_type;
    }

public function getContentType ( ) : string { if ( empty ( $ this -> content_type ) && ! empty ( $ this -> file ) ) { $ this -> content_type = $ this -> getMimeType ( $ this -> file ) ; } return $ this -> content_type ; }

Returns content type of file

Tries to autodetect content type when no type is set.

@return string


public function regenerateId($idOld, RequestApplicationInterface $app, $deleteOldSession = false)
    {
        $self = $this;
        $dataOld = [];
        $promise = $this->read($idOld)->then(
            function($data) { return $data; },
            function() { return []; }
        )->then(function($data) use ($idOld, &$dataOld) {
            $dataOld = $data;
            return $this->destroy($idOld)->then(null, function() { return true; });
        })->then(
            function() use ($self, &$app) {
                return $self->createId($app);
            }
        )->then(
            function($newId) use ($self, &$dataOld, $deleteOldSession) {
                $retCallback = function() use ($newId) { return $newId; };
                $dataNew = $deleteOldSession ? [] : $dataOld;
                return $self->write($newId, $dataNew)->then($retCallback, $retCallback);
            },
            function() use ($idOld) {
                $message = sprintf('Failed to regenerate session ID for session "%s"', $idOld);
                throw new SessionException($message);
            }
        );
        return $promise;
    }

Regenerate session id
@param string                      $idOld
@param RequestApplicationInterface $app
@param bool                        $deleteOldSession
@return ExtendedPromiseInterface  with new session ID (string)


public function createId(RequestApplicationInterface $app)
    {
        $ip = $app->reqHelper->getRemoteIP();
        if (empty($ip)) {
            $ip = '127.0.0.1';
        }
        $time = microtime();
        try {
            $rand = \Reaction::$app->security->generateRandomString(16);
        } catch (\Exception $exception) {
            $rand = mt_rand(11111, 99999);
        }
        $id = md5($ip . ':' . $time . ':' . $rand);
        $self = $this;
        return $this->checkSessionId($id)->then(
            function() use($id) { return $id; },
            function() use ($self, &$app) { return $self->createId($app); }
        );
    }

public function createId ( RequestApplicationInterface $ app ) { $ ip = $ app -> reqHelper -> getRemoteIP ( ) ; if ( empty ( $ ip ) ) { $ ip = '127.0.0.1' ; } $ time = microtime ( ) ; try { $ rand = \ Reaction :: $ app -> security -> generateRandomString ( 16 ) ; } catch ( \ Exception $ exception ) { $ rand = mt_rand ( 11111 , 99999 ) ; } $ id = md5 ( $ ip . ':' . $ time . ':' . $ rand ) ; $ self = $ this ; return $ this -> checkSessionId ( $ id ) -> then ( function ( ) use ( $ id ) { return $ id ; } , function ( ) use ( $ self , & $ app ) { return $ self -> createId ( $ app ) ; } ) ; }

Return a new session ID
@param RequestApplicationInterface $app
@return ExtendedPromiseInterface  with session ID valid for session handler


protected function createGcTimer()
    {
        if (isset($this->_timer) && $this->_timer instanceof TimerInterface) {
            $this->loop->cancelTimer($this->_timer);
        }
        $this->_timer = $this->loop->addPeriodicTimer($this->timerInterval, [$this, 'gc']);
    }

protected function createGcTimer ( ) { if ( isset ( $ this -> _timer ) && $ this -> _timer instanceof TimerInterface ) { $ this -> loop -> cancelTimer ( $ this -> _timer ) ; } $ this -> _timer = $ this -> loop -> addPeriodicTimer ( $ this -> timerInterval , [ $ this , 'gc' ] ) ; }


public function setContent($content)
    {
        if ($content instanceof FormView) {
            $this->contentType = 'form';
        } elseif ($content instanceof TableView) {
            $this->contentType = 'table';
        } elseif (is_array($content)) {
            $this->contentType = 'data';
        } else {
            $this->contentType = 'html';
        }
        $this->content = $content;
        return $this;
    }

public function setContent ( $ content ) { if ( $ content instanceof FormView ) { $ this -> contentType = 'form' ; } elseif ( $ content instanceof TableView ) { $ this -> contentType = 'table' ; } elseif ( is_array ( $ content ) ) { $ this -> contentType = 'data' ; } else { $ this -> contentType = 'html' ; } $ this -> content = $ content ; return $ this ; }

Sets the content.

@param mixed $content
@return Modal


public function setButtons(array $buttons)
    {
        $resolver = static::getButtonOptionsResolver();
        $tmp = [];
        foreach ($buttons as $options) {
            $tmp[] = $resolver->resolve($options);
        }
        $this->buttons = $tmp;
        return $this;
    }

public function setButtons ( array $ buttons ) { $ resolver = static :: getButtonOptionsResolver ( ) ; $ tmp = [ ] ; foreach ( $ buttons as $ options ) { $ tmp [ ] = $ resolver -> resolve ( $ options ) ; } $ this -> buttons = $ tmp ; return $ this ; }

Sets the buttons.

@param array $buttons
@return Modal


public function addButton(array $options, $prepend = false)
    {
        $resolver = static::getButtonOptionsResolver();
        $options = $resolver->resolve($options);
        if ($prepend) {
            array_unshift($this->buttons, $options);
        } else {
            array_push($this->buttons, $options);
        }
        return $this;
    }

public function addButton ( array $ options , $ prepend = false ) { $ resolver = static :: getButtonOptionsResolver ( ) ; $ options = $ resolver -> resolve ( $ options ) ; if ( $ prepend ) { array_unshift ( $ this -> buttons , $ options ) ; } else { array_push ( $ this -> buttons , $ options ) ; } return $ this ; }

Adds the button.

@param array $options
@param bool $prepend
@return Modal


static public function validateType($type, $throwException = true)
    {
        if (in_array($type, [
            self::TYPE_DEFAULT,
            self::TYPE_INFO,
            self::TYPE_PRIMARY,
            self::TYPE_SUCCESS,
            self::TYPE_WARNING,
            self::TYPE_DANGER,
        ])) {
            return true;
        }

        if ($throwException) {
            throw new \InvalidArgumentException(sprintf('Invalid modal type "%s".', $type));
        }

        return false;
    }

static
public
function
validateType
(
$
type
,
$
throwException
=
true
)
{
if
(
in_array
(
$
type
,
[
self
::
TYPE_DEFAULT
,
self
::
TYPE_INFO
,
self
::
TYPE_PRIMARY
,
self
::
TYPE_SUCCESS
,
self
::
TYPE_WARNING
,
self
::
TYPE_DANGER
,
]
)
)
{
return
true
;
}
if
(
$
throwException
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'Invalid modal type "%s".'
,
$
type
)
)
;
}
return
false
;
}

Validates the modal type.

@param string $type
@param bool $throwException
@return bool
@throws \InvalidArgumentException


static public function validateSize($size, $throwException = true)
    {
        if (in_array($size, [
            self::SIZE_NORMAL,
            self::SIZE_SMALL,
            self::SIZE_WIDE,
            self::SIZE_LARGE,
        ])) {
            return true;
        }

        if ($throwException) {
            throw new \InvalidArgumentException(sprintf('Invalid modal size "%s".', $size));
        }

        return false;
    }

static
public
function
validateSize
(
$
size
,
$
throwException
=
true
)
{
if
(
in_array
(
$
size
,
[
self
::
SIZE_NORMAL
,
self
::
SIZE_SMALL
,
self
::
SIZE_WIDE
,
self
::
SIZE_LARGE
,
]
)
)
{
return
true
;
}
if
(
$
throwException
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'Invalid modal size "%s".'
,
$
size
)
)
;
}
return
false
;
}

Validates the modal size.

@param string $size
@param bool $throwException
@return bool
@throws \InvalidArgumentException


public function registerCommands()
    {
        $this->add(new DirectoryAddCommand());
        $this->add(new DirectoryDeleteCommand());
        $this->add(new DownloadCommand());
        $this->add(new ExportCommand());
        $this->add(new FileAddCommand());
        $this->add(new FileDeleteCommand());
        $this->add(new FileUpdateCommand());
        $this->add(new StatusCommand());
        $this->add(new UploadTranslationCommand());
        $this->add(new DownSyncCommand());
        $this->add(new ExtractCommand());
        $this->add(new UpSyncCommand());
    }

public function registerCommands ( ) { $ this -> add ( new DirectoryAddCommand ( ) ) ; $ this -> add ( new DirectoryDeleteCommand ( ) ) ; $ this -> add ( new DownloadCommand ( ) ) ; $ this -> add ( new ExportCommand ( ) ) ; $ this -> add ( new FileAddCommand ( ) ) ; $ this -> add ( new FileDeleteCommand ( ) ) ; $ this -> add ( new FileUpdateCommand ( ) ) ; $ this -> add ( new StatusCommand ( ) ) ; $ this -> add ( new UploadTranslationCommand ( ) ) ; $ this -> add ( new DownSyncCommand ( ) ) ; $ this -> add ( new ExtractCommand ( ) ) ; $ this -> add ( new UpSyncCommand ( ) ) ; }

Register crowdin commands in the application.

Register crowdin commands in the application .


function Archive_Tar($p_tarname, $p_compress = null)
    {
        $this->PEAR();
        $this->_compress = false;
        $this->_compress_type = 'none';
        if (($p_compress === null) || ($p_compress == '')) {
            if (@file_exists($p_tarname)) {
                if ($fp = @fopen($p_tarname, "rb")) {
                    // look for gzip magic cookie
                    $data = fread($fp, 2);
                    fclose($fp);
                    if ($data == "\37\213") {
                        $this->_compress = true;
                        $this->_compress_type = 'gz';
                        // No sure it's enought for a magic code ....
                    } elseif ($data == "BZ") {
                        $this->_compress = true;
                        $this->_compress_type = 'bz2';
                    }
                }
            } else {
                // probably a remote file or some file accessible
                // through a stream interface
                if (substr($p_tarname, -2) == 'gz') {
                    $this->_compress = true;
                    $this->_compress_type = 'gz';
                } elseif ((substr($p_tarname, -3) == 'bz2') ||
                          (substr($p_tarname, -2) == 'bz')) {
                    $this->_compress = true;
                    $this->_compress_type = 'bz2';
                }
            }
        } else {
            if (($p_compress === true) || ($p_compress == 'gz')) {
                $this->_compress = true;
                $this->_compress_type = 'gz';
            } else if ($p_compress == 'bz2') {
                $this->_compress = true;
                $this->_compress_type = 'bz2';
            } else {
                $this->_error("Unsupported compression type '$p_compress'\n".
                    "Supported types are 'gz' and 'bz2'.\n");
                return false;
            }
        }
        $this->_tarname = $p_tarname;
        if ($this->_compress) { // assert zlib or bz2 extension support
            if ($this->_compress_type == 'gz')
                $extname = 'zlib';
            else if ($this->_compress_type == 'bz2')
                $extname = 'bz2';

            if (!extension_loaded($extname)) {
                PEAR::loadExtension($extname);
            }
            if (!extension_loaded($extname)) {
                $this->_error("The extension '$extname' couldn't be found.\n".
                    "Please make sure your version of PHP was built ".
                    "with '$extname' support.\n");
                return false;
            }
        }
    }

Archive_Tar Class constructor. This flavour of the constructor only
declare a new Archive_Tar object, identifying it by the name of the
tar file.
If the compress argument is set the tar will be read or created as a
gzip or bz2 compressed TAR file.

@param string $p_tarname  The name of the tar archive to create
@param string $p_compress can be null, 'gz' or 'bz2'. This
parameter indicates if gzip or bz2 compression
is required.  For compatibility reason the
boolean value 'true' means 'gz'.

@access public

Archive_Tar Class constructor . This flavour of the constructor only declare a new Archive_Tar object identifying it by the name of the tar file . If the compress argument is set the tar will be read or created as a gzip or bz2 compressed TAR file .


function addString($p_filename, $p_string, $p_datetime = false)
    {
        $v_result = true;

        if (!$this->_isArchive()) {
            if (!$this->_openWrite()) {
                return false;
            }
            $this->_close();
        }

        if (!$this->_openAppend())
            return false;

        // Need to check the get back to the temporary file ? ....
        $v_result = $this->_addString($p_filename, $p_string, $p_datetime);

        $this->_writeFooter();

        $this->_close();

        return $v_result;
    }

This method add a single string as a file at the
end of the existing archive. If the archive does not yet exists it
is created.

@param string $p_filename A string which contains the full
filename path that will be associated
with the string.
@param string $p_string   The content of the file added in
the archive.
@param int    $p_datetime A custom date/time (unix timestamp)
for the file (optional).

@return true on success, false on error.
@access public

This method add a single string as a file at the end of the existing archive . If the archive does not yet exists it is created .


function _maliciousFilename($file)
    {
        if (strpos($file, '/../') !== false) {
            return true;
        }
        if (strpos($file, '../') === 0) {
            return true;
        }
        return false;
    }

function _maliciousFilename ( $ file ) { if ( strpos ( $ file , '/../' ) !== false ) { return true ; } if ( strpos ( $ file , '../' ) === 0 ) { return true ; } return false ; }

Detect and report a malicious file name

@param string $file

@return bool
@access private


public function parseCommand(UserEventInterface $event, EventQueueInterface $queue)
    {
        // Get the pattern to identify commands
        if ($this->nick) {
            $nick = $event->getConnection()->getNickname();
            $identity = $this->getNickPattern($nick);
        } else {
            $identity = $this->identityPattern;
        }

        // Verify this event contains a command and remove the substring
        // identifying it as one
        $eventParams = $event->getParams();
        $target = $event->getCommand() === 'PRIVMSG'
            ? $eventParams['receivers']
            : $eventParams['nickname'];
        $message = $eventParams['text'];
        if ($identity) {
            if (preg_match($identity, $message, $match)) {
                $message = preg_replace($identity, '', $message);
            } elseif (preg_match($this->channelPattern, $target)) {
                return;
            }
        }

        // Parse the command and its parameters
        if (!preg_match($this->commandPattern, $message, $match)) {
            return;
        }
        $customCommand = $match['command'];
        if (!empty($match['params'])
            && preg_match_all($this->paramsPattern, $match['params'], $matches)) {
            $customParams = array_map(
                function($param) {
                    return trim($param, '"');
                },
                $matches[0]
            );
        } else {
            $customParams = array();
        }

        // Populate an event object with the parsed data
        $commandEvent = $this->getCommandEvent();
        $commandEvent->fromEvent($event);
        $commandEvent->setCustomCommand($customCommand);
        $commandEvent->setCustomParams($customParams);

        // Emit the event object to listeners
        $customEventName = 'command.' . strtolower($customCommand);
        $customEventParams = array($commandEvent, $queue);
        $this->getEventEmitter()->emit($customEventName, $customEventParams);
    }

Parses user events for commands and emits them as events.

@param \Phergie\Irc\Event\UserEventInterface $event
@param \Phergie\Irc\Bot\React\EventQueueInterface $queue

Parses user events for commands and emits them as events .


public function migrateFrom($otherObject)
    {
        $otherObjectClass = get_class($otherObject);

        // same object no migrations needed
        if ($otherObjectClass === $this->className) {
            return $otherObject;
        }

        $versionPath = new VersionPathSearch($this->reader);
        $migrations = $versionPath->find($otherObjectClass, $this->className);

        if (count($migrations) === 0) {
            throw new VersionPathNotFoundException($otherObjectClass, $this->className);
        }

        foreach ($migrations as $migration) {
            $otherObject = $migration->action->run($otherObject, $this->options);
        }

        return $otherObject;
    }

public
function
migrateFrom
(
$
otherObject
)
{
$
otherObjectClass
=
get_class
(
$
otherObject
)
;
// same object no migrations needed
if
(
$
otherObjectClass
===
$
this
->
className
)
{
return
$
otherObject
;
}
$
versionPath
=
new
VersionPathSearch
(
$
this
->
reader
)
;
$
migrations
=
$
versionPath
->
find
(
$
otherObjectClass
,
$
this
->
className
)
;
if
(
count
(
$
migrations
)
===
0
)
{
throw
new
VersionPathNotFoundException
(
$
otherObjectClass
,
$
this
->
className
)
;
}
foreach
(
$
migrations
as
$
migration
)
{
$
otherObject
=
$
migration
->
action
->
run
(
$
otherObject
,
$
this
->
options
)
;
}
return
$
otherObject
;
}

Get object from other version.

@param mixed $otherObject  Object instance.

@throws Exception\VersionPathNotFoundException

@return mixed Migrated object.


public function getUniqueKeys($table, $include_primary = false)
    {
        $this->checkTableArgument($table);
        return $this->model_definition['tables'][$table]['unique_keys'];
    }

public function getUniqueKeys ( $ table , $ include_primary = false ) { $ this -> checkTableArgument ( $ table ) ; return $ this -> model_definition [ 'tables' ] [ $ table ] [ 'unique_keys' ] ; }

Get unique keys on table

@param string $table table name
@param boolean $include_primary include primary keys in the list
@throws Exception\InvalidArgumentException
@throws Exception\ErrorException
@throws Exception\NoPrimaryKeyException
@throws Exception\ExceptionInterface
@throws Exception\TableNotFoundException
@return array


public function getPrimaryKey($table)
    {
        $this->checkTableArgument($table);
        $pks = $this->getPrimaryKeys($table);
        if (count($pks) > 1) {
            $keys = implode(',', $pks);
            throw new Exception\MultiplePrimaryKeyException(__METHOD__ . ". Multiple primary keys found on table '$table':  $keys");
        }
        return $pks[0];
    }

Return unique table primary key

@throws Exception\InvalidArgumentException
@throws Exception\ErrorException
@throws Exception\NoPrimaryKeyException when no pk
@throws Exception\MultiplePrimaryKeyException when multiple pk found
@throws Exception\ExceptionInterface
@throws Exception\TableNotFoundException

@param string $table
@return string|int primary key


public function getPrimaryKeys($table)
    {
        $this->checkTableArgument($table);
        $pks = $this->model_definition['tables'][$table]['primary_keys'];
        if (count($pks) == 0) {
            throw new Exception\NoPrimaryKeyException(__METHOD__ . ". No primary keys found on table '$table'.");
        }
        return $pks;
    }

Return composite primary keys

@throws Exception\InvalidArgumentException
@throws Exception\ErrorException
@throws Exception\NoPrimaryKeyException
@throws Exception\ExceptionInterface
@throws Exception\TableNotFoundException

@param string $table
@return array primary keys


protected function getPriority(): PriorityInterface
    {
        if ($this->priority === null) {
            $this->priority = new CriticalPriority();
        }

        return $this->priority;
    }

protected function getPriority ( ) : PriorityInterface { if ( $ this -> priority === null ) { $ this -> priority = new CriticalPriority ( ) ; } return $ this -> priority ; }

Get priority.

@return PriorityInterface


protected function getValidator(): ValidatorInterface
    {
        if ($this->validator === null) {
            $this->validator = new GreaterThanValidator(
                $this->getPriority()->getValue()
            );
        }

        return $this->validator;
    }

protected function getValidator ( ) : ValidatorInterface { if ( $ this -> validator === null ) { $ this -> validator = new GreaterThanValidator ( $ this -> getPriority ( ) -> getValue ( ) ) ; } return $ this -> validator ; }

Get validator.

@return ValidatorInterface


protected static function loadMimeTypes($magicFile)
    {
        if ($magicFile === null) {
            $magicFile = static::$mimeMagicFile;
        }
        $magicFile = \Reaction::$app->getAlias($magicFile);
        if (!isset(self::$_mimeTypes[$magicFile])) {
            self::$_mimeTypes[$magicFile] = require $magicFile;
        }

        return self::$_mimeTypes[$magicFile];
    }

protected static function loadMimeTypes ( $ magicFile ) { if ( $ magicFile === null ) { $ magicFile = static :: $ mimeMagicFile ; } $ magicFile = \ Reaction :: $ app -> getAlias ( $ magicFile ) ; if ( ! isset ( self :: $ _mimeTypes [ $ magicFile ] ) ) { self :: $ _mimeTypes [ $ magicFile ] = require $ magicFile ; } return self :: $ _mimeTypes [ $ magicFile ] ; }

Loads MIME types from the specified file.
@param string $magicFile the path (or alias) of the file that contains all available MIME type information.
If this is not set, the file specified by [[mimeMagicFile]] will be used.
@return array the mapping from file extensions to MIME types

Loads MIME types from the specified file .


protected static function loadMimeAliases($aliasesFile)
    {
        if ($aliasesFile === null) {
            $aliasesFile = static::$mimeAliasesFile;
        }
        $aliasesFile = \Reaction::$app->getAlias($aliasesFile);
        if (!isset(self::$_mimeAliases[$aliasesFile])) {
            self::$_mimeAliases[$aliasesFile] = require $aliasesFile;
        }

        return self::$_mimeAliases[$aliasesFile];
    }

protected static function loadMimeAliases ( $ aliasesFile ) { if ( $ aliasesFile === null ) { $ aliasesFile = static :: $ mimeAliasesFile ; } $ aliasesFile = \ Reaction :: $ app -> getAlias ( $ aliasesFile ) ; if ( ! isset ( self :: $ _mimeAliases [ $ aliasesFile ] ) ) { self :: $ _mimeAliases [ $ aliasesFile ] = require $ aliasesFile ; } return self :: $ _mimeAliases [ $ aliasesFile ] ; }

Loads MIME aliases from the specified file.
@param string $aliasesFile the path (or alias) of the file that contains MIME type aliases.
If this is not set, the file specified by [[mimeAliasesFile]] will be used.
@return array the mapping from file extensions to MIME types

Loads MIME aliases from the specified file .


public static function unlink($path)
    {
        $isWindows = DIRECTORY_SEPARATOR === '\\';

        if (!$isWindows) {
            return unlink($path);
        }

        if (is_link($path) && is_dir($path)) {
            return rmdir($path);
        }

        try {
            return unlink($path);
        } catch (ErrorException $e) {
            // last resort measure for Windows
            $lines = [];
            exec('DEL /F/Q ' . escapeshellarg($path), $lines, $deleteError);
            return $deleteError !== 0;
        }
    }

public
static
function
unlink
(
$
path
)
{
$
isWindows
=
DIRECTORY_SEPARATOR
===
'\\'
;
if
(
!
$
isWindows
)
{
return
unlink
(
$
path
)
;
}
if
(
is_link
(
$
path
)
&&
is_dir
(
$
path
)
)
{
return
rmdir
(
$
path
)
;
}
try
{
return
unlink
(
$
path
)
;
}
catch
(
ErrorException
$
e
)
{
// last resort measure for Windows
$
lines
=
[
]
;
exec
(
'DEL /F/Q '
.
escapeshellarg
(
$
path
)
,
$
lines
,
$
deleteError
)
;
return
$
deleteError
!==
0
;
}
}

Removes a file or symlink in a cross-platform way

@param string $path
@return bool

Removes a file or symlink in a cross - platform way


public static function permissionsAsString($modeOctal) {
        $modeStr = '';
        foreach (static::$_permissionsByteMap as $bytes => $flag) {
            $modeStr .= (($modeOctal & $bytes) ? $flag : '-');
        }
        return $modeStr;
    }

public static function permissionsAsString ( $ modeOctal ) { $ modeStr = '' ; foreach ( static :: $ _permissionsByteMap as $ bytes => $ flag ) { $ modeStr .= ( ( $ modeOctal & $ bytes ) ? $ flag : '-' ) ; } return $ modeStr ; }

Convert octal permissions to string
@param int $modeOctal Octal mode (0755). Do not omit zero, must be octal, not decimal!
@return string String permissions representation (rwxr-xr-x)


public static function permissionsAsOctal($modeStr) {
        $modeStr = str_pad($modeStr, 9, '-', STR_PAD_RIGHT);
        $modeOctal = 0x0;
        $num = 0;
        foreach (static::$_permissionsByteMap as $bytes => $flag) {
            $modeOctal += (($modeStr[$num] === $flag) ? $bytes : 0x0);
            $num++;
        }
        return $modeOctal;
    }

public static function permissionsAsOctal ( $ modeStr ) { $ modeStr = str_pad ( $ modeStr , 9 , '-' , STR_PAD_RIGHT ) ; $ modeOctal = 0x0 ; $ num = 0 ; foreach ( static :: $ _permissionsByteMap as $ bytes => $ flag ) { $ modeOctal += ( ( $ modeStr [ $ num ] === $ flag ) ? $ bytes : 0x0 ) ; $ num ++ ; } return $ modeOctal ; }

Convert string representation of permissions to octal
@param string $modeStr String permissions (rwxr-xr-x)
@return int Octal permissions representation


public function innerJoin($table, $alias = null)
    {
        $join = new \Labi\Database\Utility\Join($this, $table, $alias, null, $this->quoteChar());
        $join->typeInner();
        $this->joins[] = $join;

        return $join;
    }

public function innerJoin ( $ table , $ alias = null ) { $ join = new \ Labi \ Database \ Utility \ Join ( $ this , $ table , $ alias , null , $ this -> quoteChar ( ) ) ; $ join -> typeInner ( ) ; $ this -> joins [ ] = $ join ; return $ join ; }


public function toSql()
    {
        if (is_null($this->table)) {
            // brak tabeli
            throw new \Exception("Please define table for select.");
        }

        // usuwam rzeczy zwiazane z przetwarzaniem zapytania
        $this->reset(true);

        // tworze bazowe zapytanie
        $alias = $this->alias;
        $table = $this->table;
        $quoteChar = $this->quoteChar();

        // build select
        $sql = "select\n";

        // columns
        $fields = array();

        // wybieram tylko te kolumny ktore nie sa ukryte
        foreach (array_keys($this->columns) as $field) {
            $column = $this->columns[$field];

            if ($column->isHidden()) {
                continue;
            }else{
                $fields[] = $field;
            }
        }

        // zliczam wszystkie kolumny
        $ccolumn = count($fields);
        $added = false;

        for ($i=0; $i < $ccolumn; $i++) {
            // pobieram zdefiniowana kolumne
            $column = $this->columns[$fields[$i]];

            if ($column->isHidden()) {
                // pomijam ukryte kolumny
                continue;
            }

            $value = $column->value();
            $calias = $column->alias();

            if (!is_null($calias)) {
                $calias = " as {$quoteChar}{$calias}{$quoteChar}";
            }else{
                $calias = "";
            }

            if(is_null($value)){
                $value = "null";
            }

            if ($i == $ccolumn-1) {
                // last column
                $sql .= "    {$value}{$calias}\n";
            }else{
                $sql .= "    {$value}{$calias},\n";
            }

            $added = true;
        }

        if ($added === false) {
            // jak nie ma kolumn to pobieram wszystkie
            $sql .= "    *\n";
        }

        $sql .= "from {$quoteChar}{$table}{$quoteChar} as {$quoteChar}{$alias}{$quoteChar}\n";

        // joins
        foreach ($this->joins as $join) {
            $sql .= $join->toSql()."\n";
        }

        // condition
        $condition = $this->condition->toSql();
        if (!is_null($condition)) {
            $sql .= "where $condition\n";
        }

        // orders
        if(count($this->orders) > 0){
            $sql .= 'order by ';
            foreach ($this->orders as $order) {
                $column = $order['column'];
                $type = $order['type'];

                $sql .= "$column $type, ";
            }

            $sql = rtrim($sql, ", ");
            $sql .= "\n";
        }

        // limit
        if (!is_null($this->limit)) {
            $offset = $this->limit['offset'];
            $limit = $this->limit['limit'];

            if($offset > 0){
                $sql .= "limit {$limit}, {$offset}";
            }else{
                $sql .= "limit {$limit}";
            }
        }

        $sql = rtrim($sql, "\n");

        return $sql;
    }

- \ Labi \ Database \ Utility \ ConditionInterface


public function search($params = array())
    {
        return $this->adapter->fetch($this->toSql(), array_merge($this->params(), $this->params(true), $params));
    }

public function search ( $ params = array ( ) ) { return $ this -> adapter -> fetch ( $ this -> toSql ( ) , array_merge ( $ this -> params ( ) , $ this -> params ( true ) , $ params ) ) ; }

+ \ Labi \ Operators \ SearcherInterface


public static function createTable($table, array $specs)
    {
        $sql = 'CREATE TABLE IF NOT EXISTS ' . static::e($table) . ' (';
        foreach($specs as $field => $opts) {
            $sql .= "\n" .  '`' . $field . '` ' . $opts['type'];
            if($opts['primary'] == true) {
                $opts['nullable'] = false;
                $opts['default'] = null;
                $sql .= ' PRIMARY KEY AUTOINCREMENT';
            }
            if(!$opts['nullable']) {
                $sql .= ' NOT NULL';
            }
            if($opts['default']) {
                $sql .= ' DEFAULT ' . $opts['default'];
            }
            $sql .= ',';
        }

        $sql = trim($sql, ',') . "\n" . ');';
        return $sql;
    }

public
static
function
createTable
(
$
table
,
array
$
specs
)
{
$
sql
=
'CREATE TABLE IF NOT EXISTS '
.
static
::
e
(
$
table
)
.
' ('
;
foreach
(
$
specs
as
$
field
=>
$
opts
)
{
$
sql
.=
"\n"
.
'`'
.
$
field
.
'` '
.
$
opts
[
'type'
]
;
if
(
$
opts
[
'primary'
]
==
true
)
{
$
opts
[
'nullable'
]
=
false
;
$
opts
[
'default'
]
=
;
$
sql
.=
' PRIMARY KEY AUTOINCREMENT'
;
}
if
(
!
$
opts
[
'nullable'
]
)
{
$
sql
.=
' NOT NULL'
;
}
if
(
$
opts
[
'default'
]
)
{
$
sql
.=
' DEFAULT '
.
$
opts
[
'default'
]
;
}
$
sql
.=
','
;
}
$
sql
=
trim
(
$
sql
,
','
)
.
"\n"
.
');'
;
return
$
sql
;
}

Compile CREATE TABLE

@param string $table
@param array $specs
@return bool


protected function loadModules()
    {
        $moduleMask = implode(
            DIRECTORY_SEPARATOR,
            array(
             $this->appPath->root()->get(),
             'src',
             $this->contextName.'Module.php',
            )
        );

        foreach ($this->fileSystem->glob($moduleMask) as $filePath) {
            $class = $this->loadModule($filePath);
            $class->build($this->containerBuilder);
        }
    }

protected function loadModules ( ) { $ moduleMask = implode ( DIRECTORY_SEPARATOR , array ( $ this -> appPath -> root ( ) -> get ( ) , 'src' , $ this -> contextName . 'Module.php' , ) ) ; foreach ( $ this -> fileSystem -> glob ( $ moduleMask ) as $ filePath ) { $ class = $ this -> loadModule ( $ filePath ) ; $ class -> build ( $ this -> containerBuilder ) ; } }

Loads all modules contained in app and builds them.

@return void

Loads all modules contained in app and builds them .


protected function getContainer()
    {
        if (!$this->container) {
            $this->container = $this->containerBuilder->build();
        }

        return $this->container;
    }

protected function getContainer ( ) { if ( ! $ this -> container ) { $ this -> container = $ this -> containerBuilder -> build ( ) ; } return $ this -> container ; }

Gets built container.

@return IContainer IoC container.


public function init()
    {
        $swears = array('fu+ck', 'sh+i+t', 'cu+nt', 'co+ck');
        $swear_jar = array();

        // Don't say bad words, kids.
        $re = '/' . implode('|', $swears) . '/i';
        $this->bot->onChannel($re, function(Event $event) use (&$swear_jar) {
            $cost = 0.25;
            $who = $event->getRequest()->getSendingUser();
            if (!isset($swear_jar[$who])) {
                $swear_jar[$who] = 0;
            }

            $price = ($swear_jar[$who] += $cost);
            $event->addResponse(
                Response::msg(
                    $event->getRequest()->getSource(),
                    sprintf("Mind your tongue $who! Now you owe \$%.2f to the swear jar.", $price)
            ));
        });
    }

Listens to channel messages and lets everyone know who owes what to
the "swear jar".

Listens to channel messages and lets everyone know who owes what to the swear jar .


public function select(array $columns = null): QueryBuilder
    {
        $this->type = Statement::SELECT;

        if (null !== $columns) {
            $this->columns = $columns;
        } else {
            $this->columns[] = '*';
        }

        return $this;
    }

public function select ( array $ columns = null ) : QueryBuilder { $ this -> type = Statement :: SELECT ; if ( null !== $ columns ) { $ this -> columns = $ columns ; } else { $ this -> columns [ ] = '*' ; } return $ this ; }

Create a SELECT query statement.

<code>
$queryBuilder->select();
$queryBuilder->select(
[
'column1',
'column2',
...
]
);
</code>

@param array|null $columns

@return static


public function table(string $table, string $alias = null): QueryBuilder
    {
        $this->table = $table . ($alias !== null ? ' ' . $alias : '');

        return $this;
    }

public
function
table
(
string
$
table
,
string
$
alias
=
)
:
QueryBuilder
{
$
this
->
table
=
$
table
.
(
$
alias
!==
' '
.
$
alias
:
''
)
;
return
$
this
;
}

Set the table on which to perform the query statement.

<code>
$queryBuilder
->select()
->table('table');

$queryBuilder
->select()
->table('table', 't');
</code>

@param string      $table
@param string|null $alias

@return static

Set the table on which to perform the query statement .


public function set(string $column, string $value): QueryBuilder
    {
        $this->values[$column] = $value;

        return $this;
    }

public function set ( string $ column , string $ value ) : QueryBuilder { $ this -> values [ $ column ] = $ value ; return $ this ; }

Add a value for a column to set.

<code>
$queryBuilder
->insert()
->table('table')
->set('column', ':column');

$queryBuilder
->update()
->table('table')
->set('column', ':column');
</code>

@param string $column
@param string $value

@return static


public function where(string $where): QueryBuilder
    {
        if (empty($this->where)) {
            $this->setWhere($where);

            return $this;
        }

        $this->setWhere($where, Statement::WHERE_AND);

        return $this;
    }

public function where ( string $ where ) : QueryBuilder { if ( empty ( $ this -> where ) ) { $ this -> setWhere ( $ where ) ; return $ this ; } $ this -> setWhere ( $ where , Statement :: WHERE_AND ) ; return $ this ; }

Add a where condition to the query statement.
- Each additional use will add an `AND` where condition.

<code>
$queryBuilder
->select()
->table('table')
->where('column = :column');

$queryBuilder
->select()
->table('table')
->where('column = :column')
->where('column2 = :column2');
</code>

@param string $where

@return static

Add a where condition to the query statement . - Each additional use will add an AND where condition .


public function orWhere(string $where): QueryBuilder
    {
        if (empty($this->where)) {
            return $this->where($where);
        }

        $this->setWhere($where, Statement::WHERE_OR);

        return $this;
    }

public function orWhere ( string $ where ) : QueryBuilder { if ( empty ( $ this -> where ) ) { return $ this -> where ( $ where ) ; } $ this -> setWhere ( $ where , Statement :: WHERE_OR ) ; return $ this ; }

Add an additional `OR` where condition to the query statement.

<code>
$queryBuilder
->select()
->table('table')
->where('column = :column')
->andWhere('column2 = :column2');
</code>

@param string $where

@return static

Add an additional OR where condition to the query statement .


public function orderByAsc(string $column): QueryBuilder
    {
        $this->setOrderBy($column, OrderBy::ASC);

        return $this;
    }

public function orderByAsc ( string $ column ) : QueryBuilder { $ this -> setOrderBy ( $ column , OrderBy :: ASC ) ; return $ this ; }

Add an order by ascending to the query statement.

<code>
$queryBuilder
->select()
->table('table')
->where('column = :column')
->orderByAsc('column');
</code>

@param string $column

@return static

Add an order by ascending to the query statement .


public function orderByDesc(string $column): QueryBuilder
    {
        $this->setOrderBy($column, OrderBy::DESC);

        return $this;
    }

public function orderByDesc ( string $ column ) : QueryBuilder { $ this -> setOrderBy ( $ column , OrderBy :: DESC ) ; return $ this ; }

Add an order by descending to the query statement.

<code>
$queryBuilder
->select()
->table('table')
->where('column = :column')
->orderByDesc('column');
</code>

@param string $column

@return static

Add an order by descending to the query statement .


public function getQuery(): string
    {
        if (null !== $this->query) {
            return $this->query;
        }

        switch ($this->type) {
            case Statement::SELECT:
                $this->query = $this->getSelectQuery();
                break;
            case Statement::UPDATE:
                $this->query = $this->getUpdateQuery();
                break;
            case Statement::INSERT:
                $this->query = $this->getInsertQuery();
                break;
            case Statement::DELETE:
                $this->query = $this->getDeleteQuery();
                break;
        }

        return $this->query;
    }

public function getQuery ( ) : string { if ( null !== $ this -> query ) { return $ this -> query ; } switch ( $ this -> type ) { case Statement :: SELECT : $ this -> query = $ this -> getSelectQuery ( ) ; break ; case Statement :: UPDATE : $ this -> query = $ this -> getUpdateQuery ( ) ; break ; case Statement :: INSERT : $ this -> query = $ this -> getInsertQuery ( ) ; break ; case Statement :: DELETE : $ this -> query = $ this -> getDeleteQuery ( ) ; break ; } return $ this -> query ; }

Get the built query string.

@return string


protected function setWhere(string $where, string $type = null): void
    {
        if (null !== $type) {
            $where = $type . ' ' . $where;
        }

        $this->where[] = $where;
    }

protected
function
setWhere
(
string
$
where
,
string
$
type
=
)
:
void
{
if
(
!==
$
type
)
{
$
where
=
$
type
.
' '
.
$
where
;
}
$
this
->
where
[
]
=
$
where
;
}

Set a where condition.

@param string      $where
@param string|null $type

@return void


protected function setOrderBy(string $column, string $order = null): void
    {
        $orderBy = $column;

        if (null !== $order) {
            $orderBy .= ' ' . $order;
        }

        $this->orderBy[] = $orderBy;
    }

protected
function
setOrderBy
(
string
$
column
,
string
$
order
=
)
:
void
{
$
orderBy
=
$
column
;
if
(
!==
$
order
)
{
$
orderBy
.=
' '
.
$
order
;
}
$
this
->
orderBy
[
]
=
$
orderBy
;
}

Set an order by condition.

@param string      $column
@param string|null $order

@return void


protected function getSelectQuery(): string
    {
        return $this->type
            . ' ' . implode(', ', $this->columns)
            . ' ' . Statement::FROM
            . ' ' . $this->table
            . ' ' . $this->getWhereQuery()
            . ' ' . $this->getOrderByQuery()
            . ' ' . $this->getLimitQuery()
            . ' ' . $this->getOffsetQuery();
    }

protected
function
getSelectQuery
(
)
:
string
{
return
$
this
->
type
.
' '
.
implode
(
', '
,
$
this
->
columns
)
.
' '
.
Statement
::
FROM
.
' '
.
$
this
->
table
.
' '
.
$
this
->
getWhereQuery
(
)
.
' '
.
$
this
->
getOrderByQuery
(
)
.
' '
.
$
this
->
getLimitQuery
(
)
.
' '
.
$
this
->
getOffsetQuery
(
)
;
}


protected function getInsertQuery(): string
    {
        return $this->type
            . ' ' . Statement::INTO
            . ' ' . $this->table
            . ' (' . implode(', ', array_keys($this->values)) . ')'
            . ' ' . Statement::VALUE
            . ' (' . implode(', ', $this->values) . ')';
    }

protected
function
getInsertQuery
(
)
:
string
{
return
$
this
->
type
.
' '
.
Statement
::
INTO
.
' '
.
$
this
->
table
.
' ('
.
implode
(
', '
,
array_keys
(
$
this
->
values
)
)
.
')'
.
' '
.
Statement
::
VALUE
.
' ('
.
implode
(
', '
,
$
this
->
values
)
.
')'
;
}


protected function getUpdateQuery(): string
    {
        return $this->type
            . ' ' . $this->table
            . ' ' . $this->getSetQuery()
            . ' ' . $this->getWhereQuery()
            . ' ' . $this->getOrderByQuery()
            . ' ' . $this->getLimitQuery();
    }

protected
function
getUpdateQuery
(
)
:
string
{
return
$
this
->
type
.
' '
.
$
this
->
table
.
' '
.
$
this
->
getSetQuery
(
)
.
' '
.
$
this
->
getWhereQuery
(
)
.
' '
.
$
this
->
getOrderByQuery
(
)
.
' '
.
$
this
->
getLimitQuery
(
)
;
}


protected function getDeleteQuery(): string
    {
        return $this->type
            . ' ' . Statement::FROM
            . ' ' . $this->table
            . ' ' . $this->getWhereQuery()
            . ' ' . $this->getOrderByQuery()
            . ' ' . $this->getLimitQuery();
    }

protected
function
getDeleteQuery
(
)
:
string
{
return
$
this
->
type
.
' '
.
Statement
::
FROM
.
' '
.
$
this
->
table
.
' '
.
$
this
->
getWhereQuery
(
)
.
' '
.
$
this
->
getOrderByQuery
(
)
.
' '
.
$
this
->
getLimitQuery
(
)
;
}


protected function getSetQuery(): string
    {
        $query = '';

        foreach ($this->values as $column => $value) {
            if (! empty($query)) {
                $query .= ', ';
            }

            $query .= $column . ' = ' . $value;
        }

        return Statement::SET . ' ' . $query;
    }

protected
function
getSetQuery
(
)
:
string
{
$
query
=
''
;
foreach
(
$
this
->
values
as
$
column
=>
$
value
)
{
if
(
!
empty
(
$
query
)
)
{
$
query
.=
', '
;
}
$
query
.=
$
column
.
' = '
.
$
value
;
}
return
Statement
::
SET
.
' '
.
$
query
;
}

Get the SET part of an INSERT query.

@return string


protected function getWhereQuery(): string
    {
        if (empty($this->where)) {
            return '';
        }

        return Statement::WHERE . ' ' . implode(' ', $this->where);
    }

protected
function
getWhereQuery
(
)
:
string
{
if
(
empty
(
$
this
->
where
)
)
{
return
''
;
}
return
Statement
::
WHERE
.
' '
.
implode
(
' '
,
$
this
->
where
)
;
}

Get the WHERE part of a query statement.

@return string

Get the WHERE part of a query statement .


protected function getOrderByQuery(): string
    {
        if (empty($this->orderBy)) {
            return '';
        }

        return Statement::ORDER_BY . ' ' . implode(', ', $this->orderBy);
    }

protected
function
getOrderByQuery
(
)
:
string
{
if
(
empty
(
$
this
->
orderBy
)
)
{
return
''
;
}
return
Statement
::
ORDER_BY
.
' '
.
implode
(
', '
,
$
this
->
orderBy
)
;
}

Get the ORDER BY part of a query statement.

@return string

Get the ORDER BY part of a query statement .


public function dispatch(Expression $expr, AbstractNode $parentNode = null)
    {
        if ($parentNode === null) {
            $parentNode = $this->queryBuilder->where();
        }

        switch (true) {
            case $expr instanceof Comparison:
                return $this->walkComparison($expr, $parentNode);

            case $expr instanceof Composite:
                return $this->walkComposite($expr, $parentNode);
        }

        throw new \RuntimeException('Unknown Expression: ' . get_class($expr));
    }

public
function
dispatch
(
Expression
$
expr
,
AbstractNode
$
parentNode
=
)
{
if
(
$
parentNode
===
)
{
$
parentNode
=
$
this
->
queryBuilder
->
where
(
)
;
}
switch
(
true
)
{
case
$
expr
instanceof
Comparison
:
return
$
this
->
walkComparison
(
$
expr
,
$
parentNode
)
;
case
$
expr
instanceof
Composite
:
return
$
this
->
walkComposite
(
$
expr
,
$
parentNode
)
;
}
throw
new
\
RuntimeException
(
'Unknown Expression: '
.
get_class
(
$
expr
)
)
;
}

Walk the given expression to build up the PHPCR-ODM query builder.

@param Expression $expr
@param AbstractNode|null $parentNode

Walk the given expression to build up the PHPCR - ODM query builder .


public function register(array $post)
    {
        /* @var $form RegisterForm */
        $form = $this->getForm(RegisterForm::class);

        $model = $this->getModel();
        $model->setRole('registered');

        $form->setHydrator($this->getHydrator());
        $form->bind($model);

        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter = $this->getInputFilter();
        $form->setInputFilter($inputFilter);

        return $this->add($post, $form);
    }

Registers a new user

@param array $post
@return int|Form
@throws \UthandoCommon\Service\ServiceException


public function editUser(UserModel $model, array $post)
    {
        if (!$model instanceof UserModel) {
            throw new UthandoUserException('$model must be an instance of UthandoUser\Model\User, ' . get_class($model) . ' given.');
        }

        $model->setDateModified();

        /* @var $form UserEditForm */
        $form = $this->getForm(UserEditForm::class);

        $form->setHydrator($this->getHydrator());
        $form->bind($model);

        /* @var $inputFilter \UthandoUser\InputFilter\UserInputFilter */
        $inputFilter = $this->getInputFilter();

        // we need to find if this email has changed,
        // if not then exclude it from validation,
        // if changed then reevaluate it.
        $email = ($model->getEmail() === $post['email']) ? $model->getEmail() : null;

        $inputFilter->addEmailNoRecordExists($email);

        $form->setInputFilter($inputFilter);

        $form->setData($post);
        $form->setValidationGroup([
            'firstname', 'lastname', 'email', 'userId', 'security'
        ]);

        if (!$form->isValid()) {
            return $form;
        }

        $saved = $this->save($form->getData());

        $this->updateSession($saved, $model);

        return $saved;

    }

Allows not admin user to edit thier profile

@param UserModel $model
@param array $post
@return int|UserEditForm
@throws UthandoUserException
@throws \UthandoCommon\Service\ServiceException


public function get_version($asArray=false) {
//		trigger_error("Deprecated function called (". __METHOD__ .")", E_USER_NOTICE);
//		return self::parse_version_file($this->versionFileLocation, $asArray);

		if($asArray) {
			$retval = $this->_versionData;
			$retval['version_string'] = self::build_full_version_string($this->_versionData);
		}
		else {
//			$retval = self::build_full_version_string($this->_versionData);
			$retval = $this->_fullVersionString;
		}

		return $retval;
	}

Retrieve our version string from the VERSION file.

Retrieve our version string from the VERSION file .


public function createRoute($routePath = null, $method = null, $params = null, $onlyReturn = false)
    {
        $withInternalCtrl = $routePath !== null;
        $routePath = isset($routePath) ? $routePath : $this->reqHelper->getPathInfo();
        $method = isset($method) ? $method : $this->reqHelper->getMethod();
        $data = Reaction::$app->router->searchRoute($this, $routePath, $method, $withInternalCtrl);
        //Parameters overwrite
        if (is_array($params) && count($data) >= 3) {
            $data[3] = $params;
        }
        $route = Reaction::create([
            'class' => RouteInterface::class,
            'app' => $this,
            'dispatchedData' => $data,
        ]);
        if (!$onlyReturn) {
            $this->_route = $route;
        }
        return $route;
    }

public
function
createRoute
(
$
routePath
=
,
$
method
=
,
$
params
=
,
$
onlyReturn
=
false
)
{
$
withInternalCtrl
=
$
routePath
!==
;
$
routePath
=
isset
(
$
routePath
)
$
routePath
:
$
this
->
reqHelper
->
getPathInfo
(
)
;
$
method
=
isset
(
$
method
)
$
method
:
$
this
->
reqHelper
->
getMethod
(
)
;
$
data
=
Reaction
::
$
app
->
router
->
searchRoute
(
$
this
,
$
routePath
,
$
method
,
$
withInternalCtrl
)
;
//Parameters overwrite
if
(
is_array
(
$
params
)
&&
count
(
$
data
)
>=
3
)
{
$
data
[
3
]
=
$
params
;
}
$
route
=
Reaction
::
create
(
[
'class'
=>
RouteInterface
::
class
,
'app'
=>
$
this
,
'dispatchedData'
=>
$
data
,
]
)
;
if
(
!
$
onlyReturn
)
{
$
this
->
_route
=
$
route
;
}
return
$
route
;
}

Create Route with given params
@param string|null $routePath
@param string|null $method
@param array|null  $params
@param bool        $onlyReturn
@return RouteInterface


public function handleRequest()
    {
        //Wait for static application initialization
        $staticInitPromise = !Reaction::$app->initialized ? Reaction::$app->initPromise : Reaction\Promise\resolve(true);
        return $staticInitPromise
            //Load Request app components
            ->then(function() {
                return $this->loadComponents();
            //Try to resolve request action
            })->then(function() {
                return $this->resolveAction();
            //Handle exceptions
            })->otherwise(function($exception) {
                if (Reaction::isConsoleApp() && $exception instanceof Reaction\Exceptions\Http\NotFoundException) {
                    $exception = new Reaction\Console\UnknownCommandException($this->reqHelper->getUrl(), $this, $exception->getCode(), $exception);
                }
                return $this->errorHandler->handleException($exception);
            //Emit EVENT_REQUEST_END event
            })->always(function() {
                return $this->emitAndWait(static::EVENT_REQUEST_END, [$this]);
            });
    }

Handle incoming request
@return ExtendedPromiseInterface


public function resolveAction($routePath = null, $method = null, $params = null)
    {
        $route = $this->createRoute($routePath, $method, $params);
        return $route->resolve();
    }

public function resolveAction ( $ routePath = null , $ method = null , $ params = null ) { $ route = $ this -> createRoute ( $ routePath , $ method , $ params ) ; return $ route -> resolve ( ) ; }

Resolve app action
@param string|null $routePath
@param string|null $method
@param array|null $params
@return Promise\ExtendedPromiseInterface


public function getHomeUrl()
    {
        return isset($this->homeUrl) ? $this->homeUrl : Reaction::$app->urlManager->getHomeUrl();
    }

public function getHomeUrl ( ) { return isset ( $ this -> homeUrl ) ? $ this -> homeUrl : Reaction :: $ app -> urlManager -> getHomeUrl ( ) ; }


public function set($id, $definition)
    {
        unset($this->_components[$id]);

        if ($definition === null) {
            unset($this->_definitions[$id]);
            return;
        }

        //Extract definition from DI Definition
        if ($definition instanceof \Reaction\DI\Definition) {
            $definition = $definition->dumpArrayDefinition();
        }

        if (is_string($definition)) {
            $config = ['class' => $definition];
        } elseif (ArrayHelper::isIndexed($definition) && count($definition) === 2) {
            $config = $definition[0];
            $params = $definition[1];
        } else {
            $config = $definition;
        }

        if (is_array($config)) {
            $config = ArrayHelper::merge(['app' => $this], $config);
            $definition = isset($params) ? [$config, $params] : $config;
        }

        if (is_object($definition) || is_callable($definition, true)) {
            // an object, a class name, or a PHP callable
            $this->_definitions[$id] = $definition;
        } elseif (is_array($definition)) {
            // a configuration array
            if (isset($definition['class'])) {
                $this->_definitions[$id] = $definition;
            } else {
                throw new InvalidConfigException("The configuration for the \"$id\" component must contain a \"class\" element.");
            }
        } else {
            throw new InvalidConfigException("Unexpected configuration type for the \"$id\" component: " . gettype($definition));
        }
    }

Registers a component definition with this locator.
Overridden to inject application instance
@param string $id
@param mixed  $definition
@throws InvalidConfigException

Registers a component definition with this locator . Overridden to inject application instance


public function restaureUtilisateur($idUser) {
		$oQb = $this->createQueryBuilder('U');

		$oQb->update()
			->set('U.dateSuppression', 'NULL')
			->where($oQb->expr()->eq('U.id', $idUser));

		$iReturn = $oQb->getQuery()->execute();

		return $iReturn;
	}

public function restaureUtilisateur ( $ idUser ) { $ oQb = $ this -> createQueryBuilder ( 'U' ) ; $ oQb -> update ( ) -> set ( 'U.dateSuppression' , 'NULL' ) -> where ( $ oQb -> expr ( ) -> eq ( 'U.id' , $ idUser ) ) ; $ iReturn = $ oQb -> getQuery ( ) -> execute ( ) ; return $ iReturn ; }

Restaure un utilisateur
@param int $idUser
@return mixed


public function getUserById($id) {
		$oQB = $this->createQueryBuilder('U');
		$oQB->select()
			->where($oQB->expr()->eq('U.id', ':id'))
			->setParameter(':id', $id);

		$aResult = $oQB->getQuery()->getOneOrNullResult();

		return $aResult;
	}

public function getUserById ( $ id ) { $ oQB = $ this -> createQueryBuilder ( 'U' ) ; $ oQB -> select ( ) -> where ( $ oQB -> expr ( ) -> eq ( 'U.id' , ':id' ) ) -> setParameter ( ':id' , $ id ) ; $ aResult = $ oQB -> getQuery ( ) -> getOneOrNullResult ( ) ; return $ aResult ; }

Retourne les informations d'un utilisateur en fonction de son id

@param int $id
@return array

Retourne les informations d un utilisateur en fonction de son id


public function getActive() {
		$oDelay = new \DateTime('now');
		$oDelay->setTimestamp(strtotime('2 minutes ago'));

		$oQb = $this->createQueryBuilder('U');
		$oQb->select()
			->where($oQb->expr()->gt('U.lastActivityAt', ':delay'))
			->setParameter(':delay', $oDelay);

        return $oQb->getQuery()->getArrayResult();
	}

public
function
getActive
(
)
{
$
oDelay
=
new
\
DateTime
(
'now'
)
;
$
oDelay
->
setTimestamp
(
strtotime
(
'2 minutes ago'
)
)
;
$
oQb
=
$
this
->
createQueryBuilder
(
'U'
)
;
$
oQb
->
select
(
)
->
where
(
$
oQb
->
expr
(
)
->
gt
(
'U.lastActivityAt'
,
':delay'
)
)
->
setParameter
(
':delay'
,
$
oDelay
)
;
return
$
oQb
->
getQuery
(
)
->
getArrayResult
(
)
;
}

Retourne les utilisateurs actifs

@return array