public function setProtocol($protocol)
    {
        $allowedProtocols = array('http', 'https');

        $protocol = strtolower( $protocol );

        if ( !in_array( $protocol,$allowedProtocols ) ) {
            throw new Exception('Unsupported Protocol: ' . $protocol . '. Supported protocols are: ' . join($allowedProtocols, ', '));
        }

        $this->protocol = $protocol;
    }

public
function
setProtocol
(
$
protocol
)
{
$
allowedProtocols
=
array
(
'http'
,
'https'
)
;
$
protocol
=
strtolower
(
$
protocol
)
;
if
(
!
in_array
(
$
protocol
,
$
allowedProtocols
)
)
{
throw
new
Exception
(
'Unsupported Protocol: '
.
$
protocol
.
'. Supported protocols are: '
.
join
(
$
allowedProtocols
,
', '
)
)
;
}
$
this
->
protocol
=
$
protocol
;
}

Set the protocol.

Supported protocols are: http, https

@param string $protocol


public function generateQuery(IDruidQueryParameters $params)
    {
        if(!$params instanceof GroupByQueryParameters)
        {
            throw new Exception('Expected $params to be instanceof GroupByQueryParameters');
        }

        $params->validate();
        $query = $params->getJSONString();
        return $query;
    }

Generate a Druid query's JSON POST body

@param IDruidQueryParameters $params

@return string|void
@throws Exception


public function setAggregators($aggregatorsArray)
    {
        $this->aggregators = array();

        foreach( $aggregatorsArray as $aggregator)
        {
            $this->aggregators[] = json_encode( $aggregator );
        }

    }

public function setAggregators ( $ aggregatorsArray ) { $ this -> aggregators = array ( ) ; foreach ( $ aggregatorsArray as $ aggregator ) { $ this -> aggregators [ ] = json_encode ( $ aggregator ) ; } }

Configure the aggregators for this request.

@param $aggregatorsArray array PHP Array of aggregators

Configure the aggregators for this request .


public function setFilters($filtersArray)
    {
        $this->filters = array();

        foreach( $filtersArray as $filter)
        {
            $this->filters[] = json_encode( $filter );
        }

    }

public function setFilters ( $ filtersArray ) { $ this -> filters = array ( ) ; foreach ( $ filtersArray as $ filter ) { $ this -> filters [ ] = json_encode ( $ filter ) ; } }

Configure the filters for this request.

@param $filtersArray PHP Array of aggregators

Configure the filters for this request .


public function setPostAggregators($postAggregatorsArray)
    {
        $this->postAggregators = array();

        foreach( $postAggregatorsArray as $postAggregator)
        {
            $this->postAggregators[] = json_encode( $postAggregator );
        }

    }

public function setPostAggregators ( $ postAggregatorsArray ) { $ this -> postAggregators = array ( ) ; foreach ( $ postAggregatorsArray as $ postAggregator ) { $ this -> postAggregators [ ] = json_encode ( $ postAggregator ) ; } }

Configure the post aggregators for this request.

@param $postAggregatorsArray array PHP Array of post aggregators

Configure the post aggregators for this request .


protected function registerClientScript()
    {
        $js = [];
        $id = $this->options['id'];
        TinyMceAsset::register($this->view);
        $this->clientOptions['selector'] = "#{$id}";

        if (!empty($this->clientOptions['language'])) {
            $language_url = LanguageAsset::register($this->view)->baseUrl . "/{$this->clientOptions['language']}.js";
            $this->clientOptions['language_url'] = $language_url;
        }

        $options = Json::encode($this->clientOptions);
        $js[] = "tinymce.init($options);";

        if ($this->triggerSaveOnBeforeValidateForm) {
            $js[] = "$('#{$id}').parents('form').on('beforeValidate', function() { tinymce.triggerSave(); });";
        }
        $this->view->registerJs(implode("\n", $js));
    }

Registers Twitter TypeAhead Bootstrap plugin and the related events


public function validate()
    {
        $flag = true;
        foreach($this->requiredParams as $param)
        {
            if(!isset($this->$param))
            {
                $this->missingParameters[] = $param;
                $flag                      = false;
            }
            else
            {
                $val = $this->$param;
                if(!is_array($val))
                {
                    $val = trim($val);
                }
                if(empty($val))
                {
                    $this->emptyParameters[] = $param;
                    $flag                    = false;
                }
            }
        }
        if(count($this->missingParameters) > 0)
        {
            throw new MissingParametersException($this->missingParameters);
        }
        if(count($this->emptyParameters) > 0)
        {
            throw new EmptyParametersException($this->emptyParameters);
        }
        return $flag;
    }

public function validate ( ) { $ flag = true ; foreach ( $ this -> requiredParams as $ param ) { if ( ! isset ( $ this -> $ param ) ) { $ this -> missingParameters [ ] = $ param ; $ flag = false ; } else { $ val = $ this -> $ param ; if ( ! is_array ( $ val ) ) { $ val = trim ( $ val ) ; } if ( empty ( $ val ) ) { $ this -> emptyParameters [ ] = $ param ; $ flag = false ; } } } if ( count ( $ this -> missingParameters ) > 0 ) { throw new MissingParametersException ( $ this -> missingParameters ) ; } if ( count ( $ this -> emptyParameters ) > 0 ) { throw new EmptyParametersException ( $ this -> emptyParameters ) ; } return $ flag ; }

Validates the query has the necessary parameters

@throws MissingParametersException


public function getJSONString()
    {
        $retString       = '{[DATA]}';
        $buffStringArray = array();
        foreach($this->allParameters as $param)
        {
            if(isset($this->$param))
            {
                $buffStringArray[] = "\"{$param}\":" . json_encode($this->$param);
            }
        }
        $buffString = implode(',', $buffStringArray);
        $retString  = str_replace('[DATA]', $buffString, $retString);
        return $retString;
    }

public function getJSONString ( ) { $ retString = '{[DATA]}' ; $ buffStringArray = array ( ) ; foreach ( $ this -> allParameters as $ param ) { if ( isset ( $ this -> $ param ) ) { $ buffStringArray [ ] = "\"{$param}\":" . json_encode ( $ this -> $ param ) ; } } $ buffString = implode ( ',' , $ buffStringArray ) ; $ retString = str_replace ( '[DATA]' , $ buffString , $ retString ) ; return $ retString ; }

Converts the current object into a JSON representation to be used as a query
@return mixed|string


public function indexAction()
    {
        $helperManager = $this->getServiceLocator()->get('viewhelpermanager');
        $basePathHelper = $helperManager->get('basePath');

        // Default to /api/docs in case the configurable path is not set
        $swaggerUrl = '/api/docs';

        // Get swagger JSON url/path from config if set
        if (isset($this->config['swagger-json-url'])) {
            $swaggerUrl = $this->config['swagger-json-url'];
        }

        // Run through basePath helper if the string doesn't start with http
        if (substr($swaggerUrl, 0, 4) !== 'http') {
            $swaggerUrl = $basePathHelper->__invoke($swaggerUrl);
        }

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        $viewModel->setVariable('swaggerUrl', $swaggerUrl);

        return $viewModel->setTemplate('swagger-ui.phtml');
    }

Display the SwaggerUI interface

@return ViewModel


protected function prepareDatabase()
    {
        if (!$this->migrator->storageExist()) {
            $this->callTask(InstallTask::class, 'main', $this->arguments, $this->options);
        }
    }

protected function prepareDatabase ( ) { if ( ! $ this -> migrator -> storageExist ( ) ) { $ this -> callTask ( InstallTask :: class , 'main' , $ this -> arguments , $ this -> options ) ; } }

Prepare the migration database for running.

@return void

Prepare the migration database for running .


public function hasColumn($table, $column)
    {
        $tableColumns = array_map('strtolower', $this->listColumnsName($table));

        return in_array(strtolower($column), $tableColumns);
    }

public function hasColumn ( $ table , $ column ) { $ tableColumns = array_map ( 'strtolower' , $ this -> listColumnsName ( $ table ) ) ; return in_array ( strtolower ( $ column ) , $ tableColumns ) ; }

Determine if the given table has a given column.

@param string $table
@param string $column

@return bool

Determine if the given table has a given column .


public function getColumnType($table, $column)
    {
        $col = $this->describeColumn($table, $column);

        if (!is_null($col)) {
            return $col->getType();
        }

        return null;
    }

public function getColumnType ( $ table , $ column ) { $ col = $ this -> describeColumn ( $ table , $ column ) ; if ( ! is_null ( $ col ) ) { return $ col -> getType ( ) ; } return null ; }

Get the data type for the given column name.

@param string $table
@param string $column

@return string

Get the data type for the given column name .


public function table($table, Closure $callback)
    {
        $this->build(Func::tap($this->createBlueprint($table), function (Blueprint $blueprint) use ($callback) {
            $blueprint->update();

            $callback($blueprint);
        }));
    }

public function table ( $ table , Closure $ callback ) { $ this -> build ( Func :: tap ( $ this -> createBlueprint ( $ table ) , function ( Blueprint $ blueprint ) use ( $ callback ) { $ blueprint -> update ( ) ; $ callback ( $ blueprint ) ; } ) ) ; }

Modify a table on the schema.

@param  string   $table
@param  \Closure $callback

@return void


public function drop($table)
    {
        $this->build(Func::tap($this->createBlueprint($table), function (Blueprint $blueprint) {
            $blueprint->drop();
        }));
    }

public function drop ( $ table ) { $ this -> build ( Func :: tap ( $ this -> createBlueprint ( $ table ) , function ( Blueprint $ blueprint ) { $ blueprint -> drop ( ) ; } ) ) ; }

Drop a table from the schema.

@param  string $table

@return void


public function dropAllTables()
    {
        @$this->disableForeignKeyConstraints();

        foreach ($this->db->listTables() as $table) {
            $this->drop($table);
        };

        @$this->enableForeignKeyConstraints();
    }

public function dropAllTables ( ) { @ $ this -> disableForeignKeyConstraints ( ) ; foreach ( $ this -> db -> listTables ( ) as $ table ) { $ this -> drop ( $ table ) ; } ; @ $ this -> enableForeignKeyConstraints ( ) ; }

Drop all tables from the database.

@return void

@throws \LogicException


public function rename($from, $to)
    {
        $this->build(Func::tap($this->createBlueprint($from), function (Blueprint $blueprint) use ($to) {
            $blueprint->update();

            $blueprint->rename($to);
        }));
    }

public function rename ( $ from , $ to ) { $ this -> build ( Func :: tap ( $ this -> createBlueprint ( $ from ) , function ( Blueprint $ blueprint ) use ( $ to ) { $ blueprint -> update ( ) ; $ blueprint -> rename ( $ to ) ; } ) ) ; }

Rename a table on the schema.

@param  string $from
@param  string $to

@return void


public function execute($sql)
    {
        $this->build(Func::tap($this->createBlueprint(null), function (Blueprint $blueprint) use ($sql) {
            $blueprint->raw();

            $blueprint->sql($sql);
        }));
    }

public function execute ( $ sql ) { $ this -> build ( Func :: tap ( $ this -> createBlueprint ( null ) , function ( Blueprint $ blueprint ) use ( $ sql ) { $ blueprint -> raw ( ) ; $ blueprint -> sql ( $ sql ) ; } ) ) ; }

Execute a raw SQL Command

@param string $sql

@return void


public function addFromRequest(UploadedFile $uploadedFile, $tag = null)
    {
        $this->getMediaAdder()
             ->performedOn($this->attachment)
             ->useMediaTag($tag)
             ->fromFile($uploadedFile);

        return $this;
    }

public function addFromRequest ( UploadedFile $ uploadedFile , $ tag = null ) { $ this -> getMediaAdder ( ) -> performedOn ( $ this -> attachment ) -> useMediaTag ( $ tag ) -> fromFile ( $ uploadedFile ) ; return $ this ; }

Creates a file object from a file an uploaded file.
@param \Symfony\Component\HttpFoundation\File\UploadedFile $uploadedFile
@param null $tag
@return self

Creates a file object from a file an uploaded file .


public function addFromFile($filePath, $tag = null)
    {
        if (is_null($filePath))
            return;

        $this->getMediaAdder()
             ->performedOn($this->attachment)
             ->useMediaTag($tag)
             ->fromFile(new SymfonyFile($filePath));

        return $this;
    }

public function addFromFile ( $ filePath , $ tag = null ) { if ( is_null ( $ filePath ) ) return ; $ this -> getMediaAdder ( ) -> performedOn ( $ this -> attachment ) -> useMediaTag ( $ tag ) -> fromFile ( new SymfonyFile ( $ filePath ) ) ; return $ this ; }

Creates a file object from a file on the disk.
@param $filePath
@param null $tag
@return self|void

Creates a file object from a file on the disk .


public function addFromRaw($rawData, $filename, $tag = null)
    {
        if (is_null($rawData))
            return;

        $tempPath = temp_path($filename);
        File::put($tempPath, $rawData);

        $this->addFromFile($tempPath, $tag);
        File::delete($tempPath);

        return $this;
    }

public function addFromRaw ( $ rawData , $ filename , $ tag = null ) { if ( is_null ( $ rawData ) ) return ; $ tempPath = temp_path ( $ filename ) ; File :: put ( $ tempPath , $ rawData ) ; $ this -> addFromFile ( $ tempPath , $ tag ) ; File :: delete ( $ tempPath ) ; return $ this ; }

Creates a file object from raw data.

@param $rawData string Raw data
@param $filename string Filename

@param null $tag
@return $this|void


public function addFromUrl($url, $filename = null, $tag = null)
    {
        if (!$stream = @fopen($url, 'rb'))
            throw new Exception(sprintf('Error opening file "%s"', $url));

        return $this->addFromRaw(
            $stream,
            !empty($filename) ? $filename : File::basename($url),
            $tag
        );
    }

public
function
addFromUrl
(
$
url
,
$
filename
=
,
$
tag
=
)
{
if
(
!
$
stream
=
@
fopen
(
$
url
,
'rb'
)
)
throw
new
Exception
(
sprintf
(
'Error opening file "%s"'
,
$
url
)
)
;
return
$
this
->
addFromRaw
(
$
stream
,
!
empty
(
$
filename
)
$
filename
:
File
::
basename
(
$
url
)
,
$
tag
)
;
}

Creates a file object from url
@param $url string URL
@param $filename string Filename
@param null $tag
@return $this
@throws \Exception


public function afterDelete()
    {
        try {
            $this->deleteThumbs();
            $this->deleteFile();
        }
        catch (Exception $ex) {
            Log::error($ex);
        }
    }

public function afterDelete ( ) { try { $ this -> deleteThumbs ( ) ; $ this -> deleteFile ( ) ; } catch ( Exception $ ex ) { Log :: error ( $ ex ) ; } }

After model is deleted
- clean up it's thumbnails

After model is deleted - clean up it s thumbnails


public function getLastModified($fileName = null)
    {
        if (!$fileName)
            $fileName = $this->disk_name;

        return $this->getStorageDisk()->lastModified($this->getStoragePath().$fileName);
    }

public function getLastModified ( $ fileName = null ) { if ( ! $ fileName ) $ fileName = $ this -> disk_name ; return $ this -> getStorageDisk ( ) -> lastModified ( $ this -> getStoragePath ( ) . $ fileName ) ; }

Returns the last modification date as a UNIX timestamp.
@return int

Returns the last modification date as a UNIX timestamp .


public function getUniqueName()
    {
        if (!is_null($this->name))
            return $this->name;

        $ext = strtolower($this->getExtension());

        $name = str_replace('.', '', uniqid(null, TRUE));
        return $this->name = $name.(strlen($ext) ? '.'.$ext : '');
    }

public function getUniqueName ( ) { if ( ! is_null ( $ this -> name ) ) return $ this -> name ; $ ext = strtolower ( $ this -> getExtension ( ) ) ; $ name = str_replace ( '.' , '' , uniqid ( null , TRUE ) ) ; return $ this -> name = $ name . ( strlen ( $ ext ) ? '.' . $ ext : '' ) ; }

Generates a unique name from the supplied file name.

Generates a unique name from the supplied file name .


public function deleteThumbs()
    {
        $pattern = 'thumb_'.$this->id.'_';

        $directory = $this->getStoragePath();
        $allFiles = $this->getStorageDisk()->files($directory);
        $paths = array_filter($allFiles, function ($file) use ($pattern) {
            return starts_with(basename($file), $pattern);
        });

        $this->getStorageDisk()->delete($paths);
    }

public function deleteThumbs ( ) { $ pattern = 'thumb_' . $ this -> id . '_' ; $ directory = $ this -> getStoragePath ( ) ; $ allFiles = $ this -> getStorageDisk ( ) -> files ( $ directory ) ; $ paths = array_filter ( $ allFiles , function ( $ file ) use ( $ pattern ) { return starts_with ( basename ( $ file ) , $ pattern ) ; } ) ; $ this -> getStorageDisk ( ) -> delete ( $ paths ) ; }


protected function deleteFile($fileName = null)
    {
        if (!$fileName) {
            $fileName = $this->name;
        }

        $directory = $this->getStoragePath();
        $filePath = $directory.$fileName;

        if ($this->getStorageDisk()->exists($filePath)) {
            $this->getStorageDisk()->delete($filePath);
        }

        $this->deleteEmptyDirectory($directory);
    }

protected function deleteFile ( $ fileName = null ) { if ( ! $ fileName ) { $ fileName = $ this -> name ; } $ directory = $ this -> getStoragePath ( ) ; $ filePath = $ directory . $ fileName ; if ( $ this -> getStorageDisk ( ) -> exists ( $ filePath ) ) { $ this -> getStorageDisk ( ) -> delete ( $ filePath ) ; } $ this -> deleteEmptyDirectory ( $ directory ) ; }

Delete file contents from storage device.
@param null $fileName
@return void

Delete file contents from storage device .


protected function deleteEmptyDirectory($directory = null)
    {
        if (!$this->isDirectoryEmpty($directory))
            return;

        $this->getStorageDisk()->deleteDirectory($directory);

        $directory = dirname($directory);
        if (!$this->isDirectoryEmpty($directory))
            return;

        $this->getStorageDisk()->deleteDirectory($directory);

        $directory = dirname($directory);
        if (!$this->isDirectoryEmpty($directory))
            return;

        $this->getStorageDisk()->deleteDirectory($directory);
    }

protected function deleteEmptyDirectory ( $ directory = null ) { if ( ! $ this -> isDirectoryEmpty ( $ directory ) ) return ; $ this -> getStorageDisk ( ) -> deleteDirectory ( $ directory ) ; $ directory = dirname ( $ directory ) ; if ( ! $ this -> isDirectoryEmpty ( $ directory ) ) return ; $ this -> getStorageDisk ( ) -> deleteDirectory ( $ directory ) ; $ directory = dirname ( $ directory ) ; if ( ! $ this -> isDirectoryEmpty ( $ directory ) ) return ; $ this -> getStorageDisk ( ) -> deleteDirectory ( $ directory ) ; }

Checks if directory is empty then deletes it,
three levels up to match the partition directory.
@param string $directory
@return void

Checks if directory is empty then deletes it three levels up to match the partition directory .


protected function isDirectoryEmpty($directory)
    {
        $path = $this->getStorageDisk()->path($directory);
        return !(new FilesystemIterator($path))->valid();
    }

protected function isDirectoryEmpty ( $ directory ) { $ path = $ this -> getStorageDisk ( ) -> path ( $ directory ) ; return ! ( new FilesystemIterator ( $ path ) ) -> valid ( ) ; }

Returns true if a directory contains no files.
@param $directory
@return bool|null

Returns true if a directory contains no files .


protected function hasFile($fileName = null)
    {
        $filePath = $this->getStoragePath().$fileName;
        return $this->getStorageDisk()->exists($filePath);
    }

protected function hasFile ( $ fileName = null ) { $ filePath = $ this -> getStoragePath ( ) . $ fileName ; return $ this -> getStorageDisk ( ) -> exists ( $ filePath ) ; }

Check file exists on storage device.
@param string $fileName
@return bool


public function getThumb($options = [])
    {
        if (!$this->isImage())
            return $this->getPath();

        $options = $this->getDefaultThumbOptions($options);

        $thumbFile = $this->getThumbFilename($options);
        if (!$this->hasFile($thumbFile))
            $this->makeThumb($thumbFile, $options);

        return $this->getPublicPath().$this->getPartitionDirectory().$thumbFile;
    }

public function getThumb ( $ options = [ ] ) { if ( ! $ this -> isImage ( ) ) return $ this -> getPath ( ) ; $ options = $ this -> getDefaultThumbOptions ( $ options ) ; $ thumbFile = $ this -> getThumbFilename ( $ options ) ; if ( ! $ this -> hasFile ( $ thumbFile ) ) $ this -> makeThumb ( $ thumbFile , $ options ) ; return $ this -> getPublicPath ( ) . $ this -> getPartitionDirectory ( ) . $ thumbFile ; }

Generates and returns a thumbnail url.
@param int $width
@param int $height
@param array $options
@return string


protected function getThumbFilename($options)
    {
        return 'thumb_'
            .$this->id.'_'
            .$options['width'].'_'.$options['height'].'_'.$options['fit'].'_'
            .substr(md5(serialize(array_except($options, ['width', 'height', 'fit']))), 0, 8).
            '.'.$options['extension'];
    }

protected function getThumbFilename ( $ options ) { return 'thumb_' . $ this -> id . '_' . $ options [ 'width' ] . '_' . $ options [ 'height' ] . '_' . $ options [ 'fit' ] . '_' . substr ( md5 ( serialize ( array_except ( $ options , [ 'width' , 'height' , 'fit' ] ) ) ) , 0 , 8 ) . '.' . $ options [ 'extension' ] ; }

Generates a thumbnail filename.
@param int $width
@param int $height
@param array $options
@return string


protected function getDefaultThumbOptions($override = [])
    {
        $defaultOptions = [
            'fit' => 'contain',
            'width' => 0,
            'height' => 0,
            'quality' => 90,
            'sharpen' => 0,
            'extension' => 'auto',
        ];

        if (!is_array($override))
            $override = ['fit' => $override];

        $options = array_merge($defaultOptions, $override);

        if (strtolower($options['extension']) == 'auto')
            $options['extension'] = strtolower($this->getExtension());

        return $options;
    }

protected function getDefaultThumbOptions ( $ override = [ ] ) { $ defaultOptions = [ 'fit' => 'contain' , 'width' => 0 , 'height' => 0 , 'quality' => 90 , 'sharpen' => 0 , 'extension' => 'auto' , ] ; if ( ! is_array ( $ override ) ) $ override = [ 'fit' => $ override ] ; $ options = array_merge ( $ defaultOptions , $ override ) ; if ( strtolower ( $ options [ 'extension' ] ) == 'auto' ) $ options [ 'extension' ] = strtolower ( $ this -> getExtension ( ) ) ; return $ options ; }

Returns the default thumbnail options.
@param array $override
@return array


protected function makeThumb($thumbFile, $options)
    {
        $thumbFile = $this->getStoragePath().$thumbFile;
        $thumbPath = $this->getStorageDisk()->path($thumbFile);
        $filePath = $this->getStorageDisk()->path($this->getDiskPath());

        if (!$this->hasFile($this->name))
            $filePath = $this->getDefaultThumbPath($thumbFile, array_get($options, 'default'));

        Manipulator::make($filePath)
                   ->manipulate(array_except($options, ['extension', 'default']))
                   ->save($thumbPath);
    }

protected function makeThumb ( $ thumbFile , $ options ) { $ thumbFile = $ this -> getStoragePath ( ) . $ thumbFile ; $ thumbPath = $ this -> getStorageDisk ( ) -> path ( $ thumbFile ) ; $ filePath = $ this -> getStorageDisk ( ) -> path ( $ this -> getDiskPath ( ) ) ; if ( ! $ this -> hasFile ( $ this -> name ) ) $ filePath = $ this -> getDefaultThumbPath ( $ thumbFile , array_get ( $ options , 'default' ) ) ; Manipulator :: make ( $ filePath ) -> manipulate ( array_except ( $ options , [ 'extension' , 'default' ] ) ) -> save ( $ thumbPath ) ; }

Generate the thumbnail
@param $thumbFile
@param array $options


public function getPublicPath()
    {
        $mediaPath = config('system.assets.attachment.path', '/storage/app/attachments');
        $mediaPath = $this->isPublic()
            ? $mediaPath.'/public'
            : $mediaPath.'/protected';

        return URL::asset($mediaPath).'/';
    }

public function getPublicPath ( ) { $ mediaPath = config ( 'system.assets.attachment.path' , '/storage/app/attachments' ) ; $ mediaPath = $ this -> isPublic ( ) ? $ mediaPath . '/public' : $ mediaPath . '/protected' ; return URL :: asset ( $ mediaPath ) . '/' ; }

Define the public address for the storage path.

Define the public address for the storage path .


public function getTempPath()
    {
        $path = temp_path().'/attachments';

        if (!File::isDirectory($path))
            File::makeDirectory($path, 0777, TRUE, TRUE);

        return $path;
    }

public function getTempPath ( ) { $ path = temp_path ( ) . '/attachments' ; if ( ! File :: isDirectory ( $ path ) ) File :: makeDirectory ( $ path , 0777 , TRUE , TRUE ) ; return $ path ; }

Define the internal working path, override this method to define.

Define the internal working path override this method to define .


public function typeEnum(Fluent $column)
    {
        $values = array_map(function ($a) {
            return "'{$a}'";
        }, $column->get('values'));

        $maxlen = 0;
        foreach ($values as $value) {
            $maxlen = max($maxlen, strlen($value));
        }

        return [
            'type'          => "varchar($maxlen) check (\"{$column->get('name')}\" in (" . implode(', ', $values) . '))',
            'typeReference' => -1
        ];
    }

Create the column type definition for a enum type.

@param \Neutrino\Support\Fluent $column

@return array

Create the column type definition for a enum type .


public function typeTime(Fluent $column)
    {
        if (!empty($column['precision'])) {
            return [
                'type'          => $this->compileTimableColumn($column, 'TIME'),
                'typeReference' => Column::TYPE_DATETIME,
            ];
        }

        return $this->_typeTime($column);
    }

public function typeTime ( Fluent $ column ) { if ( ! empty ( $ column [ 'precision' ] ) ) { return [ 'type' => $ this -> compileTimableColumn ( $ column , 'TIME' ) , 'typeReference' => Column :: TYPE_DATETIME , ] ; } return $ this -> _typeTime ( $ column ) ; }

Create the column type definition for a timeTz type.

@param \Neutrino\Support\Fluent $column

@return array

Create the column type definition for a timeTz type .


public function typeTimestamp(Fluent $column)
    {
        if (!empty($column['precision'])) {
            return [
                'type'          => $this->compileTimableColumn($column, 'TIMESTAMP'),
                'typeReference' => Column::TYPE_TIMESTAMP,
            ];
        }

        return $this->_typeTimestamp($column);
    }

public function typeTimestamp ( Fluent $ column ) { if ( ! empty ( $ column [ 'precision' ] ) ) { return [ 'type' => $ this -> compileTimableColumn ( $ column , 'TIMESTAMP' ) , 'typeReference' => Column :: TYPE_TIMESTAMP , ] ; } return $ this -> _typeTimestamp ( $ column ) ; }

Create the column type definition for a timestampTz type.

@param \Neutrino\Support\Fluent $column

@return array

Create the column type definition for a timestampTz type .


protected function curlWriteFunction($ch, $content)
    {
        if (!$this->hasStarted) {
            $this->hasStarted = true;

            $this->getEventsManager()->fire(self::EVENT_START, $this);
        }

        $length = strlen($content);

        $this->getEventsManager()->fire(self::EVENT_PROGRESS, $this, $content);

        return $length;
    }

protected function curlWriteFunction ( $ ch , $ content ) { if ( ! $ this -> hasStarted ) { $ this -> hasStarted = true ; $ this -> getEventsManager ( ) -> fire ( self :: EVENT_START , $ this ) ; } $ length = strlen ( $ content ) ; $ this -> getEventsManager ( ) -> fire ( self :: EVENT_PROGRESS , $ this , $ content ) ; return $ length ; }

Curl WRITEFUNCTION handler

@param resource $ch
@param string   $content

@return int


public function mainAction()
    {
        $this->line('Compiling js... ');

        $options = $this->config->assets->js->toArray();

        $result = $this->getDI()->get(ClosureCompiler::class)->compile($options);

        if (!empty($result['errors'])) {
            $this->outputErrors($result['errors'], 'errors', 'error', $options);
        }

        if (!empty($result['warnings'])) {
            $this->outputErrors($result['warnings'], 'warnings', 'warn', $options);
        }

        $this->block([str_pad(strtoupper('STATISTICS'), 40, ' ', STR_PAD_BOTH)], 'question', 4);

        $statistics = [];
        foreach ($result['statistics'] as $type => $statistic) {
            $statistics[] = ['stats' => $type, 'value' => $statistic];
        }
        $this->table($statistics);

        $this->info('Success');
    }

public
function
mainAction
(
)
{
$
this
->
line
(
'Compiling js... '
)
;
$
options
=
$
this
->
config
->
assets
->
js
->
toArray
(
)
;
$
result
=
$
this
->
getDI
(
)
->
get
(
ClosureCompiler
::
class
)
->
compile
(
$
options
)
;
if
(
!
empty
(
$
result
[
'errors'
]
)
)
{
$
this
->
outputErrors
(
$
result
[
'errors'
]
,
'errors'
,
'error'
,
$
options
)
;
}
if
(
!
empty
(
$
result
[
'warnings'
]
)
)
{
$
this
->
outputErrors
(
$
result
[
'warnings'
]
,
'warnings'
,
'warn'
,
$
options
)
;
}
$
this
->
block
(
[
str_pad
(
strtoupper
(
'STATISTICS'
)
,
40
,
' '
,
STR_PAD_BOTH
)
]
,
'question'
,
4
)
;
$
statistics
=
[
]
;
foreach
(
$
result
[
'statistics'
]
as
$
type
=>
$
statistic
)
{
$
statistics
[
]
=
[
'stats'
=>
$
type
,
'value'
=>
$
statistic
]
;
}
$
this
->
table
(
$
statistics
)
;
$
this
->
info
(
'Success'
)
;
}

Compilation, Optimization, Minification of assets js.
Use the Closure Compile API.

@option --verbose-externs : Display errors & warnings of externals files

Compilation Optimization Minification of assets js . Use the Closure Compile API .


public function bootstrap(Application $app)
    {
        // Workaround for CLI and URL based in subdirectory
        if ($app->runningInConsole()) {
            $app['url']->forceRootUrl($app['config']->get('app.url'));
        }

        // Register singletons
        $app->singleton('string', function () {
            return new \Igniter\Flame\Support\StrHelper;
        });

        // Change extensions and themes paths based on config
        if ($extensionsPath = $app['config']->get('system.extensionsPath'))
            $app->useExtensionsPath($extensionsPath);

        if ($themesPath = $app['config']->get('system.themesPath'))
            $app->useThemesPath($themesPath);

        if ($assetsPath = $app['config']->get('system.assetsPath'))
            $app->useAssetsPath($assetsPath);

        // Set execution context
        $requestPath = $this->normalizeUrl($app['request']->path());
        $adminUri = $this->normalizeUrl($app['config']->get('system.adminUri', 'admin'));
        $app->setAppContext(starts_with($requestPath, $adminUri) ? 'admin' : 'main');
    }

Register specifics for TastyIgniter.

@param  \Illuminate\Contracts\Foundation\Application $app

@return void


protected function normalizeUrl($url)
    {
        if (substr($url, 0, 1) != '/')
            $url = '/'.$url;

        if (!strlen($url))
            $url = '/';

        return $url;
    }

protected function normalizeUrl ( $ url ) { if ( substr ( $ url , 0 , 1 ) != '/' ) $ url = '/' . $ url ; if ( ! strlen ( $ url ) ) $ url = '/' ; return $ url ; }

Adds leading slash from a URL.

@param string $url URL to normalize.

@return string Returns normalized URL.


public function add($pattern, $paths = null, $httpMethods = null)
    {
        foreach ($httpMethods as $httpMethod) {
            $this->application->{strtolower($httpMethod)}($pattern, $this->pathToHandler($paths));
        }

        return null;
    }

public function add ( $ pattern , $ paths = null , $ httpMethods = null ) { foreach ( $ httpMethods as $ httpMethod ) { $ this -> application -> { strtolower ( $ httpMethod ) } ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; } return null ; }

Adds a route to the router on any HTTP method

@param string $pattern
@param mixed  $paths
@param mixed  $httpMethods

@return \Phalcon\Mvc\Router\RouteInterface


public function addGet($pattern, $paths = null)
    {
        return $this->application->get($pattern, $this->pathToHandler($paths));
    }

public function addGet ( $ pattern , $ paths = null ) { return $ this -> application -> get ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; }

Adds a route to the router that only match if the HTTP method is GET

@param string $pattern
@param mixed  $paths

@return \Phalcon\Mvc\Router\RouteInterface


public function addPost($pattern, $paths = null)
    {
        return $this->application->post($pattern, $this->pathToHandler($paths));
    }

public function addPost ( $ pattern , $ paths = null ) { return $ this -> application -> post ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; }

Adds a route to the router that only match if the HTTP method is POST

@param string $pattern
@param mixed  $paths

@return \Phalcon\Mvc\Router\RouteInterface


public function addPut($pattern, $paths = null)
    {
        return $this->application->put($pattern, $this->pathToHandler($paths));
    }

public function addPut ( $ pattern , $ paths = null ) { return $ this -> application -> put ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; }

Adds a route to the router that only match if the HTTP method is PUT

@param string $pattern
@param mixed  $paths

@return \Phalcon\Mvc\Router\RouteInterface


public function addPatch($pattern, $paths = null)
    {
        return $this->application->patch($pattern, $this->pathToHandler($paths));
    }

public function addPatch ( $ pattern , $ paths = null ) { return $ this -> application -> patch ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; }

Adds a route to the router that only match if the HTTP method is PATCH

@param string $pattern
@param mixed  $paths

@return \Phalcon\Mvc\Router\RouteInterface


public function addDelete($pattern, $paths = null)
    {
        return $this->application->delete($pattern, $this->pathToHandler($paths));
    }

public function addDelete ( $ pattern , $ paths = null ) { return $ this -> application -> delete ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; }

Adds a route to the router that only match if the HTTP method is DELETE

@param string $pattern
@param mixed  $paths

@return \Phalcon\Mvc\Router\RouteInterface


public function addOptions($pattern, $paths = null)
    {
        return $this->application->options($pattern, $this->pathToHandler($paths));
    }

public function addOptions ( $ pattern , $ paths = null ) { return $ this -> application -> options ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; }

Add a route to the router that only match if the HTTP method is OPTIONS

@param string $pattern
@param mixed  $paths

@return \Phalcon\Mvc\Router\RouteInterface


public function addHead($pattern, $paths = null)
    {
        return $this->application->head($pattern, $this->pathToHandler($paths));
    }

public function addHead ( $ pattern , $ paths = null ) { return $ this -> application -> head ( $ pattern , $ this -> pathToHandler ( $ paths ) ) ; }

Adds a route to the router that only match if the HTTP method is HEAD

@param string $pattern
@param mixed  $paths

@return \Phalcon\Mvc\Router\RouteInterface


public function render($context = [])
    {
        $this->mergeGlobals($context);

        unset($context['this']);

        $obLevel = ob_get_level();
        ob_start();

        extract($context);

        // We'll evaluate the contents of the view inside a try/catch block so we can
        // flush out any stray output that might get out before an error occurs or
        // an exception is thrown. This prevents any partial views from leaking.
        try {
            $filePath = $this->path;
            include $filePath;
        }
        catch (Exception $e) {
            $this->handleException($e, $obLevel);
        }
        catch (Throwable $e) {
            $this->handleException(new FatalThrowableError($e), $obLevel);
        }

        return ob_get_clean();
    }

Renders the template.

@param array $context An array of parameters to pass to the template

@return string The rendered template
@throws \Exception
@throws \Throwable


public function source($name = null)
    {
        if (is_null($name)) {
            $name = $this->getDefaultSourceName();
        }

        return $this->sources[$name];
    }

public function source ( $ name = null ) { if ( is_null ( $ name ) ) { $ name = $ this -> getDefaultSourceName ( ) ; } return $ this -> sources [ $ name ] ; }

Get a source instance.

@param  string $name

@return \Igniter\Flame\Pagic\Source\SourceInterface


public function create($name, $path, $table = null, $create = false)
    {
        $this->ensureMigrationDoesntAlreadyExist($name, $path);

        $stub = $this->getStubContent($table, $create);

        $populatedStub = $this->populateStub($name, $stub, $table);

        $path = $this->getPath($name, $path);

        file_put_contents($path, $populatedStub);

        return $path;
    }

public function create ( $ name , $ path , $ table = null , $ create = false ) { $ this -> ensureMigrationDoesntAlreadyExist ( $ name , $ path ) ; $ stub = $ this -> getStubContent ( $ table , $ create ) ; $ populatedStub = $ this -> populateStub ( $ name , $ stub , $ table ) ; $ path = $ this -> getPath ( $ name , $ path ) ; file_put_contents ( $ path , $ populatedStub ) ; return $ path ; }

Create a new migration at the given path.

@param  string $name
@param  string $path
@param  string $table
@param  bool   $create

@return string
@throws \Exception

Create a new migration at the given path .


protected function ensureMigrationDoesntAlreadyExist($name, $path)
    {
        if (class_exists($className = $this->getClassName($name))) {
            throw new InvalidArgumentException("A {$className} class already exists.");
        }

        // TODO Review check for version 2.0
        if(!empty($files = glob($path . '/*_*.php'))){
            foreach ($files as $file) {
                $file = str_replace('.php', '', basename($file));

                $migration = $this->prefix->deletePrefix($file);

                if($className === $this->getClassName($migration)){
                    throw new InvalidArgumentException("A {$className} class already exists.");
                }
            }
        }
    }

protected
function
ensureMigrationDoesntAlreadyExist
(
$
name
,
$
path
)
{
if
(
class_exists
(
$
className
=
$
this
->
getClassName
(
$
name
)
)
)
{
throw
new
InvalidArgumentException
(
"A {$className} class already exists."
)
;
}
// TODO Review check for version 2.0
if
(
!
empty
(
$
files
=
glob
(
$
path
.
'/*_*.php'
)
)
)
{
foreach
(
$
files
as
$
file
)
{
$
file
=
str_replace
(
'.php'
,
''
,
basename
(
$
file
)
)
;
$
migration
=
$
this
->
prefix
->
deletePrefix
(
$
file
)
;
if
(
$
className
===
$
this
->
getClassName
(
$
migration
)
)
{
throw
new
InvalidArgumentException
(
"A {$className} class already exists."
)
;
}
}
}
}

Ensure that a migration with the given name doesn't already exist.

@param  string $name
@param  string $path

@return void

@throws \InvalidArgumentException

Ensure that a migration with the given name doesn t already exist .


protected function getStubContent($table, $create)
    {
        if (is_null($table)) {
            $file = $this->stubsPath() . '/blank.stub';
        } else {
            $stub = $create ? 'create.stub' : 'update.stub';

            $file = $this->stubsPath() . '/' . $stub;
        }

        return file_get_contents($file);
    }

protected function getStubContent ( $ table , $ create ) { if ( is_null ( $ table ) ) { $ file = $ this -> stubsPath ( ) . '/blank.stub' ; } else { $ stub = $ create ? 'create.stub' : 'update.stub' ; $ file = $ this -> stubsPath ( ) . '/' . $ stub ; } return file_get_contents ( $ file ) ; }

Get the migration stub file.

@param  string $table
@param  bool   $create

@return string


protected function getPath($name, $path)
    {
        if (!is_null($prefix = $this->prefix->getPrefix())) {
            $prefix .= '_';
        }

        return $path . '/' . $prefix . $name . '.php';
    }

protected function getPath ( $ name , $ path ) { if ( ! is_null ( $ prefix = $ this -> prefix -> getPrefix ( ) ) ) { $ prefix .= '_' ; } return $ path . '/' . $ prefix . $ name . '.php' ; }

Get the full path to the migration.

@param  string $name
@param  string $path

@return string


public function scopeCausedBy(Builder $query, Model $causer)
    {
        return $query
            ->where('causer_type', $causer->getMorphClass())
            ->where('causer_id', $causer->getKey());
    }

public function scopeCausedBy ( Builder $ query , Model $ causer ) { return $ query -> where ( 'causer_type' , $ causer -> getMorphClass ( ) ) -> where ( 'causer_id' , $ causer -> getKey ( ) ) ; }

Scope a query to only include activities by a given causer.

@param \Igniter\Flame\Database\Builder $query
@param Model $causer

@return \Illuminate\Database\Eloquent\Builder

Scope a query to only include activities by a given causer .


public function scopeForSubject(Builder $query, Model $subject)
    {
        return $query
            ->where('subject_type', $subject->getMorphClass())
            ->where('subject_id', $subject->getKey());
    }

public function scopeForSubject ( Builder $ query , Model $ subject ) { return $ query -> where ( 'subject_type' , $ subject -> getMorphClass ( ) ) -> where ( 'subject_id' , $ subject -> getKey ( ) ) ; }

Scope a query to only include activities for a given subject.

@param \Igniter\Flame\Database\Builder $query
@param Model $subject

@return \Illuminate\Database\Eloquent\Builder

Scope a query to only include activities for a given subject .


protected function buildArrayExpression($targetKey, $arrayItems = [])
    {
        $expression = [];

        // Opening expression for array items ($1)
        $expression[] = $this->buildArrayOpeningExpression($arrayItems);

        // The target key opening ($2)
        $expression[] = '([\'|"]'.$targetKey.'[\'|"]\s*=>\s*)';

        // The target value to be replaced ($3)
        $expression[] = '(?:[aA][rR]{2}[aA][yY]\(|[\[])([^\]|)]*)[\]|)]';

        return '/'.implode('', $expression).'/';
    }

Single level arrays only
@param $targetKey
@param array $arrayItems
@return string


protected function getMigrationPaths()
    {
        // Here, we will check to see if a path option has been defined. If it has we will
        // use the path relative to the root of the installation folder so our database
        // migrations may be run for any customized path from within the application.
        if ($this->hasOption('path') && $this->getOption('path')) {
            return array_map(function ($path) {
                return BASE_PATH . '/' . $path;
            }, (array)$this->getOption('path'));
        }

        return array_merge(
            [$this->getMigrationPath()], $this->migrator->paths()
        );
    }

Get all of the migration paths.

@return array


public function mainAction()
    {
        $compileDir = $this->config->view->compiled_path;

        $this->rm($compileDir);

        $this->info('Compiled views cleared!');
    }

public
function
mainAction
(
)
{
$
compileDir
=
$
this
->
config
->
view
->
compiled_path
;
$
this
->
rm
(
$
compileDir
)
;
$
this
->
info
(
'Compiled views cleared!'
)
;
}

Clear all compiled view files.

@description Clear all compiled view files.


public function setParams($parameters, $merge = false)
    {
        if ($merge) {
            $this->params = array_merge($this->params, $parameters);
        } else {
            $this->params = $parameters;
        }

        return $this;
    }

public function setParams ( $ parameters , $ merge = false ) { if ( $ merge ) { $ this -> params = array_merge ( $ this -> params , $ parameters ) ; } else { $ this -> params = $ parameters ; } return $ this ; }

Define the parameters

@param array $parameters
@param bool $merge Merge or Erase current parameters

@return $this


public function setHeaders($headers, $merge = false)
    {
        $this->header->setHeaders($headers, $merge);

        return $this;
    }

public function setHeaders ( $ headers , $ merge = false ) { $ this -> header -> setHeaders ( $ headers , $ merge ) ; return $ this ; }

Define the headers

@param array $headers
@param bool $merge Merge or Erase current headers

@return $this


public function setProxy($host, $port = 8080, $access = null)
    {
        $this->proxy = [
            'host'   => $host,
            'port'   => $port,
            'access' => $access,
        ];

        return $this;
    }

public function setProxy ( $ host , $ port = 8080 , $ access = null ) { $ this -> proxy = [ 'host' => $ host , 'port' => $ port , 'access' => $ access , ] ; return $ this ; }

Define proxy setting

@param string $host
@param int $port
@param string $access

@return $this


public function setCookies($cookies, $merge = false)
    {
        if ($merge) {
            $this->cookies = array_merge($this->cookies, $cookies);
        } else {
            $this->cookies = $cookies;
        }

        return $this;
    }

public function setCookies ( $ cookies , $ merge = false ) { if ( $ merge ) { $ this -> cookies = array_merge ( $ this -> cookies , $ cookies ) ; } else { $ this -> cookies = $ cookies ; } return $ this ; }

Define the cookies

@param array $cookies
@param bool $merge Merge or Erase current cookies

@return $this


public function setCookie($key, $value)
    {
        if (is_null($key)) {
            $this->cookies[] = $value;
        } else {
            $this->cookies[$key] = $value;
        }

        return $this;
    }

public function setCookie ( $ key , $ value ) { if ( is_null ( $ key ) ) { $ this -> cookies [ ] = $ value ; } else { $ this -> cookies [ $ key ] = $ value ; } return $ this ; }

Define a cookie

@param null|string $key
@param string $value

@return $this
@throws \InvalidArgumentException


public function setOptions($options, $merge = false)
    {
        if ($merge) {
            $this->options = array_merge($this->options, $options);
        } else {
            $this->options = $options;
        }

        return $this;
    }

public function setOptions ( $ options , $ merge = false ) { if ( $ merge ) { $ this -> options = array_merge ( $ this -> options , $ options ) ; } else { $ this -> options = $ options ; } return $ this ; }

Define the options

@param array $options
@param bool $merge Est-ce que l'on ajoute les options aux options existantes, ou les ecrases

@return $this


public function send()
    {
        $this
            ->buildParams()
            ->buildProxy()
            ->buildCookies()
            ->buildHeaders();

        $this->response = new Response();

        return $this->makeCall();
    }

public function send ( ) { $ this -> buildParams ( ) -> buildProxy ( ) -> buildCookies ( ) -> buildHeaders ( ) ; $ this -> response = new Response ( ) ; return $ this -> makeCall ( ) ; }

Send the request & return the response

@return \Neutrino\HttpClient\Response


public function request($method, $uri, array $params = [], array $options = [])
    {
        $this
            ->setMethod($method)
            ->setUri($uri);

        if (!empty($params)) {
            $this->setParams($params, true);
        }
        if (!empty($options['headers'])) {
            $this->setHeaders($options['headers'], true);
        }
        if (isset($options['full'])) {
            $this->setFullResponse($options['full']);
        }
        if (isset($options['json'])) {
            $this->setJsonRequest($options['json']);
        }

        return $this;
    }

public function request ( $ method , $ uri , array $ params = [ ] , array $ options = [ ] ) { $ this -> setMethod ( $ method ) -> setUri ( $ uri ) ; if ( ! empty ( $ params ) ) { $ this -> setParams ( $ params , true ) ; } if ( ! empty ( $ options [ 'headers' ] ) ) { $ this -> setHeaders ( $ options [ 'headers' ] , true ) ; } if ( isset ( $ options [ 'full' ] ) ) { $ this -> setFullResponse ( $ options [ 'full' ] ) ; } if ( isset ( $ options [ 'json' ] ) ) { $ this -> setJsonRequest ( $ options [ 'json' ] ) ; } return $ this ; }

Build a HTTP request

@param string $method
@param string $uri
@param array $params
@param array $options

@return $this


public function build(Db $db, DialectInterface $grammar)
    {
        switch ($this->action) {
            case 'create':
                return $this->buildCreate($db, $grammar);
            case 'update':
                return $this->buildUpdate($db, $grammar);
            case 'dropIfExists':
                return $this->buildDrop($db, true);
            case 'drop':
                return $this->buildDrop($db, false);
            case 'raw':
                return $this->buildRaw($db, $grammar);
            default:
                if (empty($this->action)) {
                    $message = "Blueprint must has action";
                } else {
                    $message = "Action '{$this->action}' not supported.";
                }
                throw new \RuntimeException($message);
        }
    }

Execute the blueprint against the database.

@param \Phalcon\Db\AdapterInterface               $db
@param \Neutrino\Database\Schema\DialectInterface $grammar

@return bool
@throws \Exception

Execute the blueprint against the database .


protected function buildTableDefinition(DialectInterface $grammar)
    {
        // Manage primary key / multiple primary keys
        $primaries = [];

        // Extract defined primary index
        foreach ($this->indexes as $key => $index) {
            if ($index->get('type') == 'PRIMARY') {
                foreach ($index->get('columns') as $column) {
                    $this->columns[$column]->primary();
                }

                unset($this->indexes[$key]);
            }
        }

        // Extract defined primary column
        foreach ($this->columns as $column) {
            if ($column->get('primary')) {
                $primaries[] = $column->get('name');

                unset($column['primary']);
            }
        }

        // Re-Build primary index
        if (($cprimaries = count($primaries)) === 1) {
            $this->columns[array_shift($primaries)]->primary();
        } elseif ($cprimaries > 0) {
            $this->primary($primaries);
        }

        // Build table definition
        $definition = [];

        foreach ($this->columns as $column) {
            $definition['columns'][] = $this->fluentToColumn($column, $grammar);
        }

        foreach ($this->indexes as $index) {
            $definition['indexes'][] = $this->fluentToIndex($index, $grammar);
        }

        foreach ($this->references as $reference) {
            $definition['references'][] = $this->fluentToReference($reference);
        }

        foreach ($this->options as $name => $value) {
            $definition['options'][strtoupper($name)] = $value;
        }

        return $definition;
    }

Build the table definition for table creation

@param \Neutrino\Database\Schema\DialectInterface $grammar

@return array


protected function buildCommands(Db $db)
    {
        $columns = $db->describeColumns($this->table, $this->schema);
        foreach ($this->columns as $column) {
            $this->buildIndexAndForeignFromFluentColumn($column);

            foreach ($columns as $c) {
                if ($c->getName() === $column->get('name')) {
                    $this->addCommand('modifyColumn', ['column' => $column, 'from' => $c]);
                    continue 2;
                }
            }

            $this->addCommand('addColumn', ['column' => $column]);
        }

        foreach ($this->indexes as $index) {
            $command = $index->get('type') === 'PRIMARY'
                ? 'addPrimary'
                : 'addIndex';

            $this->addCommand($command, ['index' => $index]);
        }

        foreach ($this->references as $reference) {
            $this->addCommand('addForeign', ['reference' => $reference]);
        }
    }

protected function buildCommands ( Db $ db ) { $ columns = $ db -> describeColumns ( $ this -> table , $ this -> schema ) ; foreach ( $ this -> columns as $ column ) { $ this -> buildIndexAndForeignFromFluentColumn ( $ column ) ; foreach ( $ columns as $ c ) { if ( $ c -> getName ( ) === $ column -> get ( 'name' ) ) { $ this -> addCommand ( 'modifyColumn' , [ 'column' => $ column , 'from' => $ c ] ) ; continue 2 ; } } $ this -> addCommand ( 'addColumn' , [ 'column' => $ column ] ) ; } foreach ( $ this -> indexes as $ index ) { $ command = $ index -> get ( 'type' ) === 'PRIMARY' ? 'addPrimary' : 'addIndex' ; $ this -> addCommand ( $ command , [ 'index' => $ index ] ) ; } foreach ( $ this -> references as $ reference ) { $ this -> addCommand ( 'addForeign' , [ 'reference' => $ reference ] ) ; } }

Build all columns, indexes, references, to commands

@param \Phalcon\Db\AdapterInterface $db

Build all columns indexes references to commands


public function index($columns, $name = null, $type = __FUNCTION__)
    {
        return $this->addIndex($type, $columns, $name);
    }

public function index ( $ columns , $ name = null , $ type = __FUNCTION__ ) { return $ this -> addIndex ( $ type , $ columns , $ name ) ; }

Specify an index for the table.

@param  string|array $columns
@param  string|null  $name
@param  string       $type Type of index

@return \Neutrino\Database\Schema\Definition


public function float($column, $scale = null)
    {
        return $this->addColumn(__FUNCTION__, $column, is_int($scale) ? ['scale' => $scale] : []);
    }

public function float ( $ column , $ scale = null ) { return $ this -> addColumn ( __FUNCTION__ , $ column , is_int ( $ scale ) ? [ 'scale' => $ scale ] : [ ] ) ; }

Create a new float column on the table.

@param  string $column
@param  int    $scale

@return \Neutrino\Database\Schema\Definition

Create a new float column on the table .


public function double($column, $scale = null)
    {
        return $this->addColumn(__FUNCTION__, $column, is_int($scale) ? ['scale' => $scale] : []);
    }

public function double ( $ column , $ scale = null ) { return $ this -> addColumn ( __FUNCTION__ , $ column , is_int ( $ scale ) ? [ 'scale' => $ scale ] : [ ] ) ; }

Create a new double column on the table.

@param  string $column
@param  int    $scale

@return \Neutrino\Database\Schema\Definition

Create a new double column on the table .


public function decimal($column, $scale = null)
    {
        return $this->addColumn(__FUNCTION__, $column, is_int($scale) ? ['scale' => $scale] : []);
    }

public function decimal ( $ column , $ scale = null ) { return $ this -> addColumn ( __FUNCTION__ , $ column , is_int ( $ scale ) ? [ 'scale' => $ scale ] : [ ] ) ; }

Create a new decimal column on the table.

@param  string $column
@param  int    $scale

@return \Neutrino\Database\Schema\Definition

Create a new decimal column on the table .


public function nullableTimestamps($precision = 0)
    {
        $this->timestamps($precision);

        $this->columns['created_at']->nullable();
        $this->columns['updated_at']->nullable();
    }

public function nullableTimestamps ( $ precision = 0 ) { $ this -> timestamps ( $ precision ) ; $ this -> columns [ 'created_at' ] -> nullable ( ) ; $ this -> columns [ 'updated_at' ] -> nullable ( ) ; }

Add nullable creation and update timestamps to the table.

@param  int $precision

@return void

Add nullable creation and update timestamps to the table .


public function nullableTimestampsTz($precision = 0)
    {
        $this->timestampsTz($precision);

        $this->columns['created_at']->nullable();
        $this->columns['updated_at']->nullable();
    }

public function nullableTimestampsTz ( $ precision = 0 ) { $ this -> timestampsTz ( $ precision ) ; $ this -> columns [ 'created_at' ] -> nullable ( ) ; $ this -> columns [ 'updated_at' ] -> nullable ( ) ; }

Add nullable creation and update timestampTz to the table.

@param  int $precision

@return void

Add nullable creation and update timestampTz to the table .


public function morphs($name, $indexName = null)
    {
        $this->unsignedInteger("{$name}_id");

        $this->string("{$name}_type");

        $this->index(["{$name}_id", "{$name}_type"], $indexName);
    }

public function morphs ( $ name , $ indexName = null ) { $ this -> unsignedInteger ( "{$name}_id" ) ; $ this -> string ( "{$name}_type" ) ; $ this -> index ( [ "{$name}_id" , "{$name}_type" ] , $ indexName ) ; }

Add the proper columns for a polymorphic table.

@param  string      $name
@param  string|null $indexName

@return void

Add the proper columns for a polymorphic table .


public function nullableMorphs($name, $indexName = null)
    {
        $this->unsignedInteger("{$name}_id")->nullable();

        $this->string("{$name}_type")->nullable();

        $this->index(["{$name}_id", "{$name}_type"], $indexName);
    }

public function nullableMorphs ( $ name , $ indexName = null ) { $ this -> unsignedInteger ( "{$name}_id" ) -> nullable ( ) ; $ this -> string ( "{$name}_type" ) -> nullable ( ) ; $ this -> index ( [ "{$name}_id" , "{$name}_type" ] , $ indexName ) ; }

Add nullable columns for a polymorphic table.

@param  string      $name
@param  string|null $indexName

@return void

Add nullable columns for a polymorphic table .


protected function addColumn($type, $name, array $parameters = [])
    {
        return $this->columns[$name] = new Definition(array_merge([
            'name' => $name,
            "type" => $type,
        ], $parameters));
    }

protected function addColumn ( $ type , $ name , array $ parameters = [ ] ) { return $ this -> columns [ $ name ] = new Definition ( array_merge ( [ 'name' => $ name , "type" => $ type , ] , $ parameters ) ) ; }

Add a new column to the blueprint.

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

@return \Neutrino\Database\Schema\Definition


protected function createReferenceName(array $columns, $on, array $references)
    {
        $strColumns = implode('_', $columns);
        $strReferences = implode('_', $references);

        $rawReferenceName = [$this->table, $strColumns, 'foreign', $on, $strReferences];

        $rawReferenceName = array_map(function ($value) {
            return trim(str_replace(['-', '.'], '_', $value), '_');
        }, $rawReferenceName);

        $rawReferenceName = array_filter($rawReferenceName);

        $index = strtolower(trim(implode('_', $rawReferenceName), '_'));

        return $index;
    }

protected function createReferenceName ( array $ columns , $ on , array $ references ) { $ strColumns = implode ( '_' , $ columns ) ; $ strReferences = implode ( '_' , $ references ) ; $ rawReferenceName = [ $ this -> table , $ strColumns , 'foreign' , $ on , $ strReferences ] ; $ rawReferenceName = array_map ( function ( $ value ) { return trim ( str_replace ( [ '-' , '.' ] , '_' , $ value ) , '_' ) ; } , $ rawReferenceName ) ; $ rawReferenceName = array_filter ( $ rawReferenceName ) ; $ index = strtolower ( trim ( implode ( '_' , $ rawReferenceName ) , '_' ) ) ; return $ index ; }

Create a default index name for the table.

@param  array  $columns
@param  string $on
@param  array  $references

@return string

Create a default index name for the table .


public static function add($array, $key, $value)
    {
        if (is_null(self::get($array, $key))) {
            self::set($array, $key, $value);
        }

        return $array;
    }

public static function add ( $ array , $ key , $ value ) { if ( is_null ( self :: get ( $ array , $ key ) ) ) { self :: set ( $ array , $ key , $ value ) ; } return $ array ; }

Add an element to an array using "dot" notation if it doesn't exist.

@param array  $array
@param string $key
@param mixed  $value

@return array

Add an element to an array using dot notation if it doesn t exist .


public static function collapse($array)
    {
        $results = [];

        foreach ($array as $values) {
            if (!self::accessible($values)) {
                continue;
            }

            $results = array_merge($results, $values);
        }

        return $results;
    }

public static function collapse ( $ array ) { $ results = [ ] ; foreach ( $ array as $ values ) { if ( ! self :: accessible ( $ values ) ) { continue ; } $ results = array_merge ( $ results , $ values ) ; } return $ results ; }

Collapse an array of arrays into a single array.

@param \ArrayAccess|array $array

@return array

Collapse an array of arrays into a single array .


public static function read($array, $key, $default = null)
    {
        if (is_null($key)) {
            return Obj::value($default);
        }

        return self::exists($array, $key) ? $array[$key] : Obj::value($default);
    }

public static function read ( $ array , $ key , $ default = null ) { if ( is_null ( $ key ) ) { return Obj :: value ( $ default ) ; } return self :: exists ( $ array , $ key ) ? $ array [ $ key ] : Obj :: value ( $ default ) ; }

Get an item from an array.

@param array  $array
@param string $key
@param mixed  $default

@return mixed


public static function fetch($array, $key, $default = null)
    {
        if (is_null($key)) {
            return Obj::value($default);
        }

        return isset($array[$key]) ? $array[$key] : Obj::value($default);
    }

public static function fetch ( $ array , $ key , $ default = null ) { if ( is_null ( $ key ) ) { return Obj :: value ( $ default ) ; } return isset ( $ array [ $ key ] ) ? $ array [ $ key ] : Obj :: value ( $ default ) ; }

Get an item, no null, from an array.

@param array  $array
@param string $key
@param mixed  $default

@return mixed


public static function pull(&$array, $key, $default = null)
    {
        $value = self::get($array, $key, $default);

        self::forget($array, $key);

        return $value;
    }

public static function pull ( & $ array , $ key , $ default = null ) { $ value = self :: get ( $ array , $ key , $ default ) ; self :: forget ( $ array , $ key ) ; return $ value ; }

Get a value from the array, and remove it.

@param array  $array
@param string $key
@param mixed  $default

@return mixed

Get a value from the array and remove it .


public static function map($callback, array $array, $recursive = false)
    {
        if($recursive){
            $func = function ($item) use (&$func, &$callback) {
                return is_array($item) ? array_map($func, $item) : call_user_func($callback, $item);
            };

            return array_map($func, $array);
        }

        return array_map($callback, $array);
    }

public static function map ( $ callback , array $ array , $ recursive = false ) { if ( $ recursive ) { $ func = function ( $ item ) use ( & $ func , & $ callback ) { return is_array ( $ item ) ? array_map ( $ func , $ item ) : call_user_func ( $ callback , $ item ) ; } ; return array_map ( $ func , $ array ) ; } return array_map ( $ callback , $ array ) ; }

Map an array recursively

@param callable $callback
@param array    $array
@param bool     $recursive Array map recursively

@return array


public static function explodePluckParameters($value, $key)
    {
        $value = is_string($value) ? explode('.', $value) : $value;

        $key = is_null($key) || is_array($key) ? $key : explode('.', $key);

        return [$value, $key];
    }

public static function explodePluckParameters ( $ value , $ key ) { $ value = is_string ( $ value ) ? explode ( '.' , $ value ) : $ value ; $ key = is_null ( $ key ) || is_array ( $ key ) ? $ key : explode ( '.' , $ key ) ; return [ $ value , $ key ] ; }

Explode the "value" and "key" arguments passed to "pluck".

@param string|array      $value
@param string|array|null $key

@return array

Explode the value and key arguments passed to pluck .


public static function levenshtein($word, $words, $order = SORT_ASC, $sort_flags = SORT_REGULAR)
    {
        foreach ($words as $w) {
            $result[$w] = levenshtein($word, $w);
        }

        if ($order & SORT_DESC) {
            arsort($result, $sort_flags);
        } else {
            asort($result, $sort_flags);
        }

        return $result;
    }

public static function levenshtein ( $ word , $ words , $ order = SORT_ASC , $ sort_flags = SORT_REGULAR ) { foreach ( $ words as $ w ) { $ result [ $ w ] = levenshtein ( $ word , $ w ) ; } if ( $ order & SORT_DESC ) { arsort ( $ result , $ sort_flags ) ; } else { asort ( $ result , $ sort_flags ) ; } return $ result ; }

Sort a words list by their levenshtein distance of word.

@param string   $word
@param string[] $words
@param int      $order
@param int      $sort_flags

@return mixed

Sort a words list by their levenshtein distance of word .


public static function capitalize($value)
    {
        static $capitalizeCache;

        $key = $value;

        if (isset($capitalizeCache[$key])) {
            return $capitalizeCache[$key];
        }

        return $capitalizeCache[$key] = ucwords(strtolower($value));
    }

public static function capitalize ( $ value ) { static $ capitalizeCache ; $ key = $ value ; if ( isset ( $ capitalizeCache [ $ key ] ) ) { return $ capitalizeCache [ $ key ] ; } return $ capitalizeCache [ $ key ] = ucwords ( strtolower ( $ value ) ) ; }

Convert a value to Capitalize case.

@param  string $value

@return string


public static function ucfirst($string)
    {
        return Str::upper(Str::substr($string, 0, 1)) . Str::substr($string, 1);
    }

public static function ucfirst ( $ string ) { return Str :: upper ( Str :: substr ( $ string , 0 , 1 ) ) . Str :: substr ( $ string , 1 ) ; }

Make a string's first character uppercase.

@param  string $string

@return string

Make a string s first character uppercase .


public function format(Location $location, string $format): string
    {
        $replace = [
            self::STREET_NUMBER => $location->getStreetNumber(),
            self::STREET_NAME => $location->getStreetName(),
            self::LOCALITY => $location->getLocality(),
            self::POSTAL_CODE => $location->getPostalCode(),
            self::SUB_LOCALITY => $location->getSubLocality(),
            self::COUNTRY_NAME => $location->getCountryName(),
            self::COUNTRY_CODE => $location->getCountryCode(),
            self::TIMEZONE => $location->getTimezone(),
        ];

        for ($level = 1; $level <= AdminLevelCollection::MAX_LEVEL_DEPTH; ++$level) {
            $adminLevel = $location->getAdminLevels()[$level] ?? null;
            $replace[self::ADMIN_LEVEL.$level] = $adminLevel ? $adminLevel->getName() : null;
            $replace[self::ADMIN_LEVEL_CODE.$level] = $adminLevel ? $adminLevel->getCode() : null;
        }

        return strtr($format, $replace);
    }

public function format ( Location $ location , string $ format ) : string { $ replace = [ self :: STREET_NUMBER => $ location -> getStreetNumber ( ) , self :: STREET_NAME => $ location -> getStreetName ( ) , self :: LOCALITY => $ location -> getLocality ( ) , self :: POSTAL_CODE => $ location -> getPostalCode ( ) , self :: SUB_LOCALITY => $ location -> getSubLocality ( ) , self :: COUNTRY_NAME => $ location -> getCountryName ( ) , self :: COUNTRY_CODE => $ location -> getCountryCode ( ) , self :: TIMEZONE => $ location -> getTimezone ( ) , ] ; for ( $ level = 1 ; $ level <= AdminLevelCollection :: MAX_LEVEL_DEPTH ; ++ $ level ) { $ adminLevel = $ location -> getAdminLevels ( ) [ $ level ] ?? null ; $ replace [ self :: ADMIN_LEVEL . $ level ] = $ adminLevel ? $ adminLevel -> getName ( ) : null ; $ replace [ self :: ADMIN_LEVEL_CODE . $ level ] = $ adminLevel ? $ adminLevel -> getCode ( ) : null ; } return strtr ( $ format , $ replace ) ; }

Transform a `Location` instance into a string representation.

@param Location $location
@param string $format

@return string

Transform a Location instance into a string representation .


protected function register()
    {
        $url = new \Phalcon\Mvc\Url();

        $appConf = $this->getDI()->getShared(Services::CONFIG)->app;

        $url->setBaseUri($appConf->base_uri);
        $url->setStaticBaseUri(isset($appConf->static_base_uri) ? $appConf->static_base_uri : $appConf->base_uri);

        return $url;
    }

protected function register ( ) { $ url = new \ Phalcon \ Mvc \ Url ( ) ; $ appConf = $ this -> getDI ( ) -> getShared ( Services :: CONFIG ) -> app ; $ url -> setBaseUri ( $ appConf -> base_uri ) ; $ url -> setStaticBaseUri ( isset ( $ appConf -> static_base_uri ) ? $ appConf -> static_base_uri : $ appConf -> base_uri ) ; return $ url ; }

The URL component is used to generate all kind of urls in the application

@return \Phalcon\Mvc\Url


protected function getComposerCmd()
    {
        if (!file_exists($this->getBasePath() . '/composer.phar')) {
            return 'composer';
        }

        $binary = ($phpBinary = getenv('PHP_BINARY')) ? $phpBinary : PHP_BINARY;

        return $binary . ' composer.phar';
    }

protected
function
getComposerCmd
(
)
{
if
(
!
file_exists
(
$
this
->
getBasePath
(
)
.
'/composer.phar'
)
)
{
return
'composer'
;
}
$
binary
=
(
$
phpBinary
=
getenv
(
'PHP_BINARY'
)
)
$
phpBinary
:
PHP_BINARY
;
return
$
binary
.
' composer.phar'
;
}

Return the composer command line

@return string


protected function buildParams()
    {
            if ($this->isPostMethod()) {
                $params = $this->params;
                if ($this->isJsonRequest()) {
                    return $this
                        ->setOption('content', $params = json_encode($params))
                        ->setHeader('Content-Type', 'application/json')
                        ->setHeader('Content-Length', strlen($params));
                }

                if (!empty($params)) {
                    if (!is_string($params)) {
                        $params = http_build_query($params);
                    }

                    return $this
                        ->setOption('content', $params)
                        ->setHeader('Content-Type', 'application/x-www-form-urlencoded')
                        ->setHeader('Content-Length', strlen($params));
                }

                return $this;
            }

            return $this->buildUrl();
    }

protected function buildParams ( ) { if ( $ this -> isPostMethod ( ) ) { $ params = $ this -> params ; if ( $ this -> isJsonRequest ( ) ) { return $ this -> setOption ( 'content' , $ params = json_encode ( $ params ) ) -> setHeader ( 'Content-Type' , 'application/json' ) -> setHeader ( 'Content-Length' , strlen ( $ params ) ) ; } if ( ! empty ( $ params ) ) { if ( ! is_string ( $ params ) ) { $ params = http_build_query ( $ params ) ; } return $ this -> setOption ( 'content' , $ params ) -> setHeader ( 'Content-Type' , 'application/x-www-form-urlencoded' ) -> setHeader ( 'Content-Length' , strlen ( $ params ) ) ; } return $ this ; } return $ this -> buildUrl ( ) ; }

Construit les parametres de la requete.

@return $this

Construit les parametres de la requete .


protected function buildHeaders()
    {
        $headers = $this->header->build();

        return $this->setOption('header', implode(PHP_EOL, $headers));
    }

protected function buildHeaders ( ) { $ headers = $ this -> header -> build ( ) ; return $ this -> setOption ( 'header' , implode ( PHP_EOL , $ headers ) ) ; }

Construit les headers de la requete.

@return $this


protected function buildProxy()
    {
        if (isset($this->proxy['host'])) {
            $uri = new Uri([
                'scheme' => 'tcp',
                'host'   => $this->proxy['host'],
                'port'   => isset($this->proxy['port']) ? $this->proxy['port'] : 80,
            ]);

            if (isset($this->proxy['access'])) {
                $uri->user = $this->proxy['access'];
            }

            $this->setOption('proxy', $uri->build());
        }

        return $this;
    }

protected function buildProxy ( ) { if ( isset ( $ this -> proxy [ 'host' ] ) ) { $ uri = new Uri ( [ 'scheme' => 'tcp' , 'host' => $ this -> proxy [ 'host' ] , 'port' => isset ( $ this -> proxy [ 'port' ] ) ? $ this -> proxy [ 'port' ] : 80 , ] ) ; if ( isset ( $ this -> proxy [ 'access' ] ) ) { $ uri -> user = $ this -> proxy [ 'access' ] ; } $ this -> setOption ( 'proxy' , $ uri -> build ( ) ) ; } return $ this ; }

Construit le proxy de la requete

@return $this


protected function buildCookies()
    {
        if (!empty($this->cookies)) {
            return $this->setHeader('Cookie', $this->getCookies(true));
        }

        return $this;
    }

protected function buildCookies ( ) { if ( ! empty ( $ this -> cookies ) ) { return $ this -> setHeader ( 'Cookie' , $ this -> getCookies ( true ) ) ; } return $ this ; }

Construit les cookies de la requete

@return $this


public static function observe($class)
    {
        $instance = new static;

        $className = is_string($class) ? $class : get_class($class);

        // When registering a model observer, we will spin through the possible events
        // and determine if this observer has that method. If it does, we will hook
        // it into the model's event system, making it convenient to watch these.
        foreach ($instance->getObservableEvents() as $event) {
            if (method_exists($class, $event)) {
                static::registerModelEvent($event, $className.'@'.$event);
            }
        }
    }

Register an observer with the Model.

@param  object|string $class

@return void


protected static function registerModelEvent($event, $callback, $priority = 0)
    {
        if (isset(static::$dispatcher)) {
            $name = static::class;

            static::$dispatcher->listen("eloquent.{$event}: {$name}", $callback, $priority);
        }
    }

protected
static
function
registerModelEvent
(
$
event
,
$
callback
,
$
priority
=
0
)
{
if
(
isset
(
static
::
$
dispatcher
)
)
{
$
name
=
static
::
class
;
static
::
$
dispatcher
->
listen
(
"eloquent.{$event}: {$name}"
,
$
callback
,
$
priority
)
;
}
}

Register a model event with the dispatcher.

@param  string $event
@param  \Closure|string $callback
@param  int $priority

@return void

Register a model event with the dispatcher .


protected function bootNicerEvents()
    {
        $class = get_called_class();

        if (isset(static::$eventsBooted[$class])) {
            return;
        }

        $radicals = ['creat', 'sav', 'updat', 'delet', 'retriev'];
        $hooks = ['before' => 'ing', 'after' => 'ed'];

        foreach ($radicals as $radical) {
            foreach ($hooks as $hook => $event) {

                $eventMethod = $radical.$event; // saving / saved
                $method = $hook.ucfirst($radical); // beforeSave / afterSave
                if ($radical != 'fetch') $method .= 'e';

                self::$eventMethod(function ($model) use ($method) {
                    $model->fireEvent('model.'.$method);

                    if ($model->methodExists($method))
                        return $model->$method();
                });
            }
        }

        /*
         * Hook to boot events
         */
        static::registerModelEvent('booted', function ($model) {
            $model->fireEvent('model.afterBoot');
            if ($model->methodExists('afterBoot'))
                return $model->afterBoot();
        });

        static::$eventsBooted[$class] = TRUE;
    }

/*
         * Hook to boot events
         */

Bind some nicer events to this model, in the format of method overrides.

Bind some nicer events to this model in the format of method overrides .


public static function flushEventListeners()
    {
        if (!isset(static::$dispatcher)) {
            return;
        }

        $instance = new static;

        foreach ($instance->getObservableEvents() as $event) {
            static::$dispatcher->forget("eloquent.{$event}: ".static::class);
        }
    }

public
static
function
flushEventListeners
(
)
{
if
(
!
isset
(
static
::
$
dispatcher
)
)
{
return
;
}
$
instance
=
new
static
;
foreach
(
$
instance
->
getObservableEvents
(
)
as
$
event
)
{
static
::
$
dispatcher
->
forget
(
"eloquent.{$event}: "
.
static
::
class
)
;
}
}

Remove all of the event listeners for the model.

@return void

Remove all of the event listeners for the model .


protected function createLocationModelQuery()
    {
        $model = $this->createLocationModel();
        $query = $model->newQuery();
        $this->extendLocationQuery($query);

        return $query;
    }

protected function createLocationModelQuery ( ) { $ model = $ this -> createLocationModel ( ) ; $ query = $ model -> newQuery ( ) ; $ this -> extendLocationQuery ( $ query ) ; return $ query ; }

Prepares a query derived from the location model.

Prepares a query derived from the location model .


public function getById($identifier)
    {
        $query = $this->createLocationModelQuery();
        $location = $query->find($identifier);

        return $location ?: null;
    }

public function getById ( $ identifier ) { $ query = $ this -> createLocationModelQuery ( ) ; $ location = $ query -> find ( $ identifier ) ; return $ location ? : null ; }

Retrieve a location by their unique identifier.

@param  mixed $identifier

@return \Igniter\Flame\Location\Models\AbstractLocation|null

Retrieve a location by their unique identifier .


public function getBySlug($slug)
    {
        $model = $this->createLocationModel();
        $query = $this->createLocationModelQuery();
        $location = $query->where($model->getSlugKeyName(), $slug)->first();

        return $location ?: null;
    }

public function getBySlug ( $ slug ) { $ model = $ this -> createLocationModel ( ) ; $ query = $ this -> createLocationModelQuery ( ) ; $ location = $ query -> where ( $ model -> getSlugKeyName ( ) , $ slug ) -> first ( ) ; return $ location ? : null ; }

Retrieve a location by their unique slug.

@param  string $slug

@return \Igniter\Flame\Location\Contracts\LocationInterface|null

Retrieve a location by their unique slug .


public function message($message = null, $level = null)
    {
        // If no message was provided, we should update
        // the most recently added message.
        if (!$message) {
            return $this->updateLastMessage(compact('level'));
        }

        if (!$message instanceof Message) {
            $message = new Message(compact('message', 'level'));
        }

        $this->messages()->push($message);

        return $this->flash();
    }

Flash a general message.

@param  string|null $message
@param  string|null $level

@return $this


public function overlay($message = null, $title = '')
    {
        if (!$message) {
            return $this->updateLastMessage(['title' => $title, 'overlay' => TRUE]);
        }

        return $this->message(
            new OverlayMessage(compact('title', 'message'))
        );
    }

public function overlay ( $ message = null , $ title = '' ) { if ( ! $ message ) { return $ this -> updateLastMessage ( [ 'title' => $ title , 'overlay' => TRUE ] ) ; } return $ this -> message ( new OverlayMessage ( compact ( 'title' , 'message' ) ) ) ; }

Flash an overlay modal.

@param  string|null $message
@param  string $title

@return $this


public function clear()
    {
        $this->store->forget($this->sessionKey);

        $this->messages = collect();

        return $this;
    }

public function clear ( ) { $ this -> store -> forget ( $ this -> sessionKey ) ; $ this -> messages = collect ( ) ; return $ this ; }

Clear all registered messages.
@return $this


public function addTask($command, $class, $action = null, array $params = [])
    {
        $params['task'] = $class;

        $params['action'] = $action;

        preg_match_all('/\{([\w_]+)\}/', $command, $matches);

        foreach ($matches[0] as $k => $match) {
            $command = str_replace($match, '([[:word:]]+)', $command);

            $params[substr($match, 1, -1)] = $k + 1;
        }

        return $this->add($command, $params);
    }

public function addTask ( $ command , $ class , $ action = null , array $ params = [ ] ) { $ params [ 'task' ] = $ class ; $ params [ 'action' ] = $ action ; preg_match_all ( '/\{([\w_]+)\}/' , $ command , $ matches ) ; foreach ( $ matches [ 0 ] as $ k => $ match ) { $ command = str_replace ( $ match , '([[:word:]]+)' , $ command ) ; $ params [ substr ( $ match , 1 , - 1 ) ] = $ k + 1 ; } return $ this -> add ( $ command , $ params ) ; }

Adds a route to the router, with task as class.

ex : $router->addTask('some', SomeTask::class);

@param string      $command
@param string      $class
@param string|null $action
@param array       $params

@return \Phalcon\Cli\Router\Route|\Phalcon\Cli\Router\RouteInterface

Adds a route to the router with task as class .


public function registering()
    {
        $di = Di::getDefault();

        $this->registerPrefix($di);
        $this->registerStorage($di);
        $this->registerMigrator($di);
        $this->registerMigrationCreator($di);
    }

public function registering ( ) { $ di = Di :: getDefault ( ) ; $ this -> registerPrefix ( $ di ) ; $ this -> registerStorage ( $ di ) ; $ this -> registerMigrator ( $ di ) ; $ this -> registerMigrationCreator ( $ di ) ; }

Called upon bootstrap the application.
Adds to container services desired services.

@return void

Called upon bootstrap the application . Adds to container services desired services .


protected function registerPrefix(DiInterface $di)
    {
        $di->set(PrefixInterface::class, function () {
            $config = $this->get(Services::CONFIG);

            return new $config->migrations->prefix;
        }, true);
    }

protected function registerPrefix ( DiInterface $ di ) { $ di -> set ( PrefixInterface :: class , function ( ) { $ config = $ this -> get ( Services :: CONFIG ) ; return new $ config -> migrations -> prefix ; } , true ) ; }

Register Migrations\Prefix

@param \Phalcon\DiInterface $di


protected function registerStorage(DiInterface $di)
    {
        $di->set(StorageInterface::class, function () {
            $config = $this->get(Services::CONFIG);

            return new $config->migrations->storage;
        }, true);
    }

protected function registerStorage ( DiInterface $ di ) { $ di -> set ( StorageInterface :: class , function ( ) { $ config = $ this -> get ( Services :: CONFIG ) ; return new $ config -> migrations -> storage ; } , true ) ; }

Register Migrations\Storage

@param \Phalcon\DiInterface $di


public function boot()
    {
        if ($module = $this->getModule(func_get_args())) {
            // Register paths for: config, translator, view
            $modulePath = app_path($module);
            $this->loadTranslationsFrom($modulePath.DIRECTORY_SEPARATOR.'language', $module);
            $this->loadViewsFrom($modulePath.DIRECTORY_SEPARATOR.'views', $module);
        }
    }


public function like($column, $value, $side = 'both', $boolean = 'and')
    {
        return $this->likeInternal($column, $value, $side, $boolean);
    }

public function like ( $ column , $ value , $ side = 'both' , $ boolean = 'and' ) { return $ this -> likeInternal ( $ column , $ value , $ side , $ boolean ) ; }

Convenient method for where like clause

@param  string $column
@param $value
@param string $side
@param string $boolean

@return \Igniter\Flame\Database\Builder


public function pluckDates($column, $keyFormat = '%Y-%m', $valueFormat = '%F %Y')
    {
        $dates = [];

        $collection = $this->selectRaw("{$column}, MONTH({$column}) as month, YEAR({$column}) as year")
                           ->groupBy([$column, 'month', 'year'])->get();

        if ($collection) {
            foreach ($collection as $date) {
                $key = mdate($keyFormat, strtotime($date[$column]));
                $value = mdate($valueFormat, strtotime($date[$column]));
                $dates[$key] = $value;
            }
        }

        return $dates;
    }

Get an array with the values of dates.

@param  string $column
@param string $keyFormat
@param string $valueFormat

@return array


public function findOrNew($id, $columns = ['*'])
    {
        if (!is_null($model = $this->find($id, $columns))) {
            return $model;
        }

        $attributes = $this->toBase()->getConnection()->getSchemaBuilder()->getColumnListing($this->model->getTable());

        return $this->model->newInstance(array_fill_keys(array_values($attributes), null))->setConnection(
            $this->toBase()->getConnection()->getName()
        );
    }

public function findOrNew ( $ id , $ columns = [ '*' ] ) { if ( ! is_null ( $ model = $ this -> find ( $ id , $ columns ) ) ) { return $ model ; } $ attributes = $ this -> toBase ( ) -> getConnection ( ) -> getSchemaBuilder ( ) -> getColumnListing ( $ this -> model -> getTable ( ) ) ; return $ this -> model -> newInstance ( array_fill_keys ( array_values ( $ attributes ) , null ) ) -> setConnection ( $ this -> toBase ( ) -> getConnection ( ) -> getName ( ) ) ; }

Find a model by its primary key or return fresh model instance
with filled attributes to use with forms.

@param  mixed $id
@param  array $columns

@return \Illuminate\Database\Eloquent\Model

Find a model by its primary key or return fresh model instance with filled attributes to use with forms .


public function user()
    {
        if ($this->loggedOut) {
            return null;
        }

        if (!is_null($this->user)) {
            return $this->user;
        }

        $user = null;

        if (!is_null($id = $this->retrieveIdentifier())) {
            $user = $this->retrieveUserByIdentifier($id);
        }

        if (empty($user)) {
            /** @var \Phalcon\Http\Response\Cookies $cookies */
            $cookies = $this->{Services::COOKIES};
            if ($cookies->has('remember_me')) {
                $recaller = $cookies->get('remember_me')->getValue();

                list($identifier, $token) = explode('|', $recaller);

                if ($identifier && $token) {
                    $user = $this->retrieveUserByToken($identifier, $token);

                    if ($user) {
                        $this->{Services::SESSION}->set($this->sessionKey(), $user->getAuthIdentifier());
                    }
                }
            }
        }

        $this->user = $user;

        return $this->user;
    }

Return the user authenticated

@return \Neutrino\Foundation\Auth\User|null


public function logout()
    {
        $this->user      = null;
        $this->loggedOut = true;

        $this->{Services::SESSION}->destroy();
        $this->{Services::COOKIES}->delete('remember_me');
    }

public function logout ( ) { $ this -> user = null ; $ this -> loggedOut = true ; $ this -> { Services :: SESSION } -> destroy ( ) ; $ this -> { Services :: COOKIES } -> delete ( 'remember_me' ) ; }


public function login(User $user, $remember = false)
    {
        if (!$user) {
            return false;
        }

        $this->regenerateSessionId();

        $this->{Services::SESSION}->set($this->sessionKey(), $user->getAuthIdentifier());

        if ($remember) {
            $rememberToken = Str::random(60);

            /** @var \Phalcon\Http\Response\Cookies|\Phalcon\Http\Response\CookiesInterface $cookies */
            $cookies = $this->{Services::COOKIES};
            $cookies->set('remember_me', $user->getAuthIdentifier() . '|' . $rememberToken, time() + (100 * 365 * 24 * 60 * 60));

            $user->setRememberToken($rememberToken);

            $user->save();
        }

        $this->user = $user;

        return true;
    }

Log a user into the application

@param User $user
@param bool $remember

@return bool


protected function retrieveUserByToken($identifier, $token)
    {
        $user = $this->retrieveUserByIdentifier($identifier);

        if (!empty($user) && $user->getRememberToken() === $token) {
            return $user;
        }

        return null;
    }

protected function retrieveUserByToken ( $ identifier , $ token ) { $ user = $ this -> retrieveUserByIdentifier ( $ identifier ) ; if ( ! empty ( $ user ) && $ user -> getRememberToken ( ) === $ token ) { return $ user ; } return null ; }

Retrieve a user by his identifier & remember token.

@param string $identifier
@param string $token

@return AuthenticableInterface|\Phalcon\Mvc\Model

Retrieve a user by his identifier & remember token .


protected function retrieveUserByCredentials(array $credentials)
    {
        $class = $this->modelClass();

        $identifier = $class::getAuthIdentifierName();
        $password   = $class::getAuthPasswordName();

        $user = $this->retrieveUserByIdentifier(Arr::fetch($credentials, $identifier));

        if ($user) {
            /** @var \Phalcon\Security $security */
            $security = $this->{Services::SECURITY};

            if($security->checkHash(Arr::fetch($credentials, $password), $user->getAuthPassword())){
                return $user;
            }
        }

        return null;
    }

protected
function
retrieveUserByCredentials
(
array
$
credentials
)
{
$
class
=
$
this
->
modelClass
(
)
;
$
identifier
=
$
class
::
getAuthIdentifierName
(
)
;
$
password
=
$
class
::
getAuthPasswordName
(
)
;
$
user
=
$
this
->
retrieveUserByIdentifier
(
Arr
::
fetch
(
$
credentials
,
$
identifier
)
)
;
if
(
$
user
)
{
/** @var \Phalcon\Security $security */
$
security
=
$
this
->
{
Services
::
SECURITY
}
;
if
(
$
security
->
checkHash
(
Arr
::
fetch
(
$
credentials
,
$
password
)
,
$
user
->
getAuthPassword
(
)
)
)
{
return
$
user
;
}
}
return
;
}

Retrieve a user by credentials

@param array $credentials

@return \Neutrino\Foundation\Auth\User


private function dbProfilerRegister()
    {
        $profiler = self::registerProfiler('db', '<i class="nuc db"></i>');

        $this->em->attach(
          Events::DB,
          function (Event $event, Adapter\Pdo $connection) use ($profiler) {
              $eventType = $event->getType();
              if ($eventType === 'beforeQuery') {
                  // Start a profile with the active connection
                  $profiler->startProfile(
                    $connection->getSQLStatement(),
                    $connection->getSqlVariables(),
                    $connection->getSQLBindTypes()
                  );
              }
              if ($eventType === 'afterQuery') {
                  // Stop the active profile
                  $profiler->stopProfile();
              }
          }
        );
    }


private function viewProfilerRegister()
    {
        $this->em->attach(
          Events::VIEW,
          function (Event $event, $src, $data) {
              $eventType = $event->getType();
              if ($eventType === 'beforeRender') {
                  self::$viewProfiles['render'][] = self::$viewProfiles['__render'][] = [
                    'initialTime' => microtime(true)
                  ];
              } elseif ($eventType === 'beforeRenderView') {
                  self::$viewProfiles['__renderViews'][] = self::$viewProfiles['renderViews'][] = [
                    'file' => $data,
                    'initialTime' => microtime(true)
                  ];
              } elseif ($eventType === 'afterRenderView') {
                  $profile = array_pop(self::$viewProfiles['__renderViews']);
                  $profile['finalTime'] = microtime(true);
                  $profile['elapsedTime'] = $profile['finalTime'] - $profile['initialTime'];

                  self::$viewProfiles['renderViews'][count(self::$viewProfiles['__renderViews'])] = $profile;
              } elseif ($eventType === 'notFoundView') {
                  self::$viewProfiles['notFoundView'][] = $data;
              } elseif ($eventType === 'afterRender') {
                  $profile = array_pop(self::$viewProfiles['__render']);
                  $profile['finalTime'] = microtime(true);
                  $profile['elapsedTime'] = $profile['finalTime'] - $profile['initialTime'];

                  self::$viewProfiles['render'][count(self::$viewProfiles['__render'])] = $profile;
              }
          }
        );
    }

private function viewProfilerRegister ( ) { $ this -> em -> attach ( Events :: VIEW , function ( Event $ event , $ src , $ data ) { $ eventType = $ event -> getType ( ) ; if ( $ eventType === 'beforeRender' ) { self :: $ viewProfiles [ 'render' ] [ ] = self :: $ viewProfiles [ '__render' ] [ ] = [ 'initialTime' => microtime ( true ) ] ; } elseif ( $ eventType === 'beforeRenderView' ) { self :: $ viewProfiles [ '__renderViews' ] [ ] = self :: $ viewProfiles [ 'renderViews' ] [ ] = [ 'file' => $ data , 'initialTime' => microtime ( true ) ] ; } elseif ( $ eventType === 'afterRenderView' ) { $ profile = array_pop ( self :: $ viewProfiles [ '__renderViews' ] ) ; $ profile [ 'finalTime' ] = microtime ( true ) ; $ profile [ 'elapsedTime' ] = $ profile [ 'finalTime' ] - $ profile [ 'initialTime' ] ; self :: $ viewProfiles [ 'renderViews' ] [ count ( self :: $ viewProfiles [ '__renderViews' ] ) ] = $ profile ; } elseif ( $ eventType === 'notFoundView' ) { self :: $ viewProfiles [ 'notFoundView' ] [ ] = $ data ; } elseif ( $ eventType === 'afterRender' ) { $ profile = array_pop ( self :: $ viewProfiles [ '__render' ] ) ; $ profile [ 'finalTime' ] = microtime ( true ) ; $ profile [ 'elapsedTime' ] = $ profile [ 'finalTime' ] - $ profile [ 'initialTime' ] ; self :: $ viewProfiles [ 'render' ] [ count ( self :: $ viewProfiles [ '__render' ] ) ] = $ profile ; } } ) ; }


protected function writeMigration($name, $table, $create)
    {
        $file = pathinfo($this->creator->create(
            $name, $this->getMigrationPath(), $table, $create
        ), PATHINFO_FILENAME);

        $this->info("Created Migration: {$file}");
    }

protected
function
writeMigration
(
$
name
,
$
table
,
$
create
)
{
$
file
=
pathinfo
(
$
this
->
creator
->
create
(
$
name
,
$
this
->
getMigrationPath
(
)
,
$
table
,
$
create
)
,
PATHINFO_FILENAME
)
;
$
this
->
info
(
"Created Migration: {$file}"
)
;
}

Write the migration file to disk.

@param  string $name
@param  string $table
@param  bool   $create


protected static function eventsToBeRecorded()
    {
        if (isset(static::$recordEvents)) {
            return collect(static::$recordEvents);
        }

        $events = collect([
            'created',
            'updated',
            'deleted',
        ]);

        if (collect(class_uses(__CLASS__))->contains(SoftDeletes::class)) {
            $events->push('restored');
        }

        return $events;
    }

protected static function eventsToBeRecorded ( ) { if ( isset ( static :: $ recordEvents ) ) { return collect ( static :: $ recordEvents ) ; } $ events = collect ( [ 'created' , 'updated' , 'deleted' , ] ) ; if ( collect ( class_uses ( __CLASS__ ) ) -> contains ( SoftDeletes :: class ) ) { $ events -> push ( 'restored' ) ; } return $ events ; }

Get the event names that should be recorded.

Get the event names that should be recorded .


private function arrayDump($var, $id = null, $idLabel = null)
    {
        $dump = '';
        if (!is_null($id)) {
            if (is_null($idLabel)) {
                $idLabel = '#' . $id;
            }
            $dump .= '' . $idLabel . '';
            $dump .= '
';
        } else {
            $dump .= '';
            $dump .= '
';
        }
        foreach ($var as $key => $val) {
            $dump .= '
canHasChild($val) ? ' nuc-close' : '') . '">';
            $dump .= $this->varDump($key) . ' => ';
            $dump .= $this->varDump($val);
            $dump .= '
';
        }

        $dump .= '
';

        return $dump;
    }

'<span class="nuc-toggle nuc-toggle-array" data-target="nuc-ref-'

Dump an array

@param array    $var
@param int|null $id
@param int|null $idLabel

@return string


private function getVarId($var)
    {
        if (is_object($var)) {
            $hash = spl_object_hash($var);
        } elseif (is_resource($var)) {
            $hash = intval($var) . '#resource#' . get_resource_type($var);
        } elseif (is_array($var) && $this->checkArrayRecursion($var)) {
            $hash = $this->getArrayId($var);
        }

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

            return $this->hash[$hash] = self::uid();
        }

        return null;
    }

private function getVarId ( $ var ) { if ( is_object ( $ var ) ) { $ hash = spl_object_hash ( $ var ) ; } elseif ( is_resource ( $ var ) ) { $ hash = intval ( $ var ) . '#resource#' . get_resource_type ( $ var ) ; } elseif ( is_array ( $ var ) && $ this -> checkArrayRecursion ( $ var ) ) { $ hash = $ this -> getArrayId ( $ var ) ; } if ( isset ( $ hash ) ) { if ( isset ( $ this -> hash [ $ hash ] ) ) { return $ this -> hash [ $ hash ] ; } return $ this -> hash [ $ hash ] = self :: uid ( ) ; } return null ; }

Return id for given object|array|resource

@param mixed $var

@return int|null


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

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

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

        $dump[] = $var;

        $hash = [];
        foreach ($var as $k => $v) {
            if (is_object($v)) {
                $hash[$k] = spl_object_hash($v);
            } elseif (is_array($v)) {
                $hash[$k] = $this->genArrayHash($v);
            } elseif (is_resource($v)) {
                $hash[$k] = intval($v) . get_resource_type($v);
            } else {
                $hash[$k] = $v;
            }
        }

        $hash = json_encode($hash);

        array_pop($dump);

        return $hash;
    }

private
function
genArrayHash
(
array
$
var
)
{
static
$
dump
;
if
(
!
isset
(
$
dump
)
)
{
$
dump
=
[
]
;
}
if
(
in_array
(
$
var
,
$
dump
,
true
)
)
{
return
'array recursion'
;
}
$
dump
[
]
=
$
var
;
$
hash
=
[
]
;
foreach
(
$
var
as
$
k
=>
$
v
)
{
if
(
is_object
(
$
v
)
)
{
$
hash
[
$
k
]
=
spl_object_hash
(
$
v
)
;
}
elseif
(
is_array
(
$
v
)
)
{
$
hash
[
$
k
]
=
$
this
->
genArrayHash
(
$
v
)
;
}
elseif
(
is_resource
(
$
v
)
)
{
$
hash
[
$
k
]
=
intval
(
$
v
)
.
get_resource_type
(
$
v
)
;
}
else
{
$
hash
[
$
k
]
=
$
v
;
}
}
$
hash
=
json_encode
(
$
hash
)
;
array_pop
(
$
dump
)
;
return
$
hash
;
}

Generate hash id for given array

@param array $var

@return string