public function actionHistory(RequestApplicationInterface $app, $limit = 10)
    {
        if ($limit === 'all') {
            $limit = null;
        } else {
            $limit = (int)$limit;
            if ($limit < 1) {
                throw new Exception('The limit must be greater than 0.');
            }
        }

        return $this->getMigrationHistory($limit)->then(
            function($migrations) use ($limit) {
                if (empty($migrations)) {
                    $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);
                } else {
                    $n = count($migrations);
                    if ($limit > 0) {
                        $this->stdout("Showing the last $n applied " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
                    } else {
                        $this->stdout("Total $n " . ($n === 1 ? 'migration has' : 'migrations have') . " been applied before:\n", Console::FG_YELLOW);
                    }
                    foreach ($migrations as $version => $time) {
                        $this->stdout("\t(" . date('Y-m-d H:i:s', $time) . ') ' . $version . "\n");
                    }
                }
                return true;
            }
        );
    }

public
function
actionHistory
(
RequestApplicationInterface
$
app
,
$
limit
=
10
)
{
if
(
$
limit
===
'all'
)
{
$
limit
=
;
}
else
{
$
limit
=
(
int
)
$
limit
;
if
(
$
limit
<
1
)
{
throw
new
Exception
(
'The limit must be greater than 0.'
)
;
}
}
return
$
this
->
getMigrationHistory
(
$
limit
)
->
then
(
function
(
$
migrations
)
use
(
$
limit
)
{
if
(
empty
(
$
migrations
)
)
{
$
this
->
stdout
(
"No migration has been done before.\n"
,
Console
::
FG_YELLOW
)
;
}
else
{
$
n
=
count
(
$
migrations
)
;
if
(
$
limit
>
0
)
{
$
this
->
stdout
(
"Showing the last $n applied "
.
(
$
n
===
1
'migration'
:
'migrations'
)
.
":\n"
,
Console
::
FG_YELLOW
)
;
}
else
{
$
this
->
stdout
(
"Total $n "
.
(
$
n
===
1
'migration has'
:
'migrations have'
)
.
" been applied before:\n"
,
Console
::
FG_YELLOW
)
;
}
foreach
(
$
migrations
as
$
version
=>
$
time
)
{
$
this
->
stdout
(
"\t("
.
date
(
'Y-m-d H:i:s'
,
$
time
)
.
') '
.
$
version
.
"\n"
)
;
}
}
return
true
;
}
)
;
}

Displays the migration history.

This command will show the list of migrations that have been applied
so far. For example,

```
console migrate/history     # showing the last 10 migrations
console migrate/history 5   # showing the last 5 migrations
console migrate/history all # showing the whole history
```

@param RequestApplicationInterface $app
@param int|string                  $limit the maximum number of migrations to be displayed.
If it is "all", the whole migration history will be displayed.
@return ExtendedPromiseInterface
@throws Exception if invalid limit value passed


public function actionNew(RequestApplicationInterface $app, $limit = 10)
    {
        if ($limit === 'all') {
            $limit = null;
        } else {
            $limit = (int)$limit;
            if ($limit < 1) {
                throw new Exception('The limit must be greater than 0.');
            }
        }

        return $this->getNewMigrations()->then(
            function($migrations) use ($limit) {
                if (empty($migrations)) {
                    $this->stdout("No new migrations found. Your system is up-to-date.\n", Console::FG_GREEN);
                } else {
                    $n = count($migrations);
                    if ($limit && $n > $limit) {
                        $migrations = array_slice($migrations, 0, $limit);
                        $this->stdout("Showing $limit out of $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
                    } else {
                        $this->stdout("Found $n new " . ($n === 1 ? 'migration' : 'migrations') . ":\n", Console::FG_YELLOW);
                    }

                    foreach ($migrations as $migration) {
                        $this->stdout("\t" . $migration . "\n");
                    }
                }
                return true;
            }
        );
    }

Displays the un-applied new migrations.

This command will show the new migrations that have not been applied.
For example,

```
console migrate/new     # showing the first 10 new migrations
console migrate/new 5   # showing the first 5 new migrations
console migrate/new all # showing all new migrations
```

@param RequestApplicationInterface $app
@param int|string                  $limit the maximum number of new migrations to be displayed.
If it is `all`, all available new migrations will be displayed.
@return ExtendedPromiseInterface
@throws Exception if invalid limit value passed

Displays the un - applied new migrations .


public function actionCreate(RequestApplicationInterface $app, $name)
    {
        if (!preg_match('/^[\w\\\\]+$/', $name)) {
            throw new Exception('The migration name should contain letters, digits, underscore and/or backslash characters only.');
        }

        list($namespace, $className) = $this->generateClassName($name);
        // Abort if name is too long
        $nameLimit = $this->getMigrationNameLimit();
        if ($nameLimit !== null && strlen($className) > $nameLimit) {
            throw new Exception('The migration name is too long.');
        }

        $migrationPath = $this->findMigrationPath($namespace);

        $file = $migrationPath . DIRECTORY_SEPARATOR . $className . '.php';
        return $this->confirm("Create new migration '$file'?")->then(
            function() use ($app, $name, $className, $namespace, $migrationPath, $file) {
                $content = $this->generateMigrationSourceCode([
                    'name' => $name,
                    'className' => $className,
                    'namespace' => $namespace,
                ], $app);
                FileHelper::createDirectory($migrationPath);
                file_put_contents($file, $content, LOCK_EX);
                $this->stdout("New migration created successfully.\n", Console::FG_GREEN);
                return true;
            }
        );
    }

Creates a new migration.

This command creates a new migration using the available migration template.
After using this command, developers should modify the created migration
skeleton by filling up the actual migration logic.

```
console migrate/create create_user_table
```

In order to generate a namespaced migration, you should specify a namespace before the migration's name.
Note that backslash (`\`) is usually considered a special character in the shell, so you need to escape it
properly to avoid shell errors or incorrect behavior.
For example:

```
console migrate/create 'app\\migrations\\createUserTable'
```

In case [[migrationPath]] is not set and no namespace is provided, the first entry of [[migrationNamespaces]] will be used.

@param RequestApplicationInterface $app
@param string                      $name the name of the new migration. This should only contain
letters, digits, underscores and/or backslashes.

Note: If the migration name is of a special form, for example create_xxx or
drop_xxx, then the generated migration file will contain extra code,
in this case for creating/dropping tables.

@return ExtendedPromiseInterface
@throws Exception if the name argument is invalid.
@throws \Reaction\Exceptions\Exception


protected function migrateDown($class)
    {
        if ($class === self::BASE_MIGRATION) {
            return resolveLazy(true);
        }

        $this->stdout("*** reverting $class\n", Console::FG_YELLOW);
        $start = microtime(true);
        $promise = new LazyPromise(function() use (&$migration, $class, $start) {
            return $this->createMigration($class)
                ->then(function($migration) {
                    /** @var MigrationInterface $migration */
                    return $migration->down();
                })->then(function() use ($class, $start) {
                    $time = microtime(true) - $start;
                    $this->stdout("*** reverted $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_GREEN);
                    return $this->removeMigrationHistory($class);
                }, function($error = null) use ($class, $start) {
                    $time = microtime(true) - $start;
                    $this->stdout("*** failed to revert $class (time: " . sprintf('%.3f', $time) . "s)\n\n", Console::FG_RED);
                    $prevException = $error instanceof \Throwable ? $error : null;
                    $exception = new Exception("Failed to revert $class (time: " . sprintf('%.3f', $time) . "s)", 0, $prevException);
                    throw new $exception;
                });
        });
        return $promise;
    }

Downgrades with the specified migration class.
@param string $class the migration class name
@return LazyPromiseInterface whether the migration is successful

Downgrades with the specified migration class .


protected function migrateToTime(RequestApplicationInterface $app, $time)
    {
        return $this->getMigrationHistory(null)->then(
            function($migrations) use ($app, $time) {
                $migrations = array_values($migrations);
                $count = 0;
                while ($count < count($migrations) && $migrations[$count] > $time) {
                    ++$count;
                }
                if ($count === 0) {
                    $this->stdout("Nothing needs to be done.\n", Console::FG_GREEN);
                } else {
                    return $this->actionDown($app, $count);
                }
                return reject(new Exception("Nothing needs to be done"));
            }
        );
    }

protected
function
migrateToTime
(
RequestApplicationInterface
$
app
,
$
time
)
{
return
$
this
->
getMigrationHistory
(
)
->
then
(
function
(
$
migrations
)
use
(
$
app
,
$
time
)
{
$
migrations
=
array_values
(
$
migrations
)
;
$
count
=
0
;
while
(
$
count
<
count
(
$
migrations
)
&&
$
migrations
[
$
count
]
>
$
time
)
{
++
$
count
;
}
if
(
$
count
===
0
)
{
$
this
->
stdout
(
"Nothing needs to be done.\n"
,
Console
::
FG_GREEN
)
;
}
else
{
return
$
this
->
actionDown
(
$
app
,
$
count
)
;
}
return
reject
(
new
Exception
(
"Nothing needs to be done"
)
)
;
}
)
;
}

Migrates to the specified apply time in the past.
@param RequestApplicationInterface $app
@param int                         $time UNIX timestamp value.
@return ExtendedPromiseInterface

Migrates to the specified apply time in the past .


protected function migrateToVersion(RequestApplicationInterface $app, $version)
    {
        $originalVersion = $version;

        return $this->getNewMigrations()->then(
            function($migrations) use ($app, $version) {
                foreach ($migrations as $i => $migration) {
                    if (strpos($migration, $version) === 0) {
                        return $this->actionUp($app, $i + 1);
                    }
                }
                return reject(null);
            }
        )->then(null, function() use ($app, $version, $originalVersion) {
            return $this->getMigrationHistory(null)
                ->then(function($migrations) use ($app, $version, $originalVersion) {
                    $migrations = array_keys($migrations);
                    foreach ($migrations as $i => $migration) {
                        if (strpos($migration, $version, $originalVersion) === 0) {
                            if ($i === 0) {
                                $this->stdout("Already at '$originalVersion'. Nothing needs to be done.\n", Console::FG_YELLOW);
                            } else {
                                $this->actionDown($app, $i);
                            }

                            return resolve(true);
                        }
                    }
                    throw new Exception("Unable to find the version '$originalVersion'.");
                });
        });
    }

Migrates to the certain version.
@param RequestApplicationInterface $app
@param string                      $version name in the full format.
@return ExtendedPromiseInterface
@throws Exception if the provided version cannot be found.


protected function _loadAdapter($autoconnect = true)
    {
        $factory = \Library\Factory::create()
            ->factoryName(__CLASS__)
            ->mustImplementAndExtend(array(
                Kernel::DATABASE_ADAPTER_ABSTRACT,
                Kernel::DATABASE_ADAPTER_INTERFACE
            ))
            ->defaultNamespace(Kernel::DATABASE_ADAPTER_DEFAULT_NAMESPACE)
            ->classNameMask(array('%s', '%s'.Kernel::DATABASE_ADAPTER_SUFFIX))
            ;
        $params = array(
            $this, $this->__db_name, $this->__adapter_options
        );
        $this->__adapter = $factory->build($this->__adapter_type, $params);
    /*
        $_adapter_class = '\Lib\DatabaseAdapter\\'.ucfirst($this->__adapter_type);
        if (!\CarteBlanche\App\Loader::classExists($_adapter_class)) {
            $_adapter_class .= 'Adapter';
        }
        if (\CarteBlanche\App\Loader::classExists($_adapter_class)) {
            try {
                $this->__adapter = new $_adapter_class(
                    $this, CarteBlanche::getPath('db_path').$this->__db_name, $this->__adapter_options
                );
            } catch ( \Exception $e ) {
                throw new \RuntimeException(
                    sprintf('An error occurred while trying to load Database Adapter "%s"!', $_adapter_class)
                );
            }
            if (!($this->__adapter instanceof \Lib\DatabaseAdapter\AbstractDatabaseAdapter)) {
                throw new \DomainException(
                    sprintf('A Database Adapter must extend the "\Lib\DatabaseAdapter\AbstractDatabaseAdapter" class (got "%s")!', $_adapter_class)
                );
            }
            if (!($this->__adapter instanceof \Lib\DatabaseAdapter\DatabaseAdapterInterface)) {
                throw new \DomainException(
                    sprintf('A Database Adapter must implements the "\Lib\DatabaseAdapter\DatabaseAdapterInterface" interface (got "%s")!', $_adapter_class)
                );
            }
        } else {
            throw new \RuntimeException(
                sprintf('Database adapter for type "%s" doesn\'t exist!', $this->__adapter_type)
            );
        }
    */
        if (true===$autoconnect) $this->connect();
        return $this;
    }

Load the database adapter

@param bool $autoconnect Build the connexion after adapter construction
@return self $this for method chaining


protected function connect()
    {
        if (empty($this->__adapter)) self::_loadAdapter();
        $this->db = $this->__adapter->connect();
        return $this;
    }

protected function connect ( ) { if ( empty ( $ this -> __adapter ) ) self :: _loadAdapter ( ) ; $ this -> db = $ this -> __adapter -> connect ( ) ; return $ this ; }


public function addCachedQuery($query, $results = null)
    {
        $this->queries[] = $query;
        if (!is_null($results))
            $this->queries_results[$query] = $results;
        return $this;
    }

public function addCachedQuery ( $ query , $ results = null ) { $ this -> queries [ ] = $ query ; if ( ! is_null ( $ results ) ) $ this -> queries_results [ $ query ] = $ results ; return $ this ; }

Add a query and its results in the object cache

@param string $query The query string to cache
@param mixed $results The results of the query execution to cache
@return self $this for method chaining


public function getCachedResults( $query )
    {
        return isset($this->queries_results[$query]) ? $this->queries_results[$query] : false;
    }

public function getCachedResults ( $ query ) { return isset ( $ this -> queries_results [ $ query ] ) ? $ this -> queries_results [ $ query ] : false ; }

Get a query from the object cache if so

@param string $query The query string to search in the cache
@return mixed The results cached if so, false otherwise


public function arrayQuery($query = null, $method = 'arrayQuery', $cached = true)
    {
        if (empty($this->__adapter)) self::_loadAdapter();
        return $this->__adapter->arrayQuery( $query, $method, $cached );
    }

public function arrayQuery ( $ query = null , $ method = 'arrayQuery' , $ cached = true ) { if ( empty ( $ this -> __adapter ) ) self :: _loadAdapter ( ) ; return $ this -> __adapter -> arrayQuery ( $ query , $ method , $ cached ) ; }

Execute an array query

@param string $query The query string to execute
@param string $method The query method to use
@param bool $cached If set to TRUE (default), the query results are first searched in the object cache
@return mixed The query result(s)
@see http://www.php.net/manual/en/function.sqlite-array-query.php


public function add_table($tablename = null, $table_structure = null)
    {
        if (empty($tablename) || empty($table_structure)) return false;

        if (!is_string($table_structure))
            $table_structure_str = join(',', self::build_fields_array( $table_structure ) );
        else
            $table_structure_str = $table_structure;
        if (!self::table_exists($tablename)) {
            $query = "CREATE TABLE $tablename ($table_structure_str);";
    /*
            $results = $this->db->queryExec($query, $err);
            if ($err) trigger_error( "Can not create table '$tablename' [$err]!", E_USER_ERROR );
    */
            $results = $this->query($query, null, 'queryExec');
            $this->addCachedQuery( $query, $results );
        }
        return self::table_exists($tablename);
    }

Add a table in the database

@param string $tablename The new table name
@param array $table_structure An array of the table fields
@return bool TRUE if the table had been created, FALSE if an error occurred


public function add_fields($tablename = null, $table_structure = null)
    {
        if (empty($tablename) || empty($table_structure)) return false;

        if (!is_string($table_structure))
            $table_structure_ar = self::build_fields_array( $table_structure );
        else
            $table_structure_ar = array($table_structure);

        if (self::table_exists($tablename)) {
            $query = "ALTER TABLE $tablename ADD COLUMN ( ".join(',', $table_structure_ar)." );";
    /*
            $this->queries[] = $query;
            $results = $this->db->queryExec($query, $err);
            if ($err) trigger_error( "Can not alter table '$tablename' [$err]!", E_USER_ERROR );
    */
            $results = $this->query($query, null, 'queryExec');
            $this->addCachedQuery( $query );
        }
        return true;
    }

Add fields in a table

@param string $tablename The new table name
@param array $table_structure An array of the table fields
@return bool TRUE if the field had been added, FALSE if an error occurred


public function table_infos($tablename = null)
    {
        if (!empty($tablename)) {
            if (isset($this->tables[$tablename]) && is_array($this->tables[$tablename]))
                return $this->tables[$tablename];
            $query = "PRAGMA table_info ('{$tablename}')";
            $results = $this->arrayQuery($query);
            $this->tables[$tablename] = $results;
            return $results;
        }
        return false;
    }

public
function
table_infos
(
$
tablename
=
)
{
if
(
!
empty
(
$
tablename
)
)
{
if
(
isset
(
$
this
->
tables
[
$
tablename
]
)
&&
is_array
(
$
this
->
tables
[
$
tablename
]
)
)
return
$
this
->
tables
[
$
tablename
]
;
$
query
=
"PRAGMA table_info ('{$tablename}')"
;
$
results
=
$
this
->
arrayQuery
(
$
query
)
;
$
this
->
tables
[
$
tablename
]
=
$
results
;
return
$
results
;
}
return
false
;
}

Get infos of a table in the database

@param string $tablename The new table name
@return array The request result row


public function table_exists($tablename = null)
    {
        if (!empty($tablename)) {
            if (isset($this->tables[$tablename])) return true;
            $query = "SELECT name FROM sqlite_master WHERE name='{$tablename}'";
            $results = $this->query($query);
            if ($results && $results->numRows()) {
                $this->tables[$tablename] = true;
                return true;
            }
        }
        return false;
    }

Check if a table exists in the database

@param string $tablename The new table name
@return bool TRUE if the table exists, FALSE otherwise


public function build_fields_array($table_structure = null)
    {
        if (empty($table_structure) || !is_array($table_structure)) return;
        $table_structure_ar=array();
        foreach($table_structure as $index=>$form) {
            if (is_string($form))
                $table_structure_ar[] = $index.' '.$form;
            else
                $table_structure_ar[] = $index.' '.$form['type'].' '
                    .( (!empty($form['null']) && $form['null']==true) ? 'null' : 'not null').' '
                    .(!empty($form['default']) ? 'default \''.$form['default'].'\'' : '').' '
                    .(!empty($form['index']) ? $form['index'] : '');
        }
        return $table_structure_ar;
    }

public
function
build_fields_array
(
$
table_structure
=
)
{
if
(
empty
(
$
table_structure
)
||
!
is_array
(
$
table_structure
)
)
return
;
$
table_structure_ar
=
array
(
)
;
foreach
(
$
table_structure
as
$
index
=>
$
form
)
{
if
(
is_string
(
$
form
)
)
$
table_structure_ar
[
]
=
$
index
.
' '
.
$
form
;
else
$
table_structure_ar
[
]
=
$
index
.
' '
.
$
form
[
'type'
]
.
' '
.
(
(
!
empty
(
$
form
[
'null'
]
)
&&
$
form
[
'null'
]
==
true
)
'null'
:
'not null'
)
.
' '
.
(
!
empty
(
$
form
[
'default'
]
)
'default \''
.
$
form
[
'default'
]
.
'\''
:
''
)
.
' '
.
(
!
empty
(
$
form
[
'index'
]
)
$
form
[
'index'
]
:
''
)
;
}
return
$
table_structure_ar
;
}

Build a query string to add a field in a table

@param array $table_structure The structure of the field
@return string The query string to create the field


public function escape($str = null, $double_quotes = false)
    {
        if (empty($this->__adapter)) self::_loadAdapter();
        return $this->__adapter->escape($str);
    }

public function escape ( $ str = null , $ double_quotes = false ) { if ( empty ( $ this -> __adapter ) ) self :: _loadAdapter ( ) ; return $ this -> __adapter -> escape ( $ str ) ; }

Escape a string using the internal PHP adapter function

@param string $str The string to escape
@param bool $double_quotes If true, the double-quotes will be doubled for escaping
@return string The escaped string


public function clear()
    {
        $this->query_type='SELECT';
        $this->fields=null;
        $this->from=null;
        $this->where='';
        $this->limit=null;
        $this->offset=null;
        $this->order_by=null;
        $this->order_way=null;
    }

public function clear ( ) { $ this -> query_type = 'SELECT' ; $ this -> fields = null ; $ this -> from = null ; $ this -> where = '' ; $ this -> limit = null ; $ this -> offset = null ; $ this -> order_by = null ; $ this -> order_way = null ; }


public function where($arg = null, $val = null, $sign = '=', $operator = 'OR')
    {
        $this->where .=
            (strlen($this->where) ? " {$operator} " : '')
            .$arg
            .( !empty($val) ? " {$sign} ".self::escape($val) : '' );
        return $this;
    }

public
function
where
(
$
arg
=
,
$
val
=
,
$
sign
=
'='
,
$
operator
=
'OR'
)
{
$
this
->
where
.=
(
strlen
(
$
this
->
where
)
" {$operator} "
:
''
)
.
$
arg
.
(
!
empty
(
$
val
)
" {$sign} "
.
self
::
escape
(
$
val
)
:
''
)
;
return
$
this
;
}

Build the condition of a query

@param string $arg The argument of the WHERE statement
@param string $val The value of the argument
@param string $sign The sign used to build the WHERE statement (default is '=')
@param string $operator An operator used if a WHERE statement was already set
@return object The whole object itself for method chaining


public function where_str($str = null, $operator = 'OR')
    {
        $this->where .=
            (strlen($this->where) ? " {$operator} " : '')
            .$str;
        return $this;
    }

public
function
where_str
(
$
str
=
,
$
operator
=
'OR'
)
{
$
this
->
where
.=
(
strlen
(
$
this
->
where
)
" {$operator} "
:
''
)
.
$
str
;
return
$
this
;
}

Add a WHERE string to a query

@param string $str The full formed WHERE statement
@param string $operator An operator used if a WHERE statement was already set
@return object The whole object itself for method chaining


public function where_in($arg = null, $val = null, $operator = 'OR')
    {
        $this->where .=
            (strlen($this->where) ? " {$operator} " : '')
            .$arg
            .( !empty($val) && is_array($val) ? " IN (".self::escape( implode(',',$val) ).")" : '' );
        return $this;
    }

public
function
where_in
(
$
arg
=
,
$
val
=
,
$
operator
=
'OR'
)
{
$
this
->
where
.=
(
strlen
(
$
this
->
where
)
" {$operator} "
:
''
)
.
$
arg
.
(
!
empty
(
$
val
)
&&
is_array
(
$
val
)
" IN ("
.
self
::
escape
(
implode
(
','
,
$
val
)
)
.
")"
:
''
)
;
return
$
this
;
}

Alias for a WHERE statement with a IN sign

@param string $arg The argument of the WHERE statement
@param array $val The array of values to select
@param string $operator An operator used if a WHERE statement was already set
@return object The whole object itself for method chaining
@see self::where()


public function or_where($arg = null, $val = null, $sign = '=')
    {
        return self::where($arg, $val, $sign, 'OR');
    }

public function or_where ( $ arg = null , $ val = null , $ sign = '=' ) { return self :: where ( $ arg , $ val , $ sign , 'OR' ) ; }

Alias for a OR WHERE statement

@param string $arg The argument of the WHERE statement
@param string $val The value of the argument
@param string $sign The sign used to build the WHERE statement (default is '=')
@return object The whole object itself for method chaining
@see self::where()


public function and_where($arg = null, $val = null, $sign = '=')
    {
        return self::where($arg, $val, $sign, 'AND');
    }

public function and_where ( $ arg = null , $ val = null , $ sign = '=' ) { return self :: where ( $ arg , $ val , $ sign , 'AND' ) ; }

Alias for a AND WHERE statement

@param string $arg The argument of the WHERE statement
@param string $val The value of the argument
@param string $sign The sign used to build the WHERE statement (default is '=')
@return object The whole object itself for method chaining
@see self::where()


public function order_by($order_by = null, $order_way = 'asc')
    {
        $this->order_by = $order_by;
        $this->order_way = $order_way;
        return $this;
    }

public function order_by ( $ order_by = null , $ order_way = 'asc' ) { $ this -> order_by = $ order_by ; $ this -> order_way = $ order_way ; return $ this ; }

Set the ORDER BY condition of a query

@param string $order_by The field name to order on
@param string $order_way The way for ordering (asc or desc - default is 'asc')
@return object The whole object itself for method chaining


public function get_query()
    {
        $query =
            strtoupper($this->query_type)
            .' '.$this->fields
            .' FROM '.$this->from
            .( !empty($this->where) ?
                ' WHERE '.$this->where : '' )
            .( !empty($this->order_by) ?
                ' ORDER BY '.$this->order_by.' '.$this->order_way
                : '' )
            .( !empty($this->limit) ?
                ' LIMIT '.$this->limit
    //				.( !empty($this->offset) ? ','.$this->offset : '' )
                : '' )
            .( !empty($this->offset) ?
                ' OFFSET '.$this->offset
                : '' )
            .';';
        return $query;
    }

Global query construction using the query constructors values

@return string A full query string


public function get()
    {
        $query = $this->get_query();
        $results = $this->query($query);
        return $results->fetchAll();
    }

public function get ( ) { $ query = $ this -> get_query ( ) ; $ results = $ this -> query ( $ query ) ; return $ results -> fetchAll ( ) ; }

Execute the query constructing it with the query constructors values

@return mixed The query results


public function get_single()
    {
        $query = $this->get_query();
        $results = $this->singleQuery($query);
        return isset($results[0]) ? $results[0] : null;
    }

public function get_single ( ) { $ query = $ this -> get_query ( ) ; $ results = $ this -> singleQuery ( $ query ) ; return isset ( $ results [ 0 ] ) ? $ results [ 0 ] : null ; }

Execute a single query constructing it with the query constructors values

@return mixed The query result as a single value


public static function getAllExtensions() {

	$coreExt = new UICoreExtension();
	$coreExt->setBuilders(array(
		"ui.html" => "YsHTML",
		"ui.jqueryCore"  => "YsJQuery",
		"ui.dialog"  => "YsUIDialog",
		"ui.tabs"  => "YsUITabs",
		"ui.accordion"  => "YsUIAccordion",
		"ui.progressbar"  => "YsUIProgressbar",
		"ui.slider"  => "YsUISlider",
		"ui.autocomplete"  => "YsUIAutocomplete",
		"ui.datepicker"  => "YsUIDatepicker",
		"ui.datetimepicker"  => "YsUIDateTimepicker",
		"ui.button"  => "YsUIButton",
		"ui.multiselect"  => "YsUIMultiSelect",
		"ui.picklist"  => "YsUIPickList",
		"ui.popup"  => "YsUIPopUp",
		"ui.selectmenu"  => "YsUISelectMenu",
		"ui.expander"  => "YsUIExpander",
		"ui.splitter"  => "YsUISplitter",
		"ui.dynaselect"  => "YsUIDynamicSelect",
		"ui.menu"  => "YsUIMenu",
		"ui.panel"  => "YsUIPanel",
		"ui.tooltip"  => "YsUITooltip",
		"ui.draggable"  => "YsUIDraggable",
		"ui.droppable"  => "YsUIDroppable",
                "ui.sortable"  => "YsUISortable",
                "ui.selectable"  => "YsUISelectable",
		"ui.resizable"  => "YsUIResizable",
		"ui.effect"  => "YsUIEffect",
		"ui.video"  => "YsUIVideo"
	));

	$uiAddonsExt = new UIAddonsExtension();
	$uiAddonsExt->setBuilders(array(
		"ui.block" => "YsBlockUI",
		"ui.box" => "YsJQBox",
		"ui.colorpicker" => "YsJQColorPicker",
		"ui.notify" => "YsPNotify",
		"ui.hotkey" => "YsKeys",
		"ui.monitor" => "YsJQMonitor",
		"ui.keypad" => "YsJQKeypad",
		"ui.calculator" => "YsJQCalculator",
		"ui.layout" => "YsJLayout",
		"ui.mask" => "YsJQMask",
		"ui.formWizard" => "YsFormWizard",
		"ui.ajaxForm" => "YsJQForm",
		"ui.validation" => "YsJQValidate",
		"ui.booklet" => "YsJQBooklet",
		"ui.cycle" => "YsJQCycle",
		"ui.ring" => "YsJQRing",
		"ui.upload" => "YsUpload",
	));

	return array(
		new HTMLExtension(),
		new JsSintaxExtension(),
		new JQueryCoreExtension(),
		new UIWidgetExtension(),
		$coreExt,
		$uiAddonsExt
	);
  }

public static function getAllExtensions ( ) { $ coreExt = new UICoreExtension ( ) ; $ coreExt -> setBuilders ( array ( "ui.html" => "YsHTML" , "ui.jqueryCore" => "YsJQuery" , "ui.dialog" => "YsUIDialog" , "ui.tabs" => "YsUITabs" , "ui.accordion" => "YsUIAccordion" , "ui.progressbar" => "YsUIProgressbar" , "ui.slider" => "YsUISlider" , "ui.autocomplete" => "YsUIAutocomplete" , "ui.datepicker" => "YsUIDatepicker" , "ui.datetimepicker" => "YsUIDateTimepicker" , "ui.button" => "YsUIButton" , "ui.multiselect" => "YsUIMultiSelect" , "ui.picklist" => "YsUIPickList" , "ui.popup" => "YsUIPopUp" , "ui.selectmenu" => "YsUISelectMenu" , "ui.expander" => "YsUIExpander" , "ui.splitter" => "YsUISplitter" , "ui.dynaselect" => "YsUIDynamicSelect" , "ui.menu" => "YsUIMenu" , "ui.panel" => "YsUIPanel" , "ui.tooltip" => "YsUITooltip" , "ui.draggable" => "YsUIDraggable" , "ui.droppable" => "YsUIDroppable" , "ui.sortable" => "YsUISortable" , "ui.selectable" => "YsUISelectable" , "ui.resizable" => "YsUIResizable" , "ui.effect" => "YsUIEffect" , "ui.video" => "YsUIVideo" ) ) ; $ uiAddonsExt = new UIAddonsExtension ( ) ; $ uiAddonsExt -> setBuilders ( array ( "ui.block" => "YsBlockUI" , "ui.box" => "YsJQBox" , "ui.colorpicker" => "YsJQColorPicker" , "ui.notify" => "YsPNotify" , "ui.hotkey" => "YsKeys" , "ui.monitor" => "YsJQMonitor" , "ui.keypad" => "YsJQKeypad" , "ui.calculator" => "YsJQCalculator" , "ui.layout" => "YsJLayout" , "ui.mask" => "YsJQMask" , "ui.formWizard" => "YsFormWizard" , "ui.ajaxForm" => "YsJQForm" , "ui.validation" => "YsJQValidate" , "ui.booklet" => "YsJQBooklet" , "ui.cycle" => "YsJQCycle" , "ui.ring" => "YsJQRing" , "ui.upload" => "YsUpload" , ) ) ; return array ( new HTMLExtension ( ) , new JsSintaxExtension ( ) , new JQueryCoreExtension ( ) , new UIWidgetExtension ( ) , $ coreExt , $ uiAddonsExt ) ; }

Get All SmarTwig Extensions

@return array An array of Yepsua\SmarTwig\Twig\Extension\*Extension instances


static public function getInstance($storagePath = null) {
        if (!self::$_instance) {
            if (empty($storagePath)) {
                throw new \Exception("Storage path need to be specified on the first instance call for ModelOperator");
            }
            self::$_instance = new ModelOperator($storagePath);
            self::$_instance->loadStructureFiles();
        }
        return self::$_instance;
    }

Return current instance
@static
@param mixed $storagePath to operate with structures and models
@return ModelOperator
@throws \Exception


public function setStoragePath($path) {
        FSService::makeWritable($path);
        $this->_storagePath    = $path;
        $this->_structuresPath = $this->_storagePath . 'structure/';
        $this->_modelsPath     = $this->_storagePath . 'classes/';
        FSService::makeWritable($this->_structuresPath);
        FSService::makeWritable($this->_modelsPath);
        $this->loadStructureFiles($this->_structuresPath);
        return $this;
    }

public function setStoragePath ( $ path ) { FSService :: makeWritable ( $ path ) ; $ this -> _storagePath = $ path ; $ this -> _structuresPath = $ this -> _storagePath . 'structure/' ; $ this -> _modelsPath = $ this -> _storagePath . 'classes/' ; FSService :: makeWritable ( $ this -> _structuresPath ) ; FSService :: makeWritable ( $ this -> _modelsPath ) ; $ this -> loadStructureFiles ( $ this -> _structuresPath ) ; return $ this ; }

Change store path
@param $path
@return $this


public function loadStructureFiles($path = null) {
        if (empty($path)) $path = $this->_structuresPath;

        $files = FSService::getInstance()->in($path, true)->find('*.yml', FSService::TYPE_FILE, FSService::HYDRATE_NAMES_PATH);
        $data  = array();
        //if (isset($files['structure.yml'])) {
        //    $data = Yaml::parse(file_get_contents($files['structure.yml']));
        //    if (is_null($data)) $data = array();
        //    unset($files['structure.yml']);
        //}
        foreach ($files as $file) {
            $modelData      = Yaml::parse(file_get_contents($file));
            $modelName      = !empty($modelData['model']) ? $modelData['model'] : substr($file, strrpos($file, '/') + 1, -4);
            $modelNamespace = "Entities";
            $data           = array_merge($data, array($modelNamespace . "\\" . ucfirst($modelName) => $modelData));
        }

        $data              = self::fixYamlStructures($data);
        $this->_structures = $data;
        return $this;
    }

//    if (is_null($data)) $data = array();

Loading structure from YAML files
First loading "structure.yml" if it exists

@param mixed $path Path where yaml are stored
@return $this

Loading structure from YAML files First loading structure . yml if it exists


public function getModelStructure($modelName) {
        if (empty($this->_structures)) {
            $this->loadStructureFiles($this->_structuresPath);
        }
        $modelName = ucfirst($modelName);
        if (empty($this->_structures[$modelName])) {
            return array();
        }
        return $this->_structures[$modelName];
    }

public function getModelStructure ( $ modelName ) { if ( empty ( $ this -> _structures ) ) { $ this -> loadStructureFiles ( $ this -> _structuresPath ) ; } $ modelName = ucfirst ( $ modelName ) ; if ( empty ( $ this -> _structures [ $ modelName ] ) ) { return array ( ) ; } return $ this -> _structures [ $ modelName ] ; }

Return array with structure for specified model

@param string $modelName
@return mixed


public function saveModelStructure($modelName) {
        $info      = $this->getStructurePathForModel($modelName);
        $filePath  = $info['path'] . '/' . $info['fileName'] . '.yml';
        $modelName = ucfirst($modelName);
        FSService::makeWritable($info['path']);
        if (is_file($filePath)) {
            unlink($filePath);
        }

        $structure = self::fixYamlStructures($this->_structures[$modelName], true);
        file_put_contents($filePath, Yaml::dump($structure, 6, 2));
        $this->_structures[$modelName] = $structure;
        return true;
    }

public function saveModelStructure ( $ modelName ) { $ info = $ this -> getStructurePathForModel ( $ modelName ) ; $ filePath = $ info [ 'path' ] . '/' . $ info [ 'fileName' ] . '.yml' ; $ modelName = ucfirst ( $ modelName ) ; FSService :: makeWritable ( $ info [ 'path' ] ) ; if ( is_file ( $ filePath ) ) { unlink ( $ filePath ) ; } $ structure = self :: fixYamlStructures ( $ this -> _structures [ $ modelName ] , true ) ; file_put_contents ( $ filePath , Yaml :: dump ( $ structure , 6 , 2 ) ) ; $ this -> _structures [ $ modelName ] = $ structure ; return true ; }

Save structure to relative YML file

@param string $modelName
@return bool


public function dataDump($models = null) {
        if (!empty($models)) {
            if (!is_array($models)) $models = array($models);
        } else {
            $models = array_keys($this->_structures);
        }

        $data_dir = $this->_storagePath . 'data/';
        FSService::makeWritable($data_dir);
        foreach ($models as $model) {
            $model     = ucfirst($model);
            $file_name = $data_dir . strtolower($model) . '.yml';
            if (!isset($this->_structures[$model])) continue;

            if (is_file($file_name)) {
                unlink($file_name);
            }
            $data = QC::create($this->_structures[$model]['table'])->execute();
            file_put_contents($file_name, Yaml::dump($data, 6, 2));
        }
    }

public function dataDump ( $ models = null ) { if ( ! empty ( $ models ) ) { if ( ! is_array ( $ models ) ) $ models = array ( $ models ) ; } else { $ models = array_keys ( $ this -> _structures ) ; } $ data_dir = $ this -> _storagePath . 'data/' ; FSService :: makeWritable ( $ data_dir ) ; foreach ( $ models as $ model ) { $ model = ucfirst ( $ model ) ; $ file_name = $ data_dir . strtolower ( $ model ) . '.yml' ; if ( ! isset ( $ this -> _structures [ $ model ] ) ) continue ; if ( is_file ( $ file_name ) ) { unlink ( $ file_name ) ; } $ data = QC :: create ( $ this -> _structures [ $ model ] [ 'table' ] ) -> execute ( ) ; file_put_contents ( $ file_name , Yaml :: dump ( $ data , 6 , 2 ) ) ; } }

Dumps current database data to YML files
@param string|array $models


public function dataLoad($models = null) {

        if (!empty($models)) {
            if (!is_array($models)) $models = array($models);
        } else {
            $models = array_keys($this->_structures);
        }

        $data_dir = $this->_storagePath . 'data/';
        foreach ($models as $model) {
            $model     = ucfirst($model);
            $file_name = $data_dir . strtolower($model) . '.yml';
            if (!isset($this->_structures[$model]) || !is_file($file_name)) continue;
            $data = Yaml::parse(file_get_contents($file_name));
            if (!is_array($data)) continue;

            QC::executeSQL('SET FOREIGN_KEY_CHECKS=0');
            QC::executeSQL('TRUNCATE `' . $this->_structures[$model]['table'] . '`');
            QC::create($this->_structures[$model]['table'])->insert($data)->execute();
        }
    }

public
function
dataLoad
(
$
models
=
)
{
if
(
!
empty
(
$
models
)
)
{
if
(
!
is_array
(
$
models
)
)
$
models
=
array
(
$
models
)
;
}
else
{
$
models
=
array_keys
(
$
this
->
_structures
)
;
}
$
data_dir
=
$
this
->
_storagePath
.
'data/'
;
foreach
(
$
models
as
$
model
)
{
$
model
=
ucfirst
(
$
model
)
;
$
file_name
=
$
data_dir
.
strtolower
(
$
model
)
.
'.yml'
;
if
(
!
isset
(
$
this
->
_structures
[
$
model
]
)
||
!
is_file
(
$
file_name
)
)
continue
;
$
data
=
Yaml
::
parse
(
file_get_contents
(
$
file_name
)
)
;
if
(
!
is_array
(
$
data
)
)
continue
;
QC
::
executeSQL
(
'SET FOREIGN_KEY_CHECKS=0'
)
;
QC
::
executeSQL
(
'TRUNCATE `'
.
$
this
->
_structures
[
$
model
]
[
'table'
]
.
'`'
)
;
QC
::
create
(
$
this
->
_structures
[
$
model
]
[
'table'
]
)
->
insert
(
$
data
)
->
execute
(
)
;
}
}

Load data from YML files into database with replacing
@param string|array $models


public function findAllForAccount(Account $account, \DateTimeImmutable $dateStart, \DateTimeImmutable $dateEnd)
    {
        $this->addWhere('account_id', $account->getId());

        $this->addWhere('transaction_date', $dateStart->format('Y-m-d'), '>=');
        $this->addWhere('transaction_date', $dateEnd->format('Y-m-d'), '<=');
        $this->addOrder('transaction_date');

        return $this->select();
    }

public function findAllForAccount ( Account $ account , \ DateTimeImmutable $ dateStart , \ DateTimeImmutable $ dateEnd ) { $ this -> addWhere ( 'account_id' , $ account -> getId ( ) ) ; $ this -> addWhere ( 'transaction_date' , $ dateStart -> format ( 'Y-m-d' ) , '>=' ) ; $ this -> addWhere ( 'transaction_date' , $ dateEnd -> format ( 'Y-m-d' ) , '<=' ) ; $ this -> addOrder ( 'transaction_date' ) ; return $ this -> select ( ) ; }

Get list of transactions for given account between specified dates.

@param Account            $account
@param \DateTimeImmutable $dateStart
@param \DateTimeImmutable $dateEnd
@return \Eureka\Package\Money\DataMapper\Data\Money\Transaction[]

Get list of transactions for given account between specified dates .


protected function setState($state)
    {
        $this->queryState = $state;
        $map = [
            static::STATE_BUSY => static::CLIENT_POOL_STATE_BUSY,
            static::STATE_READY => static::CLIENT_POOL_STATE_READY,
        ];
        $statePool = isset($map[$state]) ? $map[$state] : static::CLIENT_POOL_STATE_NOT_READY;
        $this->changeState($statePool);
    }

protected function setState ( $ state ) { $ this -> queryState = $ state ; $ map = [ static :: STATE_BUSY => static :: CLIENT_POOL_STATE_BUSY , static :: STATE_READY => static :: CLIENT_POOL_STATE_READY , ] ; $ statePool = isset ( $ map [ $ state ] ) ? $ map [ $ state ] : static :: CLIENT_POOL_STATE_NOT_READY ; $ this -> changeState ( $ statePool ) ; }


public function getBacklogLength() : int
    {
        return array_reduce(
            $this->commandQueue,
            function ($a, CommandInterface $command) {
                if ($command instanceof Query || $command instanceof Sync) {
                    $a++;
                }
                return $a;
            },
            0);
    }

public function getBacklogLength ( ) : int { return array_reduce ( $ this -> commandQueue , function ( $ a , CommandInterface $ command ) { if ( $ command instanceof Query || $ command instanceof Sync ) { $ a ++ ; } return $ a ; } , 0 ) ; }

Get Query commands queue length
@return int


public function processQueue()
    {
        if (count($this->commandQueue) === 0 && $this->queryState === static::STATE_READY && $this->autoDisconnect) {
            $this->commandQueue[] = new Terminate();
        }

        if (count($this->commandQueue) === 0) {
            return;
        }

        if ($this->connStatus === $this::CONNECTION_BAD) {
            $this->failAllCommandsWith(new \Exception('Bad connection: ' . $this->lastError));
            if ($this->stream) {
                $this->stream->end();
                $this->stream = null;
            }
            return;
        }

        while (count($this->commandQueue) > 0 && $this->queryState === static::STATE_READY) {
            /** @var CommandInterface $c */
            $c = array_shift($this->commandQueue);
            if (!$c->isActive()) {
                continue;
            }
            $this->debug('Sending ' . get_class($c));
            if ($c instanceof Query) {
                $this->debug('Sending simple query: ' . $c->getQueryString());
            }
            $this->stream->write($c->encodedMessage());
            if ($c instanceof Terminate) {
                $this->stream->end();
            }
            if ($c->shouldWaitForComplete()) {
                $this->setState($this::STATE_BUSY);
                if ($c instanceof Query) {
                    $this->queryType = $this::QUERY_SIMPLE;
                } elseif ($c instanceof Sync) {
                    $this->queryType = $this::QUERY_EXTENDED;
                }

                $this->currentCommand = $c;

                return;
            }
        }
    }

public
function
processQueue
(
)
{
if
(
count
(
$
this
->
commandQueue
)
===
0
&&
$
this
->
queryState
===
static
::
STATE_READY
&&
$
this
->
autoDisconnect
)
{
$
this
->
commandQueue
[
]
=
new
Terminate
(
)
;
}
if
(
count
(
$
this
->
commandQueue
)
===
0
)
{
return
;
}
if
(
$
this
->
connStatus
===
$
this
::
CONNECTION_BAD
)
{
$
this
->
failAllCommandsWith
(
new
\
Exception
(
'Bad connection: '
.
$
this
->
lastError
)
)
;
if
(
$
this
->
stream
)
{
$
this
->
stream
->
end
(
)
;
$
this
->
stream
=
;
}
return
;
}
while
(
count
(
$
this
->
commandQueue
)
>
0
&&
$
this
->
queryState
===
static
::
STATE_READY
)
{
/** @var CommandInterface $c */
$
c
=
array_shift
(
$
this
->
commandQueue
)
;
if
(
!
$
c
->
isActive
(
)
)
{
continue
;
}
$
this
->
debug
(
'Sending '
.
get_class
(
$
c
)
)
;
if
(
$
c
instanceof
Query
)
{
$
this
->
debug
(
'Sending simple query: '
.
$
c
->
getQueryString
(
)
)
;
}
$
this
->
stream
->
write
(
$
c
->
encodedMessage
(
)
)
;
if
(
$
c
instanceof
Terminate
)
{
$
this
->
stream
->
end
(
)
;
}
if
(
$
c
->
shouldWaitForComplete
(
)
)
{
$
this
->
setState
(
$
this
::
STATE_BUSY
)
;
if
(
$
c
instanceof
Query
)
{
$
this
->
queryType
=
$
this
::
QUERY_SIMPLE
;
}
elseif
(
$
c
instanceof
Sync
)
{
$
this
->
queryType
=
$
this
::
QUERY_EXTENDED
;
}
$
this
->
currentCommand
=
$
c
;
return
;
}
}
}


public function query($query): Observable
    {
        return new AnonymousObservable(
            function (ObserverInterface $observer, SchedulerInterface $scheduler = null) use ($query) {
                if ($this->connStatus === $this::CONNECTION_NEEDED) {
                    $this->start();
                }
                if ($this->connStatus === $this::CONNECTION_BAD) {
                    $observer->onError(new \Exception('Connection failed'));
                    return new EmptyDisposable();
                }

                $q = new Query($query, $observer);
                $this->commandQueue[] = $q;
                $this->changeQueueCountInc();

                $this->processQueue();

                return new CallbackDisposable(function() use ($q) {
                    $this->changeQueueCountDec();
                    if ($this->currentCommand === $q && $q->isActive()) {
                        $this->cancelRequest();
                    }
                    $q->cancel();
                });
            }
        );

    }

public
function
query
(
$
query
)
:
Observable
{
return
new
AnonymousObservable
(
function
(
ObserverInterface
$
observer
,
SchedulerInterface
$
scheduler
=
)
use
(
$
query
)
{
if
(
$
this
->
connStatus
===
$
this
::
CONNECTION_NEEDED
)
{
$
this
->
start
(
)
;
}
if
(
$
this
->
connStatus
===
$
this
::
CONNECTION_BAD
)
{
$
observer
->
onError
(
new
\
Exception
(
'Connection failed'
)
)
;
return
new
EmptyDisposable
(
)
;
}
$
q
=
new
Query
(
$
query
,
$
observer
)
;
$
this
->
commandQueue
[
]
=
$
q
;
$
this
->
changeQueueCountInc
(
)
;
$
this
->
processQueue
(
)
;
return
new
CallbackDisposable
(
function
(
)
use
(
$
q
)
{
$
this
->
changeQueueCountDec
(
)
;
if
(
$
this
->
currentCommand
===
$
q
&&
$
q
->
isActive
(
)
)
{
$
this
->
cancelRequest
(
)
;
}
$
q
->
cancel
(
)
;
}
)
;
}
)
;
}

Execute simple query
@param string $query
@return Observable


protected function setConnStatus($status)
    {
        $this->connStatus = $status;
        $map = [
            static::CONNECTION_BAD => static::CLIENT_POOL_STATE_CLOSING,
            static::CONNECTION_CLOSED => static::CLIENT_POOL_STATE_CLOSING,
            static::CONNECTION_OK => static::CLIENT_POOL_STATE_READY,
        ];
        if (isset($map[$status])) {
            $this->changeState($map[$status]);
        }
    }

protected function setConnStatus ( $ status ) { $ this -> connStatus = $ status ; $ map = [ static :: CONNECTION_BAD => static :: CLIENT_POOL_STATE_CLOSING , static :: CONNECTION_CLOSED => static :: CLIENT_POOL_STATE_CLOSING , static :: CONNECTION_OK => static :: CLIENT_POOL_STATE_READY , ] ; if ( isset ( $ map [ $ status ] ) ) { $ this -> changeState ( $ map [ $ status ] ) ; } }

Set connection status
@param int $status


protected function handleMessage(ParserInterface $message)
    {
        $this->debug('Handling ' . get_class($message));
        if ($message instanceof DataRow) {
            $this->handleDataRow($message);
        } elseif ($message instanceof Authentication) {
            $this->handleAuthentication($message);
        } elseif ($message instanceof BackendKeyData) {
            $this->handleBackendKeyData($message);
        } elseif ($message instanceof CommandComplete) {
            $this->handleCommandComplete($message);
        } elseif ($message instanceof CopyInResponse) {
            $this->handleCopyInResponse($message);
        } elseif ($message instanceof CopyOutResponse) {
            $this->handleCopyOutResponse($message);
        } elseif ($message instanceof EmptyQueryResponse) {
            $this->handleEmptyQueryResponse($message);
        } elseif ($message instanceof ErrorResponse) {
            $this->handleErrorResponse($message);
        } elseif ($message instanceof NoticeResponse) {
            $this->handleNoticeResponse($message);
        } elseif ($message instanceof ParameterStatus) {
            $this->handleParameterStatus($message);
        } elseif ($message instanceof ParseComplete) {
            $this->handleParseComplete($message);
        } elseif ($message instanceof ReadyForQuery) {
            $this->handleReadyForQuery($message);
        } elseif ($message instanceof RowDescription) {
            $this->handleRowDescription($message);
        }
    }

protected
function
handleMessage
(
ParserInterface
$
message
)
{
$
this
->
debug
(
'Handling '
.
get_class
(
$
message
)
)
;
if
(
$
message
instanceof
DataRow
)
{
$
this
->
handleDataRow
(
$
message
)
;
}
elseif
(
$
message
instanceof
Authentication
)
{
$
this
->
handleAuthentication
(
$
message
)
;
}
elseif
(
$
message
instanceof
BackendKeyData
)
{
$
this
->
handleBackendKeyData
(
$
message
)
;
}
elseif
(
$
message
instanceof
CommandComplete
)
{
$
this
->
handleCommandComplete
(
$
message
)
;
}
elseif
(
$
message
instanceof
CopyInResponse
)
{
$
this
->
handleCopyInResponse
(
$
message
)
;
}
elseif
(
$
message
instanceof
CopyOutResponse
)
{
$
this
->
handleCopyOutResponse
(
$
message
)
;
}
elseif
(
$
message
instanceof
EmptyQueryResponse
)
{
$
this
->
handleEmptyQueryResponse
(
$
message
)
;
}
elseif
(
$
message
instanceof
ErrorResponse
)
{
$
this
->
handleErrorResponse
(
$
message
)
;
}
elseif
(
$
message
instanceof
NoticeResponse
)
{
$
this
->
handleNoticeResponse
(
$
message
)
;
}
elseif
(
$
message
instanceof
ParameterStatus
)
{
$
this
->
handleParameterStatus
(
$
message
)
;
}
elseif
(
$
message
instanceof
ParseComplete
)
{
$
this
->
handleParseComplete
(
$
message
)
;
}
elseif
(
$
message
instanceof
ReadyForQuery
)
{
$
this
->
handleReadyForQuery
(
$
message
)
;
}
elseif
(
$
message
instanceof
RowDescription
)
{
$
this
->
handleRowDescription
(
$
message
)
;
}
}

Handle message response callback
@param ParserInterface $message
@throws \Exception


private function processData($data)
    {
        if ($this->currentMessage) {
            $overflow = $this->currentMessage->parseData($data);
            // json_encode can slow things down here
            //$this->debug("onData: " . json_encode($overflow) . "");
            if ($overflow === false) {
                // there was not enough data to complete the message
                // leave this as the currentParser
                return '';
            }

            $this->handleMessage($this->currentMessage);

            $this->currentMessage = null;

            return $overflow;
        }

        if (strlen($data) == 0) {
            return '';
        }

        $type = $data[0];

        $message = Message::createMessageFromIdentifier($type);
        if ($message !== false) {
            $this->currentMessage = $message;
            return $data;
        }

//        if (in_array($type, ['R', 'S', 'D', 'K', '2', '3', 'C', 'd', 'c', 'G', 'H', 'W', 'D', 'I', 'E', 'V', 'n', 'N', 'A', 't', '1', 's', 'Z', 'T'])) {
//            $this->currentParser = [$this, 'parse1PlusLenMessage'];
//            call_user_func($this->currentParser, $data);
//        } else {
//            echo "Unhandled message \"".$type."\"";
//        }
    }

Data processing callback
@param mixed $data
@return bool|string


private function cancelRequest()
    {
        if ($this->currentCommand !== null) {
            $this->socket->connect($this->uri)->then(function (DuplexStreamInterface $conn) {
                $cancelRequest = new CancelRequest($this->backendKeyData->getPid(), $this->backendKeyData->getKey());
                $conn->end($cancelRequest->encodedMessage());
            }, function (\Throwable $e) {
                $this->debug("Error connecting for cancellation... " . $e->getMessage() . "\n");
            });
        }
    }

private
function
cancelRequest
(
)
{
if
(
$
this
->
currentCommand
!==
)
{
$
this
->
socket
->
connect
(
$
this
->
uri
)
->
then
(
function
(
DuplexStreamInterface
$
conn
)
{
$
cancelRequest
=
new
CancelRequest
(
$
this
->
backendKeyData
->
getPid
(
)
,
$
this
->
backendKeyData
->
getKey
(
)
)
;
$
conn
->
end
(
$
cancelRequest
->
encodedMessage
(
)
)
;
}
,
function
(
\
Throwable
$
e
)
{
$
this
->
debug
(
"Error connecting for cancellation... "
.
$
e
->
getMessage
(
)
.
"\n"
)
;
}
)
;
}
}


public function provider($provider)
    {
        $this->checkDisabled();

        $this->checkProvider($provider);

        $this->setConfig($provider);

        return Socialite::driver($provider)->redirect();
    }

public function provider ( $ provider ) { $ this -> checkDisabled ( ) ; $ this -> checkProvider ( $ provider ) ; $ this -> setConfig ( $ provider ) ; return Socialite :: driver ( $ provider ) -> redirect ( ) ; }

Redirect the user to the provider authentication page.

@return Response

Redirect the user to the provider authentication page .


public function callback(Request $request, $provider)
    {
        $this->checkDisabled();

        $this->checkProvider($provider);

        $this->setConfig($provider);

        $user = User::find(Auth::id());

        $redirectAfter = url('/');

        if ($user) {
            $redirectAfter = !($user->hasPermission('laralum::access') || $user->superAdmin()) ?: route('laralum::social.integrations');
        }

        $user = Socialite::driver($provider)->user();

        if ($user->getEmail() && $user->getName()) {
            if (Auth::check()) {
                if (!Social::where(['user_id' => Auth::id(), 'provider' => $provider])->first()) {
                    $this->registerSocial($provider, $user);

                    return redirect($redirectAfter)->with('success', __('laralum_social::general.provider_linked', ['provider' => $provider]));
                }

                return redirect($redirectAfter)->with('error', __('laralum_social::general.provider_already_linked', ['provider' => $provider]));
            }

            $sa = Social::where(['email' => $user->getEmail(), 'provider' => $provider])->first();

            if ($sa) {
                Auth::login($sa->user);

                return redirect($redirectAfter)->with('success', __('laralum_social::general.logged_in', ['provider' => $provider]));
            }

            abort(403, 'Registrations are not allowed using the social feature');
        }

        abort(403, 'The provider did not return a valid email or name to register the user');
    }

Obtain the user information from the provider.

@return Response

Obtain the user information from the provider .


public function unlink($provider)
    {
        $this->checkDisabled();

        $user = User::findOrFail(Auth::id());
        $redirectAfter = $user->hasPermission('laralum::access') || $user->superAdmin() ? route('laralum::social.integrations') : url('/');

        $link = Social::where(['user_id' => Auth::id(), 'provider' => $provider])->first();

        if (!$link) {
            return redirect($redirectAfter)->with('success', __('laralum_social::general.link_not_found', ['provider' => $provider]));
        }

        $link->delete();

        return redirect($redirectAfter)->with('success', __('laralum_social::general.unlinked', ['provider' => $provider]));
    }

Unlink the social account.

@param string $provider

@return Response


public function settings(Request $request)
    {
        $this->authorize('update', Settings::class);

        $this->settings->update([
            'enabled'                 => $request->enabled ? true : false,
            'allow_register'          => $request->allow_register ? false : false, // Not enabled yet
            'facebook_client_id'      => $request->facebook_client_id ? encrypt($request->facebook_client_id) : null,
            'facebook_client_secret'  => $request->facebook_client_secret ? encrypt($request->facebook_client_secret) : null,
            'twitter_client_id'       => $request->twitter_client_id ? encrypt($request->twitter_client_id) : null,
            'twitter_client_secret'   => $request->twitter_client_secret ? encrypt($request->twitter_client_secret) : null,
            'linkedin_client_id'      => $request->linkedin_client_id ? encrypt($request->linkedin_client_id) : null,
            'linkedin_client_secret'  => $request->linkedin_client_secret ? encrypt($request->linkedin_client_secret) : null,
            'google_client_id'        => $request->google_client_id ? encrypt($request->google_client_id) : null,
            'google_client_secret'    => $request->google_client_secret ? encrypt($request->google_client_secret) : null,
            'github_client_id'        => $request->github_client_id ? encrypt($request->github_client_id) : null,
            'github_client_secret'    => $request->github_client_secret ? encrypt($request->github_client_secret) : null,
            'bitbucket_client_id'     => $request->bitbucket_client_id ? encrypt($request->bitbucket_client_id) : null,
            'bitbucket_client_secret' => $request->bitbucket_client_secret ? encrypt($request->bitbucket_client_secret) : null,
        ]);

        $this->settings->touch();

        return redirect()->route('laralum::settings.index', ['p' => 'Social'])->with('success', __('laralum_social::general.updated_settings'));
    }

Update the social settings.

@return Response


private function checkProvider($provider)
    {
        $ci = $provider.'_client_id';
        $cs = $provider.'_client_secret';

        if (!$this->settings->$ci || !$this->settings->$cs) {
            abort(404, __('laralum_social::general.provider_not_found', ['provider' => $provider]));
        }
    }

Check if the provider is enabled or not.

@param string $provider

Check if the provider is enabled or not .


private function setConfig($provider)
    {
        $ci = $provider.'_client_id';
        $cs = $provider.'_client_secret';

        config(['services.'.$provider => [
            'client_id'     => decrypt($this->settings->$ci),
            'client_secret' => decrypt($this->settings->$cs),
            'redirect'      => route('laralum_public::social.callback', ['provider' => $provider]),
        ]]);
    }

private function setConfig ( $ provider ) { $ ci = $ provider . '_client_id' ; $ cs = $ provider . '_client_secret' ; config ( [ 'services.' . $ provider => [ 'client_id' => decrypt ( $ this -> settings -> $ ci ) , 'client_secret' => decrypt ( $ this -> settings -> $ cs ) , 'redirect' => route ( 'laralum_public::social.callback' , [ 'provider' => $ provider ] ) , ] ] ) ; }

Set the configuration to run socialite with a defined provider.

@param string $provider

Set the configuration to run socialite with a defined provider .


private function registerSocial($provider, $user, $dbuser = null)
    {
        return Social::create([
            'user_id'      => $dbuser ? $dbuser->id : Auth::user()->id,
            'provider'     => $provider,
            'token'        => $user->token,
            'secret_token' => isset($user->tokenSecret) ? $user->tokenSecret : null,
            'email'        => $user->getEmail(),
        ]);
    }

private function registerSocial ( $ provider , $ user , $ dbuser = null ) { return Social :: create ( [ 'user_id' => $ dbuser ? $ dbuser -> id : Auth :: user ( ) -> id , 'provider' => $ provider , 'token' => $ user -> token , 'secret_token' => isset ( $ user -> tokenSecret ) ? $ user -> tokenSecret : null , 'email' => $ user -> getEmail ( ) , ] ) ; }

Registers the social account.

@param string                     $provider
@param mixed                      $user
@param \Laralum\Users\Models\User $dbuser

@return bool


public function cleanupTimerCallback() {
        $now = time();
        $keys = [];
        foreach ($this->_timestamps as $key => $timestamp) {
            if ($timestamp < $now) {
                $keys[] = $key;
            }
        }
        if (!empty($keys)) {
            $this->deleteMultiple($keys);
        }
    }

public function cleanupTimerCallback ( ) { $ now = time ( ) ; $ keys = [ ] ; foreach ( $ this -> _timestamps as $ key => $ timestamp ) { if ( $ timestamp < $ now ) { $ keys [ ] = $ key ; } } if ( ! empty ( $ keys ) ) { $ this -> deleteMultiple ( $ keys ) ; } }


protected function packRecord($record = []) {
        $tsKey = $this->timestampKey;
        $dtKey = $this->dataKey;
        $data = $record;
        $record = [];
        $record[$dtKey] = $data;
        $record[$tsKey] = time();
        return $record;
    }

protected function packRecord ( $ record = [ ] ) { $ tsKey = $ this -> timestampKey ; $ dtKey = $ this -> dataKey ; $ data = $ record ; $ record = [ ] ; $ record [ $ dtKey ] = $ data ; $ record [ $ tsKey ] = time ( ) ; return $ record ; }

Pack record into array with needed format
@param mixed $record
@return array


protected function unpackRecord($record = []) {
        $tsKey = $this->timestampKey;
        $dtKey = $this->dataKey;
        if (!is_array($record) || !isset($record[$tsKey]) || !ArrayHelper::keyExists($dtKey, $record)) {
            return $record;
        }
        return $record[$dtKey];
    }

protected function unpackRecord ( $ record = [ ] ) { $ tsKey = $ this -> timestampKey ; $ dtKey = $ this -> dataKey ; if ( ! is_array ( $ record ) || ! isset ( $ record [ $ tsKey ] ) || ! ArrayHelper :: keyExists ( $ dtKey , $ record ) ) { return $ record ; } return $ record [ $ dtKey ] ; }

Unpack data from record
@param array $record
@return mixed


protected function createCleanupTimer() {
        if (isset($this->_timer)) {
            $this->loop->cancelTimer($this->_timer);
        }
        $this->_timer = $this->loop->addPeriodicTimer($this->timerInterval, [$this, 'cleanupTimerCallback']);
    }

protected function createCleanupTimer ( ) { if ( isset ( $ this -> _timer ) ) { $ this -> loop -> cancelTimer ( $ this -> _timer ) ; } $ this -> _timer = $ this -> loop -> addPeriodicTimer ( $ this -> timerInterval , [ $ this , 'cleanupTimerCallback' ] ) ; }


protected function hasSubMenu($menu_item_id)
    {
        // Submenu always available with a path > 1
        if (count($this->meta['path']) > 1)
            return true;

        // Decide if the first level menu has any visible submenu items
        foreach ($this->menu as $item) {
            // Find the desired menu item in the first level
            if ($item['menu_item_id'] == $menu_item_id) {
                // Loop through each submenu item
                foreach ($item['submenu'] as $sub_item) {
                    // If there is at least one active item
                    if ($sub_item['is_active'] == true) {
                        // There is a submenu to display
                        return true;
                    }
                }
            }
        }

        return false;
    }

Determine if the top level of a selected path has a submenu to display

@param $menu_item_id
@return bool


public function setAccountId($accountId)
    {
        $accountId = (int) $accountId;

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

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

        $this->accountId = $accountId;

        return $this;
    }

Set value for field "account_id"

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


public function setUserId($userId)
    {
        $userId = (int) $userId;

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

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

        $this->userId = $userId;

        return $this;
    }

Set value for field "user_id"

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


public function getAccount($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinOneCacheAccount) {
            $mapper = new AccountMapper($this->dependencyContainer->getDatabase('money'));
            $this->joinOneCacheAccount = $mapper->findByKeys(array(
                'account_id' => $this->getAccountId(),
            ));
        }

        return $this->joinOneCacheAccount;
    }

public function getAccount ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinOneCacheAccount ) { $ mapper = new AccountMapper ( $ this -> dependencyContainer -> getDatabase ( 'money' ) ) ; $ this -> joinOneCacheAccount = $ mapper -> findByKeys ( array ( 'account_id' => $ this -> getAccountId ( ) , ) ) ; } return $ this -> joinOneCacheAccount ; }

Get Account data object.

@param  bool $isForceReload
@return Account


public function getUser($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinOneCacheUser) {
            $mapper = new UserMapper($this->dependencyContainer->getDatabase('user'));
            $this->joinOneCacheUser = $mapper->findByKeys(array(
                'user_id' => $this->getUserId(),
            ));
        }

        return $this->joinOneCacheUser;
    }

public function getUser ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinOneCacheUser ) { $ mapper = new UserMapper ( $ this -> dependencyContainer -> getDatabase ( 'user' ) ) ; $ this -> joinOneCacheUser = $ mapper -> findByKeys ( array ( 'user_id' => $ this -> getUserId ( ) , ) ) ; } return $ this -> joinOneCacheUser ; }

Get User data object.

@param  bool $isForceReload
@return User


public function next(OrdercloudRequest $request, OrdercloudHttpException $exception)
    {
        return $this->successor->generateException($request, $exception);
    }

public function next ( OrdercloudRequest $ request , OrdercloudHttpException $ exception ) { return $ this -> successor -> generateException ( $ request , $ exception ) ; }

Pass the exception to be handled by the successor.

@param OrdercloudRequest       $request
@param OrdercloudHttpException $exception

@return OrdercloudRequestException

Pass the exception to be handled by the successor .


public function filter($str)
    {
        if (is_array($str)) {
            foreach ($str as $k => $v) {
                $str[$k] = strip_tags($v);
            }

            return $str;
        }

        return strip_tags($str);
    }

public function filter ( $ str ) { if ( is_array ( $ str ) ) { foreach ( $ str as $ k => $ v ) { $ str [ $ k ] = strip_tags ( $ v ) ; } return $ str ; } return strip_tags ( $ str ) ; }

Clears html tags from source string
@param  string|array $str Source string
@return string       Filtered string


function initializeConfig(&$config)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $class => $info) {
            if (!$info['config_vars']) {
                continue;
            }

            $config->_addConfigVars($class, $info['config_vars']);
        }
    }

function initializeConfig ( & $ config ) { if ( ! isset ( $ GLOBALS [ '_PEAR_INSTALLER_ROLES' ] ) ) { PEAR_Installer_Role :: registerRoles ( ) ; } foreach ( $ GLOBALS [ '_PEAR_INSTALLER_ROLES' ] as $ class => $ info ) { if ( ! $ info [ 'config_vars' ] ) { continue ; } $ config -> _addConfigVars ( $ class , $ info [ 'config_vars' ] ) ; } }

Set up any additional configuration variables that file roles require

Never call this directly, it is called by the PEAR_Config constructor
@param PEAR_Config
@access private
@static


function getValidRoles($release, $clear = false)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        static $ret = array();
        if ($clear) {
            $ret = array();
        }

        if (isset($ret[$release])) {
            return $ret[$release];
        }

        $ret[$release] = array();
        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
            if (in_array($release, $okreleases['releasetypes'])) {
                $ret[$release][] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
            }
        }

        return $ret[$release];
    }

function getValidRoles ( $ release , $ clear = false ) { if ( ! isset ( $ GLOBALS [ '_PEAR_INSTALLER_ROLES' ] ) ) { PEAR_Installer_Role :: registerRoles ( ) ; } static $ ret = array ( ) ; if ( $ clear ) { $ ret = array ( ) ; } if ( isset ( $ ret [ $ release ] ) ) { return $ ret [ $ release ] ; } $ ret [ $ release ] = array ( ) ; foreach ( $ GLOBALS [ '_PEAR_INSTALLER_ROLES' ] as $ role => $ okreleases ) { if ( in_array ( $ release , $ okreleases [ 'releasetypes' ] ) ) { $ ret [ $ release ] [ ] = strtolower ( str_replace ( 'PEAR_Installer_Role_' , '' , $ role ) ) ; } } return $ ret [ $ release ] ; }

Get a list of file roles that are valid for the particular release type.

For instance, src files serve no purpose in regular php releases.
@param string
@param bool clear cache
@return array
@static

Get a list of file roles that are valid for the particular release type .


function getBaseinstallRoles($clear = false)
    {
        if (!isset($GLOBALS['_PEAR_INSTALLER_ROLES'])) {
            PEAR_Installer_Role::registerRoles();
        }

        static $ret;
        if ($clear) {
            unset($ret);
        }

        if (isset($ret)) {
            return $ret;
        }

        $ret = array();
        foreach ($GLOBALS['_PEAR_INSTALLER_ROLES'] as $role => $okreleases) {
            if ($okreleases['honorsbaseinstall']) {
                $ret[] = strtolower(str_replace('PEAR_Installer_Role_', '', $role));
            }
        }

        return $ret;
    }

function getBaseinstallRoles ( $ clear = false ) { if ( ! isset ( $ GLOBALS [ '_PEAR_INSTALLER_ROLES' ] ) ) { PEAR_Installer_Role :: registerRoles ( ) ; } static $ ret ; if ( $ clear ) { unset ( $ ret ) ; } if ( isset ( $ ret ) ) { return $ ret ; } $ ret = array ( ) ; foreach ( $ GLOBALS [ '_PEAR_INSTALLER_ROLES' ] as $ role => $ okreleases ) { if ( $ okreleases [ 'honorsbaseinstall' ] ) { $ ret [ ] = strtolower ( str_replace ( 'PEAR_Installer_Role_' , '' , $ role ) ) ; } } return $ ret ; }

Return an array of roles that are affected by the baseinstalldir attribute

Most roles ignore this attribute, and instead install directly into:
PackageName/filepath
so a tests file tests/file.phpt is installed into PackageName/tests/filepath.php
@param bool clear cache
@return array
@static


public function shorten(): string
    {
        // Shorten only what is longer than the length
        if (strlen($this->string) < $this->length) {
            return $this->string;
        }

        // Shorten string by length
        $this->result = substr($this->string, 0, $this->length);

        // Shorten further until last occurence of a ' '
        $string = substr($this->result, 0, strrpos($this->result, $this->endstring));

        if (!empty($this->wrap_url)) {
            $addition = 'wrap_url . '">' . $this->addition . '';
        }

        // Add addition
        $this->result .= $addition;

        // Done.
        return $this->result;
    }

Shortens a string to the given length and appends the additional string that can be wrapped by a link when a
wrap url is set.

@return string

Shortens a string to the given length and appends the additional string that can be wrapped by a link when a wrap url is set .


public function setBlocksize($blocksize)
    {
        if (($blocksize < 0) || ($blocksize > 9)) {

            throw new Zend_Filter_Exception('Blocksize must be between 0 and 9');
        }

        $this->_options['blocksize'] = (int) $blocksize;
        return $this;
    }

public
function
setBlocksize
(
$
blocksize
)
{
if
(
(
$
blocksize
<
0
)
||
(
$
blocksize
>
9
)
)
{
throw
new
Zend_Filter_Exception
(
'Blocksize must be between 0 and 9'
)
;
}
$
this
->
_options
[
'blocksize'
]
=
(
int
)
$
blocksize
;
return
$
this
;
}

Sets a new blocksize

@param integer $level
@return Zend_Filter_Compress_Bz2


public function get($key, $defaultValue = null) {
        return ArrayHelper::getValue($this->data, $key, $defaultValue);
    }

public function get ( $ key , $ defaultValue = null ) { return ArrayHelper :: getValue ( $ this -> data , $ key , $ defaultValue ) ; }

Get config data by its key
@param string $key
@param mixed  $defaultValue
@return mixed


protected function generateNames() {
        $env = getenv('APP_ENV');
        $env = strtolower((!empty($env) ? $env : \Reaction::APP_ENV_PROD));
        $suffixes = ['', $env, 'local'];
        $templates = ['main', $this->appType];
        $configFiles = [];
        foreach ($templates as $tpl) {
            foreach ($suffixes as $sfx) {
                $tplSuffix = $sfx ? '.' . $sfx : '';
                foreach ($this->extensions as $ext) {
                    $configFiles[] = $tpl . $tplSuffix . '.' . $ext;
                }
            }
        }
        return $configFiles;
    }

protected function generateNames ( ) { $ env = getenv ( 'APP_ENV' ) ; $ env = strtolower ( ( ! empty ( $ env ) ? $ env : \ Reaction :: APP_ENV_PROD ) ) ; $ suffixes = [ '' , $ env , 'local' ] ; $ templates = [ 'main' , $ this -> appType ] ; $ configFiles = [ ] ; foreach ( $ templates as $ tpl ) { foreach ( $ suffixes as $ sfx ) { $ tplSuffix = $ sfx ? '.' . $ sfx : '' ; foreach ( $ this -> extensions as $ ext ) { $ configFiles [ ] = $ tpl . $ tplSuffix . '.' . $ ext ; } } } return $ configFiles ; }

Generate config files names
@return array


public function merge($data = [], $key = null) {
        if (!isset($key)) {
            $this->data = ArrayHelper::merge($this->data, $data);
        } else {
            if (!isset($this->data[$key])) {
                $this->data[$key] = $data;
            } else {
                if (is_array($this->data[$key])) {
                    $this->data[$key] = ArrayHelper::merge($this->data[$key], $data);
                } else {
                    $this->data[$key] = $data;
                }
            }
        }
    }

public function merge ( $ data = [ ] , $ key = null ) { if ( ! isset ( $ key ) ) { $ this -> data = ArrayHelper :: merge ( $ this -> data , $ data ) ; } else { if ( ! isset ( $ this -> data [ $ key ] ) ) { $ this -> data [ $ key ] = $ data ; } else { if ( is_array ( $ this -> data [ $ key ] ) ) { $ this -> data [ $ key ] = ArrayHelper :: merge ( $ this -> data [ $ key ] , $ data ) ; } else { $ this -> data [ $ key ] = $ data ; } } } }

Merge config data with given one
@param array       $data
@param string|null $key


public function readData() {
        if (empty($this->names)) {
            $this->names = $this->generateNames();
        }
        //Add default configs
        $defaultPath = dirname(__DIR__) . DIRECTORY_SEPARATOR . $this->configPathDefault;
        $paths = [$defaultPath, $this->path];
        $confData = [];
        foreach ($paths as $basePath) {
            foreach ($this->names as $_name_) {
                $_fileName_ = $this->normalizeConfigPath($_name_, $basePath);
                if (($fileConfig = $this->readFileData($_fileName_)) !== null) {
                    $confData[] = $fileConfig;
                }
            }
        }
        if (empty($confData)) {
            return [];
        } elseif (count($confData) === 1) {
            return reset($confData);
        }
        return static::mergeConfigs(...$confData);
    }

public
function
readData
(
)
{
if
(
empty
(
$
this
->
names
)
)
{
$
this
->
names
=
$
this
->
generateNames
(
)
;
}
//Add default configs
$
defaultPath
=
dirname
(
__DIR__
)
.
DIRECTORY_SEPARATOR
.
$
this
->
configPathDefault
;
$
paths
=
[
$
defaultPath
,
$
this
->
path
]
;
$
confData
=
[
]
;
foreach
(
$
paths
as
$
basePath
)
{
foreach
(
$
this
->
names
as
$
_name_
)
{
$
_fileName_
=
$
this
->
normalizeConfigPath
(
$
_name_
,
$
basePath
)
;
if
(
(
$
fileConfig
=
$
this
->
readFileData
(
$
_fileName_
)
)
!==
)
{
$
confData
[
]
=
$
fileConfig
;
}
}
}
if
(
empty
(
$
confData
)
)
{
return
[
]
;
}
elseif
(
count
(
$
confData
)
===
1
)
{
return
reset
(
$
confData
)
;
}
return
static
::
mergeConfigs
(
...
$
confData
)
;
}


protected function readFileData($_fileName_ = null) {
        if (!file_exists($_fileName_)) {
            return null;
        }
        /** @noinspection PhpIncludeInspection */
        $_conf_data_ = include $_fileName_;
        return is_array($_conf_data_) ? $_conf_data_ : [];
    }

Read particular config file
@param string $_fileName_
@return array|null


protected function normalizeConfigPath($filePath, $basePath = null) {
        if (null === $basePath) {
            $basePath = $this->path;
        }
        $fullPath = strpos($filePath, '/') === 0 ? $filePath : $basePath . DIRECTORY_SEPARATOR . $filePath;
        return $fullPath;
    }

protected function normalizeConfigPath ( $ filePath , $ basePath = null ) { if ( null === $ basePath ) { $ basePath = $ this -> path ; } $ fullPath = strpos ( $ filePath , '/' ) === 0 ? $ filePath : $ basePath . DIRECTORY_SEPARATOR . $ filePath ; return $ fullPath ; }

Normalize config file path
@param string $filePath
@param string|null $basePath
@return string


protected function apply(DomainEventMessageInterface $domainEventMessage): EventSourcedAggregate
    {
        $this->getMethod($domainEventMessage, 'on')($domainEventMessage->getPayload());

        return $this;
    }

protected function apply ( DomainEventMessageInterface $ domainEventMessage ) : EventSourcedAggregate { $ this -> getMethod ( $ domainEventMessage , 'on' ) ( $ domainEventMessage -> getPayload ( ) ) ; return $ this ; }

Apply domain event message to aggregate.

@param DomainEventMessageInterface $domainEventMessage
@return EventSourcedAggregate
@throws MethodNotFound

Apply domain event message to aggregate .


protected function record(PayloadInterface $payload, array $metaData = null): void
    {
        $domainEventMessage = new DomainEventMessage(
            $payload,
            new PayloadType($payload),
            new DateTime(),
            $this->getIdentifier(),
            $this->getNextVersion(),
            array_replace_recursive(
                $this
                    ->getCommandMessage()
                    ->getMetaData(),
                $metaData
            )
        );

        $this
            ->apply($domainEventMessage)
            ->addDomainEventMessage($domainEventMessage);
    }

protected function record ( PayloadInterface $ payload , array $ metaData = null ) : void { $ domainEventMessage = new DomainEventMessage ( $ payload , new PayloadType ( $ payload ) , new DateTime ( ) , $ this -> getIdentifier ( ) , $ this -> getNextVersion ( ) , array_replace_recursive ( $ this -> getCommandMessage ( ) -> getMetaData ( ) , $ metaData ) ) ; $ this -> apply ( $ domainEventMessage ) -> addDomainEventMessage ( $ domainEventMessage ) ; }

Record payload and meta data into a new domain event message.

Meta data from the command message will be recursively replaced with given meta data and added to the domain
event message.

@param PayloadInterface $payload
@param array|null       $metaData
@throws MethodNotFound

Record payload and meta data into a new domain event message .


public function setRelated($model = null, $data = null, $id = null)
    {
        if (!empty($model) && !empty($data)) {
            if (!empty($id)) {
                if (!isset($this->data[$model]))
                    $this->data[$model] = array();
                if (!is_array($this->data[$model]))
                    $this->data[$model] = array_filter( array( $this->data[$model] ) );
                $this->data[$model][$id] = $data;
            } else
                $this->data[$model] = $data;
        }
    }

public function setRelated ( $ model = null , $ data = null , $ id = null ) { if ( ! empty ( $ model ) && ! empty ( $ data ) ) { if ( ! empty ( $ id ) ) { if ( ! isset ( $ this -> data [ $ model ] ) ) $ this -> data [ $ model ] = array ( ) ; if ( ! is_array ( $ this -> data [ $ model ] ) ) $ this -> data [ $ model ] = array_filter ( array ( $ this -> data [ $ model ] ) ) ; $ this -> data [ $ model ] [ $ id ] = $ data ; } else $ this -> data [ $ model ] = $ data ; } }

Sets one of the object related object

@param string $model The name of the related model
@param array $data An array of the contents of the related object
@param int $id The related object primary ID in case of multi-relations


public function attached($presenter) {
		parent::attached($presenter);

		if($this->ajaxEnabled && $this->autoAjax && $presenter instanceof Nette\Application\UI\Presenter && $presenter->isAjax()) {
			$this->redrawControl();
		}
	}

public function attached ( $ presenter ) { parent :: attached ( $ presenter ) ; if ( $ this -> ajaxEnabled && $ this -> autoAjax && $ presenter instanceof Nette \ Application \ UI \ Presenter && $ presenter -> isAjax ( ) ) { $ this -> redrawControl ( ) ; } }

Automatic snippet invalidation
Do not call manually


protected function redrawNothing() {
		foreach($this->getPresenter()->getComponents(TRUE, 'Nette\Application\UI\IRenderable') as $component) {
			$component->redrawControl(NULL, FALSE);
		}
	}

protected function redrawNothing ( ) { foreach ( $ this -> getPresenter ( ) -> getComponents ( TRUE , 'Nette\Application\UI\IRenderable' ) as $ component ) { $ component -> redrawControl ( NULL , FALSE ) ; } }

Useful for cases where you don't want automatic AJAX to kick in.

Useful for cases where you don t want automatic AJAX to kick in .


final public function go($destination, $args = [], $snippets = [], $presenterForward = FALSE) {
		if($this->ajaxEnabled && $this->presenter->isAjax()) {
			foreach($snippets as $snippet) {
				$this->redrawControl($snippet);
			}

			if($presenterForward) {
				$this->presenterForward($destination, $args);
			} else {
				$this->forward($destination, $args);
			}
		} else {
			$this->redirect($destination, $args);
		}
	}

final public function go ( $ destination , $ args = [ ] , $ snippets = [ ] , $ presenterForward = FALSE ) { if ( $ this -> ajaxEnabled && $ this -> presenter -> isAjax ( ) ) { foreach ( $ snippets as $ snippet ) { $ this -> redrawControl ( $ snippet ) ; } if ( $ presenterForward ) { $ this -> presenterForward ( $ destination , $ args ) ; } else { $ this -> forward ( $ destination , $ args ) ; } } else { $ this -> redirect ( $ destination , $ args ) ; } }

If AJAX, then forward, else redirect.

@param string $destination
@param array $args
@param array $snippets Not needed if we only have one unnamed snippet
@param bool $presenterForward Prefer $presenter->forward() over $this->forward()


protected function initPlugins($plugins = '') {
		if (is_dir(dirname(__FILE__).'/TwigPlugins')) {
			$this->loadPluginsFromDirectory(dirname(__FILE__).'/TwigPlugins');
		}

		if (isset($plugins)) {
			if (is_array($plugins)) {
				foreach ($plugins as $path) {
					$this->loadPluginsFromDirectory($path);
				}
			} elseif ($plugins != '') {
				$this->loadPluginsFromDirectory($plugins);
			}
		}
	}

protected function initPlugins ( $ plugins = '' ) { if ( is_dir ( dirname ( __FILE__ ) . '/TwigPlugins' ) ) { $ this -> loadPluginsFromDirectory ( dirname ( __FILE__ ) . '/TwigPlugins' ) ; } if ( isset ( $ plugins ) ) { if ( is_array ( $ plugins ) ) { foreach ( $ plugins as $ path ) { $ this -> loadPluginsFromDirectory ( $ path ) ; } } elseif ( $ plugins != '' ) { $ this -> loadPluginsFromDirectory ( $ plugins ) ; } } }

Init plugins and extra plugins on the engine

@param string|array Path(s) to plugins sirectory


public function setVars($list) {
		foreach ($list as $k=>$v) {
			$this->setVar($k,$v);
		}
	}

public function setVars ( $ list ) { foreach ( $ list as $ k => $ v ) { $ this -> setVar ( $ k , $ v ) ; } }

Set many variables

@paral array $list List of key/value pairs to set as variables


protected function fetchFromString() {
		// loader is created each time as value of index can be changed
		// maybe there is way to do this without creating new loader each time
		$loader = new \Twig_Loader_Array(array('index' => $this->template_data));
		$this->setLoader($loader);

		return $this->render('index', $this->template_vars);
	}

Fetch prepared string template and return complete html document

@return string HTML document with all data included


protected function loadPluginsFromDirectory($dirpath) {
		if (!is_dir($dirpath)) {
			return false;
		}

		$contents = @scandir($dirpath);

		if (is_array($contents)) {
			foreach ($contents as $file) {
				if (substr($file,-4) == '.php') {
					$class = '\\' . substr($file,0,-4);

					if($class != '') {
						// is this secure enough?
						// we don't use autoloader as we don't know how taht plugins are stored
						require_once($dirpath.'/'.$file);

						try {
							$twig_object = new $class();

							if ($twig_object instanceof \Twig_Extension) {
								$this->addExtension($twig_object);
							}
						} catch (\Extension $e) {
						}
					}
				}
			}
		}
	}


public static function fromAssociativeArray(array $data): BusinessHours
    {
        if (!isset($data['days'], $data['timezone']) || !\is_array($data['days'])) {
            throw new \InvalidArgumentException('Array is not valid.');
        }

        $days = [];
        foreach ($data['days'] as $day) {
            $days[] = DayBuilder::fromAssociativeArray($day);
        }

        return new BusinessHours($days, new \DateTimeZone($data['timezone']));
    }

public
static
function
fromAssociativeArray
(
array
$
data
)
:
BusinessHours
{
if
(
!
isset
(
$
data
[
'days'
]
,
$
data
[
'timezone'
]
)
||
!
\
is_array
(
$
data
[
'days'
]
)
)
{
throw
new
\
InvalidArgumentException
(
'Array is not valid.'
)
;
}
$
days
=
[
]
;
foreach
(
$
data
[
'days'
]
as
$
day
)
{
$
days
[
]
=
DayBuilder
::
fromAssociativeArray
(
$
day
)
;
}
return
new
BusinessHours
(
$
days
,
new
\
DateTimeZone
(
$
data
[
'timezone'
]
)
)
;
}

Build a BusinessHours from an array.

@param array $data The business hours data.
@return BusinessHours


public static function shiftToTimezone(BusinessHours $businessHours, \DateTimeZone $newTimezone): BusinessHours
    {
        $now = new \DateTime('now');
        $oldTimezone = $businessHours->getTimezone();
        $offset = $newTimezone->getOffset($now) - $oldTimezone->getOffset($now);

        if ($offset === 0) {
            return clone $businessHours;
        }

        $tmpDays = \array_fill_keys(Day::getDaysOfWeek(), []);
        foreach ($businessHours->getDays() as $day) {
            foreach ($day->getOpeningHoursIntervals() as $interval) {
                $start = $interval->getStart()->toSeconds() + $offset;
                $end = $interval->getEnd()->toSeconds() + $offset;

                // Current day.
                if ($start < 86400 && $end > 0) {
                    $startForCurrentDay = \max($start, 0);
                    $endForCurrentDay = \min($end, 86400);

                    $dayOfWeek = $day->getDayOfWeek();
                    $interval = new TimeInterval(
                        TimeBuilder::fromSeconds($startForCurrentDay),
                        TimeBuilder::fromSeconds($endForCurrentDay)
                    );
                    $tmpDays[$dayOfWeek][] = $interval;
                }

                // Previous day.
                if ($start < 0) {
                    $startForPreviousDay = 86400 + $start;
                    $endForPreviousDay = \min(86400, 86400 + $end);

                    $dayOfWeek = self::getPreviousDayOfWeek($day->getDayOfWeek());
                    $interval = new TimeInterval(
                        TimeBuilder::fromSeconds($startForPreviousDay),
                        TimeBuilder::fromSeconds($endForPreviousDay)
                    );
                    $tmpDays[$dayOfWeek][] = $interval;
                }

                // Next day.
                if ($end > 86400) {
                    $startForNextDay = \max(0, $start - 86400);
                    $endForNextDay = $end - 86400;

                    $dayOfWeek = self::getNextDayOfWeek($day->getDayOfWeek());
                    $interval = new TimeInterval(
                        TimeBuilder::fromSeconds($startForNextDay),
                        TimeBuilder::fromSeconds($endForNextDay)
                    );
                    $tmpDays[$dayOfWeek][] = $interval;
                }
            }
        }

        $tmpDays = \array_filter($tmpDays);
        $days = self::flattenDaysIntervals($tmpDays);

        return new BusinessHours($days, $newTimezone);
    }

public
static
function
shiftToTimezone
(
BusinessHours
$
businessHours
,
\
DateTimeZone
$
newTimezone
)
:
BusinessHours
{
$
now
=
new
\
DateTime
(
'now'
)
;
$
oldTimezone
=
$
businessHours
->
getTimezone
(
)
;
$
offset
=
$
newTimezone
->
getOffset
(
$
now
)
$
oldTimezone
->
getOffset
(
$
now
)
;
if
(
$
offset
===
0
)
{
return
clone
$
businessHours
;
}
$
tmpDays
=
\
array_fill_keys
(
Day
::
getDaysOfWeek
(
)
,
[
]
)
;
foreach
(
$
businessHours
->
getDays
(
)
as
$
day
)
{
foreach
(
$
day
->
getOpeningHoursIntervals
(
)
as
$
interval
)
{
$
start
=
$
interval
->
getStart
(
)
->
toSeconds
(
)
+
$
offset
;
$
end
=
$
interval
->
getEnd
(
)
->
toSeconds
(
)
+
$
offset
;
// Current day.
if
(
$
start
<
86400
&&
$
end
>
0
)
{
$
startForCurrentDay
=
\
max
(
$
start
,
0
)
;
$
endForCurrentDay
=
\
min
(
$
end
,
86400
)
;
$
dayOfWeek
=
$
day
->
getDayOfWeek
(
)
;
$
interval
=
new
TimeInterval
(
TimeBuilder
::
fromSeconds
(
$
startForCurrentDay
)
,
TimeBuilder
::
fromSeconds
(
$
endForCurrentDay
)
)
;
$
tmpDays
[
$
dayOfWeek
]
[
]
=
$
interval
;
}
// Previous day.
if
(
$
start
<
0
)
{
$
startForPreviousDay
=
86400
+
$
start
;
$
endForPreviousDay
=
\
min
(
86400
,
86400
+
$
end
)
;
$
dayOfWeek
=
self
::
getPreviousDayOfWeek
(
$
day
->
getDayOfWeek
(
)
)
;
$
interval
=
new
TimeInterval
(
TimeBuilder
::
fromSeconds
(
$
startForPreviousDay
)
,
TimeBuilder
::
fromSeconds
(
$
endForPreviousDay
)
)
;
$
tmpDays
[
$
dayOfWeek
]
[
]
=
$
interval
;
}
// Next day.
if
(
$
end
>
86400
)
{
$
startForNextDay
=
\
max
(
0
,
$
start
86400
)
;
$
endForNextDay
=
$
end
86400
;
$
dayOfWeek
=
self
::
getNextDayOfWeek
(
$
day
->
getDayOfWeek
(
)
)
;
$
interval
=
new
TimeInterval
(
TimeBuilder
::
fromSeconds
(
$
startForNextDay
)
,
TimeBuilder
::
fromSeconds
(
$
endForNextDay
)
)
;
$
tmpDays
[
$
dayOfWeek
]
[
]
=
$
interval
;
}
}
}
$
tmpDays
=
\
array_filter
(
$
tmpDays
)
;
$
days
=
self
::
flattenDaysIntervals
(
$
tmpDays
)
;
return
new
BusinessHours
(
$
days
,
$
newTimezone
)
;
}

Create a new BusinessHours with a different timezone from an existing BusinessHours.

@param BusinessHours $businessHours The original business hours.
@param \DateTimeZone $newTimezone The new timezone.
@return BusinessHours

Create a new BusinessHours with a different timezone from an existing BusinessHours .


private static function flattenDaysIntervals(array $days): array
    {
        \ksort($days);

        $flattenDays = [];
        foreach ($days as $dayOfWeek => $intervals) {
            $flattenDays[] = DayBuilder::fromArray($dayOfWeek, $intervals);
        }

        return $flattenDays;
    }

private static function flattenDaysIntervals ( array $ days ) : array { \ ksort ( $ days ) ; $ flattenDays = [ ] ; foreach ( $ days as $ dayOfWeek => $ intervals ) { $ flattenDays [ ] = DayBuilder :: fromArray ( $ dayOfWeek , $ intervals ) ; } return $ flattenDays ; }

Flatten days intervals.

@param array $days The days to flatten.
@return DayInterface[]


function _validateWarning($code, $params = array())
    {
        $this->_stack->push($code, 'warning', $params, false, false, debug_backtrace());
    }

function _validateWarning ( $ code , $ params = array ( ) ) { $ this -> _stack -> push ( $ code , 'warning' , $ params , false , false , debug_backtrace ( ) ) ; }

Validation warning.  Does not mark the object contents invalid.
@param error code
@param array error information
@access private

Validation warning . Does not mark the object contents invalid .


function getFileContents($file)
    {
        if ($this->_archiveFile == $this->_packageFile) { // unpacked
            $dir = dirname($this->_packageFile);
            $file = $dir . DIRECTORY_SEPARATOR . $file;
            $file = str_replace(array('/', '\\'),
                array(DIRECTORY_SEPARATOR, DIRECTORY_SEPARATOR), $file);
            if (file_exists($file) && is_readable($file)) {
                return implode('', file($file));
            }
        } else { // tgz
            if (!class_exists('Archive_Tar')) {
                require_once 'Archive/Tar.php';
            }
            $tar = &new Archive_Tar($this->_archiveFile);
            $tar->pushErrorHandling(PEAR_ERROR_RETURN);
            if ($file != 'package.xml' && $file != 'package2.xml') {
                $file = $this->getPackage() . '-' . $this->getVersion() . '/' . $file;
            }
            $file = $tar->extractInString($file);
            $tar->popErrorHandling();
            if (PEAR::isError($file)) {
                return PEAR::raiseError("Cannot locate file '$file' in archive");
            }
            return $file;
        }
    }

function
getFileContents
(
$
file
)
{
if
(
$
this
->
_archiveFile
==
$
this
->
_packageFile
)
{
// unpacked
$
dir
=
dirname
(
$
this
->
_packageFile
)
;
$
file
=
$
dir
.
DIRECTORY_SEPARATOR
.
$
file
;
$
file
=
str_replace
(
array
(
'/'
,
'\\'
)
,
array
(
DIRECTORY_SEPARATOR
,
DIRECTORY_SEPARATOR
)
,
$
file
)
;
if
(
file_exists
(
$
file
)
&&
is_readable
(
$
file
)
)
{
return
implode
(
''
,
file
(
$
file
)
)
;
}
}
else
{
// tgz
if
(
!
class_exists
(
'Archive_Tar'
)
)
{
require_once
'Archive/Tar.php'
;
}
$
tar
=
&
new
Archive_Tar
(
$
this
->
_archiveFile
)
;
$
tar
->
pushErrorHandling
(
PEAR_ERROR_RETURN
)
;
if
(
$
file
!=
'package.xml'
&&
$
file
!=
'package2.xml'
)
{
$
file
=
$
this
->
getPackage
(
)
.
'-'
.
$
this
->
getVersion
(
)
.
'/'
.
$
file
;
}
$
file
=
$
tar
->
extractInString
(
$
file
)
;
$
tar
->
popErrorHandling
(
)
;
if
(
PEAR
::
isError
(
$
file
)
)
{
return
PEAR
::
raiseError
(
"Cannot locate file '$file' in archive"
)
;
}
return
$
file
;
}
}

Get the contents of a file listed within the package.xml
@param string
@return string

Get the contents of a file listed within the package . xml


protected function parseImports(array $imports, $configPath)
    {
        foreach ($imports as $import) {
            $config = $this->parse(dirname($configPath) . '/' .$import['resource']);
            if ($config !== null) {
                $this->_configSettings = $this->mergeConfigurations(
                    $this->_configSettings, $config
                );
            }
        }
    }

protected function parseImports ( array $ imports , $ configPath ) { foreach ( $ imports as $ import ) { $ config = $ this -> parse ( dirname ( $ configPath ) . '/' . $ import [ 'resource' ] ) ; if ( $ config !== null ) { $ this -> _configSettings = $ this -> mergeConfigurations ( $ this -> _configSettings , $ config ) ; } } }

Parses imports statement on YML file.

@param array  $imports    Imported YML files to be parsed
@param string $configPath Path to master YML file

@return void


protected function parse($input, $exceptionOnInvalidType = false,
        $objectSupport = false
    ) {
        // if input is a file, process it
        $file = '';
        if (strpos($input, "\n") === false && is_file($input)) {
            if (false === is_readable($input)) {
                throw new ParseException(
                    sprintf(
                        'Unable to parse "%s" as the file is not readable.', $input
                    )
                );
            }

            $file = $input;
            $input = file_get_contents($file);
        }

        $input = str_replace(
            array_keys($this->_vars), array_values($this->_vars), $input
        );

        $yaml = new Parser();

        try {
            return $yaml->parse($input, $exceptionOnInvalidType, $objectSupport);
        } catch (ParseException $e) {
            if ($file) {
                $e->setParsedFile($file);
            }

            throw $e;
        }
    }

Parses YAML into a PHP array.

@param string $input                  Path to file or string containing YAML
@param bool   $exceptionOnInvalidType True if an exception must be thrown on
invalid types false otherwise
@param bool   $objectSupport          True if object support is enabled,
false otherwise

@return array The YAML converted to a PHP array

@throws ParseException If the YAML is not valid


protected function setYamlPatameters()
    {
        foreach ($this->_configSettings['parameters'] as $key => $value) {
            $this->_vars['%'.$key.'%'] = $value;
        }
    }

protected function setYamlPatameters ( ) { foreach ( $ this -> _configSettings [ 'parameters' ] as $ key => $ value ) { $ this -> _vars [ '%' . $ key . '%' ] = $ value ; } }