private function checkArrayRecursion(array $var)
    {
        static $dump;

        if (!isset($dump)) {
            $dump = [];
        }

        if (in_array($var, $dump, true)) {
            return true;
        }

        $dump[] = $var;

        $return = false;

        foreach ($var as $item) {
            if (is_object($item) && $this->checkObjectRecursion($item)) {
                $return = true;
                break;
            }
            if (is_array($item) && $this->checkArrayRecursion($item)) {
                $return = true;
                break;
            }
        }

        array_pop($dump);

        return $return;
    }

private function checkArrayRecursion ( array $ var ) { static $ dump ; if ( ! isset ( $ dump ) ) { $ dump = [ ] ; } if ( in_array ( $ var , $ dump , true ) ) { return true ; } $ dump [ ] = $ var ; $ return = false ; foreach ( $ var as $ item ) { if ( is_object ( $ item ) && $ this -> checkObjectRecursion ( $ item ) ) { $ return = true ; break ; } if ( is_array ( $ item ) && $ this -> checkArrayRecursion ( $ item ) ) { $ return = true ; break ; } } array_pop ( $ dump ) ; return $ return ; }

Check if an array contains any recursion

@param array $var

@return bool


private function checkObjectRecursion($obj)
    {
        static $dump;

        if (!isset($dump)) {
            $dump = [];
        }

        if (in_array($obj, $dump, true)) {
            return true;
        }

        $dump[] = $obj;

        $return = false;

        $props = Reflexion::getReflectionProperties($obj);
        foreach ($props as $prop) {
            $val = Reflexion::get($obj, $prop->getName());
            if (is_array($val) && $this->checkArrayRecursion($val)) {
                $return = true;
                break;
            } elseif (is_object($val) && $this->checkObjectRecursion($val)) {
                $return = true;
                break;
            }
        }
        foreach ($obj as $val) {
            if (is_array($val) && $this->checkArrayRecursion($val)) {
                $return = true;
                break;
            } elseif (is_object($val) && $this->checkObjectRecursion($val)) {
                $return = true;
                break;
            }
        }

        array_pop($dump);

        return $return;
    }

private function checkObjectRecursion ( $ obj ) { static $ dump ; if ( ! isset ( $ dump ) ) { $ dump = [ ] ; } if ( in_array ( $ obj , $ dump , true ) ) { return true ; } $ dump [ ] = $ obj ; $ return = false ; $ props = Reflexion :: getReflectionProperties ( $ obj ) ; foreach ( $ props as $ prop ) { $ val = Reflexion :: get ( $ obj , $ prop -> getName ( ) ) ; if ( is_array ( $ val ) && $ this -> checkArrayRecursion ( $ val ) ) { $ return = true ; break ; } elseif ( is_object ( $ val ) && $ this -> checkObjectRecursion ( $ val ) ) { $ return = true ; break ; } } foreach ( $ obj as $ val ) { if ( is_array ( $ val ) && $ this -> checkArrayRecursion ( $ val ) ) { $ return = true ; break ; } elseif ( is_object ( $ val ) && $ this -> checkObjectRecursion ( $ val ) ) { $ return = true ; break ; } } array_pop ( $ dump ) ; return $ return ; }

Check if an object contains any recursion

@param $obj

@return bool


public static function dump(...$vars)
    {
        // We force the start of the session so that it is initialized before the first exit.
        switch (session_status()) {
            case PHP_SESSION_DISABLED:
            case PHP_SESSION_ACTIVE:
                break;
            default:
                $di = Di::getDefault();
                if ($di->has(Services::SESSION)) {
                    $di->get(Services::SESSION);
                } else {
                    session_start();
                }
        }

        foreach ($vars as $var) {
            $id = 'nuc-dump-' . self::uid();

            $dump = (new self)->varDump($var);

            echo self::outputBasic() . "
$dump
";
        }
    }

Dumps information about a variable

@param mixed ...$vars


public function mainAction()
    {
        $this->displayHeader();

        $routes = $this->router->getRoutes();

        $delimiter = Route::getDelimiter();
        foreach ($routes as $route) {
            /** @var Route $route */
            // Default route
            $pattern = $route->getPattern();
            if ($pattern === "#^(?:$delimiter)?([a-zA-Z0-9\\_\\-]+)[$delimiter]{0,1}$#" ||
                $pattern === "#^(?:$delimiter)?([a-zA-Z0-9\\_\\-]+)$delimiter([a-zA-Z0-9\\.\\_]+)($delimiter.*)*$#"
            ) {
                continue;
            }

            $this->describeRoute($route);
        }

        $datas = [];

        foreach ($this->describes as $describe) {
            if (isset($describe['__exception'])) {
                $datas[$describe['cmd']] = Decorate::error(explode(PHP_EOL, $describe['__exception'], 2)[0]);
            } else {
                $datas[$describe['cmd']] = explode(PHP_EOL, $describe['description'], 2)[0];
            }
        }

        $this->notice('Available Commands :');

        (new Group($this->output, $datas, Group::SORT_ASC))->display();
    }

List all commands available.

@description List all commands available.


protected function describeRoute(Route $route)
    {
        $paths = $route->getPaths();

        $class = $paths['task'];

        $action = Arr::fetch($paths, 'action', 'main') . $this->dispatcher->getActionSuffix();

        $this->scanned[$class . '::' . $action] = true;

        $compiled = Helper::describeRoutePattern($route, true);

        $this->describe($compiled, $class, $action);
    }

protected function describeRoute ( Route $ route ) { $ paths = $ route -> getPaths ( ) ; $ class = $ paths [ 'task' ] ; $ action = Arr :: fetch ( $ paths , 'action' , 'main' ) . $ this -> dispatcher -> getActionSuffix ( ) ; $ this -> scanned [ $ class . '::' . $ action ] = true ; $ compiled = Helper :: describeRoutePattern ( $ route , true ) ; $ this -> describe ( $ compiled , $ class , $ action ) ; }

Describe a \Phalcon\Cli\Router\Route

@param \Phalcon\Cli\Router\Route $route

Describe a \ Phalcon \ Cli \ Router \ Route


public function addDirectories($directories)
    {
        $this->directories = array_merge($this->directories, (array)$directories);

        $this->directories = array_unique($this->directories);
    }

public function addDirectories ( $ directories ) { $ this -> directories = array_merge ( $ this -> directories , ( array ) $ directories ) ; $ this -> directories = array_unique ( $ this -> directories ) ; }

Add directories to the class loader.

@param  string|array $directories

@return void


protected function normalizeClass($class)
    {
        // Strip first slash
        $class = ltrim($class, '\\');

        // Work backwards through the namespace names of the fully-qualified
        // class name to find a mapped file name
        $pos = strrpos($class, '\\');

        // Retain the trailing namespace separator in the prefix
        $directory = substr($class, 0, $pos + 1);

        // The rest is the relative class name
        $relativeClass = substr($class, $pos + 1);
        $directory = str_replace(['\\', '.'], DIRECTORY_SEPARATOR, $directory);

        $directory = trim($directory, DIRECTORY_SEPARATOR);

        $lowerClass = strtolower($directory).DIRECTORY_SEPARATOR.$relativeClass;
        $upperClass = $directory.DIRECTORY_SEPARATOR.$relativeClass;

        return [$lowerClass, $upperClass];
    }

Get the normal file name for a class.

@param  string $class

@return array


protected function loadMappedClass($class)
    {
        list($lowerClass, $upperClass) = $this->normalizeClass($class);

        // Look through registered directories
        foreach ($this->directories as $directory) {

            // If the mapped class exists, require it
            if ($this->isRealFilePath($path = $directory.DIRECTORY_SEPARATOR.$lowerClass.'.php')) {
                $this->requireClass($class, $path);

                return $path;
            }

            if ($this->isRealFilePath($path = $directory.DIRECTORY_SEPARATOR.$upperClass.'.php')) {
                $this->requireClass($class, $path);

                return TRUE;
            }
        }

        // never found it
        return FALSE;
    }

Load the mapped class for a directory prefix and relative class.

@param string $class The class name.

@return mixed bool false if no mapped file can be loaded, or the
name of the mapped file that was loaded.

Load the mapped class for a directory prefix and relative class .


protected function requireClass($class, $path)
    {
        require_once $this->basePath.DIRECTORY_SEPARATOR.$path;

        $this->manifest[$class] = $path;

        $this->manifestIsDirty = TRUE;
    }

protected function requireClass ( $ class , $ path ) { require_once $ this -> basePath . DIRECTORY_SEPARATOR . $ path ; $ this -> manifest [ $ class ] = $ path ; $ this -> manifestIsDirty = TRUE ; }

If a file exists, require it from the file system.

@param $class
@param string $path The file to require.

@return void True if the file exists, false if not.

If a file exists require it from the file system .


protected function loadManifest()
    {
        if (!is_null($this->manifest)) {
            return;
        }

        if (file_exists($this->manifestPath)) {
            try {
                $this->manifest = $this->files->getRequire($this->manifestPath);

                if (!is_array($this->manifest)) {
                    $this->manifest = [];
                }
            } catch (Exception $ex) {
                $this->manifest = [];
            }
        }
        else {
            $this->manifest = [];
        }
    }

protected function loadManifest ( ) { if ( ! is_null ( $ this -> manifest ) ) { return ; } if ( file_exists ( $ this -> manifestPath ) ) { try { $ this -> manifest = $ this -> files -> getRequire ( $ this -> manifestPath ) ; if ( ! is_array ( $ this -> manifest ) ) { $ this -> manifest = [ ] ; } } catch ( Exception $ ex ) { $ this -> manifest = [ ] ; } } else { $ this -> manifest = [ ] ; } }

Load the manifest into memory.

@return void


protected function write(array $manifest)
    {
        if (!is_writable($path = dirname($this->manifestPath))) {
            throw new Exception('The '.$path.' directory must be present and writable.');
        }

        $this->files->put(
            $this->manifestPath, '<?php return '.var_export($manifest, TRUE).';'
        );
    }

Write the manifest array to filesystem.

@param  array $manifest

@return void
@throws \Exception

Write the manifest array to filesystem .


public function loadFromDrivers($locale, $group, $namespace = null)
    {
        return collect($this->drivers)->map(function ($className) {
            return app($className);
        })->mapWithKeys(function (Contracts\Driver $driver) use ($locale, $group, $namespace) {
            return $driver->load($locale, $group, $namespace);
        })->toArray();
    }

public function loadFromDrivers ( $ locale , $ group , $ namespace = null ) { return collect ( $ this -> drivers ) -> map ( function ( $ className ) { return app ( $ className ) ; } ) -> mapWithKeys ( function ( Contracts \ Driver $ driver ) use ( $ locale , $ group , $ namespace ) { return $ driver -> load ( $ locale , $ group , $ namespace ) ; } ) -> toArray ( ) ; }

Get storage driver.

@param $locale
@param $group
@param null $namespace

@return Contracts\Driver


protected function loadPath($path, $locale, $group)
    {
        return collect(['_lang.php', '.php'])
            ->reduce(function ($output, $ext) use ($path, $locale, $group) {
                if ($this->files->exists($full = "{$path}/{$locale}/{$group}{$ext}")) {
                    $output = array_merge($output, $this->files->getRequire($full));
                }

                return $output;
            }, []);
    }

protected function loadPath ( $ path , $ locale , $ group ) { return collect ( [ '_lang.php' , '.php' ] ) -> reduce ( function ( $ output , $ ext ) use ( $ path , $ locale , $ group ) { if ( $ this -> files -> exists ( $ full = "{$path}/{$locale}/{$group}{$ext}" ) ) { $ output = array_merge ( $ output , $ this -> files -> getRequire ( $ full ) ) ; } return $ output ; } , [ ] ) ; }

Load a locale from a given path.

@param  string $path
@param  string $locale
@param  string $group

@return array


public function setConstraint(\Closure $callback)
    {
        $this->items = [];
        $this->loaded = FALSE;
        $this->queryConstraint = $callback;
    }

public function setConstraint ( \ Closure $ callback ) { $ this -> items = [ ] ; $ this -> loaded = FALSE ; $ this -> queryConstraint = $ callback ; }

Set the query constraint.

@param \Closure $callback


protected function parseReadData($data)
    {
        $results = [];

        foreach ($data as $row) {
            if (is_array($row)) {
                $key = $row[$this->keyColumn];
                $value = $this->parseKeyValue($row[$this->valueColumn]);
            }
            elseif (is_object($row)) {
                $key = $row->{$this->keyColumn};
                $value = $this->parseKeyValue($row->{$this->valueColumn});
            }
            else {
                throw new UnexpectedValueException('Expected array or object, got '.gettype($row));
            }

            Arr::set($results, $key, $value);
        }

        return $results;
    }

protected
function
parseReadData
(
$
data
)
{
$
results
=
[
]
;
foreach
(
$
data
as
$
row
)
{
if
(
is_array
(
$
row
)
)
{
$
key
=
$
row
[
$
this
->
keyColumn
]
;
$
value
=
$
this
->
parseKeyValue
(
$
row
[
$
this
->
valueColumn
]
)
;
}
elseif
(
is_object
(
$
row
)
)
{
$
key
=
$
row
->
{
$
this
->
keyColumn
}
;
$
value
=
$
this
->
parseKeyValue
(
$
row
->
{
$
this
->
valueColumn
}
)
;
}
else
{
throw
new
UnexpectedValueException
(
'Expected array or object, got '
.
gettype
(
$
row
)
)
;
}
Arr
::
set
(
$
results
,
$
key
,
$
value
)
;
}
return
$
results
;
}

Parse data coming from the database.

@param  \Illuminate\Support\Collection $data

@return array


protected function newQuery($insert = FALSE)
    {
        $query = $this->db->table($this->table);

        if (!$insert) {
            foreach ($this->extraColumns as $key => $value) {
                $query->where($key, '=', $value);
            }
        }

        if ($this->queryConstraint !== null) {
            $callback = $this->queryConstraint;
            $callback($query, $insert);
        }

        return $query;
    }

protected function newQuery ( $ insert = FALSE ) { $ query = $ this -> db -> table ( $ this -> table ) ; if ( ! $ insert ) { foreach ( $ this -> extraColumns as $ key => $ value ) { $ query -> where ( $ key , '=' , $ value ) ; } } if ( $ this -> queryConstraint !== null ) { $ callback = $ this -> queryConstraint ; $ callback ( $ query , $ insert ) ; } return $ query ; }

Create a new query builder instance.

@param  $insert  boolean  Whether the query is an insert or not.

@return \Illuminate\Database\Query\Builder


private static function hasColorSupport()
    {
        if (isset(self::$hasColorSupport)) {
            return self::$hasColorSupport;
        }

        if (DIRECTORY_SEPARATOR === '\\') {
            return self::$hasColorSupport =
                (10 == PHP_WINDOWS_VERSION_MAJOR && PHP_WINDOWS_VERSION_BUILD >= 10586)
                || false !== getenv('ANSICON')
                || 'ON' === getenv('ConEmuANSI')
                || 'xterm' === getenv('TERM');
        }

        return self::$hasColorSupport = function_exists('posix_isatty') && @posix_isatty(STDOUT);
    }

private static function hasColorSupport ( ) { if ( isset ( self :: $ hasColorSupport ) ) { return self :: $ hasColorSupport ; } if ( DIRECTORY_SEPARATOR === '\\' ) { return self :: $ hasColorSupport = ( 10 == PHP_WINDOWS_VERSION_MAJOR && PHP_WINDOWS_VERSION_BUILD >= 10586 ) || false !== getenv ( 'ANSICON' ) || 'ON' === getenv ( 'ConEmuANSI' ) || 'xterm' === getenv ( 'TERM' ) ; } return self :: $ hasColorSupport = function_exists ( 'posix_isatty' ) && @ posix_isatty ( STDOUT ) ; }

Check if console has color support

@return bool


public static function apply($text, $foreground = null, $background = null, array $options = [])
    {
        if (!self::hasColorSupport()) {
            return $text;
        }

        $setCodes   = [];
        $unsetCodes = [];

        if (null !== $foreground) {
            $setCodes[]   = self::$availableForegroundColors[$foreground]['set'];
            $unsetCodes[] = self::$availableForegroundColors[$foreground]['unset'];
        }
        if (null !== $background) {
            $setCodes[]   = self::$availableBackgroundColors[$background]['set'];
            $unsetCodes[] = self::$availableBackgroundColors[$background]['unset'];
        }
        if (!empty($options)) {
            foreach ($options as $option) {
                $setCodes[]   = self::$availableOptions[$option]['set'];
                $unsetCodes[] = self::$availableOptions[$option]['unset'];
            }
        }

        if (0 === count($setCodes)) {
            return $text;
        }

        return sprintf("\033[%sm%s\033[%sm", implode(';', $setCodes), $text, implode(';', $unsetCodes));
    }

public static function apply ( $ text , $ foreground = null , $ background = null , array $ options = [ ] ) { if ( ! self :: hasColorSupport ( ) ) { return $ text ; } $ setCodes = [ ] ; $ unsetCodes = [ ] ; if ( null !== $ foreground ) { $ setCodes [ ] = self :: $ availableForegroundColors [ $ foreground ] [ 'set' ] ; $ unsetCodes [ ] = self :: $ availableForegroundColors [ $ foreground ] [ 'unset' ] ; } if ( null !== $ background ) { $ setCodes [ ] = self :: $ availableBackgroundColors [ $ background ] [ 'set' ] ; $ unsetCodes [ ] = self :: $ availableBackgroundColors [ $ background ] [ 'unset' ] ; } if ( ! empty ( $ options ) ) { foreach ( $ options as $ option ) { $ setCodes [ ] = self :: $ availableOptions [ $ option ] [ 'set' ] ; $ unsetCodes [ ] = self :: $ availableOptions [ $ option ] [ 'unset' ] ; } } if ( 0 === count ( $ setCodes ) ) { return $ text ; } return sprintf ( "\033[%sm%s\033[%sm" , implode ( ';' , $ setCodes ) , $ text , implode ( ';' , $ unsetCodes ) ) ; }

Applies the style to a given text.

@param string $text The text to style=
@param null   $foreground
@param null   $background
@param array  $options

@return string


public function getRan()
    {
        $data = $this->getData();

        array_multisort(
            array_column($data, 'batch'), SORT_ASC,
            array_column($data, 'migration'), SORT_ASC,
            $data
        );

        return Arr::pluck($data, 'migration');
    }

public function getRan ( ) { $ data = $ this -> getData ( ) ; array_multisort ( array_column ( $ data , 'batch' ) , SORT_ASC , array_column ( $ data , 'migration' ) , SORT_ASC , $ data ) ; return Arr :: pluck ( $ data , 'migration' ) ; }


public function getMigrations($steps)
    {
        $data = $this->getData();

        $data = array_filter($data, function ($datum) {
            return (int)$datum['batch'] >= 1;
        });

        array_multisort(
            array_column($data, 'batch'), SORT_DESC,
            array_column($data, 'migration'), SORT_DESC,
            $data
        );

        return array_slice($data, 0, $steps);
    }

public function getMigrations ( $ steps ) { $ data = $ this -> getData ( ) ; $ data = array_filter ( $ data , function ( $ datum ) { return ( int ) $ datum [ 'batch' ] >= 1 ; } ) ; array_multisort ( array_column ( $ data , 'batch' ) , SORT_DESC , array_column ( $ data , 'migration' ) , SORT_DESC , $ data ) ; return array_slice ( $ data , 0 , $ steps ) ; }

Get list of migrations.

@param  int $steps

@return array


public function run($paths = [], array $options = [])
    {
        $this->notes = [];

        // Once we grab all of the migration files for the path, we will compare them
        // against the migrations that have already been run for this package then
        // run each of the outstanding migrations against a database connection.
        $files = $this->getMigrationFiles($paths);

        $this->requireFiles($migrations = $this->pendingMigrations(
            $files, $this->storage->getRan()
        ));

        // Once we have all these migrations that are outstanding we are ready to run
        // we will go ahead and run them "up". This will execute each migration as
        // an operation against a database. Then we'll return this list of them.
        $this->runPending($migrations, $options);

        return $migrations;
    }

Run the pending migrations at a given path.

@param array|string $paths
@param array        $options

@return array
@throws \Exception

Run the pending migrations at a given path .


protected function runUp($file, $batch, $pretend = false)
    {
        // First we will resolve a "real" instance of the migration class from this
        // migration file name. Once we have the instances we can run the actual
        // command such as "up" or "down", or we can just simulate the action.
        $migration = $this->resolve(
            $name = $this->getMigrationName($file)
        );

        if ($pretend) {
            $this->pretendToRun($name, $migration, 'up');

            return;
        }

        $this->note(Decorate::notice('Migrating:') . " {$name}");

        $this->runMigration($migration, 'up');

        // Once we have run a migrations class, we will log that it was run in this
        // repository so that we don't try to run it next time we do a migration
        // in the application. A migration repository keeps the migrate order.
        $this->storage->log($name, $batch);

        $this->note(Decorate::info('Migrated:') . " {$name}");
    }

Run "up" a migration instance.

@param string $file
@param int    $batch
@param bool   $pretend

@return void
@throws \Exception


protected function getMigrationsForRollback(array $options)
    {
        $steps = Arr::get($options, 'step', 0);

        if ($steps > 0) {
            return $this->storage->getMigrations($steps);
        } else {
            return $this->storage->getLast();
        }
    }

protected function getMigrationsForRollback ( array $ options ) { $ steps = Arr :: get ( $ options , 'step' , 0 ) ; if ( $ steps > 0 ) { return $ this -> storage -> getMigrations ( $ steps ) ; } else { return $ this -> storage -> getLast ( ) ; } }

Get the migrations for a rollback operation.

@param  array $options

@return array

Get the migrations for a rollback operation .


protected function rollbackMigrations(array $migrations, $paths, array $options)
    {
        $rolledBack = [];

        $pretend = Arr::get($options, 'pretend', false);

        $this->requireFiles($files = $this->getMigrationFiles($paths));

        // Next we will run through all of the migrations and call the "down" method
        // which will reverse each migration in order. This getLast method on the
        // repository already returns these migration's names in reverse order.
        foreach ($migrations as $migration) {
            $migration = (object)$migration;

            if (!$file = Arr::get($files, $migration->migration)) {
                continue;
            }

            $rolledBack[] = $file;

            $this->runDown($file, $migration, $pretend);
        }

        return $rolledBack;
    }

Rollback the given migrations.

@param array        $migrations
@param array|string $paths
@param array         $options

@return array
@throws \Exception


public function reset($paths = [], array $options = [])
    {
        $this->notes = [];

        // Next, we will reverse the migration list so we can run them back in the
        // correct order for resetting this database. This will allow us to get
        // the database back into its "empty" state ready for the migrations.
        $migrations = array_reverse($this->storage->getRan());

        if (count($migrations) === 0) {
            $this->note(Decorate::info('Nothing to rollback.'));

            return [];
        } else {
            return $this->resetMigrations($migrations, $paths, $options);
        }
    }

Rolls all of the currently applied migrations back.

@param array|string $paths
@param array        $options

@return array
@throws \Exception

Rolls all of the currently applied migrations back .


protected function resetMigrations(array $migrations, array $paths, array $options)
    {
        // Since the getRan method that retrieves the migration name just gives us the
        // migration name, we will format the names into objects with the name as a
        // property on the objects so that we can pass it to the rollback method.
        $migrations = array_map(function ($m) {
            return (object)['migration' => $m];
        }, $migrations);

        return $this->rollbackMigrations($migrations, $paths, $options);
    }

Reset the given migrations.

@param array $migrations
@param array $paths
@param array $options

@return array
@throws \Exception


protected function runDown($file, $migration, $pretend = false)
    {
        // First we will get the file name of the migration so we can resolve out an
        // instance of the migration. Once we get an instance we can either run a
        // pretend execution of the migration or we can run the real migration.
        $instance = $this->resolve(
            $name = $this->getMigrationName($file)
        );

        if ($pretend) {
            $this->pretendToRun($name, $instance, 'down');

            return;
        }

        $this->note(Decorate::notice('Rolling back:') . " {$name}");

        $this->runMigration($instance, 'down');

        // Once we have successfully run the migration "down" we will remove it from
        // the migration repository so it will be considered to have not been run
        // by the application then will be able to fire by any later operation.
        $this->storage->delete($migration->migration);

        $this->note(Decorate::info('Rolled back:') . " {$name}");
    }

Run "down" a migration instance.

@param string $file
@param object $migration
@param bool   $pretend

@return void
@throws \Exception


protected function pretendToRun($name, $instance, $method)
    {
        $this->note(Decorate::info($name) . ': ');

        $queries = Db::pretend(function () use ($instance, $method) {
            $this->runMigration($instance, $method);
        });

        $sql = Highlighter::factory(SQL::class, Shell::class);

        foreach ($queries as $query) {
            $this->note($sql->highlight($query));
        }

        $this->note('');
    }

protected
function
pretendToRun
(
$
name
,
$
instance
,
$
method
)
{
$
this
->
note
(
Decorate
::
info
(
$
name
)
.
': '
)
;
$
queries
=
Db
::
pretend
(
function
(
)
use
(
$
instance
,
$
method
)
{
$
this
->
runMigration
(
$
instance
,
$
method
)
;
}
)
;
$
sql
=
Highlighter
::
factory
(
SQL
::
class
,
Shell
::
class
)
;
foreach
(
$
queries
as
$
query
)
{
$
this
->
note
(
$
sql
->
highlight
(
$
query
)
)
;
}
$
this
->
note
(
''
)
;
}

Pretend to run the migrations.

@param $name
@param $instance
@param $method


public function getMigrationFiles($paths)
    {
        $paths = array_map(function ($path) {
            return glob($path . '/*_*.php');
        }, (array)$paths);

        $paths = array_filter(Arr::collapse($paths));

        $migrations = [];
        foreach ($paths as $path) {
            $migrations[$this->getMigrationName($path)] = $path;
        }

        ksort($migrations, SORT_REGULAR);

        return $migrations;
    }

public function getMigrationFiles ( $ paths ) { $ paths = array_map ( function ( $ path ) { return glob ( $ path . '/*_*.php' ) ; } , ( array ) $ paths ) ; $ paths = array_filter ( Arr :: collapse ( $ paths ) ) ; $ migrations = [ ] ; foreach ( $ paths as $ path ) { $ migrations [ $ this -> getMigrationName ( $ path ) ] = $ path ; } ksort ( $ migrations , SORT_REGULAR ) ; return $ migrations ; }

Get all of the migration files in a given path.

@param  string|array $paths

@return array

Get all of the migration files in a given path .


private static function clearLoader($compileDir)
    {
        if (file_exists($compileDir . 'loader.php')) {
            @unlink($compileDir . 'loader.php');
        }
        if (file_exists($compileDir . 'compile.php')) {
            @unlink($compileDir . 'compile.php');
        }
    }

private static function clearLoader ( $ compileDir ) { if ( file_exists ( $ compileDir . 'loader.php' ) ) { @ unlink ( $ compileDir . 'loader.php' ) ; } if ( file_exists ( $ compileDir . 'compile.php' ) ) { @ unlink ( $ compileDir . 'compile.php' ) ; } }

Deleting Compiled Files

@param string $compileDir


protected function primary($name, $type, array $options = [])
    {
        static::addColumn($name, $type, isset($options['map']) ? $options['map'] : $name);

        static::$metaDatasClass[static::class][MetaData::MODELS_PRIMARY_KEY][] = $name;
        static::$metaDatasClass[static::class][MetaData::MODELS_NOT_NULL][] = $name;

        if (
            (!isset($options['identity']) || $options['identity']) &&
            (!isset($options['multiple']) || !$options['multiple'])
        ) {
            static::$metaDatasClass[static::class][MetaData::MODELS_IDENTITY_COLUMN] = $name;
        }
        if (
            (!isset($options['autoIncrement']) || $options['autoIncrement']) &&
            (!isset($options['multiple']) || !$options['multiple'])
        ) {
            static::$metaDatasClass[static::class][MetaData::MODELS_AUTOMATIC_DEFAULT_INSERT][$name] = true;
        }
    }

protected function primary ( $ name , $ type , array $ options = [ ] ) { static :: addColumn ( $ name , $ type , isset ( $ options [ 'map' ] ) ? $ options [ 'map' ] : $ name ) ; static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_PRIMARY_KEY ] [ ] = $ name ; static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_NOT_NULL ] [ ] = $ name ; if ( ( ! isset ( $ options [ 'identity' ] ) || $ options [ 'identity' ] ) && ( ! isset ( $ options [ 'multiple' ] ) || ! $ options [ 'multiple' ] ) ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_IDENTITY_COLUMN ] = $ name ; } if ( ( ! isset ( $ options [ 'autoIncrement' ] ) || $ options [ 'autoIncrement' ] ) && ( ! isset ( $ options [ 'multiple' ] ) || ! $ options [ 'multiple' ] ) ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_AUTOMATIC_DEFAULT_INSERT ] [ $ name ] = true ; } }

Define the primary column

@param string $name
@param int    $type
@param array  $options


protected function column($name, $type, array $options = [])
    {
        static::addColumn($name, $type, isset($options['map']) ? $options['map'] : $name);

        static::$metaDatasClass[static::class][MetaData::MODELS_NON_PRIMARY_KEY][] = $name;

        if (isset($options['nullable']) && $options['nullable']) {
            static::$metaDatasClass[static::class][MetaData::MODELS_EMPTY_STRING_VALUES][$name] = true;
        } else {
            static::$metaDatasClass[static::class][MetaData::MODELS_NOT_NULL][] = $name;
        }

        if (isset($options['default'])) {
            static::$metaDatasClass[static::class][MetaData::MODELS_DEFAULT_VALUES][$name] = $options['default'];
        }

        if (isset($options['autoInsert']) && $options['autoInsert']) {
            static::$metaDatasClass[static::class][MetaData::MODELS_AUTOMATIC_DEFAULT_INSERT][$name] = true;
        }

        if (isset($options['autoUpdate']) && $options['autoUpdate']) {
            static::$metaDatasClass[static::class][MetaData::MODELS_AUTOMATIC_DEFAULT_UPDATE][$name] = true;
        }
    }

protected function column ( $ name , $ type , array $ options = [ ] ) { static :: addColumn ( $ name , $ type , isset ( $ options [ 'map' ] ) ? $ options [ 'map' ] : $ name ) ; static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_NON_PRIMARY_KEY ] [ ] = $ name ; if ( isset ( $ options [ 'nullable' ] ) && $ options [ 'nullable' ] ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_EMPTY_STRING_VALUES ] [ $ name ] = true ; } else { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_NOT_NULL ] [ ] = $ name ; } if ( isset ( $ options [ 'default' ] ) ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DEFAULT_VALUES ] [ $ name ] = $ options [ 'default' ] ; } if ( isset ( $ options [ 'autoInsert' ] ) && $ options [ 'autoInsert' ] ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_AUTOMATIC_DEFAULT_INSERT ] [ $ name ] = true ; } if ( isset ( $ options [ 'autoUpdate' ] ) && $ options [ 'autoUpdate' ] ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_AUTOMATIC_DEFAULT_UPDATE ] [ $ name ] = true ; } }

Define a column

@param string $name
@param int    $type
@param array  $options


protected function timestampable($name, array $options = [])
    {
        if ((isset($options['autoInsert']) && $options['autoInsert']) ||
            (isset($options['autoUpdate']) && $options['autoUpdate'])
        ) {
            throw new \RuntimeException('Model: A timestampable field can\'t have autoInsert or autoUpdate.');
        }

        self::column($name, isset($options['type']) ? $options['type'] : Column::TYPE_DATETIME, $options);

        $params = [];

        if (!isset($options['default']) && isset($options['insert']) && $options['insert']) {
            $params['beforeValidationOnCreate'] = [
                'field'  => $name,
                'format' => isset($options['format']) ? $options['format'] : DATE_ATOM
            ];
        }

        if (isset($options['update']) && $options['update']) {
            $params['beforeValidationOnUpdate'] = [
                'field'  => $name,
                'format' => isset($options['format']) ? $options['format'] : DATE_ATOM
            ];
        }

        if(empty($params)){
            throw new \RuntimeException('Model: A timestampable field needs to have at least insert or update.');
        }

        $this->addBehavior(new Timestampable($params));
    }

Define a timestampable column.
Automatically add the Timestampable behavior.

@param string $name
@param array  $options

Define a timestampable column . Automatically add the Timestampable behavior .


protected function softDeletable($name, array $options = [])
    {
        if ((isset($options['autoInsert']) && $options['autoInsert']) ||
            (isset($options['autoUpdate']) && $options['autoUpdate'])
        ) {
            throw new \RuntimeException('Model: A timestampable field can\'t have autoInsert or autoUpdate.');
        }

        self::column($name, isset($options['type']) ? $options['type'] : Column::TYPE_BOOLEAN, $options);

        $this->addBehavior(new SoftDelete([
            'field' => $name,
            'value' => isset($options['value']) ? $options['value'] : true
        ]));
    }

Define a softDeleted column.
Automatically add the SoftDelete behavior.

@param string $name
@param array  $options

Define a softDeleted column . Automatically add the SoftDelete behavior .


private static function addColumn($name, $type, $map)
    {
        static::$columnsMapClass[static::class][$name] = $map;

        static::$metaDatasClass[static::class][MetaData::MODELS_ATTRIBUTES][] = $name;
        static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES][$name] = $type;

        static::describeColumnType($name, $type);
    }

private static function addColumn ( $ name , $ type , $ map ) { static :: $ columnsMapClass [ static :: class ] [ $ name ] = $ map ; static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_ATTRIBUTES ] [ ] = $ name ; static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES ] [ $ name ] = $ type ; static :: describeColumnType ( $ name , $ type ) ; }

Add column type

@param string $name
@param int    $type
@param string $map


private static function describeColumnType($name, $type)
    {
        if ($type === null) {
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_BIND][$name] = Column::BIND_PARAM_NULL;
        } elseif (
            $type === Column::TYPE_BIGINTEGER ||
            $type === Column::TYPE_INTEGER ||
            $type === Column::TYPE_TIMESTAMP
        ) {
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_BIND][$name] = Column::BIND_PARAM_INT;
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_NUMERIC][$name] = true;
        } elseif (
            $type === Column::TYPE_DECIMAL ||
            $type === Column::TYPE_FLOAT ||
            $type === Column::TYPE_DOUBLE
        ) {
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_BIND][$name] = Column::BIND_PARAM_DECIMAL;
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_NUMERIC][$name] = true;
        } elseif (
            $type === Column::TYPE_JSON ||
            $type === Column::TYPE_TEXT ||
            $type === Column::TYPE_CHAR ||
            $type === Column::TYPE_VARCHAR ||
            $type === Column::TYPE_DATE ||
            $type === Column::TYPE_DATETIME
        ) {
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_BIND][$name] = Column::BIND_PARAM_STR;
        } elseif (
            $type === Column::TYPE_BLOB ||
            $type === Column::TYPE_JSONB ||
            $type === Column::TYPE_MEDIUMBLOB ||
            $type === Column::TYPE_TINYBLOB ||
            $type === Column::TYPE_LONGBLOB
        ) {
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_BIND][$name] = Column::BIND_PARAM_BLOB;
        } elseif ($type === Column::TYPE_BOOLEAN) {
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_BIND][$name] = Column::BIND_PARAM_BOOL;
        } else {
            static::$metaDatasClass[static::class][MetaData::MODELS_DATA_TYPES_BIND][$name] = Column::BIND_SKIP;
        }
    }

private static function describeColumnType ( $ name , $ type ) { if ( $ type === null ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_BIND ] [ $ name ] = Column :: BIND_PARAM_NULL ; } elseif ( $ type === Column :: TYPE_BIGINTEGER || $ type === Column :: TYPE_INTEGER || $ type === Column :: TYPE_TIMESTAMP ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_BIND ] [ $ name ] = Column :: BIND_PARAM_INT ; static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_NUMERIC ] [ $ name ] = true ; } elseif ( $ type === Column :: TYPE_DECIMAL || $ type === Column :: TYPE_FLOAT || $ type === Column :: TYPE_DOUBLE ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_BIND ] [ $ name ] = Column :: BIND_PARAM_DECIMAL ; static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_NUMERIC ] [ $ name ] = true ; } elseif ( $ type === Column :: TYPE_JSON || $ type === Column :: TYPE_TEXT || $ type === Column :: TYPE_CHAR || $ type === Column :: TYPE_VARCHAR || $ type === Column :: TYPE_DATE || $ type === Column :: TYPE_DATETIME ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_BIND ] [ $ name ] = Column :: BIND_PARAM_STR ; } elseif ( $ type === Column :: TYPE_BLOB || $ type === Column :: TYPE_JSONB || $ type === Column :: TYPE_MEDIUMBLOB || $ type === Column :: TYPE_TINYBLOB || $ type === Column :: TYPE_LONGBLOB ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_BIND ] [ $ name ] = Column :: BIND_PARAM_BLOB ; } elseif ( $ type === Column :: TYPE_BOOLEAN ) { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_BIND ] [ $ name ] = Column :: BIND_PARAM_BOOL ; } else { static :: $ metaDatasClass [ static :: class ] [ MetaData :: MODELS_DATA_TYPES_BIND ] [ $ name ] = Column :: BIND_SKIP ; } }

Define a column type

@param string $name
@param int    $type


protected function hasOption(...$options)
    {
        foreach ($options as $option) {
            if (Arr::has($this->options, $option)) {
                return true;
            }
        }

        return false;
    }

protected function hasOption ( ... $ options ) { foreach ( $ options as $ option ) { if ( Arr :: has ( $ this -> options , $ option ) ) { return true ; } } return false ; }

Check if option has been passed

@param string[] ...$options

@return bool


protected function isParentIdSame()
	{
		$dirty = $this->getDirty();
		$oldNavItem = self::where('id','=',$this->id)->first();
		$oldParent = $oldNavItem->parent;
		$oldParentId = $oldParent->id;
		$isParentColumnSet = isset($dirty[$this->getParentColumnName()]);
		if ($isParentColumnSet)
		{
			$isNewParentSameAsOld = $dirty[$this->getParentColumnName()] == $oldParentId;
		}
		else
		{
			$isNewParentSameAsOld = false;
		}
		return $isParentColumnSet && $isNewParentSameAsOld;
	}

protected function isParentIdSame ( ) { $ dirty = $ this -> getDirty ( ) ; $ oldNavItem = self :: where ( 'id' , '=' , $ this -> id ) -> first ( ) ; $ oldParent = $ oldNavItem -> parent ; $ oldParentId = $ oldParent -> id ; $ isParentColumnSet = isset ( $ dirty [ $ this -> getParentColumnName ( ) ] ) ; if ( $ isParentColumnSet ) { $ isNewParentSameAsOld = $ dirty [ $ this -> getParentColumnName ( ) ] == $ oldParentId ; } else { $ isNewParentSameAsOld = false ; } return $ isParentColumnSet && $ isNewParentSameAsOld ; }

Returns true if the parent_id value in the database is different to the current value in the model's dirty attributes
@return bool

Returns true if the parent_id value in the database is different to the current value in the model s dirty attributes


public function scopeLive($query)
	{
		return $query->where('status', '=', self::APPROVED)
			->where('published_date', '<=', \Carbon\Carbon::now());
	}

public function scopeLive ( $ query ) { return $ query -> where ( 'status' , '=' , self :: APPROVED ) -> where ( 'published_date' , '<=' , \ Carbon \ Carbon :: now ( ) ) ; }

Adds a query scope to add conditions to query object

@param $query
@return mixed


public function getPathAttribute()
	{
		$ancestors = $this->getAncestors();
		$return = array();
		foreach($ancestors as $ancestor) {
			$return[] = $ancestor->name;
		}
		$return[] = $this->name;
		return implode(' > ', $return);
	}

public
function
getPathAttribute
(
)
{
$
ancestors
=
$
this
->
getAncestors
(
)
;
$
return
=
array
(
)
;
foreach
(
$
ancestors
as
$
ancestor
)
{
$
return
[
]
=
$
ancestor
->
name
;
}
$
return
[
]
=
$
this
->
name
;
return
implode
(
' > '
,
$
return
)
;
}

Accessor for path attribute, which is a string consisting of the ancestors of each node, separated by " > ".
@return string

Accessor for path attribute which is a string consisting of the ancestors of each node separated by > .


protected function register()
    {
        $app = $this->config->app;

        $crypt = new \Phalcon\Crypt($app->cipher);

        $crypt->setKey($app->key);

        return $crypt;
    }

protected function register ( ) { $ app = $ this -> config -> app ; $ crypt = new \ Phalcon \ Crypt ( $ app -> cipher ) ; $ crypt -> setKey ( $ app -> key ) ; return $ crypt ; }

Return the service to register

Called when the services container tries to resolve the service

@return mixed


public function mainAction()
    {
        $this->output->write(Decorate::notice(str_pad('Generating configuration cache', 40, ' ')), false);

        $preloader = new ConfigPreloader();

        try {
            $preloader->compile();

            $this->info("Success");
        } catch (\Exception $e) {
            $this->error("Error");
            $this->block([$e->getMessage()], 'error');
        }
    }

public
function
mainAction
(
)
{
$
this
->
output
->
write
(
Decorate
::
notice
(
str_pad
(
'Generating configuration cache'
,
40
,
' '
)
)
,
false
)
;
$
preloader
=
new
ConfigPreloader
(
)
;
try
{
$
preloader
->
compile
(
)
;
$
this
->
info
(
"Success"
)
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
error
(
"Error"
)
;
$
this
->
block
(
[
$
e
->
getMessage
(
)
]
,
'error'
)
;
}
}

Configuration cache.

@description Cache the configuration.

@throws \Exception


public function renameTable($from, $to, $schema = null)
    {
        return "RENAME TABLE " . $this->prepareTable($from, $schema) . " TO " . $this->prepareTable($to, $schema);
    }

public
function
renameTable
(
$
from
,
$
to
,
$
schema
=
)
{
return
"RENAME TABLE "
.
$
this
->
prepareTable
(
$
from
,
$
schema
)
.
" TO "
.
$
this
->
prepareTable
(
$
to
,
$
schema
)
;
}

Generates SQL for rename table

@param string      $from
@param string      $to
@param null|string $schema

@return string


public static function bootHasPermalink()
    {
        if (!property_exists(get_called_class(), 'permalinkable')) {
            throw new Exception(sprintf(
                'You must define a $permalinkable property in %s to use the HasPermalink trait.', get_called_class()
            ));
        }

        static::saving(function (Model $model) {
            $model->generatePermalinkOnSave();
        });
    }

Boot the sortable trait for this model.
@return void
@throws \Exception

Boot the sortable trait for this model .


public function getSlugKeyName()
    {
        if (property_exists($this, 'slugKeyName')) {
            return $this->slugKeyName;
        }

        $config = $this->permalinkable();
        $name = reset($config);
        $key = key($config);

        // check for short configuration
        if ($key === 0) {
            return $name;
        }

        return $key;
    }

public
function
getSlugKeyName
(
)
{
if
(
property_exists
(
$
this
,
'slugKeyName'
)
)
{
return
$
this
->
slugKeyName
;
}
$
config
=
$
this
->
permalinkable
(
)
;
$
name
=
reset
(
$
config
)
;
$
key
=
key
(
$
config
)
;
// check for short configuration
if
(
$
key
===
0
)
{
return
$
name
;
}
return
$
key
;
}

Primary slug column of this model.
@return string


public function scopeFindSimilarSlugs($query, $attribute, array $config, $slug)
    {
        $separator = $config['separator'];

        return $query->where($attribute, $slug)
                     ->orWhere($attribute, 'LIKE', $slug.$separator.'%');
    }

public function scopeFindSimilarSlugs ( $ query , $ attribute , array $ config , $ slug ) { $ separator = $ config [ 'separator' ] ; return $ query -> where ( $ attribute , $ slug ) -> orWhere ( $ attribute , 'LIKE' , $ slug . $ separator . '%' ) ; }

Query scope for finding "similar" slugs, used to determine uniqueness.

@param \Illuminate\Database\Eloquent\Builder $query
@param string $attribute
@param array $config
@param string $slug

@return \Illuminate\Database\Eloquent\Builder

Query scope for finding similar slugs used to determine uniqueness .


public function query($sqlStatement, $placeholders = null, $dataTypes = null, ...$args)
    {
        return $this->uses()->query($sqlStatement, $placeholders, $dataTypes, ...$args);
    }

public function query ( $ sqlStatement , $ placeholders = null , $ dataTypes = null , ... $ args ) { return $ this -> uses ( ) -> query ( $ sqlStatement , $ placeholders , $ dataTypes , ... $ args ) ; }

Sends SQL statements to the database server returning the success state.
Use this method only when the SQL statement sent to the server return rows

@param string $sqlStatement
@param mixed $placeholders
@param mixed $dataTypes
@param array $args
@return bool|ResultInterface

Sends SQL statements to the database server returning the success state . Use this method only when the SQL statement sent to the server return rows


public function execute($sqlStatement, $placeholders = null, $dataTypes = null, ...$args)
    {
        return $this->uses()->execute($sqlStatement, $placeholders, $dataTypes, ...$args);
    }

public function execute ( $ sqlStatement , $ placeholders = null , $ dataTypes = null , ... $ args ) { return $ this -> uses ( ) -> execute ( $ sqlStatement , $ placeholders , $ dataTypes , ... $ args ) ; }

Sends SQL statements to the database server returning the success state.
Use this method only when the SQL statement sent to the server doesn't return any rows

@param string $sqlStatement
@param mixed $placeholders
@param mixed $dataTypes
@param array $args
@return bool

Sends SQL statements to the database server returning the success state . Use this method only when the SQL statement sent to the server doesn t return any rows


public function describeColumns($table, $schema = null, ...$args)
    {
        return $this->uses()->describeColumns($table, $schema, ...$args);
    }

public function describeColumns ( $ table , $ schema = null , ... $ args ) { return $ this -> uses ( ) -> describeColumns ( $ table , $ schema , ... $ args ) ; }

Returns an array of Phalcon\Db\Column objects describing a table

@param string $table
@param string $schema
@param array $args
@return ColumnInterface[]

Returns an array of Phalcon \ Db \ Column objects describing a table


public function fetchOne($sqlQuery, $fetchMode = 2, $placeholders = null, ...$args)
    {
        return $this->uses()->fetchOne($sqlQuery, $fetchMode, $placeholders, ...$args);
    }

public function fetchOne ( $ sqlQuery , $ fetchMode = 2 , $ placeholders = null , ... $ args ) { return $ this -> uses ( ) -> fetchOne ( $ sqlQuery , $ fetchMode , $ placeholders , ... $ args ) ; }

Returns the first row in a SQL query result

@param string $sqlQuery
@param int $fetchMode
@param int $placeholders
@param array $args
@return array


public function fetchAll($sqlQuery, $fetchMode = 2, $placeholders = null, ...$args)
    {
        return $this->uses()->fetchAll($sqlQuery, $fetchMode, $placeholders, ...$args);
    }

public function fetchAll ( $ sqlQuery , $ fetchMode = 2 , $ placeholders = null , ... $ args ) { return $ this -> uses ( ) -> fetchAll ( $ sqlQuery , $ fetchMode , $ placeholders , ... $ args ) ; }

Dumps the complete result of a query into an array

@param string $sqlQuery
@param int $fetchMode
@param int $placeholders
@param array $args
@return array


public function insert($table, array $values, $fields = null, $dataTypes = null, ...$args)
    {
        return $this->uses()->insert($table, $values, $fields, $dataTypes, ...$args); }

public function insert ( $ table , array $ values , $ fields = null , $ dataTypes = null , ... $ args ) { return $ this -> uses ( ) -> insert ( $ table , $ values , $ fields , $ dataTypes , ... $ args ) ; }

Inserts data into a table using custom RDBMS SQL syntax

@param mixed $table
@param array $values
@param mixed $fields
@param mixed $dataTypes
@param array $args
@return mixed


public function update($table, $fields, $values, $whereCondition = null, $dataTypes = null, ...$args)
    {
        return $this->uses()->update($table, $fields, $values, $whereCondition, $dataTypes, ...$args);
    }

public function update ( $ table , $ fields , $ values , $ whereCondition = null , $ dataTypes = null , ... $ args ) { return $ this -> uses ( ) -> update ( $ table , $ fields , $ values , $ whereCondition , $ dataTypes , ... $ args ) ; }

Updates data on a table using custom RDBMS SQL syntax

@param mixed $table
@param mixed $fields
@param mixed $values
@param mixed $whereCondition
@param mixed $dataTypes
@param array $args
@return mixed


public function delete($table, $whereCondition = null, $placeholders = null, $dataTypes = null, ...$args)
    {
        return $this->uses()->delete($table, $whereCondition, $placeholders, $dataTypes, ...$args);
    }

public function delete ( $ table , $ whereCondition = null , $ placeholders = null , $ dataTypes = null , ... $ args ) { return $ this -> uses ( ) -> delete ( $ table , $ whereCondition , $ placeholders , $ dataTypes , ... $ args ) ; }

Deletes data from a table using custom RDBMS SQL syntax

@param string $table
@param string $whereCondition
@param array $placeholders
@param array $dataTypes
@param array $args
@return boolean


public function limit($sqlQuery, $number, ...$args)
    {
        return $this->uses()->limit($sqlQuery, $number, ...$args);
    }

public function limit ( $ sqlQuery , $ number , ... $ args ) { return $ this -> uses ( ) -> limit ( $ sqlQuery , $ number , ... $ args ) ; }

Appends a LIMIT clause to sqlQuery argument

@param mixed $sqlQuery
@param mixed $number
@param array $args
@return mixed


public function tableExists($tableName, $schemaName = null, ...$args)
    {
        return $this->uses()->tableExists($tableName, $schemaName, ...$args);
    }

public function tableExists ( $ tableName , $ schemaName = null , ... $ args ) { return $ this -> uses ( ) -> tableExists ( $ tableName , $ schemaName , ... $ args ) ; }

Generates SQL checking for the existence of a schema.table

@param string $tableName
@param string $schemaName
@param array $args
@return bool

Generates SQL checking for the existence of a schema . table


public function viewExists($viewName, $schemaName = null, ...$args)
    {
        return $this->uses()->viewExists($viewName, $schemaName, ...$args);
    }

public function viewExists ( $ viewName , $ schemaName = null , ... $ args ) { return $ this -> uses ( ) -> viewExists ( $ viewName , $ schemaName , ... $ args ) ; }

Generates SQL checking for the existence of a schema.view

@param string $viewName
@param string $schemaName
@param array $args
@return bool

Generates SQL checking for the existence of a schema . view


public function createTable($tableName, $schemaName, array $definition, ...$args)
    {
        return $this->uses()->createTable($tableName, $schemaName, $definition, ...$args); }

public function createTable ( $ tableName , $ schemaName , array $ definition , ... $ args ) { return $ this -> uses ( ) -> createTable ( $ tableName , $ schemaName , $ definition , ... $ args ) ; }

Creates a table

@param string $tableName
@param string $schemaName
@param array $definition
@param array $args
@return bool


public function createView($viewName, array $definition, $schemaName = null, ...$args)
    {
        return $this->uses()->createView($viewName, $definition, $schemaName, ...$args); }

public function createView ( $ viewName , array $ definition , $ schemaName = null , ... $ args ) { return $ this -> uses ( ) -> createView ( $ viewName , $ definition , $ schemaName , ... $ args ) ; }

Creates a view

@param string $viewName
@param array $definition
@param string $schemaName
@param array $args
@return bool


public function dropView($viewName, $schemaName = null, $ifExists = true, ...$args)
    {
        return $this->uses()->dropView($viewName, $schemaName, $ifExists, ...$args);
    }

public function dropView ( $ viewName , $ schemaName = null , $ ifExists = true , ... $ args ) { return $ this -> uses ( ) -> dropView ( $ viewName , $ schemaName , $ ifExists , ... $ args ) ; }

Drops a view

@param string $viewName
@param string $schemaName
@param bool $ifExists
@param array $args
@return bool


public function addColumn($tableName, $schemaName, ColumnInterface $column, ...$args)
    {
        return $this->uses()->addColumn($tableName, $schemaName, $column, ...$args); }

public function addColumn ( $ tableName , $ schemaName , ColumnInterface $ column , ... $ args ) { return $ this -> uses ( ) -> addColumn ( $ tableName , $ schemaName , $ column , ... $ args ) ; }

Adds a column to a table

@param string $tableName
@param string $schemaName
@param ColumnInterface $column
@param array $args
@return bool


public function modifyColumn($tableName, $schemaName, ColumnInterface $column, ColumnInterface $currentColumn = null, ...$args)
    {
        return $this->uses()->modifyColumn($tableName, $schemaName, $column, $currentColumn, ...$args); }

public function modifyColumn ( $ tableName , $ schemaName , ColumnInterface $ column , ColumnInterface $ currentColumn = null , ... $ args ) { return $ this -> uses ( ) -> modifyColumn ( $ tableName , $ schemaName , $ column , $ currentColumn , ... $ args ) ; }

Modifies a table column based on a definition

@param string $tableName
@param string $schemaName
@param ColumnInterface $column
@param ColumnInterface $currentColumn
@param array $args
@return bool


public function dropColumn($tableName, $schemaName, $columnName, ...$args)
    {
        return $this->uses()->dropColumn($tableName, $schemaName, $columnName, ...$args);
    }

public function dropColumn ( $ tableName , $ schemaName , $ columnName , ... $ args ) { return $ this -> uses ( ) -> dropColumn ( $ tableName , $ schemaName , $ columnName , ... $ args ) ; }

Drops a column from a table

@param string $tableName
@param string $schemaName
@param string $columnName
@param array $args
@return bool


public function addIndex($tableName, $schemaName, IndexInterface $index, ...$args)
    {
        return $this->uses()->addIndex($tableName, $schemaName, $index, ...$args); }

public function addIndex ( $ tableName , $ schemaName , IndexInterface $ index , ... $ args ) { return $ this -> uses ( ) -> addIndex ( $ tableName , $ schemaName , $ index , ... $ args ) ; }

Adds an index to a table

@param string $tableName
@param string $schemaName
@param IndexInterface $index
@param array $args
@return bool


public function dropIndex($tableName, $schemaName, $indexName, ...$args)
    {
        return $this->uses()->dropIndex($tableName, $schemaName, $indexName, ...$args);
    }

public function dropIndex ( $ tableName , $ schemaName , $ indexName , ... $ args ) { return $ this -> uses ( ) -> dropIndex ( $ tableName , $ schemaName , $ indexName , ... $ args ) ; }

Drop an index from a table

@param string $tableName
@param string $schemaName
@param string $indexName
@param array $args
@return bool


public function addPrimaryKey($tableName, $schemaName, IndexInterface $index, ...$args)
    {
        return $this->uses()->addPrimaryKey($tableName, $schemaName, $index, ...$args); }

public function addPrimaryKey ( $ tableName , $ schemaName , IndexInterface $ index , ... $ args ) { return $ this -> uses ( ) -> addPrimaryKey ( $ tableName , $ schemaName , $ index , ... $ args ) ; }

Adds a primary key to a table

@param string $tableName
@param string $schemaName
@param IndexInterface $index
@param array $args
@return bool


public function dropPrimaryKey($tableName, $schemaName, ...$args)
    {
        return $this->uses()->dropPrimaryKey($tableName, $schemaName, ...$args);
    }

public function dropPrimaryKey ( $ tableName , $ schemaName , ... $ args ) { return $ this -> uses ( ) -> dropPrimaryKey ( $ tableName , $ schemaName , ... $ args ) ; }

Drops primary key from a table

@param string $tableName
@param string $schemaName
@param array $args
@return bool


public function addForeignKey($tableName, $schemaName, ReferenceInterface $reference, ...$args)
    {
        return $this->uses()->addForeignKey($tableName, $schemaName, $reference, ...$args); }

public function addForeignKey ( $ tableName , $ schemaName , ReferenceInterface $ reference , ... $ args ) { return $ this -> uses ( ) -> addForeignKey ( $ tableName , $ schemaName , $ reference , ... $ args ) ; }

Adds a foreign key to a table

@param string $tableName
@param string $schemaName
@param ReferenceInterface $reference
@param array $args
@return bool


public function dropForeignKey($tableName, $schemaName, $referenceName, ...$args)
    {
        return $this->uses()->dropForeignKey($tableName, $schemaName, $referenceName, ...$args);
    }

public function dropForeignKey ( $ tableName , $ schemaName , $ referenceName , ... $ args ) { return $ this -> uses ( ) -> dropForeignKey ( $ tableName , $ schemaName , $ referenceName , ... $ args ) ; }

Drops a foreign key from a table

@param string $tableName
@param string $schemaName
@param string $referenceName
@param array $args
@return bool


public function describeIndexes($table, $schema = null, ...$args)
    {
        return $this->uses()->describeIndexes($table, $schema, ...$args);
    }

public function describeIndexes ( $ table , $ schema = null , ... $ args ) { return $ this -> uses ( ) -> describeIndexes ( $ table , $ schema , ... $ args ) ; }

Lists table indexes

@param string $table
@param string $schema
@param array $args
@return IndexInterface[]


public function describeReferences($table, $schema = null, ...$args)
    {
        return $this->uses()->describeReferences($table, $schema, ...$args);
    }

public function describeReferences ( $ table , $ schema = null , ... $ args ) { return $ this -> uses ( ) -> describeReferences ( $ table , $ schema , ... $ args ) ; }

Lists table references

@param string $table
@param string $schema
@param array $args
@return ReferenceInterface[]


public function tableOptions($tableName, $schemaName = null, ...$args)
    {
        return $this->uses()->tableOptions($tableName, $schemaName, ...$args);
    }

public function tableOptions ( $ tableName , $ schemaName = null , ... $ args ) { return $ this -> uses ( ) -> tableOptions ( $ tableName , $ schemaName , ... $ args ) ; }

Gets creation options from a table

@param string $tableName
@param string $schemaName
@param array $args
@return array


public function getPanel()
	{
		$latte = new Latte\Engine;

		$latte->addFilter('storageId', [$this, 'getStorageId']);
		$latte->addFilter('colorRange', [$this, 'getColorInRange']);

		$args = [
			'title' => $this->getTitle(),
			'collector' => $this->collector,
		];

		if ($this->collector->getQueries())
		{
			$this->extremes = $this->collector->getTimeExtremes();
		}

		return $latte->renderToString(__DIR__ . '/queryPanel.latte', $args);
	}

public function getPanel ( ) { $ latte = new Latte \ Engine ; $ latte -> addFilter ( 'storageId' , [ $ this , 'getStorageId' ] ) ; $ latte -> addFilter ( 'colorRange' , [ $ this , 'getColorInRange' ] ) ; $ args = [ 'title' => $ this -> getTitle ( ) , 'collector' => $ this -> collector , ] ; if ( $ this -> collector -> getQueries ( ) ) { $ this -> extremes = $ this -> collector -> getTimeExtremes ( ) ; } return $ latte -> renderToString ( __DIR__ . '/queryPanel.latte' , $ args ) ; }

Renders HTML code for custom panel.

@return string html
@internal


public function addColumn($tableName, $schemaName, Db\ColumnInterface $column)
    {
        return $this->dialect->addColumn($tableName, $schemaName, $column);
    }

public function addColumn ( $ tableName , $ schemaName , Db \ ColumnInterface $ column ) { return $ this -> dialect -> addColumn ( $ tableName , $ schemaName , $ column ) ; }

Generates SQL to add a column to a table

@param string                      $tableName
@param string                      $schemaName
@param \Phalcon\Db\ColumnInterface $column

@return string


public function modifyColumn(
        $tableName,
        $schemaName,
        Db\ColumnInterface $column,
        Db\ColumnInterface $currentColumn = null
    )
    {
        return $this->dialect->modifyColumn($tableName, $schemaName, $column, $currentColumn);
    }

public function modifyColumn ( $ tableName , $ schemaName , Db \ ColumnInterface $ column , Db \ ColumnInterface $ currentColumn = null ) { return $ this -> dialect -> modifyColumn ( $ tableName , $ schemaName , $ column , $ currentColumn ) ; }

Generates SQL to modify a column in a table

@param string                      $tableName
@param string                      $schemaName
@param \Phalcon\Db\ColumnInterface $column
@param \Phalcon\Db\ColumnInterface $currentColumn

@return string


public function dropColumn($tableName, $schemaName, $columnName)
    {
        return $this->dialect->dropColumn($tableName, $schemaName, $columnName);
    }

public function dropColumn ( $ tableName , $ schemaName , $ columnName ) { return $ this -> dialect -> dropColumn ( $ tableName , $ schemaName , $ columnName ) ; }

Generates SQL to delete a column from a table

@param string $tableName
@param string $schemaName
@param string $columnName

@return string


public function dropIndex($tableName, $schemaName, $indexName)
    {
        return $this->dialect->dropIndex($tableName, $schemaName, $indexName);
    }

public function dropIndex ( $ tableName , $ schemaName , $ indexName ) { return $ this -> dialect -> dropIndex ( $ tableName , $ schemaName , $ indexName ) ; }

Generates SQL to delete an index from a table

@param string $tableName
@param string $schemaName
@param string $indexName

@return string


public function addPrimaryKey($tableName, $schemaName, Db\IndexInterface $index)
    {
        return $this->dialect->addPrimaryKey($tableName, $schemaName, $index);
    }

public function addPrimaryKey ( $ tableName , $ schemaName , Db \ IndexInterface $ index ) { return $ this -> dialect -> addPrimaryKey ( $ tableName , $ schemaName , $ index ) ; }

Generates SQL to add the primary key to a table

@param string                     $tableName
@param string                     $schemaName
@param \Phalcon\Db\IndexInterface $index

@return string


public function dropForeignKey($tableName, $schemaName, $referenceName)
    {
        return $this->dialect->dropForeignKey($tableName, $schemaName, $referenceName);
    }

public function dropForeignKey ( $ tableName , $ schemaName , $ referenceName ) { return $ this -> dialect -> dropForeignKey ( $ tableName , $ schemaName , $ referenceName ) ; }

Generates SQL to delete a foreign key from a table

@param string $tableName
@param string $schemaName
@param string $referenceName

@return string


public function createTable($tableName, $schemaName, array $definition)
    {
        return $this->dialect->createTable($tableName, $schemaName, $definition);
    }

public function createTable ( $ tableName , $ schemaName , array $ definition ) { return $ this -> dialect -> createTable ( $ tableName , $ schemaName , $ definition ) ; }

Generates SQL to create a table

@param string $tableName
@param string $schemaName
@param array  $definition

@return string


public function createView($viewName, array $definition, $schemaName = null)
    {
        return $this->dialect->createView($viewName, $definition, $schemaName);
    }

public function createView ( $ viewName , array $ definition , $ schemaName = null ) { return $ this -> dialect -> createView ( $ viewName , $ definition , $ schemaName ) ; }

Generates SQL to create a view

@param string $viewName
@param array  $definition
@param string $schemaName

@return string


public function dropTable($tableName, $schemaName = null, $ifExists = null)
    {
        return $this->dialect->dropTable($tableName, $schemaName, $ifExists);
    }

public function dropTable ( $ tableName , $ schemaName = null , $ ifExists = null ) { return $ this -> dialect -> dropTable ( $ tableName , $ schemaName , $ ifExists ) ; }

Generates SQL to drop a table

@param string $tableName
@param string $schemaName
@param bool   $ifExists

@return string


public function dropView($viewName, $schemaName = null, $ifExists = true)
    {
        return $this->dialect->dropView($viewName, $schemaName, $ifExists);
    }

public function dropView ( $ viewName , $ schemaName = null , $ ifExists = true ) { return $ this -> dialect -> dropView ( $ viewName , $ schemaName , $ ifExists ) ; }

Generates SQL to drop a view

@param string $viewName
@param string $schemaName
@param bool   $ifExists

@return string


protected function bindPathsInContainer()
    {
        parent::bindPathsInContainer();

        foreach (['extensions', 'themes', 'assets', 'temp'] as $path) {
            $this->instance('path.'.$path, $this->{$path.'Path'}());
        }
    }

protected function bindPathsInContainer ( ) { parent :: bindPathsInContainer ( ) ; foreach ( [ 'extensions' , 'themes' , 'assets' , 'temp' ] as $ path ) { $ this -> instance ( 'path.' . $ path , $ this -> { $ path . 'Path' } ( ) ) ; } }

Bind all of the application paths in the container.

@return void

Bind all of the application paths in the container .


public function hasDatabase()
    {
        try {
            $hasDatabase = is_null($this->hasDatabase)
                ? $this['db.connection']->getSchemaBuilder()->hasTable('settings')
                : $this->hasDatabase;
        }
        catch (Exception $ex) {
            $hasDatabase = FALSE;
        }

        return $this->hasDatabase = $hasDatabase;
    }

public function hasDatabase ( ) { try { $ hasDatabase = is_null ( $ this -> hasDatabase ) ? $ this [ 'db.connection' ] -> getSchemaBuilder ( ) -> hasTable ( 'settings' ) : $ this -> hasDatabase ; } catch ( Exception $ ex ) { $ hasDatabase = FALSE ; } return $ this -> hasDatabase = $ hasDatabase ; }

Returns true if a database connection is present.
@return boolean

Returns true if a database connection is present .


protected function register()
    {
        /** @var \Phalcon\Config|\stdClass $config */
        $config = $this->getDI()->getShared(Services::CONFIG)->log;

        $adapter = isset($config->adapter) ? $config->adapter : null;
        switch ($adapter) {
            case null:
            case FileLoggerAdapter::class:
            case 'File':
                $adapter = FileLoggerAdapter::class;

                $name = isset($config->path) ? $config->path :  null;
                break;

            case 'Firelogger':
            case 'Stream':
            case 'Syslog':
            case 'Udplogger':
                $adapter = '\Phalcon\Logger\Adapter\\' . ucfirst($adapter);

                $name = isset($config->name) ? $config->name :  'phalcon';
                break;
            default:
                if(!class_exists($adapter)){
                    throw new \RuntimeException("Logger adapter $adapter not implemented.");
                }

                $name = isset($config->name) ? $config->name : (isset($config->path) ? $config->path : 'phalcon');
        }

        if (empty($name)) {
            throw new \RuntimeException('Required parameter {name|path} missing.');
        }

        if (empty($config->options)) {
            throw new \RuntimeException('Required parameter {options} missing.');
        }

        return new $adapter($name, (array)$config->options);
    }

Register the logger

@return \Phalcon\Logger\AdapterInterface


public function boot()
    {
        $this->loadViewsFrom(__DIR__.'/resources/views', 'notifications');

        if ($this->app->runningInConsole()) {
            $this->publishes([
                __DIR__.'/resources/views' => $this->app->resourcePath('views/vendor/notifications'),
            ], 'laravel-notifications');
        }
    }

public function boot ( ) { $ this -> loadViewsFrom ( __DIR__ . '/resources/views' , 'notifications' ) ; if ( $ this -> app -> runningInConsole ( ) ) { $ this -> publishes ( [ __DIR__ . '/resources/views' => $ this -> app -> resourcePath ( 'views/vendor/notifications' ) , ] , 'laravel-notifications' ) ; } }

Boot the application services.

@return void


protected function fillableFromArray(array $attributes)
    {
        if (count($this->getFillable()) > 0) {
            return array_intersect_key($attributes, array_flip(
                array_merge(['fileName'], $this->getFillable())
            ));
        }

        return $attributes;
    }

protected function fillableFromArray ( array $ attributes ) { if ( count ( $ this -> getFillable ( ) ) > 0 ) { return array_intersect_key ( $ attributes , array_flip ( array_merge ( [ 'fileName' ] , $ this -> getFillable ( ) ) ) ) ; } return $ attributes ; }

Get the fillable attributes of a given array.

@param  array $attributes

@return array

Get the fillable attributes of a given array .


public function isFillable($key)
    {
        // File name is always treated as a fillable attribute.
        if ($key === 'fileName') {
            return TRUE;
        }

        // If the key is in the "fillable" array, we can of course assume that it's
        // a fillable attribute. Otherwise, we will check the guarded array when
        // we need to determine if the attribute is black-listed on the model.
        if (in_array($key, $this->getFillable())) {
            return TRUE;
        }

        return empty($this->getFillable()) &&
            !Str::startsWith($key, '_');
    }

Determine if the given attribute may be mass assigned.

@param  string $key

@return bool

Determine if the given attribute may be mass assigned .


public function convert($amount, $from = null, $to = null, $format = TRUE)
    {
        // Get currencies involved
        $from = $from ?: $this->config('default');
        $to = $to ?: $this->getUserCurrency();

        // Get exchange rates
        $from_rate = $this->getCurrencyProp($from, 'currency_rate');
        $to_rate = $this->getCurrencyProp($to, 'currency_rate');

        // Skip invalid to currency rates
        if ($to_rate === null) {
            return null;
        }

        // Convert amount
        $value = $amount * $to_rate * (1 / $from_rate);

        // Should the result be formatted?
        if ($format === TRUE) {
            return $this->format($value, $to);
        }

        // Return value
        return $value;
    }

public
function
convert
(
$
amount
,
$
from
=
,
$
to
=
,
$
format
=
TRUE
)
{
// Get currencies involved
$
from
=
$
from
:
$
this
->
config
(
'default'
)
;
$
to
=
$
to
:
$
this
->
getUserCurrency
(
)
;
// Get exchange rates
$
from_rate
=
$
this
->
getCurrencyProp
(
$
from
,
'currency_rate'
)
;
$
to_rate
=
$
this
->
getCurrencyProp
(
$
to
,
'currency_rate'
)
;
// Skip invalid to currency rates
if
(
$
to_rate
===
)
{
return
;
}
// Convert amount
$
value
=
$
amount
*
$
to_rate
*
(
1
/
$
from_rate
)
;
// Should the result be formatted?
if
(
$
format
===
TRUE
)
{
return
$
this
->
format
(
$
value
,
$
to
)
;
}
// Return value
return
$
value
;
}

Format given number.

@param float $amount
@param string $from
@param string $to
@param bool $format

@return string


public function isActive($code)
    {
        return $code && (bool)Arr::get($this->getCurrency($code), 'currency_status', FALSE);
    }

public function isActive ( $ code ) { return $ code && ( bool ) Arr :: get ( $ this -> getCurrency ( $ code ) , 'currency_status' , FALSE ) ; }

Determine if the provided currency is active.

@param string $code

@return bool

Determine if the provided currency is active .


public function getCurrencies()
    {
        if ($this->currenciesCache === null) {
            if (config('app.debug', FALSE) === TRUE) {
                $this->currenciesCache = $this->getDriver()->all();
            }
            else {
                $this->currenciesCache = $this->cache->rememberForever('igniter.currency', function () {
                    return $this->getDriver()->all();
                });
            }
        }

        return $this->currenciesCache;
    }

public function getCurrencies ( ) { if ( $ this -> currenciesCache === null ) { if ( config ( 'app.debug' , FALSE ) === TRUE ) { $ this -> currenciesCache = $ this -> getDriver ( ) -> all ( ) ; } else { $ this -> currenciesCache = $ this -> cache -> rememberForever ( 'igniter.currency' , function ( ) { return $ this -> getDriver ( ) -> all ( ) ; } ) ; } } return $ this -> currenciesCache ; }


public function registerModules(array $modules, $merge = false)
    {
        if (!empty($this->modules) || !empty($modules)) {
            parent::registerModules(array_merge($this->modules, $modules), $merge);
        }
    }

public function registerModules ( array $ modules , $ merge = false ) { if ( ! empty ( $ this -> modules ) || ! empty ( $ modules ) ) { parent :: registerModules ( array_merge ( $ this -> modules , $ modules ) , $ merge ) ; } }

This methods registers the middlewares to be used by the application

@param array $modules
@param bool  $merge


public function attach(Listener $listener)
    {
        /** @var \Phalcon\Application $this */
        $listener->setDI($this->getDI());

        $listener->setEventsManager($this->getEventsManager());

        $listener->attach();
    }

public
function
attach
(
Listener
$
listener
)
{
/** @var \Phalcon\Application $this */
$
listener
->
setDI
(
$
this
->
getDI
(
)
)
;
$
listener
->
setEventsManager
(
$
this
->
getEventsManager
(
)
)
;
$
listener
->
attach
(
)
;
}

Attach an Listener

@param Listener $listener

@throws \Exception


protected function generateResetCode()
    {
        $random = str_random(42);
        while ($this->newQuery()->where('reset_code', $random)->count() > 0) {
            $random = str_random(42);
        }

        return $random;
    }

protected function generateResetCode ( ) { $ random = str_random ( 42 ) ; while ( $ this -> newQuery ( ) -> where ( 'reset_code' , $ random ) -> count ( ) > 0 ) { $ random = str_random ( 42 ) ; } return $ random ; }

Generate a unique hash for this order.
@return string


public function completeResetPassword($code, $password)
    {
        if (!$this->checkResetPasswordCode($code))
            return FALSE;

        $this->password = $password;
        $this->reset_time = null;
        $this->reset_code = null;

        return $this->save();
    }

public function completeResetPassword ( $ code , $ password ) { if ( ! $ this -> checkResetPasswordCode ( $ code ) ) return FALSE ; $ this -> password = $ password ; $ this -> reset_time = null ; $ this -> reset_code = null ; return $ this -> save ( ) ; }

Sets the new password on user requested reset

@param $code
@param $password

@return bool
@throws \Exception


public function checkResetPasswordCode($resetCode)
    {
        if ($this->reset_code != $resetCode)
            return FALSE;

        $expiration = self::$resetExpiration;
        if ($expiration > 0) {
            if (Carbon::now()->gte($this->reset_time->addMinutes($expiration))) {
                // Reset password request has expired, so clear code.
                $this->clearResetPasswordCode();

                return FALSE;
            }
        }

        return TRUE;
    }

Checks if the provided user reset password code is valid without actually resetting the password.

@param string $resetCode

@return bool

Checks if the provided user reset password code is valid without actually resetting the password .


public function completeActivation($activationCode)
    {
        if ($this->is_activated) {
            throw new Exception('User is already active!');
        }

        if ($activationCode == $this->activation_code) {
            $this->activation_code = null;
            $this->status = TRUE;
            $this->is_activated = TRUE;
            $this->date_activated = $this->freshTimestamp();
            $this->save();

            return TRUE;
        }

        return FALSE;
    }

public
function
completeActivation
(
$
activationCode
)
{
if
(
$
this
->
is_activated
)
{
throw
new
Exception
(
'User is already active!'
)
;
}
if
(
$
activationCode
==
$
this
->
activation_code
)
{
$
this
->
activation_code
=
;
$
this
->
status
=
TRUE
;
$
this
->
is_activated
=
TRUE
;
$
this
->
date_activated
=
$
this
->
freshTimestamp
(
)
;
$
this
->
save
(
)
;
return
TRUE
;
}
return
FALSE
;
}

Attempts to activate the given user by checking the activate code. If the user is activated already, an Exception is thrown.
@param string $activationCode
@return bool

Attempts to activate the given user by checking the activate code . If the user is activated already an Exception is thrown .


public static function ask(Writer $output, $input, Question $question)
    {
        if (!isset($input)) {
            $input = STDIN;
        }

        $output->line('');

        $response = self::prompt($output, $input, $question);

        if (is_null($response) || $response === '') {
            return $question->getDefault();
        }

        return $response;
    }

public static function ask ( Writer $ output , $ input , Question $ question ) { if ( ! isset ( $ input ) ) { $ input = STDIN ; } $ output -> line ( '' ) ; $ response = self :: prompt ( $ output , $ input , $ question ) ; if ( is_null ( $ response ) || $ response === '' ) { return $ question -> getDefault ( ) ; } return $ response ; }

Do the ask of an question

@param \Neutrino\Cli\Output\Writer     $output
@param resource                        $input
@param \Neutrino\Cli\Question\Question $question

@return null|string


public function registerCurrency()
    {
        $this->app->singleton('currency', function ($app) {

            $this->app['events']->fire('currency.beforeRegister', [$this]);

            return new Currency(
                $app->config->get('currency', []),
                $app['cache']
            );
        });
    }

public function registerCurrency ( ) { $ this -> app -> singleton ( 'currency' , function ( $ app ) { $ this -> app [ 'events' ] -> fire ( 'currency.beforeRegister' , [ $ this ] ) ; return new Currency ( $ app -> config -> get ( 'currency' , [ ] ) , $ app [ 'cache' ] ) ; } ) ; }

Register currency provider.

@return void


protected function routeMiddleware()
    {
        $router = $this->router;
        $dispatcher = $this->dispatcher;

        if (!$dispatcher->wasForwarded() && $router->wasMatched()) {
            $actionMethod = $dispatcher->getActionName();

            $route = $router->getMatchedRoute();

            $paths = $route->getPaths();

            if (!empty($paths['middleware'])) {
                $middlewares = $paths['middleware'];

                if (!is_array($middlewares)) {
                    $middlewares = [$middlewares];
                }

                foreach ($middlewares as $key => $middleware) {
                    if (is_int($key)) {
                        $middlewareClass  = $middleware;
                        $middlewareParams = [];
                    } else {
                        $middlewareClass  = $key;
                        $middlewareParams = !is_array($middlewares) ? [$middleware] : $middleware;
                    }

                    $this->middleware($middlewareClass, ...$middlewareParams)->only([$actionMethod]);
                }
            }
        }
    }

protected function routeMiddleware ( ) { $ router = $ this -> router ; $ dispatcher = $ this -> dispatcher ; if ( ! $ dispatcher -> wasForwarded ( ) && $ router -> wasMatched ( ) ) { $ actionMethod = $ dispatcher -> getActionName ( ) ; $ route = $ router -> getMatchedRoute ( ) ; $ paths = $ route -> getPaths ( ) ; if ( ! empty ( $ paths [ 'middleware' ] ) ) { $ middlewares = $ paths [ 'middleware' ] ; if ( ! is_array ( $ middlewares ) ) { $ middlewares = [ $ middlewares ] ; } foreach ( $ middlewares as $ key => $ middleware ) { if ( is_int ( $ key ) ) { $ middlewareClass = $ middleware ; $ middlewareParams = [ ] ; } else { $ middlewareClass = $ key ; $ middlewareParams = ! is_array ( $ middlewares ) ? [ $ middleware ] : $ middleware ; } $ this -> middleware ( $ middlewareClass , ... $ middlewareParams ) -> only ( [ $ actionMethod ] ) ; } } } }

Register middleware was attached in the route.

Register middleware was attached in the route .


protected function middleware($middlewareClass, ...$params)
    {
        $middleware = new $middlewareClass(static::class, ...$params);

        $this->{Services::APP}->attach($middleware);

        return $middleware;
    }

protected function middleware ( $ middlewareClass , ... $ params ) { $ middleware = new $ middlewareClass ( static :: class , ... $ params ) ; $ this -> { Services :: APP } -> attach ( $ middleware ) ; return $ middleware ; }

Attach a ControllerMiddleware.

On controllers, only ControllerMiddleware are attachable,
because the middleware registration, passed by the controller, will made at the controller instantiation.
Because of this, the events
"Application::boot"
"Dispatch::beforeDispatchLoop"
"Dispatch::BeforeDispatch"
can not be caught.

@param string $middlewareClass
@param mixed  ...$params

@return \Neutrino\Foundation\Middleware\Controller


public static function getReflectionClass($class)
    {
        $class = self::toClassName($class);

        if (!isset(self::$cache[$class]['class'])) {
            self::$cache[$class]['class'] = new \ReflectionClass($class);
        }

        return self::$cache[$class]['class'];
    }

public static function getReflectionClass ( $ class ) { $ class = self :: toClassName ( $ class ) ; if ( ! isset ( self :: $ cache [ $ class ] [ 'class' ] ) ) { self :: $ cache [ $ class ] [ 'class' ] = new \ ReflectionClass ( $ class ) ; } return self :: $ cache [ $ class ] [ 'class' ] ; }

Return the reflection class of an object or a class

@param string|object $object

@return \ReflectionClass


public static function set($object, $property, $value)
    {
        $property = self::getReflectionProperty($object, $property);

        if (is_string($object) || $property->isStatic()) {
            if (($declaringClass = $property->getDeclaringClass()->getName()) !== self::toClassName($object)) {
                self::getReflectionProperty($declaringClass, $property->getName())->setValue(null, $value);
                return;
            }

            $property->setValue(null, $value);
            return;
        }

        $property->setValue($object, $value);
    }

public static function set ( $ object , $ property , $ value ) { $ property = self :: getReflectionProperty ( $ object , $ property ) ; if ( is_string ( $ object ) || $ property -> isStatic ( ) ) { if ( ( $ declaringClass = $ property -> getDeclaringClass ( ) -> getName ( ) ) !== self :: toClassName ( $ object ) ) { self :: getReflectionProperty ( $ declaringClass , $ property -> getName ( ) ) -> setValue ( null , $ value ) ; return ; } $ property -> setValue ( null , $ value ) ; return ; } $ property -> setValue ( $ object , $ value ) ; }

Set the value of a property of an object or a class

@param string|object $object
@param string $property
@param mixed  $value


public static function get($object, $property)
    {
        $property = self::getReflectionProperty($object, $property);

        if (is_string($object) || $property->isStatic()) {
            if (($declaringClass = $property->getDeclaringClass()->getName()) !== self::toClassName($object)) {
                return self::getReflectionProperty($declaringClass, $property->getName())->getValue(null);
            }

            return $property->getValue(null);
        }

        return $property->getValue($object);
    }

public static function get ( $ object , $ property ) { $ property = self :: getReflectionProperty ( $ object , $ property ) ; if ( is_string ( $ object ) || $ property -> isStatic ( ) ) { if ( ( $ declaringClass = $ property -> getDeclaringClass ( ) -> getName ( ) ) !== self :: toClassName ( $ object ) ) { return self :: getReflectionProperty ( $ declaringClass , $ property -> getName ( ) ) -> getValue ( null ) ; } return $ property -> getValue ( null ) ; } return $ property -> getValue ( $ object ) ; }

Get the value of a property of an object or a class

@param string|object $object
@param string       $property

@return mixed


public static function invoke($object, $method, ...$params)
    {
        $method = self::getReflectionMethod($object, $method);

        if (is_string($object) || $method->isStatic()) {
            if (($declaringClass = $method->getDeclaringClass()->getName()) !== self::toClassName($object)) {
                return self::getReflectionMethod($declaringClass, $method->getName())->invokeArgs(null, $params);
            }

            return $method->invokeArgs(null, $params);
        }

        return $method->invokeArgs($object, $params);
    }

public static function invoke ( $ object , $ method , ... $ params ) { $ method = self :: getReflectionMethod ( $ object , $ method ) ; if ( is_string ( $ object ) || $ method -> isStatic ( ) ) { if ( ( $ declaringClass = $ method -> getDeclaringClass ( ) -> getName ( ) ) !== self :: toClassName ( $ object ) ) { return self :: getReflectionMethod ( $ declaringClass , $ method -> getName ( ) ) -> invokeArgs ( null , $ params ) ; } return $ method -> invokeArgs ( null , $ params ) ; } return $ method -> invokeArgs ( $ object , $ params ) ; }

Invoke a method of an object or a class

Don't support reference variables.

@param string|object $object
@param string       $method
@param array        ...$params

@return mixed


public function save($keyName = null, $content = null, $lifetime = null, $stopBuffer = true)
    {
        return $this->uses()->save($keyName, $content, $lifetime, $stopBuffer);
    }

public function save ( $ keyName = null , $ content = null , $ lifetime = null , $ stopBuffer = true ) { return $ this -> uses ( ) -> save ( $ keyName , $ content , $ lifetime , $ stopBuffer ) ; }

Stores cached content into the file backend and stops the frontend

@param int|string $keyName
@param string     $content
@param int        $lifetime
@param boolean    $stopBuffer

@return bool


public function exists($keyName = null, $lifetime = null)
    {
        return $this->uses()->exists($keyName, $lifetime);
    }

public function exists ( $ keyName = null , $ lifetime = null ) { return $ this -> uses ( ) -> exists ( $ keyName , $ lifetime ) ; }

Checks if cache exists and it hasn't expired

@param string $keyName
@param int    $lifetime

@return boolean

Checks if cache exists and it hasn t expired


protected function getUserCurrency(Request $request)
    {
        // Check request for currency
        $currency = $request->get('currency');
        if ($currency && currency()->isActive($currency) === TRUE) {
            return $currency;
        }

        // Get currency from session
        $currency = $request->getSession()->get('igniter.currency');
        if ($currency && currency()->isActive($currency) === TRUE) {
            return $currency;
        }

        return null;
    }

protected
function
getUserCurrency
(
Request
$
request
)
{
// Check request for currency
$
currency
=
$
request
->
get
(
'currency'
)
;
if
(
$
currency
&&
currency
(
)
->
isActive
(
$
currency
)
===
TRUE
)
{
return
$
currency
;
}
// Get currency from session
$
currency
=
$
request
->
getSession
(
)
->
get
(
'igniter.currency'
)
;
if
(
$
currency
&&
currency
(
)
->
isActive
(
$
currency
)
===
TRUE
)
{
return
$
currency
;
}
return
;
}

Get the user selected currency.

@param Request $request

@return string|null


public function isEqual(CoordinatesInterface $coordinate)
    {
        return bccomp($this->latitude, $coordinate->getLatitude(), $this->getPrecision()) === 0
            AND bccomp($this->longitude, $coordinate->getLongitude(), $this->getPrecision()) === 0;
    }

public function isEqual ( CoordinatesInterface $ coordinate ) { return bccomp ( $ this -> latitude , $ coordinate -> getLatitude ( ) , $ this -> getPrecision ( ) ) === 0 AND bccomp ( $ this -> longitude , $ coordinate -> getLongitude ( ) , $ this -> getPrecision ( ) ) === 0 ; }

Returns a boolean determining coordinates equality
@param  CoordinatesInterface $coordinate
@return boolean


public function render($name = null)
    {
        $args = func_get_args();
        $args[] = config('app.locale');

        return $this->executeCallback(static::class, __FUNCTION__, $args, function () use ($name) {
            $block = $this->prepareQuery($this->createModel())
                ->where('name', $name)
                ->published()
                ->first();

            return $block ? $block->present()->body : '';
        });
    }

public function render ( $ name = null ) { $ args = func_get_args ( ) ; $ args [ ] = config ( 'app.locale' ) ; return $ this -> executeCallback ( static :: class , __FUNCTION__ , $ args , function ( ) use ( $ name ) { $ block = $ this -> prepareQuery ( $ this -> createModel ( ) ) -> where ( 'name' , $ name ) -> published ( ) -> first ( ) ; return $ block ? $ block -> present ( ) -> body : '' ; } ) ; }

Get the content of a block.

@param string $name unique name of the block

@return string html


public function bindEvent($event, $callback, $priority = 0)
    {
        $this->emitterEvents[$event][$priority][] = $callback;
        unset($this->emitterEventSorted[$event]);

        return $this;
    }

public function bindEvent ( $ event , $ callback , $ priority = 0 ) { $ this -> emitterEvents [ $ event ] [ $ priority ] [ ] = $ callback ; unset ( $ this -> emitterEventSorted [ $ event ] ) ; return $ this ; }

Create a new event binding.

@param string $event The event name to listen for
@param callable $callback The callback to call when emitted
@param int $priority

@return static


protected function emitterEventSortEvents($eventName)
    {
        $this->emitterEventSorted[$eventName] = [];

        if (isset($this->emitterEvents[$eventName])) {
            krsort($this->emitterEvents[$eventName]);

            $this->emitterEventSorted[$eventName] = call_user_func_array('array_merge', $this->emitterEvents[$eventName]);
        }
    }

protected function emitterEventSortEvents ( $ eventName ) { $ this -> emitterEventSorted [ $ eventName ] = [ ] ; if ( isset ( $ this -> emitterEvents [ $ eventName ] ) ) { krsort ( $ this -> emitterEvents [ $ eventName ] ) ; $ this -> emitterEventSorted [ $ eventName ] = call_user_func_array ( 'array_merge' , $ this -> emitterEvents [ $ eventName ] ) ; } }

Sort the listeners for a given event by priority.

@param  string $eventName

@return void

Sort the listeners for a given event by priority .


public function unbindEvent($event = null)
    {
        // Multiple events
        if (is_array($event)) {
            foreach ($event as $_event) {
                $this->unbindEvent($_event);
            }

            return;
        }

        if ($event === null) {
            unset($this->emitterSingleEvents);
            unset($this->emitterEvents);
            unset($this->emitterEventSorted);

            return $this;
        }

        if (isset($this->emitterSingleEvents[$event]))
            unset($this->emitterSingleEvents[$event]);

        if (isset($this->emitterEvents[$event]))
            unset($this->emitterEvents[$event]);

        if (isset($this->emitterEventSorted[$event]))
            unset($this->emitterEventSorted[$event]);

        return $this;
    }

public
function
unbindEvent
(
$
event
=
)
{
// Multiple events
if
(
is_array
(
$
event
)
)
{
foreach
(
$
event
as
$
_event
)
{
$
this
->
unbindEvent
(
$
_event
)
;
}
return
;
}
if
(
$
event
===
)
{
unset
(
$
this
->
emitterSingleEvents
)
;
unset
(
$
this
->
emitterEvents
)
;
unset
(
$
this
->
emitterEventSorted
)
;
return
$
this
;
}
if
(
isset
(
$
this
->
emitterSingleEvents
[
$
event
]
)
)
unset
(
$
this
->
emitterSingleEvents
[
$
event
]
)
;
if
(
isset
(
$
this
->
emitterEvents
[
$
event
]
)
)
unset
(
$
this
->
emitterEvents
[
$
event
]
)
;
if
(
isset
(
$
this
->
emitterEventSorted
[
$
event
]
)
)
unset
(
$
this
->
emitterEventSorted
[
$
event
]
)
;
return
$
this
;
}

Destroys an event binding.

@param string $event Event to destroy

@return self


public function fireEvent($event, $params = [], $halt = FALSE)
    {
        if (!is_array($params)) $params = [$params];
        $result = [];

        // Single events
        if (isset($this->emitterSingleEvents[$event])) {
            foreach ($this->emitterSingleEvents[$event] as $callback) {
                $response = call_user_func_array($callback, $params);
                if (is_null($response)) continue;
                if ($halt) return $response;
                $result[] = $response;
            }

            unset($this->emitterSingleEvents[$event]);
        }

        // Recurring events, with priority
        if (isset($this->emitterEvents[$event])) {

            if (!isset($this->emitterEventSorted[$event]))
                $this->emitterEventSortEvents($event);

            foreach ($this->emitterEventSorted[$event] as $callback) {
                $response = call_user_func_array($callback, $params);
                if (is_null($response)) continue;
                if ($halt) return $response;
                $result[] = $response;
            }
        }

        return $halt ? null : $result;
    }

public
function
fireEvent
(
$
event
,
$
params
=
[
]
,
$
halt
=
FALSE
)
{
if
(
!
is_array
(
$
params
)
)
$
params
=
[
$
params
]
;
$
result
=
[
]
;
// Single events
if
(
isset
(
$
this
->
emitterSingleEvents
[
$
event
]
)
)
{
foreach
(
$
this
->
emitterSingleEvents
[
$
event
]
as
$
callback
)
{
$
response
=
call_user_func_array
(
$
callback
,
$
params
)
;
if
(
is_null
(
$
response
)
)
continue
;
if
(
$
halt
)
return
$
response
;
$
result
[
]
=
$
response
;
}
unset
(
$
this
->
emitterSingleEvents
[
$
event
]
)
;
}
// Recurring events, with priority
if
(
isset
(
$
this
->
emitterEvents
[
$
event
]
)
)
{
if
(
!
isset
(
$
this
->
emitterEventSorted
[
$
event
]
)
)
$
this
->
emitterEventSortEvents
(
$
event
)
;
foreach
(
$
this
->
emitterEventSorted
[
$
event
]
as
$
callback
)
{
$
response
=
call_user_func_array
(
$
callback
,
$
params
)
;
if
(
is_null
(
$
response
)
)
continue
;
if
(
$
halt
)
return
$
response
;
$
result
[
]
=
$
response
;
}
}
return
$
halt
:
$
result
;
}

Fire an event and call the listeners.

@param string $event Event name
@param array $params Event parameters
@param boolean $halt Halt after first non-null result

@return string|array Collection of event results / Or single result (if halted)


public function getDI()
    {
        if (!isset($this->_di)) {
            $this->setDI(Di::getDefault());
        }

        return $this->_di;
    }

public function getDI ( ) { if ( ! isset ( $ this -> _di ) ) { $ this -> setDI ( Di :: getDefault ( ) ) ; } return $ this -> _di ; }

Returns the internal dependency injector

@return DiInterface


public function has($name)
    {
        return isset($this->headers[$name]) || array_key_exists($name, $this->headers);
    }

public function has ( $ name ) { return isset ( $ this -> headers [ $ name ] ) || array_key_exists ( $ name , $ this -> headers ) ; }

Determine if a header exists with a specific key.

@param string $name

@return boolean

Determine if a header exists with a specific key .


public function setHeaders(array $fields, $merge = false)
    {
        if ($merge) {
            $this->headers = array_merge($this->headers, $fields);
        } else {
            $this->headers = $fields;
        }

        return $this;
    }

public function setHeaders ( array $ fields , $ merge = false ) { if ( $ merge ) { $ this -> headers = array_merge ( $ this -> headers , $ fields ) ; } else { $ this -> headers = $ fields ; } return $ this ; }

Set multiple headers.

<code>
$headers = [
'X-Foo' => 'bar',
'Content-Type' => 'application/json',
];

$curl->addMultiple($headers);
</code>

@param array $fields
@param bool $merge

@return $this


public function build()
    {
        $headers = [];

        foreach ($this->headers as $name => $value) {
            $headers[] = $name . ': ' . $value;
        }

        return $headers;
    }

public
function
build
(
)
{
$
headers
=
[
]
;
foreach
(
$
this
->
headers
as
$
name
=>
$
value
)
{
$
headers
[
]
=
$
name
.
': '
.
$
value
;
}
return
$
headers
;
}

Return the header builded for the HTTP Request

@return array


public static function checkCoordinatesEllipsoid(CoordinatesInterface $a, CoordinatesInterface $b)
    {
        if ($a->getEllipsoid() != $b->getEllipsoid()) {
            throw new GeoliteException('The ellipsoids for both coordinates must match !');
        }
    }

Check if coordinates have the same ellipsoid.

@param \Igniter\Flame\Geolite\Contracts\CoordinatesInterface $a A coordinate.
@param \Igniter\Flame\Geolite\Contracts\CoordinatesInterface $b A coordinate.

@throws \Igniter\Flame\Geolite\Exception\GeoliteException

Check if coordinates have the same ellipsoid .