protected function getFiltersAsArray()
    {
        $filters = $this->getSession('filters');

        foreach ($filters as $key => $value) {
            if ($value instanceof ArrayCollection) {
                $filters[$key] = $filters[$key]->map(
                    function ($entity) {
                        return $entity->getId();
                    }
                )->toArray();

            } else if (is_array($value)) {
                foreach ($value as $_key => $_value) {
                    if ($this->filterIsEntity($_value)) {
                        $filters[$key][$_key] = $_value->getId();
                    }
                }

            } else if ($this->filterIsEntity($value)) {
                $filters[$key] = $value->getId();
            }
        }

        return $filters;
    }

protected function getFiltersAsArray ( ) { $ filters = $ this -> getSession ( 'filters' ) ; foreach ( $ filters as $ key => $ value ) { if ( $ value instanceof ArrayCollection ) { $ filters [ $ key ] = $ filters [ $ key ] -> map ( function ( $ entity ) { return $ entity -> getId ( ) ; } ) -> toArray ( ) ; } else if ( is_array ( $ value ) ) { foreach ( $ value as $ _key => $ _value ) { if ( $ this -> filterIsEntity ( $ _value ) ) { $ filters [ $ key ] [ $ _key ] = $ _value -> getId ( ) ; } } } else if ( $ this -> filterIsEntity ( $ value ) ) { $ filters [ $ key ] = $ value -> getId ( ) ; } } return $ filters ; }

Retrieves the filters from the session as an array,
possibly multi dimensional.
It will try to

@return array

Retrieves the filters from the session as an array possibly multi dimensional . It will try to


public function createForm(array $formOptions = [])
    {
        $defaults = $this->filterDefaults();

        $this->form = $this->formFactory->create(
            $this->formType,
            $defaults,
            $formOptions
        );
        if ($this->request) {
            $this->form->handleRequest($this->request);
        }

        return $this->form;
    }

public function createForm ( array $ formOptions = [ ] ) { $ defaults = $ this -> filterDefaults ( ) ; $ this -> form = $ this -> formFactory -> create ( $ this -> formType , $ defaults , $ formOptions ) ; if ( $ this -> request ) { $ this -> form -> handleRequest ( $ this -> request ) ; } return $ this -> form ; }

Creates the filter form and pulls the filter values from request.

@param array $formOptions Options to pass to the form.
@return \Symfony\Component\Form\FormInterface

Creates the filter form and pulls the filter values from request .


public function storeResult($idOnlyQb)
    {
        $result = $idOnlyQb->getQuery()->getArrayResult();

        $resultIds = array_column($result, 'id');

        $this->mergeSession(['ids' => $resultIds]);
    }

public function storeResult ( $ idOnlyQb ) { $ result = $ idOnlyQb -> getQuery ( ) -> getArrayResult ( ) ; $ resultIds = array_column ( $ result , 'id' ) ; $ this -> mergeSession ( [ 'ids' => $ resultIds ] ) ; }

Stores the full list of record IDs in the session.

@param  \Doctrine\ORM\QueryBuilder $idOnlyQb The query builder

@return void

Stores the full list of record IDs in the session .


public function getPagination($query)
    {
        $pagination = $this->paginator->paginate(
            $query,
            $this->pageFromQuery(),
            $this->getPageLimit()
        );

        return $pagination;
    }

public function getPagination ( $ query ) { $ pagination = $ this -> paginator -> paginate ( $ query , $ this -> pageFromQuery ( ) , $ this -> getPageLimit ( ) ) ; return $ pagination ; }

Returns the configured KNP Paginator instance.

@param  \Doctrine\ORM\Query $query The query

@return \Knp\Component\Pager\Pagination\PaginationInterface

Returns the configured KNP Paginator instance .


public function prevNext($currentRecordId)
    {
        $recordIds = (array) $this->getSession('ids');
        $prevRecordId = $nextRecordId = null;

        $currentKey = array_search($currentRecordId, $recordIds);
        if (false !== $currentKey) {
            if ($currentKey > 0) {
                $prevRecordId = $recordIds[$currentKey - 1];
            }
            if ($currentKey < count($recordIds) - 1) {
                $nextRecordId = $recordIds[$currentKey + 1];
            }
        }

        return [$prevRecordId, $nextRecordId];
    }

public function prevNext ( $ currentRecordId ) { $ recordIds = ( array ) $ this -> getSession ( 'ids' ) ; $ prevRecordId = $ nextRecordId = null ; $ currentKey = array_search ( $ currentRecordId , $ recordIds ) ; if ( false !== $ currentKey ) { if ( $ currentKey > 0 ) { $ prevRecordId = $ recordIds [ $ currentKey - 1 ] ; } if ( $ currentKey < count ( $ recordIds ) - 1 ) { $ nextRecordId = $ recordIds [ $ currentKey + 1 ] ; } } return [ $ prevRecordId , $ nextRecordId ] ; }

Finds the previous and next IDs in the record list.
Returns an array with the first key as the previous
and second key as the next system ID.
Either key can be NULL if there is no previous or next.

@param  int $currentRecordId The current record ID

@return array

Finds the previous and next IDs in the record list . Returns an array with the first key as the previous and second key as the next system ID . Either key can be NULL if there is no previous or next .


public function toArray()
    {
        return [
            'icon' => $this->icon,
            'title' => $this->title,
            'subtitle' => $this->subtitle,
            'fields' => $this->fields->map(function ($field) {
                return $field->toArray();
            })->all(),
            'query' => $this->query,
        ];
    }

public function toArray ( ) { return [ 'icon' => $ this -> icon , 'title' => $ this -> title , 'subtitle' => $ this -> subtitle , 'fields' => $ this -> fields -> map ( function ( $ field ) { return $ field -> toArray ( ) ; } ) -> all ( ) , 'query' => $ this -> query , ] ; }

Gets all support data in an array.

@return array


private function addField(array $args, $type = null)
    {
        if (count($args) !== 2) {
            throw new InvalidFieldParametersException('You need pass only name, and title parameters to field');
        }

        return $this->fields->put($args[0], new Field($this, $args[0], $type, $args[1]));
    }

Put a field object in the collection.

@param array  $args
@param string $type

@throws InvalidFieldParametersException

@return Field


protected function processOptions(InputInterface $input)
    {

        if ($this->getContainer()->offsetExists('dbs')) {
            $params = $this->getContainer()['dbs'][$input->getOption('connection')]
                ->getParams();
            $this->getHelperSet()->set(
                new ConnectionHelper(
                    $this->getContainer()['dbs'][$input->getOption('connection')],
                    'db'
                )
            );
        } else {
            $params = $this->getHelper('db')->getConnection()->getParams();
        }

        if ($input->getOption('user') != null) {
            $params['user'] = $input->getOption('user');
            $params['password'] = $input->getOption('password');
        }

        unset($params['dbname']);
        unset($params['path']);

        $this->setConnection(DriverManager::getConnection($params));
    }

protected function processOptions ( InputInterface $ input ) { if ( $ this -> getContainer ( ) -> offsetExists ( 'dbs' ) ) { $ params = $ this -> getContainer ( ) [ 'dbs' ] [ $ input -> getOption ( 'connection' ) ] -> getParams ( ) ; $ this -> getHelperSet ( ) -> set ( new ConnectionHelper ( $ this -> getContainer ( ) [ 'dbs' ] [ $ input -> getOption ( 'connection' ) ] , 'db' ) ) ; } else { $ params = $ this -> getHelper ( 'db' ) -> getConnection ( ) -> getParams ( ) ; } if ( $ input -> getOption ( 'user' ) != null ) { $ params [ 'user' ] = $ input -> getOption ( 'user' ) ; $ params [ 'password' ] = $ input -> getOption ( 'password' ) ; } unset ( $ params [ 'dbname' ] ) ; unset ( $ params [ 'path' ] ) ; $ this -> setConnection ( DriverManager :: getConnection ( $ params ) ) ; }

Processes input options, sets connection without database selected.
If default connection change overrides existing connection helper.
@param InputInterface $input Console input instance
@throws \Doctrine\DBAL\DBALException
@return void

Processes input options sets connection without database selected . If default connection change overrides existing connection helper .


protected function getConnectionParams($connectionName = null)
    {
        return ($connectionName != null ) ?
            $this->getContainer()['dbs'][$connectionName]->getParams():
            $this->getHelper('db')->getConnection()->getParams();
    }

protected function getConnectionParams ( $ connectionName = null ) { return ( $ connectionName != null ) ? $ this -> getContainer ( ) [ 'dbs' ] [ $ connectionName ] -> getParams ( ) : $ this -> getHelper ( 'db' ) -> getConnection ( ) -> getParams ( ) ; }

Gets connection params
@param string|null $connectionName Connection name like 'default'
@return array


public function isInstalled($db_name)
    {
        if (empty($dbname)) $dbname='default';
        return file_exists(CarteBlanche::getFullPath('db_dir') . CarteBlanche::getConfig($dbname.'_database.db_name'));
    }

public function isInstalled ( $ db_name ) { if ( empty ( $ dbname ) ) $ dbname = 'default' ; return file_exists ( CarteBlanche :: getFullPath ( 'db_dir' ) . CarteBlanche :: getConfig ( $ dbname . '_database.db_name' ) ) ; }


public function getSql()
    {
        if ($this->adapter === null) {
            $msg = __METHOD__ . ": Error, prior to use execute method you must provide a valid database adapter. See Select::setDbAdapter() method.";
            throw new Exception\InvalidUsageException($msg);
        }
        $sql = new Sql($this->adapter);
        return $sql->getSqlStringForSqlObject($this);
    }

Return an sql string accordingly to the internat database adapter

@throws Exception\InvalidUsageException
@return string


public function execute()
    {
        if ($this->adapter === null) {
            $msg = __METHOD__ . ": Error, prior to use execute method you must provide a valid database adapter. See Select::setDbAdapter() method.";
            throw new Exception\InvalidUsageException($msg);
        }
        $sql = new Sql($this->adapter);
        $sql_string = $sql->getSqlStringForSqlObject($this);

        //return $this->adapter->createStatement($sql_string)->execute();
        //return $this->adapter->query($sql_string, Adapter::QUERY_MODE_EXECUTE);
        $result = $this->adapter->getDriver()->getConnection()->execute($sql_string);
        $resultset = new ResultSet();
        $resultset->initialize($result);
        return $resultset;
    }

Execute the query and return a Zend\Db\Resultset\ResultSet object

@throws Exception\InvalidUsageException
@return \Zend\Db\ResultSet\ResultSet

Execute the query and return a Zend \ Db \ Resultset \ ResultSet object


public function getRepository(string $entity): Repository
    {
        if (isset($this->repositories[$entity])) {
            return $this->repositories[$entity];
        }

        /** @var Entity|string $entity */
        $repository = $entity::getRepository() ?? PDORepository::class;

        return $this->repositories[$entity] = new $repository($this, $entity, $entity::getTable());
    }

public
function
getRepository
(
string
$
entity
)
:
Repository
{
if
(
isset
(
$
this
->
repositories
[
$
entity
]
)
)
{
return
$
this
->
repositories
[
$
entity
]
;
}
/** @var Entity|string $entity */
$
repository
=
$
entity
::
getRepository
(
)
??
PDORepository
::
class
;
return
$
this
->
repositories
[
$
entity
]
=
new
$
repository
(
$
this
,
$
entity
,
$
entity
::
getTable
(
)
)
;
}

Get a repository instance.

@param string $entity

@return Repository


public function create(Entity $entity): void
    {
        $id = spl_object_id($entity);

        $this->createModels[$id] = $entity;
    }

public function create ( Entity $ entity ) : void { $ id = spl_object_id ( $ entity ) ; $ this -> createModels [ $ id ] = $ entity ; }

Set a model for creation on transaction commit.

@param \Valkyrja\ORM\Entity $entity

@return void

Set a model for creation on transaction commit .


public function save(Entity $entity): void
    {
        $id = spl_object_id($entity);

        $this->saveModels[$id] = $entity;
    }

public function save ( Entity $ entity ) : void { $ id = spl_object_id ( $ entity ) ; $ this -> saveModels [ $ id ] = $ entity ; }

Set a model for saving on transaction commit.

@param Entity $entity

@return void

Set a model for saving on transaction commit .


public function remove(Entity $entity): bool
    {
        // Get the id of the object
        $id = spl_object_id($entity);

        // If the model is set to be created
        if (isset($this->createModels[$id])) {
            // Unset it
            unset($this->createModels[$id]);

            return true;
        }

        // If the model is set to be saved
        if (isset($this->saveModels[$id])) {
            // Unset it
            unset($this->saveModels[$id]);

            return true;
        }

        // The model wasn't set for creation or saving
        return false;
    }

Remove a model previously set for creation or save.

@param \Valkyrja\ORM\Entity $entity The entity instance to remove.

@return bool

Remove a model previously set for creation or save .


public function commit(): bool
    {
        // Iterate through the models awaiting creation
        foreach ($this->createModels as $cid => $createModel) {
            // Create the model
            $this->getRepository(\get_class($createModel))->create($createModel);
            // Unset the model
            unset($this->createModels[$cid]);
        }

        // Iterate through the models awaiting save
        foreach ($this->saveModels as $sid => $saveModel) {
            // Save the model
            $this->getRepository(\get_class($saveModel))->save($saveModel);
            // Unset the model
            unset($this->saveModels[$sid]);
        }

        return $this->store()->commit();
    }

Commit all items in the transaction.

@throws InvalidArgumentException
@throws InvalidEntityException

@return bool


protected function getStore(string $name = null): PDO
    {
        $name = $name ?? $this->app->config()['database']['default'];

        if (isset($this->stores[$name])) {
            return $this->stores[$name];
        }

        $config = $this->getStoreConfig($name);

        return $this->stores[$name] = $this->getStoreFromConfig($config);
    }

protected function getStore ( string $ name = null ) : PDO { $ name = $ name ?? $ this -> app -> config ( ) [ 'database' ] [ 'default' ] ; if ( isset ( $ this -> stores [ $ name ] ) ) { return $ this -> stores [ $ name ] ; } $ config = $ this -> getStoreConfig ( $ name ) ; return $ this -> stores [ $ name ] = $ this -> getStoreFromConfig ( $ config ) ; }

Get a pdo store by name.

@param string|null $name

@throws InvalidArgumentException

@return PDO


protected function getStoreConfig(string $name): array
    {
        $config = $this->app->config('database.connections.' . $name);

        if (null === $config) {
            throw new InvalidArgumentException('Invalid connection name specified: ' . $name);
        }

        return $config;
    }

protected
function
getStoreConfig
(
string
$
name
)
:
array
{
$
config
=
$
this
->
app
->
config
(
'database.connections.'
.
$
name
)
;
if
(
===
$
config
)
{
throw
new
InvalidArgumentException
(
'Invalid connection name specified: '
.
$
name
)
;
}
return
$
config
;
}

Get the store config.

@param string|null $name

@throws InvalidArgumentException

@return array


protected function getStoreFromConfig(array $config): PDO
    {
        $dsn = $config['driver']
            . ':host=' . $config['host']
            . ';port=' . $config['port']
            . ';dbname=' . $config['database']
            . ';charset=' . $config['charset'];

        return new PDO(
            $dsn,
            $config['username'],
            $config['password'],
            []
        );
    }

protected function getStoreFromConfig ( array $ config ) : PDO { $ dsn = $ config [ 'driver' ] . ':host=' . $ config [ 'host' ] . ';port=' . $ config [ 'port' ] . ';dbname=' . $ config [ 'database' ] . ';charset=' . $ config [ 'charset' ] ; return new PDO ( $ dsn , $ config [ 'username' ] , $ config [ 'password' ] , [ ] ) ; }

Get the store from the config.

@param array $config

@return PDO


private function validate($password): void {
    if(strlen($password) < $this->validationMinLength()) {
      throw new InvalidArgumentException("The password must be at least {$this->validationMinLength()} characters long");
    }

    if(strlen($password) > $this->validationMaxLength()) {
      throw new InvalidArgumentException("The password must be no more than {$this->validationMaxLength()} characters long");
    }
  }

Ensures the password is valid

@throws  InvalidArgumentException  If the password is not valid

@param  string  $password  The password to validate

@return  void


public static function from($accept = null, $acceptLanguage = null, $acceptEncoding = null, $acceptCharset = null)
    {
        $medias = static::parse($accept, '/');
        $languages = static::parse($acceptLanguage, '-');
        $encodings = static::parse($acceptEncoding);
        $charsets = static::parse($acceptCharset);

        return new static($medias, $languages, $encodings, $charsets);
    }

public static function from ( $ accept = null , $ acceptLanguage = null , $ acceptEncoding = null , $ acceptCharset = null ) { $ medias = static :: parse ( $ accept , '/' ) ; $ languages = static :: parse ( $ acceptLanguage , '-' ) ; $ encodings = static :: parse ( $ acceptEncoding ) ; $ charsets = static :: parse ( $ acceptCharset ) ; return new static ( $ medias , $ languages , $ encodings , $ charsets ) ; }

Parse from strings

@param string $accept
@param string $acceptLanguage
@param string $acceptEncoding
@param string $acceptCharset

@return static


protected static function parse($string, $separator = null)
    {
        $items = [];
        if($string) {
            $string = strtolower(str_replace(' ', '', $string));
            $rows = explode(',', $string);
            foreach($rows as $row) {
                @list($item, $quality) = explode(';q=', $row);
                if(!$quality) {
                    if($separator) {
                        @list($part, $subpart) = explode($separator, $item);
                        $quality = ($part = '*' or $subpart == '*') ? 0 : 1;
                    }
                    else {
                        $quality = ($item == '*') ? 0 : 1;
                    }
                }
                $items[$item] = (float)$quality;
            }
            sort($items);
            $items = array_keys($items);
        }

        return $items;
    }

protected
static
function
parse
(
$
string
,
$
separator
=
)
{
$
items
=
[
]
;
if
(
$
string
)
{
$
string
=
strtolower
(
str_replace
(
' '
,
''
,
$
string
)
)
;
$
rows
=
explode
(
','
,
$
string
)
;
foreach
(
$
rows
as
$
row
)
{
@
list
(
$
item
,
$
quality
)
=
explode
(
';q='
,
$
row
)
;
if
(
!
$
quality
)
{
if
(
$
separator
)
{
@
list
(
$
part
,
$
subpart
)
=
explode
(
$
separator
,
$
item
)
;
$
quality
=
(
$
part
=
'*'
or
$
subpart
==
'*'
)
0
:
1
;
}
else
{
$
quality
=
(
$
item
==
'*'
)
0
:
1
;
}
}
$
items
[
$
item
]
=
(
float
)
$
quality
;
}
sort
(
$
items
)
;
$
items
=
array_keys
(
$
items
)
;
}
return
$
items
;
}

Accept string parsing

@param string $string
@param string $separator
@return array


protected static function compare($needle, array $haystack)
    {
        foreach($haystack as $row) {
            if(fnmatch($row, $needle)) {
                return true;
            }
        }
        return false;
    }

protected static function compare ( $ needle , array $ haystack ) { foreach ( $ haystack as $ row ) { if ( fnmatch ( $ row , $ needle ) ) { return true ; } } return false ; }

Compare for negociation

@param string $needle
@param array $haystack
@return bool


public function earthRadius($latitude) {
    $radLat = deg2rad($latitude);

    $x = cos($radLat) / $this->earthRadiusSemimajor();
    $y = sin($radLat) / $this->earthRadiusSemiminor();

    return 1 / (sqrt($x * $x + $y * $y));
  }

public function earthRadius ( $ latitude ) { $ radLat = deg2rad ( $ latitude ) ; $ x = cos ( $ radLat ) / $ this -> earthRadiusSemimajor ( ) ; $ y = sin ( $ radLat ) / $ this -> earthRadiusSemiminor ( ) ; return 1 / ( sqrt ( $ x * $ x + $ y * $ y ) ) ; }

Get the radius of the Earth at a specific latitude.

@param float $latitude
The latitude at which to get the radius of the Earth.

@return float
The radius of the Earth at this latitude in meters.

Get the radius of the Earth at a specific latitude .


public function convertDecToDMS($coordinate) {

    $dms = array();
    $parts = explode('.', $coordinate);

    // The degrees portion.
    $dms['degrees'] = $parts[0];

    // Calculate the minutes
    $temp = ("0." . $parts[1]) * 3600;
    $dms['minutes'] = floor($temp / 60);

    // Find the seconds left over
    $dms['seconds'] = $temp - ($dms['minutes'] * 60);

    return $dms;
  }

public
function
convertDecToDMS
(
$
coordinate
)
{
$
dms
=
array
(
)
;
$
parts
=
explode
(
'.'
,
$
coordinate
)
;
// The degrees portion.
$
dms
[
'degrees'
]
=
$
parts
[
0
]
;
// Calculate the minutes
$
temp
=
(
"0."
.
$
parts
[
1
]
)
*
3600
;
$
dms
[
'minutes'
]
=
floor
(
$
temp
/
60
)
;
// Find the seconds left over
$
dms
[
'seconds'
]
=
$
temp
(
$
dms
[
'minutes'
]
*
60
)
;
return
$
dms
;
}

Convert a coordinate into Degree Minute Second format.

@param float $coordinate
The coordinate in decimal format to convert.

@return array
An array with the keys degrees, minutes, and seconds

Convert a coordinate into Degree Minute Second format .


public function convertDMStoDec($degrees, $minutes, $seconds) {
    if ($degrees < 0) {
      return $degrees - ((($minutes * 60) + $seconds) / 3600);
    }

    return $degrees + ((($minutes * 60) + $seconds) / 3600);
  }

public function convertDMStoDec ( $ degrees , $ minutes , $ seconds ) { if ( $ degrees < 0 ) { return $ degrees - ( ( ( $ minutes * 60 ) + $ seconds ) / 3600 ) ; } return $ degrees + ( ( ( $ minutes * 60 ) + $ seconds ) / 3600 ) ; }

Convert Degrees Minutes Seconds to Decimal for a coordinate.

@param int $degrees
@param int $minutes
@param float $seconds

@return float
The coordinate in decimal format.

Convert Degrees Minutes Seconds to Decimal for a coordinate .


public function productionRendering()
    {
        $args   = array('message'=>$this->getAppMessage());
        $ft     = CarteBlanche::getContainer()->get('front_controller');
        return ($ft ? $ft->renderProductionError($args, 500) : parent::__toString());
    }

public function productionRendering ( ) { $ args = array ( 'message' => $ this -> getAppMessage ( ) ) ; $ ft = CarteBlanche :: getContainer ( ) -> get ( 'front_controller' ) ; return ( $ ft ? $ ft -> renderProductionError ( $ args , 500 ) : parent :: __toString ( ) ) ; }

Render of a production error

@return string


public function debugRendering()
    {
        $args   = array('message'=>$this->getAppMessage());
        $ft     = CarteBlanche::getContainer()->get('front_controller');
        return ($ft ? $ft->renderError($args, $this) : parent::__toString());
    }

public function debugRendering ( ) { $ args = array ( 'message' => $ this -> getAppMessage ( ) ) ; $ ft = CarteBlanche :: getContainer ( ) -> get ( 'front_controller' ) ; return ( $ ft ? $ ft -> renderError ( $ args , $ this ) : parent :: __toString ( ) ) ; }


public function log()
    {
        CarteBlanche::log(
            $this->getAppMessage()."\n".$this->getTraceAsString(),
            \Library\Logger::ERROR
        );
    }

public function log ( ) { CarteBlanche :: log ( $ this -> getAppMessage ( ) . "\n" . $ this -> getTraceAsString ( ) , \ Library \ Logger :: ERROR ) ; }

Log the exception in `history.log`

@return void


public function actionConfig(RequestApplicationInterface $app, $filePath)
    {
        $filePath = Reaction::getAlias($filePath);
        if (file_exists($filePath)) {
            $confirmPromise = $this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?");
        } else {
            $confirmPromise = resolve(true);
        }

        return $confirmPromise
            ->then(function() use ($filePath) {
                $array = VarDumper::export($this->getOptionValues($this->getCurrentAction()));
                $content = <<<EOD
<?php
/**
 * Configuration file for 'console {$this->getUniqueId()}/{$this->defaultAction}' command.
 *
 * This file is automatically generated by 'console {$this->getUniqueId()}/{$this->getCurrentAction()}' command.
 * It contains parameters for source code messages extraction.
 * You may modify this file to suit your needs.
 *
 * You can use 'console {$this->getUniqueId()}/{$this->getCurrentAction()}-template' command to create
 * template configuration file with detailed description for each parameter.
 */
return $array;

EOD;
                return FileHelperAsc::exists($filePath)
                    ->then(null, function() use ($filePath) {
                        return FileHelperAsc::create($filePath, $this->filesystemMode);
                    })->then(function() use ($filePath, $content) {
                        return FileHelperAsc::putContents($filePath, $content);
                    })->then(function() use ($filePath) {
                        $this->stdout("Configuration file created: '{$filePath}'.\n\n", Console::FG_GREEN);
                        return true;
                    }, function($error) use ($filePath) {
                        $this->stdout("Configuration file was NOT created: '{$filePath}'.\n\n", Console::FG_RED);
                        return reject($error);
                    });
            });
    }

Creates a configuration file for the "extract" command using command line options specified.

The generated configuration file contains parameters required
for source code messages extraction.
You may use this configuration file with the "extract" command.

@param RequestApplicationInterface $app
@param string                      $filePath output file name or alias.
@return ExtendedPromiseInterface

Creates a configuration file for the extract command using command line options specified .


public function actionConfigTemplate(RequestApplicationInterface $app, $filePath)
    {
        $filePath = Reaction::getAlias($filePath);

        if (file_exists($filePath)) {
            $confirmPromise = $this->confirm("File '{$filePath}' already exists. Do you wish to overwrite it?");
        } else {
            $confirmPromise = resolve(true);
        }

        return $confirmPromise
            ->then(function() use ($filePath) {
                if (!copy(Reaction::getAlias('@reaction/Views/message/config.php'), $filePath)) {
                    return reject(new Exception("Configuration file template was NOT created at '{$filePath}'."));
                }
                $this->stdout("Configuration file template created at '{$filePath}'.\n\n", Console::FG_GREEN);
                return true;
            });
    }

Creates a configuration file template for the "extract" command.

The created configuration file contains detailed instructions on
how to customize it to fit for your needs. After customization,
you may use this configuration file with the "extract" command.

@param RequestApplicationInterface $app
@param string                      $filePath output file name or alias.
@return ExtendedPromiseInterface

Creates a configuration file template for the extract command .


protected function saveMessagesToPHP($messages, $dirName, $overwrite, $removeUnused, $sort, $markUnused)
    {
        $promises = [];
        foreach ($messages as $category => $msgs) {
            $file = str_replace('\\', '/', "$dirName/$category.php");
            $path = dirname($file);
            $msgs = array_values(array_unique($msgs));
            $coloredFileName = Console::ansiFormat($file, [Console::FG_CYAN]);
            $this->stdout("Saving messages to $coloredFileName...\n");
            $promises[] = FileHelperAsc::createDir($path, $this->filesystemMode)
                ->then(function() use ($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused) {
                    return $this->saveMessagesCategoryToPHP($msgs, $file, $overwrite, $removeUnused, $sort, $category, $markUnused);
                });
        }
        return all($promises);
    }

Writes messages into PHP files.

@param array $messages
@param string $dirName name of the directory to write to
@param bool $overwrite if existing file should be overwritten without backup
@param bool $removeUnused if obsolete translations should be removed
@param bool $sort if translations should be sorted
@param bool $markUnused if obsolete translations should be marked
@return ExtendedPromiseInterface


protected function saveMessagesToPOT($messages, $dirName, $catalog)
    {
        $file = str_replace('\\', '/', "$dirName/$catalog.pot");
        FileHelper::createDirectory(dirname($file), $this->filesystemMode);
        $this->stdout("Saving messages to $file...\n");

        $poFile = new GettextPoFile();

        $merged = [];

        $hasSomethingToWrite = false;
        foreach ($messages as $category => $msgs) {
            $msgs = array_values(array_unique($msgs));

            sort($msgs);
            foreach ($msgs as $message) {
                $merged[$category . chr(4) . $message] = '';
            }
            $this->stdout("Category \"$category\" merged.\n");
            $hasSomethingToWrite = true;
        }
        if ($hasSomethingToWrite) {
            return new Promise(function($r, $c) use ($poFile, $merged, $file) {
                ksort($merged);
                $poFile->save($merged, $file);
                $this->stdout("Translation saved.\n", Console::FG_GREEN);
                return true;
            });
        } else {
            $this->stdout("Nothing to save.\n", Console::FG_GREEN);
            return resolve(true);
        }
    }

protected
function
saveMessagesToPOT
(
$
messages
,
$
dirName
,
$
catalog
)
{
$
file
=
str_replace
(
'\\'
,
'/'
,
"$dirName/$catalog.pot"
)
;
FileHelper
::
createDirectory
(
dirname
(
$
file
)
,
$
this
->
filesystemMode
)
;
$
this
->
stdout
(
"Saving messages to $file...\n"
)
;
$
poFile
=
new
GettextPoFile
(
)
;
$
merged
=
[
]
;
$
hasSomethingToWrite
=
false
;
foreach
(
$
messages
as
$
category
=>
$
msgs
)
{
$
msgs
=
array_values
(
array_unique
(
$
msgs
)
)
;
sort
(
$
msgs
)
;
foreach
(
$
msgs
as
$
message
)
{
$
merged
[
$
category
.
chr
(
4
)
.
$
message
]
=
''
;
}
$
this
->
stdout
(
"Category \"$category\" merged.\n"
)
;
$
hasSomethingToWrite
=
true
;
}
if
(
$
hasSomethingToWrite
)
{
return
new
Promise
(
function
(
$
r
,
$
c
)
use
(
$
poFile
,
$
merged
,
$
file
)
{
ksort
(
$
merged
)
;
$
poFile
->
save
(
$
merged
,
$
file
)
;
$
this
->
stdout
(
"Translation saved.\n"
,
Console
::
FG_GREEN
)
;
return
true
;
}
)
;
}
else
{
$
this
->
stdout
(
"Nothing to save.\n"
,
Console
::
FG_GREEN
)
;
return
resolve
(
true
)
;
}
}

Writes messages into POT file.

@param array $messages
@param string $dirName name of the directory to write to
@param string $catalog message catalog
@return ExtendedPromiseInterface


public static function fromArray(array $data): Time
    {
        if (!isset($data['hours'])) {
            throw new \InvalidArgumentException('Array is not valid.');
        }

        return new Time(
            $data['hours'],
            $data['minutes'] ?? 0,
            $data['seconds'] ?? 0
        );
    }

public
static
function
fromArray
(
array
$
data
)
:
Time
{
if
(
!
isset
(
$
data
[
'hours'
]
)
)
{
throw
new
\
InvalidArgumentException
(
'Array is not valid.'
)
;
}
return
new
Time
(
$
data
[
'hours'
]
,
$
data
[
'minutes'
]
??
0
,
$
data
[
'seconds'
]
??
0
)
;
}

Create a new Time from an array.

@param array $data The data.
@return Time


public static function fromString($time): Time
    {
        if (empty($time)) {
            throw new \InvalidArgumentException('Invalid time "".');
        }

        try {
            $date = new \DateTime($time);
        } catch (\Exception $e) {
            throw new \InvalidArgumentException(\sprintf('Invalid time "%s".', $time), 0, $e);
        }

        $return = static::fromDate($date);
        if (\strpos($time, '24') === 0) {
            $return->setHours(24);
        }

        return $return;
    }

public
static
function
fromString
(
$
time
)
:
Time
{
if
(
empty
(
$
time
)
)
{
throw
new
\
InvalidArgumentException
(
'Invalid time "".'
)
;
}
try
{
$
date
=
new
\
DateTime
(
$
time
)
;
}
catch
(
\
Exception
$
e
)
{
throw
new
\
InvalidArgumentException
(
\
sprintf
(
'Invalid time "%s".'
,
$
time
)
,
0
,
$
e
)
;
}
$
return
=
static
::
fromDate
(
$
date
)
;
if
(
\
strpos
(
$
time
,
'24'
)
===
0
)
{
$
return
->
setHours
(
24
)
;
}
return
$
return
;
}

Create a new time from a string.

@param string $time The time as a string.
@return Time
@throws \InvalidArgumentException If the passed time is invalid.


public static function fromDate(\DateTime $date): Time
    {
        return new Time((int)$date->format('H'), (int)$date->format('i'), (int)$date->format('s'));
    }

public static function fromDate ( \ DateTime $ date ) : Time { return new Time ( ( int ) $ date -> format ( 'H' ) , ( int ) $ date -> format ( 'i' ) , ( int ) $ date -> format ( 's' ) ) ; }

Create a new time from a date.

@param \DateTime $date The date.
@return Time


public static function fromSeconds(int $seconds): Time
    {
        if ($seconds < 0 || $seconds > 86400) {
            throw new \InvalidArgumentException(\sprintf('Invalid time "%s".', $seconds));
        }

        $data = [
            'hours' => (int)($seconds / 3600),
            'minutes' => ($seconds / 60) % 60,
            'seconds' => $seconds % 60
        ];

        return self::fromArray($data);
    }

public
static
function
fromSeconds
(
int
$
seconds
)
:
Time
{
if
(
$
seconds
<
0
||
$
seconds
>
86400
)
{
throw
new
\
InvalidArgumentException
(
\
sprintf
(
'Invalid time "%s".'
,
$
seconds
)
)
;
}
$
data
=
[
'hours'
=>
(
int
)
(
$
seconds
/
3600
)
,
'minutes'
=>
(
$
seconds
/
60
)
%
60
,
'seconds'
=>
$
seconds
%
60
]
;
return
self
::
fromArray
(
$
data
)
;
}

Create a new time from seconds.

@param integer $seconds The seconds.
@return Time


public function invalidateTags($tags)
    {
        if (empty($tags) || !$this->isEnabled()) {
            return;
        }

        $tags = $this->encodeTags($tags);

        foreach ($tags as $tag) {
            if (!in_array($tag, $this->invalidateTags)) {
                $this->invalidateTags[] = $tag;
            }
        }
    }

public function invalidateTags ( $ tags ) { if ( empty ( $ tags ) || ! $ this -> isEnabled ( ) ) { return ; } $ tags = $ this -> encodeTags ( $ tags ) ; foreach ( $ tags as $ tag ) { if ( ! in_array ( $ tag , $ this -> invalidateTags ) ) { $ this -> invalidateTags [ ] = $ tag ; } } }


public function flush()
    {
        if (!empty($this->invalidateTags)) {
            $this->tagHandler->invalidateTags($this->invalidateTags);
        }

        if (!empty($this->responseTags)) {
            $this->tagHandler->addTags($this->responseTags);
        }

        $this->reset();
    }

public function flush ( ) { if ( ! empty ( $ this -> invalidateTags ) ) { $ this -> tagHandler -> invalidateTags ( $ this -> invalidateTags ) ; } if ( ! empty ( $ this -> responseTags ) ) { $ this -> tagHandler -> addTags ( $ this -> responseTags ) ; } $ this -> reset ( ) ; }


private function encodeTags($tags)
    {
        if (!is_array($tags)) {
            $tags = array($tags);
        }

        if ($this->config['tag']['encode']) {
            $tmp = [];
            foreach ($tags as $tag) {
                $tmp[] = hash('crc32b', $this->config['tag']['secret'].$tag, false);
            }
            $tags = $tmp;
        }

        return $tags;
    }

private function encodeTags ( $ tags ) { if ( ! is_array ( $ tags ) ) { $ tags = array ( $ tags ) ; } if ( $ this -> config [ 'tag' ] [ 'encode' ] ) { $ tmp = [ ] ; foreach ( $ tags as $ tag ) { $ tmp [ ] = hash ( 'crc32b' , $ this -> config [ 'tag' ] [ 'secret' ] . $ tag , false ) ; } $ tags = $ tmp ; } return $ tags ; }

Encodes the tags.

@param mixed $tags
@return array


public function register()
	{
		$namespace = $this->package->getNamespace();
		$config = $this->app->make('config');

		try
		{
			$path = $this->getPath() . '/config.php';
			if($this->app->environment() === 'testing') {
				if( ! $this->filesystem->exists($path)) {
					return $config->set([
						$namespace => $this->getOptions()
					]);
				}
			}
			return $config->set([
				$namespace => include($path)
			]);
		} catch(\Exception $e) {
			$msg = "You need to publish the configs for the package {$this->package->getName()}";
			$this->error(new PackageConfigMissing($msg));
		}
	}

Register the resources if needed

@return String


public function all(bool $asString = true): array
    {
        if (! $asString) {
            return $this->cookies;
        }

        $flattenedCookies = [];

        /** @var array $path */
        foreach ($this->cookies as $path) {
            /** @var array $cookies */
            foreach ($path as $cookies) {
                /** @var \Valkyrja\Http\Cookie $cookie */
                foreach ($cookies as $cookie) {
                    $flattenedCookies[] = $cookie;
                }
            }
        }

        return $flattenedCookies;
    }

Returns an array with all cookies.

@param bool $asString [optional] Get the cookies as a string?

@return \Valkyrja\Http\Cookie[]


public function set(Cookie $cookie): self
    {
        $this->cookies[$cookie->getDomain()][$cookie->getPath()][$cookie->getName()] = $cookie;

        return $this;
    }

public function set ( Cookie $ cookie ) : self { $ this -> cookies [ $ cookie -> getDomain ( ) ] [ $ cookie -> getPath ( ) ] [ $ cookie -> getName ( ) ] = $ cookie ; return $ this ; }

Set a response cookie.

@param Cookie $cookie The cookie object

@return \Valkyrja\Http\Cookies


public function remove(string $name, string $path = '/', string $domain = null): self
    {
        $path = $path ?? '/';

        unset($this->cookies[$domain][$path][$name]);

        if (empty($this->cookies[$domain][$path])) {
            unset($this->cookies[$domain][$path]);

            if (empty($this->cookies[$domain])) {
                unset($this->cookies[$domain]);
            }
        }

        return $this;
    }

public function remove ( string $ name , string $ path = '/' , string $ domain = null ) : self { $ path = $ path ?? '/' ; unset ( $ this -> cookies [ $ domain ] [ $ path ] [ $ name ] ) ; if ( empty ( $ this -> cookies [ $ domain ] [ $ path ] ) ) { unset ( $ this -> cookies [ $ domain ] [ $ path ] ) ; if ( empty ( $ this -> cookies [ $ domain ] ) ) { unset ( $ this -> cookies [ $ domain ] ) ; } } return $ this ; }

Removes a cookie from the array, but does not unset it in the browser.

@param string $name   Cookie name
@param string $path   [optional] Cookie path
@param string $domain [optional] Cookie domain

@return \Valkyrja\Http\Cookies

Removes a cookie from the array but does not unset it in the browser .


function confirmDialog($params)
    {
        $answers = $prompts = $types = array();
        foreach ($params as $param) {
            $prompts[$param['name']] = $param['prompt'];
            $types[$param['name']]   = $param['type'];
            $answers[$param['name']] = isset($param['default']) ? $param['default'] : '';
        }

        $tried = false;
        do {
            if ($tried) {
                $i = 1;
                foreach ($answers as $var => $value) {
                    if (!strlen($value)) {
                        echo $this->bold("* Enter an answer for #" . $i . ": ({$prompts[$var]})\n");
                    }
                    $i++;
                }
            }

            $answers = $this->userDialog('', $prompts, $types, $answers);
            $tried   = true;
        } while (is_array($answers) && count(array_filter($answers)) != count($prompts));

        return $answers;
    }

function
confirmDialog
(
$
params
)
{
$
answers
=
$
prompts
=
$
types
=
array
(
)
;
foreach
(
$
params
as
$
param
)
{
$
prompts
[
$
param
[
'name'
]
]
=
$
param
[
'prompt'
]
;
$
types
[
$
param
[
'name'
]
]
=
$
param
[
'type'
]
;
$
answers
[
$
param
[
'name'
]
]
=
isset
(
$
param
[
'default'
]
)
$
param
[
'default'
]
:
''
;
}
$
tried
=
false
;
do
{
if
(
$
tried
)
{
$
i
=
1
;
foreach
(
$
answers
as
$
var
=>
$
value
)
{
if
(
!
strlen
(
$
value
)
)
{
echo
$
this
->
bold
(
"* Enter an answer for #"
.
$
i
.
": ({$prompts[$var]})\n"
)
;
}
$
i
++
;
}
}
$
answers
=
$
this
->
userDialog
(
''
,
$
prompts
,
$
types
,
$
answers
)
;
$
tried
=
true
;
}
while
(
is_array
(
$
answers
)
&&
count
(
array_filter
(
$
answers
)
)
!=
count
(
$
prompts
)
)
;
return
$
answers
;
}

Ask for user input, confirm the answers and continue until the user is satisfied
@param array an array of arrays, format array('name' => 'paramname', 'prompt' =>
'text to display', 'type' => 'string'[, default => 'default value'])
@return array

Ask for user input confirm the answers and continue until the user is satisfied


protected function getLabels()
    {
        $pluralName = $this->getPluralName();
        $singularName = $this->getSingularName();

        return array(
            'name' => $singularName,
            'singular_name' => $singularName,
            'add_new' => 'Add New',
            'add_new_item' => 'Add New ' . $singularName,
            'edit_item' => 'Edit ' . $singularName,
            'new_item' => 'New ' . $singularName,
            'all_items' => 'All ' . $pluralName,
            'view_item' => 'View ' . $singularName,
            'search_items' => 'Search ' . $pluralName,
            'not_found' => 'No ' . $pluralName . ' found',
            'not_found_in_trash' => 'No ' . $pluralName . ' found in Trash',
            'parent_item_colon' => '',
            'menu_name' => $pluralName
        );
    }

protected
function
getLabels
(
)
{
$
pluralName
=
$
this
->
getPluralName
(
)
;
$
singularName
=
$
this
->
getSingularName
(
)
;
return
array
(
'name'
=>
$
singularName
,
'singular_name'
=>
$
singularName
,
'add_new'
=>
'Add New'
,
'add_new_item'
=>
'Add New '
.
$
singularName
,
'edit_item'
=>
'Edit '
.
$
singularName
,
'new_item'
=>
'New '
.
$
singularName
,
'all_items'
=>
'All '
.
$
pluralName
,
'view_item'
=>
'View '
.
$
singularName
,
'search_items'
=>
'Search '
.
$
pluralName
,
'not_found'
=>
'No '
.
$
pluralName
.
' found'
,
'not_found_in_trash'
=>
'No '
.
$
pluralName
.
' found in Trash'
,
'parent_item_colon'
=>
''
,
'menu_name'
=>
$
pluralName
)
;
}

Gets the labels used in the args

@return array
@author Tim Perry


public function WrappedSession()
    {
        LivePubHelper::require_session();
        $obj = LivePubHelper::wrap($_SESSION);
        $obj->setVar('_SESSION');
        return $obj;
    }

public function WrappedSession ( ) { LivePubHelper :: require_session ( ) ; $ obj = LivePubHelper :: wrap ( $ _SESSION ) ; $ obj -> setVar ( '_SESSION' ) ; return $ obj ; }

returns a viewable wrapper around the session


public function getTablePrimaryKey($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_PK, $refresh);
    }

public function getTablePrimaryKey ( $ name , $ refresh = false ) { return $ this -> getTableMetadata ( $ name , SchemaInterface :: META_PK , $ refresh ) ; }

Obtains the primary key for the named table.
@param string $name table name. The table name may contain schema name if any. Do not quote the table name.
@param bool $refresh whether to reload the information even if it is found in the cache.
@return Constraint|null table primary key, `null` if the table has no primary key.

Obtains the primary key for the named table .


public function getTableForeignKeys($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_FK, $refresh);
    }

public function getTableForeignKeys ( $ name , $ refresh = false ) { return $ this -> getTableMetadata ( $ name , SchemaInterface :: META_FK , $ refresh ) ; }

Obtains the foreign keys information for the named table.
@param string $name table name. The table name may contain schema name if any. Do not quote the table name.
@param bool $refresh whether to reload the information even if it is found in the cache.
@return ForeignKeyConstraint[] table foreign keys.

Obtains the foreign keys information for the named table .


public function getTableIndexes($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_INDEXES, $refresh);
    }

public function getTableIndexes ( $ name , $ refresh = false ) { return $ this -> getTableMetadata ( $ name , SchemaInterface :: META_INDEXES , $ refresh ) ; }

Obtains the indexes information for the named table.
@param string $name table name. The table name may contain schema name if any. Do not quote the table name.
@param bool $refresh whether to reload the information even if it is found in the cache.
@return IndexConstraint[] table indexes.

Obtains the indexes information for the named table .


public function getTableUniques($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_UNIQUES, $refresh);
    }

public function getTableUniques ( $ name , $ refresh = false ) { return $ this -> getTableMetadata ( $ name , SchemaInterface :: META_UNIQUES , $ refresh ) ; }

Obtains the unique constraints information for the named table.
@param string $name table name. The table name may contain schema name if any. Do not quote the table name.
@param bool $refresh whether to reload the information even if it is found in the cache.
@return Constraint[] table unique constraints.

Obtains the unique constraints information for the named table .


public function getTableChecks($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_CHECKS, $refresh);
    }

public function getTableChecks ( $ name , $ refresh = false ) { return $ this -> getTableMetadata ( $ name , SchemaInterface :: META_CHECKS , $ refresh ) ; }

Obtains the check constraints information for the named table.
@param string $name table name. The table name may contain schema name if any. Do not quote the table name.
@param bool $refresh whether to reload the information even if it is found in the cache.
@return CheckConstraint[] table check constraints.

Obtains the check constraints information for the named table .


public function getTableDefaultValues($name, $refresh = false)
    {
        return $this->getTableMetadata($name, SchemaInterface::META_DEFAULTS, $refresh);
    }

public function getTableDefaultValues ( $ name , $ refresh = false ) { return $ this -> getTableMetadata ( $ name , SchemaInterface :: META_DEFAULTS , $ refresh ) ; }

Obtains the default value constraints information for the named table.
@param string $name table name. The table name may contain schema name if any. Do not quote the table name.
@param bool $refresh whether to reload the information even if it is found in the cache.
@return DefaultValueConstraint[] table default value constraints.

Obtains the default value constraints information for the named table .


public function get($key)
    {
        return $this->container->hasParameter($key) ? $this->container->getParameter($key) : null;
    }

public function get ( $ key ) { return $ this -> container -> hasParameter ( $ key ) ? $ this -> container -> getParameter ( $ key ) : null ; }

Get a setting value.

@param $key string
@return string|null


protected function checkAccess($permission, $arguments = '') {
		if ( $this->acl === false )
			return true;

		$driver = "acl" . ucfirst( $this->driver );

		return $this->$driver($permission, $arguments);
	}

protected function checkAccess ( $ permission , $ arguments = '' ) { if ( $ this -> acl === false ) return true ; $ driver = "acl" . ucfirst ( $ this -> driver ) ; return $ this -> $ driver ( $ permission , $ arguments ) ; }

Will check user access depending on the driver being used.
Defaults to using laravel Auth Guard driver

@param  [string] $permission	Necessary permission to check
@param  [mixed] $arguments	Additional arguments to pass
@return [boolean]

Will check user access depending on the driver being used . Defaults to using laravel Auth Guard driver


public function distinct(bool $enable = true)
    {
        $this->changed = true;
        $this->distinct = $enable;

        return $this;
    }

public function distinct ( bool $ enable = true ) { $ this -> changed = true ; $ this -> distinct = $ enable ; return $ this ; }

Toggle the DISTINCT flag in a SELECT query.

@param bool $enable
@return self

Toggle the DISTINCT flag in a SELECT query .


public function columns(string ...$column)
    {
        $this->changed = true;
        $this->columns = $column;

        return $this;
    }

public function columns ( string ... $ column ) { $ this -> changed = true ; $ this -> columns = $ column ; return $ this ; }

Set the columns for the SELECT query.

@param string $column
@return self


public function join(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['JOIN', $table, $on];

        return $this;
    }

public function join ( string $ table , array $ on ) { $ this -> changed = true ; $ this -> joins [ ] = [ 'JOIN' , $ table , $ on ] ; return $ this ; }

Setup a JOIN table.

@param string $table
@param array $on
@return self


public function innerJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['INNER JOIN', $table, $on];

        return $this;
    }

public
function
innerJoin
(
string
$
table
,
array
$
on
)
{
$
this
->
changed
=
true
;
$
this
->
joins
[
]
=
[
'INNER JOIN'
,
$
table
,
$
on
]
;
return
$
this
;
}

Setup a INNER JOIN table.

@param string $table
@param array $on
@return self


public function leftJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['LEFT JOIN', $table, $on];

        return $this;
    }

public
function
leftJoin
(
string
$
table
,
array
$
on
)
{
$
this
->
changed
=
true
;
$
this
->
joins
[
]
=
[
'LEFT JOIN'
,
$
table
,
$
on
]
;
return
$
this
;
}

Setup a LEFT JOIN table.

@param string $table
@param array $on
@return self


public function leftOuterJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['LEFT OUTER JOIN', $table, $on];

        return $this;
    }

public
function
leftOuterJoin
(
string
$
table
,
array
$
on
)
{
$
this
->
changed
=
true
;
$
this
->
joins
[
]
=
[
'LEFT OUTER JOIN'
,
$
table
,
$
on
]
;
return
$
this
;
}

Setup a LEFT OUTER JOIN table.

@param string $table
@param array $on
@return self


public function rightJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['RIGHT JOIN', $table, $on];

        return $this;
    }

public
function
rightJoin
(
string
$
table
,
array
$
on
)
{
$
this
->
changed
=
true
;
$
this
->
joins
[
]
=
[
'RIGHT JOIN'
,
$
table
,
$
on
]
;
return
$
this
;
}

Setup a RIGHT JOIN table.

@param string $table
@param array $on
@return self


public function outerJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['OUTER JOIN', $table, $on];

        return $this;
    }

public
function
outerJoin
(
string
$
table
,
array
$
on
)
{
$
this
->
changed
=
true
;
$
this
->
joins
[
]
=
[
'OUTER JOIN'
,
$
table
,
$
on
]
;
return
$
this
;
}

Setup a OUTER JOIN table.

@param string $table
@param array $on
@return self


public function fullOuterJoin(string $table, array $on)
    {
        $this->changed = true;
        $this->joins[] = ['FULL OUTER JOIN', $table, $on];

        return $this;
    }

public
function
fullOuterJoin
(
string
$
table
,
array
$
on
)
{
$
this
->
changed
=
true
;
$
this
->
joins
[
]
=
[
'FULL OUTER JOIN'
,
$
table
,
$
on
]
;
return
$
this
;
}

Setup a FULL OUTER JOIN table.

@param string $table
@param array $on
@return self


public function groupBy(string ...$field)
    {
        $this->changed = true;
        $this->groupBy = $field;

        return $this;
    }

public function groupBy ( string ... $ field ) { $ this -> changed = true ; $ this -> groupBy = $ field ; return $ this ; }

Set grouping fields to the query.

@param string $field
@return self


public function andHaving(array $conditions)
    {
        $this->changed = true;
        $this->having = [
            'AND',
            $this->having,
            $conditions,
        ];

        return $this;
    }

public function andHaving ( array $ conditions ) { $ this -> changed = true ; $ this -> having = [ 'AND' , $ this -> having , $ conditions , ] ; return $ this ; }

Add AND conditions for groups in HAVING clauses.

NOTE: Placeholders in HAVING clauses don't work with SQLite, according to
the PHP bug referenced in the @see tag below.

@param array $conditions
@return self
@see https://bugs.php.net/bug.php?id=60281

Add AND conditions for groups in HAVING clauses .


public function orHaving(array $conditions)
    {
        $this->changed = true;
        $this->having = [
            'OR',
            $this->having,
            $conditions,
        ];

        return $this;
    }

public function orHaving ( array $ conditions ) { $ this -> changed = true ; $ this -> having = [ 'OR' , $ this -> having , $ conditions , ] ; return $ this ; }

Add OR conditions for groups in HAVING clauses.

NOTE: Placeholders in HAVING clauses don't work with SQLite, according to
the PHP bug referenced in the @see tag below.

@param array $conditions
@return self
@see https://bugs.php.net/bug.php?id=60281

Add OR conditions for groups in HAVING clauses .


public function orderBy(string ...$field)
    {
        $this->changed = true;
        $this->orderBy = $field;

        return $this;
    }

public function orderBy ( string ... $ field ) { $ this -> changed = true ; $ this -> orderBy = $ field ; return $ this ; }

Setup fields for the ORDER BY clause.

@param string $field
@return self


public function limit(int $limit, int $offset = null)
    {
        $this->changed = true;
        $this->limit = $limit;

        if ($offset !== null) {
            $this->offset = $offset;
        }

        return $this;
    }

public function limit ( int $ limit , int $ offset = null ) { $ this -> changed = true ; $ this -> limit = $ limit ; if ( $ offset !== null ) { $ this -> offset = $ offset ; } return $ this ; }

Set a LIMIT and optional OFFSET.

@param int $limit
@param int|null $offset
@return self


public function offset(int $offset)
    {
        $this->changed = true;
        $this->offset = $offset;

        return $this;
    }

public function offset ( int $ offset ) { $ this -> changed = true ; $ this -> offset = $ offset ; return $ this ; }

Set an OFFSET to the LIMIT clause.

@param int $offset
@return self


protected function build()
    {
        if (!$this->from) {
            throw new \RuntimeException("No tables provided for FROM clause");
        }

        $this->placeholders = [];
        $this->placeholderCounter = 1;

        $sql = ['SELECT'];

        if ($this->distinct) {
            $sql[] = 'DISTINCT';
        }

        $sql[] = implode(', ', $this->columns);

        $sql[] = 'FROM';
        $sql[] = implode(', ', $this->from);

        if ($this->joins) {
            foreach ($this->joins as $join) {
                $sql[] = $join[0];
                $sql[] = $join[1];
                $sql[] = 'ON';
                $sql[] = is_string($join[2])
                       ? $join[2]
                       : $this->buildConditions($join[2], false);
            }
        }

        if ($this->conditions) {
            $sql[] = 'WHERE';
            $sql[] = $this->buildConditions($this->conditions);
        }

        if ($this->groupBy) {
            $sql[] = 'GROUP BY';
            $sql[] = implode(', ', $this->groupBy);
        }

        if ($this->having) {
            $sql[] = 'HAVING';
            $sql[] = $this->buildConditions($this->having);
        }

        if ($this->orderBy) {
            $sql[] = 'ORDER BY';
            $sql[] = implode(', ', $this->orderBy);
        }

        if ($this->limit || $this->offset) {
            $sql[] = 'LIMIT';

            $parts = [];

            if ($this->offset) {
                if (!$this->limit) {
                    $this->limit = PHP_INT_MAX;
                }
                $parts[] = $this->addPlaceholder($this->offset);
            }

            if ($this->limit) {
                $parts[] = $this->addPlaceholder($this->limit);
            }

            $sql[] = implode(', ', $parts);
        }

        $this->sql = implode(' ', $sql);
        $this->changed = false;
    }

protected
function
build
(
)
{
if
(
!
$
this
->
from
)
{
throw
new
\
RuntimeException
(
"No tables provided for FROM clause"
)
;
}
$
this
->
placeholders
=
[
]
;
$
this
->
placeholderCounter
=
1
;
$
sql
=
[
'SELECT'
]
;
if
(
$
this
->
distinct
)
{
$
sql
[
]
=
'DISTINCT'
;
}
$
sql
[
]
=
implode
(
', '
,
$
this
->
columns
)
;
$
sql
[
]
=
'FROM'
;
$
sql
[
]
=
implode
(
', '
,
$
this
->
from
)
;
if
(
$
this
->
joins
)
{
foreach
(
$
this
->
joins
as
$
join
)
{
$
sql
[
]
=
$
join
[
0
]
;
$
sql
[
]
=
$
join
[
1
]
;
$
sql
[
]
=
'ON'
;
$
sql
[
]
=
is_string
(
$
join
[
2
]
)
$
join
[
2
]
:
$
this
->
buildConditions
(
$
join
[
2
]
,
false
)
;
}
}
if
(
$
this
->
conditions
)
{
$
sql
[
]
=
'WHERE'
;
$
sql
[
]
=
$
this
->
buildConditions
(
$
this
->
conditions
)
;
}
if
(
$
this
->
groupBy
)
{
$
sql
[
]
=
'GROUP BY'
;
$
sql
[
]
=
implode
(
', '
,
$
this
->
groupBy
)
;
}
if
(
$
this
->
having
)
{
$
sql
[
]
=
'HAVING'
;
$
sql
[
]
=
$
this
->
buildConditions
(
$
this
->
having
)
;
}
if
(
$
this
->
orderBy
)
{
$
sql
[
]
=
'ORDER BY'
;
$
sql
[
]
=
implode
(
', '
,
$
this
->
orderBy
)
;
}
if
(
$
this
->
limit
||
$
this
->
offset
)
{
$
sql
[
]
=
'LIMIT'
;
$
parts
=
[
]
;
if
(
$
this
->
offset
)
{
if
(
!
$
this
->
limit
)
{
$
this
->
limit
=
PHP_INT_MAX
;
}
$
parts
[
]
=
$
this
->
addPlaceholder
(
$
this
->
offset
)
;
}
if
(
$
this
->
limit
)
{
$
parts
[
]
=
$
this
->
addPlaceholder
(
$
this
->
limit
)
;
}
$
sql
[
]
=
implode
(
', '
,
$
parts
)
;
}
$
this
->
sql
=
implode
(
' '
,
$
sql
)
;
$
this
->
changed
=
false
;
}


public function renderLink($href, $label = '', array $options = [], array $attributes = [])
    {
        $options['type'] = 'link';
        $options['path'] = $href;

        return $this->renderButton($label, $options, $attributes);
    }

public function renderLink ( $ href , $ label = '' , array $ options = [ ] , array $ attributes = [ ] ) { $ options [ 'type' ] = 'link' ; $ options [ 'path' ] = $ href ; return $ this -> renderButton ( $ label , $ options , $ attributes ) ; }

Renders the link.

@param $href
@param string $label
@param array $options
@param array $attributes
@return string


public function renderButton($label = '', array $options = [], array $attributes = [])
    {
        $options = $this->getButtonOptionsResolver()->resolve($options);

        $tag = 'button';
        $classes = ['btn', 'btn-'.$options['theme'], 'btn-'.$options['size']];
        $defaultAttributes = [
        	'class' => sprintf('btn btn-%s btn-%s', $options['theme'], $options['size']),
        ];
        if ($options['type'] == 'link') {
            if (0 == strlen($options['path'])) {
                throw new \InvalidArgumentException('"path" option must be defined for "link" button type.');
            }
            $tag = 'a';
            $defaultAttributes['href'] = $options['path'];
        } else {
            $defaultAttributes['type'] = $options['type'];
        }

        if (array_key_exists('class', $attributes)) {
            $classes = array_merge($classes, explode(' ', $attributes['class']));
            unset($attributes['class']);
        }
        $defaultAttributes['class'] = implode(' ', $classes);
        $attributes = array_merge($defaultAttributes, $attributes);

        $icon = '';
        if(0 < strlen($options['icon'])) {
            $icon = $options['fa_icon'] ? 'fa fa-'.$options['icon'] : 'glyphicon glyphicon-'.$options['icon'];
        }

        return $this->controlsTemplate->renderBlock('button', [
            'tag'   => $tag,
            'attr'  => $attributes,
            'label' => $label,
            'icon'  => $icon,
        ]);
    }

Renders the button.

@param string $label
@param array $options
@param array $attributes
@return string
@throws \InvalidArgumentException


public function renderLocaleSwitcher($attributes = [])
    {
        // TODO Check if this is a (esi) sub request, as this must never be used in a esi fragment.
        if (null === $request = $this->requestStack->getCurrentRequest()) {
            return '';
        }

        if (!array_key_exists('class', $attributes)) {
            $attributes['class'] = 'list-inline locale-switcher';
        }

        return $this->controlsTemplate->renderBlock('locale_switcher', [
            'locales' => $this->config['locales'],
            'request' => $request,
            'attr' => $attributes,
        ]);
    }

Renders the locale switcher.

@param array $attributes
@return string


public function __equationToString()
    {
        $str = '';
        $a = $this->getSlope();
        if ($a!=1) {
            $str .= "({$a} * x)";
        } else {
            $str .= "x";
        }
        $b = $this->getYIntercept();
        if ($b!=0) {
            $str .= " + {$b}";
        }
        return "y = f(x){ {$str} }";
    }

public
function
__equationToString
(
)
{
$
str
=
''
;
$
a
=
$
this
->
getSlope
(
)
;
if
(
$
a
!=
1
)
{
$
str
.=
"({$a} * x)"
;
}
else
{
$
str
.=
"x"
;
}
$
b
=
$
this
->
getYIntercept
(
)
;
if
(
$
b
!=
0
)
{
$
str
.=
" + {$b}"
;
}
return
"y = f(x){ {$str} }"
;
}

Write an algebraic function of the line

y = (a * x) + b

@return  string


public function getOrdinateByAbscissa($x)
    {
        if ($this->isHorizontal()) {
            return $this->getPointA()->getOrdinate();
        }
        return (($this->getSlope() * $x) + $this->getYIntercept());
    }

public function getOrdinateByAbscissa ( $ x ) { if ( $ this -> isHorizontal ( ) ) { return $ this -> getPointA ( ) -> getOrdinate ( ) ; } return ( ( $ this -> getSlope ( ) * $ x ) + $ this -> getYIntercept ( ) ) ; }

Get the ordinate of a point of the line by its abscissa

@param   float   $x
@return  float


public function getAbscissaByOrdinate($y)
    {
        if ($this->isVertical()) {
            return $this->getPointA()->getAbscissa();
        }
        return (($y - $this->getYIntercept()) / $this->getSlope());
    }

public function getAbscissaByOrdinate ( $ y ) { if ( $ this -> isVertical ( ) ) { return $ this -> getPointA ( ) -> getAbscissa ( ) ; } return ( ( $ y - $ this -> getYIntercept ( ) ) / $ this -> getSlope ( ) ) ; }

Get the abscissa of a point of the line by its ordinate

@param   float   $y
@return  float


public function findOrFail($id)
    {
        $record = $this->find($id);
        if ($record === false) {
            throw new Exception\NotFoundException(__METHOD__ . ": cannot find record '$id' in table '$this->table'");
        }
        return $record;
    }

Find a record by primary key, throw a NotFoundException if record does not exists

@param integer|string|array $id

@throws Exception\NotFoundException
@throws Exception\InvalidArgumentException when the id is not valid
@throws Exception\PrimaryKeyNotFoundException

@return Record

Find a record by primary key throw a NotFoundException if record does not exists


public function findOneByOrFail($predicate, $combination = Predicate\PredicateSet::OP_AND)
    {
        $record = $this->findOneBy($predicate, $combination);
        if ($record === false) {
            throw new Exception\NotFoundException(__METHOD__ . ": cannot findOneBy record in table '$this->table'");
        }
        return $record;
    }

Find a record by unique key and trhow an exception id record cannot be found

@param  Where|\Closure|string|array|Predicate\PredicateInterface $predicate
@param  string $combination One of the OP_* constants from Predicate\PredicateSet

@throws Exception\NotFoundException when the record is not found
@throws Exception\ColumnNotFoundException when a column in the predicate does not exists
@throws Exception\MultipleMatchesException when more than one record match the predicate
@throws Exception\InvalidArgumentException when the predicate is not correct / invalid column

@return Record


public function exists($id)
    {
        $result = $this->select()->where($this->getPrimaryKeyPredicate($id))
                        ->columns(['count' => new Expression('count(*)')])
                        ->execute()
                        ->toArray();

        return ($result[0]['count'] > 0);
    }

public function exists ( $ id ) { $ result = $ this -> select ( ) -> where ( $ this -> getPrimaryKeyPredicate ( $ id ) ) -> columns ( [ 'count' => new Expression ( 'count(*)' ) ] ) -> execute ( ) -> toArray ( ) ; return ( $ result [ 0 ] [ 'count' ] > 0 ) ; }

Test if a record exists

@param integer|string|array $id

@throws Exception\InvalidArgumentException when the id is invalid
@throws Exception\PrimaryKeyNotFoundException

@return boolean


public function existsBy($predicate, $combination = Predicate\PredicateSet::OP_AND)
    {
        try {
            $select = $this->select()->where($predicate, $combination)
                    ->columns(['count' => new Expression('count(*)')]);
            $result = $select->execute()
                             ->toArray();
        } catch (\Exception $e) {
            throw new Exception\InvalidArgumentException(__METHOD__ . ": invaid usage ({$e->getMessage()})");
        }

        return ($result[0]['count'] > 0);
    }

public
function
existsBy
(
$
predicate
,
$
combination
=
Predicate
\
PredicateSet
::
OP_AND
)
{
try
{
$
select
=
$
this
->
select
(
)
->
where
(
$
predicate
,
$
combination
)
->
columns
(
[
'count'
=>
new
Expression
(
'count(*)'
)
]
)
;
$
result
=
$
select
->
execute
(
)
->
toArray
(
)
;
}
catch
(
\
Exception
$
e
)
{
throw
new
Exception
\
InvalidArgumentException
(
__METHOD__
.
": invaid usage ({$e->getMessage()})"
)
;
}
return
(
$
result
[
0
]
[
'count'
]
>
0
)
;
}

Test if a record exists by a predicate

@param  Where|\Closure|string|array|Predicate\PredicateInterface $predicate
@param  string $combination One of the OP_* constants from Predicate\PredicateSet

@throws Exception\InvalidArgumentException when the predicate is not correct

@return boolean


public function deleteBy($predicate, $combination = Predicate\PredicateSet::OP_AND)
    {
        $delete = $this->sql->delete($this->prefixed_table)
                ->where($predicate, $combination);

        $statement = $this->sql->prepareStatementForSqlObject($delete);
        $result = $statement->execute();
        return $result->getAffectedRows();
    }

public function deleteBy ( $ predicate , $ combination = Predicate \ PredicateSet :: OP_AND ) { $ delete = $ this -> sql -> delete ( $ this -> prefixed_table ) -> where ( $ predicate , $ combination ) ; $ statement = $ this -> sql -> prepareStatementForSqlObject ( $ delete ) ; $ result = $ statement -> execute ( ) ; return $ result -> getAffectedRows ( ) ; }

Delete a record by predicate

@param  Where|\Closure|string|array|Predicate\PredicateInterface $predicate
@param  string $combination One of the OP_* constants from Predicate\PredicateSet

@return integer the number of affected rows (can be be influenced by triggers or cascade)


public function deleteOrFail($id)
    {
        $deleted = $this->delete($id);
        if ($deleted == 0) {
            throw new Exception\NotFoundException(__METHOD__ . ": cannot delete record '$id' in table '$this->table'");
        }
        return $this;
    }

Delete a record or throw an Exception

@param integer|string|array $id primary key value

@throws Exception\InvalidArgumentException if $id is not valid
@throws Exception\NotFoundException if record does not exists

@return Table


public function update($data, $predicate, $combination = Predicate\PredicateSet::OP_AND, $validate_datatypes = false)
    {
        $prefixed_table = $this->prefixed_table;

        if ($data instanceof ArrayObject) {
            $d = (array) $data;
        } elseif (is_array($data)) {
            $d = $data;
        } else {
            throw new Exception\InvalidArgumentException(__METHOD__ . ": requires data to be array or an ArrayObject");
        }

        $this->checkDataColumns($d);

        if ($validate_datatypes) {
            $this->validateDatatypes($d);
        }

        $update = $this->sql->update($prefixed_table);
        $update->set($d);
        $update->where($predicate, $combination);

        $result = $this->executeStatement($update);

        return  $result->getAffectedRows();
    }

Update data into table

@param array|ArrayObject $data
@param  Where|\Closure|string|array|Predicate\PredicateInterface $predicate
@param  string $combination One of the OP_* constants from Predicate\PredicateSet
@param  boolean $validate_datatypes ensure all datatype are compatible with column definition

@throws Exception\InvalidArgumentException
@throws Exception\ColumnNotFoundException when $data contains columns that does not exists in table
@throws Exception\ForeignKeyException when insertion failed because of an invalid foreign key
@throws Exception\DuplicateEntryException when insertion failed because of an invalid foreign key
@throws Exception\NotNullException when insertion failed because a column cannot be null
@throws Exception\RuntimeException when insertion failed for another reason

@return int number of affected rows


public function insert($data, $validate_datatypes = false)
    {
        $prefixed_table = $this->prefixed_table;

        if ($data instanceof \ArrayObject) {
            $d = (array) $data;
        } elseif (is_array($data)) {
            $d = $data;
        } else {
            $type = gettype($data);
            throw new Exception\InvalidArgumentException(__METHOD__ . ": expects data to be array or ArrayObject. Type receive '$type'");
        }

        $this->checkDataColumns($d);

        if ($validate_datatypes) {
            $this->validateDatatypes($d);
        }

        $insert = $this->sql->insert($prefixed_table);
        $insert->values($d);

        $this->executeStatement($insert);

        $pks = $this->getPrimaryKeys();

        // Should never happen, as getPrimaryKeys throws Exception when no pk exists
        //@codeCoverageIgnoreStart
        if (!is_array($pks)) {
            $msg = __METHOD__ . " Error getting primary keys of table " . $this->table . ", require array, returned type is: " . gettype($pks) ;
            throw new Exception\UnexpectedValueException($msg);
        }
        //@codeCoverageIgnoreEnd

        $nb_pks = count($pks);
        if ($nb_pks > 1) {
            // In multiple keys there should not be autoincrement value
            $id = [];
            foreach ($pks as $pk) {
                $id[$pk] = $d[$pk];
            }
        } elseif (array_key_exists($pks[0], $d) && $d[$pks[0]] !== null) {
            // not using autogenerated value
            //$id = $d[$this->getPrimaryKey()];
            $id = $d[$pks[0]];
        } else {
            $id = $this->tableManager->getDbAdapter()->getDriver()->getLastGeneratedValue();
        }

        return $this->findOrFail($id);
    }

Insert data into table

@param array|ArrayObject $data
@param boolean $validate_datatypes ensure data are compatible with database columns datatypes

@throws Exception\InvalidArgumentException when data is not an array or an ArrayObject
@throws Exception\ColumnNotFoundException when $data contains columns that does not exists in table
@throws Exception\ForeignKeyException when insertion failed because of an invalid foreign key
@throws Exception\DuplicateEntryException when insertion failed because of an invalid foreign key
@throws Exception\NotNullException when insertion failed because a column cannot be null
@throws Exception\RuntimeException when insertion failed for another reason

@return Record


public function relation()
    {
        if ($this->relation === null) {
            $this->relation = new Table\Relation($this);
        }
        return $this->relation;
    }

public function relation ( ) { if ( $ this -> relation === null ) { $ this -> relation = new Table \ Relation ( $ this ) ; } return $ this -> relation ; }

Return table relation reader

@return Table\Relation


public function getPrimaryKeys()
    {
        if ($this->primary_keys === null) {
            try {
                $this->primary_keys = $this->tableManager->metadata()->getPrimaryKeys($this->prefixed_table);
            } catch (\Soluble\Schema\Exception\NoPrimaryKeyException $e) {
                throw new Exception\PrimaryKeyNotFoundException(__METHOD__ . ': ' . $e->getMessage());
            //@codeCoverageIgnoreStart
            } catch (\Soluble\Schema\Exception\ExceptionInterface $e) {
                throw new Exception\RuntimeException(__METHOD__ . ": Cannot determine primary key on table " . $this->prefixed_table);
            }
            //@codeCoverageIgnoreEnd
        }
        return $this->primary_keys;
    }

Return table primary keys

@throws Exception\PrimaryKeyNotFoundException when no pk
@throws Exception\RuntimeException when it cannot determine primary key on table

@return array


public function getPrimaryKey()
    {
        if ($this->primary_key === null) {
            $pks = $this->getPrimaryKeys();
            if (count($pks) > 1) {
                throw new Exception\MultiplePrimaryKeysFoundException(__METHOD__ . ": Error getting unique primary key on table, multiple found on table " . $this->prefixed_table);
            }
            $this->primary_key = $pks[0];
        }
        return $this->primary_key;
    }

Return primary key, if multiple primary keys found will
throw an exception

@throws Exception\PrimaryKeyNotFoundException when no pk found
@throws Exception\MultiplePrimaryKeysFoundException when multiple primary keys found
@throws Exception\RuntimeException when it cannot determine primary key on table

@return int|string

Return primary key if multiple primary keys found will throw an exception


public function getColumnsInformation()
    {
        if ($this->column_information === null) {
            $this->column_information = $this->tableManager
                    ->metadata()
                    ->getColumnsInformation($this->prefixed_table);
        }
        return $this->column_information;
    }

public function getColumnsInformation ( ) { if ( $ this -> column_information === null ) { $ this -> column_information = $ this -> tableManager -> metadata ( ) -> getColumnsInformation ( $ this -> prefixed_table ) ; } return $ this -> column_information ; }

Return list of table columns

@throws Soluble\Db\Metadata\Exception\InvalidArgumentException
@throws Soluble\Db\Metadata\Exception\ErrorException
@throws Soluble\Db\Metadata\Exception\ExceptionInterface
@throws Soluble\Db\Metadata\Exception\TableNotFoundException

@return array


protected function executeStatement($sqlObject)
    {
        if ($sqlObject instanceof PreparableSqlInterface) {
            $statement = $this->sql->prepareStatementForSqlObject($sqlObject);
        } elseif (is_string($sqlObject)) {
            $statement = $this->tableManager->getDbAdapter()->createStatement($sqlObject);
        } else {
            //@codeCoverageIgnoreStart
            throw new Exception\InvalidArgumentException(__METHOD__ . ': expects sqlObject to be string or PreparableInterface');
             //@codeCoverageIgnoreEnd
        }
        try {
            $result = $statement->execute();
        } catch (\Exception $e) {
            // In ZF2, PDO_Mysql and MySQLi return different exception,
            // attempt to normalize by catching one exception instead
            // of RuntimeException and InvalidQueryException

            $messages = [];
            $ex = $e;
            do {
                $messages[] = $ex->getMessage();
            } while ($ex = $ex->getPrevious());
            $message = implode(', ', array_unique($messages));

            $lmsg = __METHOD__ . ':' . strtolower($message) . '(code:' . $e->getCode() . ')';

            if (strpos($lmsg, 'cannot be null') !== false) {
                // Integrity constraint violation: 1048 Column 'non_null_column' cannot be null
                $rex = new Exception\NotNullException(__METHOD__ . ': ' . $message, $e->getCode(), $e);
                throw $rex;
            } elseif (strpos($lmsg, 'duplicate entry') !== false) {
                $rex = new Exception\DuplicateEntryException(__METHOD__ . ': ' . $message, $e->getCode(), $e);
                throw $rex;
            } elseif (strpos($lmsg, 'constraint violation') !== false ||
                    strpos($lmsg, 'foreign key') !== false) {
                $rex = new Exception\ForeignKeyException(__METHOD__ . ': ' . $message, $e->getCode(), $e);
                throw $rex;
            } else {
                if ($sqlObject instanceof SqlInterface) {
                    $sql_string = $sqlObject->getSqlString($this->sql->getAdapter()->getPlatform());
                } else {
                    $sql_string = $sqlObject;
                }
                $iqex = new Exception\RuntimeException(__METHOD__ . ': ' . $message . "[$sql_string]", $e->getCode(), $e);
                throw $iqex;
            }
        }
        return $result;
    }

Execute a statement

@todo move to driver if not will only support MySQL

@throws Exception\ForeignKeyException when insertion failed because of an invalid foreign key
@throws Exception\DuplicateEntryException when insertion failed because of an invalid foreign key
@throws Exception\NotNullException when insertion failed because a column cannot be null
@throws Exception\RuntimeException when insertion failed for another reason

@param string|PreparableSqlInterface $sqlObject
@return \Zend\Db\Adapter\Driver\ResultInterface


protected function getPrimaryKeyPredicate($id)
    {
        if (!is_scalar($id) && !is_array($id)) {
            throw new Exception\InvalidArgumentException(__METHOD__ . ": Id must be scalar or array, type " . gettype($id) . " received");
        }
        $keys = $this->getPrimaryKeys();
        if (count($keys) == 1) {
            $pk = $keys[0];
            if (!is_scalar($id)) {
                $type = gettype($id);
                throw new Exception\InvalidArgumentException(__METHOD__ . ": invalid primary key value. Table '{$this->table}' has a single primary key '$pk'. Argument must be scalar, '$type' given");
            }
            $predicate = [$pk => $id];
        } else {
            if (!is_array($id)) {
                $pks = implode(',', $keys);
                $type = gettype($id);
                throw new Exception\InvalidArgumentException(__METHOD__ . ": invalid primary key value. Table '{$this->table}' has multiple primary keys '$pks'. Argument must be an array, '$type' given");
            }

            $matched_keys = array_diff($id, $keys);
            if (count($matched_keys) == count($keys)) {
                $predicate = $matched_keys;
            } else {
                $pks = implode(',', $keys);
                $vals = implode(',', $matched_keys);
                throw new Exception\InvalidArgumentException(__METHOD__ . ": incomplete primary key value. Table '{$this->table}' has multiple primary keys '$pks', values received '$vals'");
            }
        }
        return $predicate;
    }

Return primary key predicate

@param integer|string|array $id

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


protected function checkDataColumns(array $data)
    {
        $diff = array_diff_key($data, $this->getColumnsInformation());
        if (count($diff) > 0) {
            $msg = implode(',', array_keys($diff));
            throw new Exception\ColumnNotFoundException(__METHOD__ . ": some specified columns '$msg' does not exists in table {$this->table}.");
        }
    }

Check if all columns exists in table

@param array $data
@throws Exception\ColumnNotFoundException


protected function parseAsArray($content)
    {
        $data = json_decode($content, true);

        return array(
            isset($data['status']) ? $data['status'] : false,
            isset($data['error']) ? $data['error'] : false,
            $data,
        );
    }

protected function parseAsArray ( $ content ) { $ data = json_decode ( $ content , true ) ; return array ( isset ( $ data [ 'status' ] ) ? $ data [ 'status' ] : false , isset ( $ data [ 'error' ] ) ? $ data [ 'error' ] : false , $ data , ) ; }

Parses the content as array.

@param string $content

@return array


protected function parseAsObject($content)
    {
        $data = json_decode($content);

        return array(
            property_exists($data, 'status') ? $data->status : false,
            property_exists($data, 'error') ? $data->error : false,
            $data
        );
    }

protected function parseAsObject ( $ content ) { $ data = json_decode ( $ content ) ; return array ( property_exists ( $ data , 'status' ) ? $ data -> status : false , property_exists ( $ data , 'error' ) ? $ data -> error : false , $ data ) ; }

Parses the content as objects.

@param string $content

@return array


public function setReturnType($returnType)
    {
        if (!in_array($returnType, array(static::RETURN_OBJECT, static::RETURN_ARRAY))) {
            throw new InvalidArgumentException(sprintf('Invalid return type "%s" given.', $returnType));
        }

        $this->returnType = $returnType;

        return $this;
    }

public
function
setReturnType
(
$
returnType
)
{
if
(
!
in_array
(
$
returnType
,
array
(
static
::
RETURN_OBJECT
,
static
::
RETURN_ARRAY
)
)
)
{
throw
new
InvalidArgumentException
(
sprintf
(
'Invalid return type "%s" given.'
,
$
returnType
)
)
;
}
$
this
->
returnType
=
$
returnType
;
return
$
this
;
}

Sets the return type of responses.

@param string $returnType

@return self
@throws InvalidArgumentException


public function run()
    {
        // Enqueue styles and scripts
        $this->action('wp_enqueue_scripts', $this->enqueue('wp'));
        $this->action('admin_enqueue_scripts', $this->enqueue('admin'));

        foreach ($this->filters as $hook) {
            add_filter($hook['hook'], $hook['callback'], $hook['priority'], $hook['accepted_args']);
        }

        foreach ($this->actions as $hook) {
            add_action($hook['hook'], $hook['callback'], $hook['priority'], $hook['accepted_args']);
        }
    }

public
function
run
(
)
{
// Enqueue styles and scripts
$
this
->
action
(
'wp_enqueue_scripts'
,
$
this
->
enqueue
(
'wp'
)
)
;
$
this
->
action
(
'admin_enqueue_scripts'
,
$
this
->
enqueue
(
'admin'
)
)
;
foreach
(
$
this
->
filters
as
$
hook
)
{
add_filter
(
$
hook
[
'hook'
]
,
$
hook
[
'callback'
]
,
$
hook
[
'priority'
]
,
$
hook
[
'accepted_args'
]
)
;
}
foreach
(
$
this
->
actions
as
$
hook
)
{
add_action
(
$
hook
[
'hook'
]
,
$
hook
[
'callback'
]
,
$
hook
[
'priority'
]
,
$
hook
[
'accepted_args'
]
)
;
}
}

Register the filters and actions with WordPress.

@since   1.0.0

Register the filters and actions with WordPress .


protected function enqueue($type)
    {
        $filter = function ($val) use ($type) {
            return in_array($val['type'], array($type, 'both'));
        };

        return function () use ($filter) {
            foreach (array_filter($this->styles, $filter) as $hook) {
                wp_enqueue_style($hook['handle'], $hook['src'], $hook['deps'], $this->version, $hook['cond']);
            }
            foreach (array_filter($this->scripts, $filter) as $hook) {
                wp_enqueue_script($hook['handle'], $hook['src'], $hook['deps'], $this->version, $hook['cond']);
            }
        };
    }

protected function enqueue ( $ type ) { $ filter = function ( $ val ) use ( $ type ) { return in_array ( $ val [ 'type' ] , array ( $ type , 'both' ) ) ; } ; return function ( ) use ( $ filter ) { foreach ( array_filter ( $ this -> styles , $ filter ) as $ hook ) { wp_enqueue_style ( $ hook [ 'handle' ] , $ hook [ 'src' ] , $ hook [ 'deps' ] , $ this -> version , $ hook [ 'cond' ] ) ; } foreach ( array_filter ( $ this -> scripts , $ filter ) as $ hook ) { wp_enqueue_script ( $ hook [ 'handle' ] , $ hook [ 'src' ] , $ hook [ 'deps' ] , $ this -> version , $ hook [ 'cond' ] ) ; } } ; }

Create a callable to enqueue resources.

@since   1.0.0
@access  protected
@param   $type
@return  callable

Create a callable to enqueue resources .


public function is($type)
    {
        if (null !== $this->type) {
            throw new LogicException('Already typed');
        }

        $this->type = $type;

        return $this;
    }

public
function
is
(
$
type
)
{
if
(
!==
$
this
->
type
)
{
throw
new
LogicException
(
'Already typed'
)
;
}
$
this
->
type
=
$
type
;
return
$
this
;
}

Define the type.

@param string $type

@return static


public function named($name)
    {
        if (null !== $this->name) {
            throw new LogicException('Already named');
        }

        $this->name = $name;

        return $this;
    }

public
function
named
(
$
name
)
{
if
(
!==
$
this
->
name
)
{
throw
new
LogicException
(
'Already named'
)
;
}
$
this
->
name
=
$
name
;
return
$
this
;
}

Define the name.

@param string $name

@return static


public function start($position)
    {
        if (null !== $this->initialPosition) {
            throw new LogicException('Start already defined');
        }

        $this->initialPosition = $position;

        return $this;
    }

public
function
start
(
$
position
)
{
if
(
!==
$
this
->
initialPosition
)
{
throw
new
LogicException
(
'Start already defined'
)
;
}
$
this
->
initialPosition
=
$
position
;
return
$
this
;
}

Define the position.

@param string $position

@return static


public function deal($damage)
    {
        if (null !== $this->damage) {
            throw new LogicException('Damage already defined');
        }

        $this->damage = $damage;

        return $this;
    }

public
function
deal
(
$
damage
)
{
if
(
!==
$
this
->
damage
)
{
throw
new
LogicException
(
'Damage already defined'
)
;
}
$
this
->
damage
=
$
damage
;
return
$
this
;
}

Define the damage.

@param int $damage

@return static


public function aim($hitLevel)
    {
        if (null !== $this->hitLevel) {
            throw new LogicException('Hit level already defined');
        }

        $this->hitLevel = $hitLevel;

        return $this;
    }

public
function
aim
(
$
hitLevel
)
{
if
(
!==
$
this
->
hitLevel
)
{
throw
new
LogicException
(
'Hit level already defined'
)
;
}
$
this
->
hitLevel
=
$
hitLevel
;
return
$
this
;
}

Define the hit level.

@param string $hitLevel

@return static


public function withMeterGain($value)
    {
        if (null !== $this->meterGain) {
            throw new LogicException('Meter gain already defined');
        }

        $this->meterGain = $value;

        return $this;
    }

public
function
withMeterGain
(
$
value
)
{
if
(
!==
$
this
->
meterGain
)
{
throw
new
LogicException
(
'Meter gain already defined'
)
;
}
$
this
->
meterGain
=
$
value
;
return
$
this
;
}

Define the meter gain.

@param int $value

@return static


public function withInputs($inputs)
    {
        if (0 < count($this->inputs)) {
            throw new LogicException('Inputs already defined');
        }

        $this->inputs = $this->parser->transforms($inputs);

        return $this;
    }

public
function
withInputs
(
$
inputs
)
{
if
(
0
<
count
(
$
this
->
inputs
)
)
{
throw
new
LogicException
(
'Inputs already defined'
)
;
}
$
this
->
inputs
=
$
this
->
parser
->
transforms
(
$
inputs
)
;
return
$
this
;
}

Define the inputs.

@param string $inputs

@return static


public function addCancel(MoveInterface $move)
    {
        foreach ($this->cancelAbilities as $cancelAbility) {
            if ($cancelAbility->equals($move)) {
                throw new LogicException(
                    sprintf('Cancel ability "%s" already defined', $move->getName())
                );
            }
        }

        $this->cancelAbilities[] = $move;

        return $this;
    }

public
function
addCancel
(
MoveInterface
$
move
)
{
foreach
(
$
this
->
cancelAbilities
as
$
cancelAbility
)
{
if
(
$
cancelAbility
->
equals
(
$
move
)
)
{
throw
new
LogicException
(
sprintf
(
'Cancel ability "%s" already defined'
,
$
move
->
getName
(
)
)
)
;
}
}
$
this
->
cancelAbilities
[
]
=
$
move
;
return
$
this
;
}

Add a cancel ability.

@param MoveInterface $move

@return static


public function startIn($frames)
    {
        if (null !== $this->startFrames) {
            throw new LogicException('Start frames already defined');
        }
        $this->startFrames = $frames;

        return $this;
    }

public
function
startIn
(
$
frames
)
{
if
(
!==
$
this
->
startFrames
)
{
throw
new
LogicException
(
'Start frames already defined'
)
;
}
$
this
->
startFrames
=
$
frames
;
return
$
this
;
}

Define the frames required to start.

@param int $frames

@return static


public function activeDuring($frames)
    {
        if (null !== $this->activeFrames) {
            throw new LogicException('Active frames already defined');
        }
        $this->activeFrames = $frames;

        return $this;
    }

public
function
activeDuring
(
$
frames
)
{
if
(
!==
$
this
->
activeFrames
)
{
throw
new
LogicException
(
'Active frames already defined'
)
;
}
$
this
->
activeFrames
=
$
frames
;
return
$
this
;
}

Define the frames displaying the move.

@param int $frames

@return static


public function recoverIn($frames)
    {
        if (null !== $this->recoveryFrames) {
            throw new LogicException('Recovery frames already defined');
        }
        $this->recoveryFrames = $frames;

        return $this;
    }

public
function
recoverIn
(
$
frames
)
{
if
(
!==
$
this
->
recoveryFrames
)
{
throw
new
LogicException
(
'Recovery frames already defined'
)
;
}
$
this
->
recoveryFrames
=
$
frames
;
return
$
this
;
}

Define the frames required to recover.

@param int $frames

@return static


public function advantageOnHit($frames)
    {
        if (null !== $this->hitAdvantage) {
            throw new LogicException('Hit advantage already defined');
        }
        $this->hitAdvantage = $frames;

        return $this;
    }

public
function
advantageOnHit
(
$
frames
)
{
if
(
!==
$
this
->
hitAdvantage
)
{
throw
new
LogicException
(
'Hit advantage already defined'
)
;
}
$
this
->
hitAdvantage
=
$
frames
;
return
$
this
;
}

Define the difference of frame with the target gets hit to get back to the neutral state.

@param int $frames

@return static

Define the difference of frame with the target gets hit to get back to the neutral state .


public function advantageOnGuard($frames)
    {
        if (null !== $this->guardAdvantage) {
            throw new LogicException('Guard advantage already defined');
        }
        $this->guardAdvantage = $frames;

        return $this;
    }

public
function
advantageOnGuard
(
$
frames
)
{
if
(
!==
$
this
->
guardAdvantage
)
{
throw
new
LogicException
(
'Guard advantage already defined'
)
;
}
$
this
->
guardAdvantage
=
$
frames
;
return
$
this
;
}

Define the difference of frame with the target on guard to get back to the neutral state.

@param int $frames

@return static

Define the difference of frame with the target on guard to get back to the neutral state .


public function build()
    {
        return new Move(
            $this->type,
            $this->name,
            $this->initialPosition,
            $this->inputs,
            $this->damage,
            $this->meterGain,
            $this->hitLevel,
            $this->cancelAbilities,
            new FrameData(
                $this->startFrames,
                $this->activeFrames,
                $this->recoveryFrames,
                $this->guardAdvantage,
                $this->hitAdvantage
            )
        );
    }

public function build ( ) { return new Move ( $ this -> type , $ this -> name , $ this -> initialPosition , $ this -> inputs , $ this -> damage , $ this -> meterGain , $ this -> hitLevel , $ this -> cancelAbilities , new FrameData ( $ this -> startFrames , $ this -> activeFrames , $ this -> recoveryFrames , $ this -> guardAdvantage , $ this -> hitAdvantage ) ) ; }

Build the desired move.

@return MoveInterface


private static function sendSlackMessage($message, $channel)
    {
        // do not send Slack messages in test mode for now
        // @todo Trap these for testing
        if (Director::isTest()) {
            return;
        }

        $hooksFromConfig = Config::inst()->get('Suilven\Notifier\Notify', 'slack_webhooks');

        // optionally override the channel
        $channelOverride = Config::inst()->get('Suilven\Notifier\Notify', 'channel_override');
        if (!empty($channelOverride)) {
            $channel = $channelOverride;
        }

        // get the appropriate webhook
        $url = null;

        if (!empty($hooksFromConfig)) {
            foreach($hooksFromConfig as $hook)
            {
                // stick with the default webhook but allow overriding on a per channel basis
                if ($hook['name'] == $channel)
                {
                    $url = $hook['url'];
                } elseif (empty($url) && $hook['name'] == 'default') {
                    $url = $hook['url'];
                }
            }
        }

        // Log an error if Slack config misconfigured
        if (empty($url)) {
            Injector::inst()->get(LoggerInterface::class)->error('The slack channel ' . $channel . ' has no webhook');
            return;
        }

        // create job
        $job = new NotifyViaSlackJob();
        $job->webhookURL = $url;
        $job->message = $message;
        $job->channel = $channel;

        // place on queue
        singleton(QueuedJobService::class)->queueJob($job);
    }

Note to self - Slack Webhook URLs have a default channel, but can be configured to send to any
BackTrace class has an error generator

Use $client->to($channel)->send($message);

@param $message
@param $channel

Note to self - Slack Webhook URLs have a default channel but can be configured to send to any BackTrace class has an error generator


public function parse(array $segments, array $data = null, array $params = null): string
    {
        // If data was passed but no params
        if (null === $params && null !== $data) {
            throw new InvalidArgumentException(
                'Route params are required when supplying data'
            );
        }

        $path         = '';
        $replace      = [];
        $replacements = [];

        // If there is data, parse the replacements
        if (null !== $data) {
            $this->parseData(
                $segments,
                $data,
                $params,
                $replace,
                $replacements
            );
        }

        // Iterate through the segments
        foreach ($segments as $index => $segment) {
            // No need to do replacements if there was no data
            if (null !== $data) {
                // Replace any parameters
                $segment = str_replace($replace, $replacements, $segment);
            }

            // If parameters were replaced or none to begin with
            if (strpos($segment, '{') === false) {
                // Append this segment
                $path .= $segment;
            }
        }

        return $path;
    }

Parse segments, data, and params into a path.

@param array $segments The segments
@param array $data     [optional] The data
@param array $params   [optional] The params

@throws \InvalidArgumentException

@return string

Parse segments data and params into a path .


protected function parseData(
        array $segments,
        array $data,
        array $params,
        array &$replace,
        array &$replacements
    ): void {
        // Iterate through all the data properties
        foreach ($data as $key => $datum) {
            // If the data isn't found in the params array it is not a valid
            // param
            if (! isset($params[$key])) {
                throw new InvalidArgumentException(
                    "Invalid route param '{$key}'"
                );
            }

            $regex = $params[$key]['regex'];

            $this->validateDatum($key, $datum, $regex);

            if (\is_array($datum)) {
                // Get the segment by the param key and replace the {key}
                // within it to get the repeatable portion of the segment
                $segment     = $this->findParamSegment(
                    $segments,
                    $params[$key]['replace']
                );
                $deliminator = str_replace(
                    $params[$key]['replace'] . '*',
                    '',
                    $segment
                );

                // Set what to replace
                $replace[] = $params[$key]['replace'] . '*';
                // With the data value to replace with
                $replacements[] = implode($deliminator, $datum);

                continue;
            }

            // Set what to replace
            $replace[] = $params[$key]['replace'];
            // With the data value to replace with
            $replacements[] = $datum;
        }
    }

Parse data for replacements.

@param array $segments     The segments
@param array $data         The data
@param array $params       The params
@param array $replace      The replace array
@param array $replacements The replacements array

@throws \InvalidArgumentException

@return void


protected function validateDatum(string $key, $datum, string $regex): void
    {
        if (\is_array($datum)) {
            foreach ($datum as $datumItem) {
                $this->validateDatum($key, $datumItem, $regex);
            }

            return;
        }

        // If the value of the data doesn't match what was specified when the route was made
        if (preg_match('/^' . $regex . '$/', $datum) === 0) {
            throw new InvalidArgumentException(
                "Route param for {$key}, '{$datum}', does not match {$regex}"
            );
        }
    }

Validate a datum.

@param string $key   The key
@param mixed  $datum The datum
@param string $regex The regex

@throws \InvalidArgumentException

@return void