public function getAcceptableContentTypes()
    {
        if ($this->_contentTypes === null) {
            if ($this->getHeaders()->get('Accept') !== null) {
                $this->_contentTypes = $this->parseAcceptHeader($this->getHeaders()->get('Accept'));
            } else {
                $this->_contentTypes = [];
            }
        }

        return $this->_contentTypes;
    }

public function getAcceptableContentTypes ( ) { if ( $ this -> _contentTypes === null ) { if ( $ this -> getHeaders ( ) -> get ( 'Accept' ) !== null ) { $ this -> _contentTypes = $ this -> parseAcceptHeader ( $ this -> getHeaders ( ) -> get ( 'Accept' ) ) ; } else { $ this -> _contentTypes = [ ] ; } } return $ this -> _contentTypes ; }

Returns the content types acceptable by the end user.

This is determined by the `Accept` HTTP header. For example,

```php
$_SERVER['HTTP_ACCEPT'] = 'text/plain; q=0.5, application/json; version=1.0, application/xml; version=2.0;';
$types = $request->getAcceptableContentTypes();
print_r($types);
// displays:
// [
//     'application/json' => ['q' => 1, 'version' => '1.0'],
//      'application/xml' => ['q' => 1, 'version' => '2.0'],
//           'text/plain' => ['q' => 0.5],
// ]
```

@return array the content types ordered by the quality score. Types with the highest scores
will be returned first. The array keys are the content types, while the array values
are the corresponding quality score and other parameters as given in the header.

Returns the content types acceptable by the end user .


public function getAcceptableLanguages()
    {
        if ($this->_languages === null) {
            if ($this->getHeaders()->has('Accept-Language')) {
                /** @var string $acceptLangHeader */
                $acceptLangHeader = $this->getHeaders()->get('Accept-Language');
                $this->_languages = array_keys($this->parseAcceptHeader($acceptLangHeader));
            } else {
                $this->_languages = [];
            }
        }

        return $this->_languages;
    }

public
function
getAcceptableLanguages
(
)
{
if
(
$
this
->
_languages
===
)
{
if
(
$
this
->
getHeaders
(
)
->
has
(
'Accept-Language'
)
)
{
/** @var string $acceptLangHeader */
$
acceptLangHeader
=
$
this
->
getHeaders
(
)
->
get
(
'Accept-Language'
)
;
$
this
->
_languages
=
array_keys
(
$
this
->
parseAcceptHeader
(
$
acceptLangHeader
)
)
;
}
else
{
$
this
->
_languages
=
[
]
;
}
}
return
$
this
->
_languages
;
}

Returns the languages acceptable by the end user.
This is determined by the `Accept-Language` HTTP header.
@return array the languages ordered by the preference level. The first element
represents the most preferred language.

Returns the languages acceptable by the end user . This is determined by the Accept - Language HTTP header .


public function getETags()
    {
        if ($this->getHeaders()->has('If-None-Match')) {
            /** @var string $ifNoneHeader */
            $ifNoneHeader = $this->getHeaders()->get('If-None-Match');
            $eTags = preg_split('/[\s,]+/', str_replace('-gzip', '', $ifNoneHeader), -1, PREG_SPLIT_NO_EMPTY);
            return is_array($eTags) ? $eTags : [];
        }

        return [];
    }

public
function
getETags
(
)
{
if
(
$
this
->
getHeaders
(
)
->
has
(
'If-None-Match'
)
)
{
/** @var string $ifNoneHeader */
$
ifNoneHeader
=
$
this
->
getHeaders
(
)
->
get
(
'If-None-Match'
)
;
$
eTags
=
preg_split
(
'/[\s,]+/'
,
str_replace
(
'-gzip'
,
''
,
$
ifNoneHeader
)
,
1
,
PREG_SPLIT_NO_EMPTY
)
;
return
is_array
(
$
eTags
)
$
eTags
:
[
]
;
}
return
[
]
;
}

Gets the Etags.

@return array The entity tags


public function getCsrfToken($regenerate = false)
    {
        if ($this->_csrfToken === null || $regenerate) {
            $token = $this->loadCsrfToken();
            if ($regenerate || empty($token)) {
                $token = $this->generateCsrfToken();
            }
            $this->_csrfToken = Reaction::$app->security->maskToken($token);
        }

        return $this->_csrfToken;
    }

public function getCsrfToken ( $ regenerate = false ) { if ( $ this -> _csrfToken === null || $ regenerate ) { $ token = $ this -> loadCsrfToken ( ) ; if ( $ regenerate || empty ( $ token ) ) { $ token = $ this -> generateCsrfToken ( ) ; } $ this -> _csrfToken = Reaction :: $ app -> security -> maskToken ( $ token ) ; } return $ this -> _csrfToken ; }

Returns the token used to perform CSRF validation.

This token is generated in a way to prevent [BREACH attacks](http://breachattack.com/). It may be passed
along via a hidden field of an HTML form or an HTTP header value to support CSRF validation.
@param bool $regenerate whether to regenerate CSRF token. When this parameter is true, each time
this method is called, a new CSRF token will be generated and persisted (in session or cookie).
@return string the token used to perform CSRF validation.

Returns the token used to perform CSRF validation .


protected function generateCsrfToken()
    {
        $token = Reaction::$app->security->generateRandomString();
        if ($this->enableCsrfCookie) {
            $cookie = $this->createCsrfCookie($token);
            $this->app->response->getCookies()->add($cookie);
        } else {
            $this->app->session->set($this->csrfParam, $token);
        }

        return $token;
    }

protected function generateCsrfToken ( ) { $ token = Reaction :: $ app -> security -> generateRandomString ( ) ; if ( $ this -> enableCsrfCookie ) { $ cookie = $ this -> createCsrfCookie ( $ token ) ; $ this -> app -> response -> getCookies ( ) -> add ( $ cookie ) ; } else { $ this -> app -> session -> set ( $ this -> csrfParam , $ token ) ; } return $ token ; }

Generates an unmasked random token used to perform CSRF validation.
@return string the random token for CSRF validation.

Generates an unmasked random token used to perform CSRF validation .


protected function getDefaultServerParams() {
        $scriptName = realpath($_SERVER['SCRIPT_FILENAME']);
        //Default script name fallback
        if (!$scriptName) {
            $scriptName = getcwd() . DIRECTORY_SEPARATOR . 'app';
        }
        $params = [
            'DOCUMENT_ROOT' => getcwd(),
            'SCRIPT_FILENAME' => $scriptName,
        ];

        return $params;
    }

protected
function
getDefaultServerParams
(
)
{
$
scriptName
=
realpath
(
$
_SERVER
[
'SCRIPT_FILENAME'
]
)
;
//Default script name fallback
if
(
!
$
scriptName
)
{
$
scriptName
=
getcwd
(
)
.
DIRECTORY_SEPARATOR
.
'app'
;
}
$
params
=
[
'DOCUMENT_ROOT'
=>
getcwd
(
)
,
'SCRIPT_FILENAME'
=>
$
scriptName
,
]
;
return
$
params
;
}

Get default server parameters
@return array


public function onLogin(InteractiveLoginEvent $event)
	{

		$user = $event->getAuthenticationToken()->getUser();
		if ($user) {
			$user->setLastLogin(new \DateTime());
			$user->setLogins($user->getLogins() + 1);
			$this->em->persist($user);
			$this->em->flush();

			/*$request = $event->getRequest();
			$session = $request->getSession();

			if (null != $user->getPreferedLocale()) {
				$locale = $user->getPreferedLocale();
				$session->set('_locale', $locale->getPrefix());

			}*/
		}

	}

Fired on login

@param InteractiveLoginEvent $event


public function crop(array $croppable, $index = 0)
    {
        $coordinates = $croppable['coordinates'][$index];

        $file = new UploadableFile($this->root_path, $croppable['image']);
        $name = $this->makeCropName($file, $coordinates);
        $path = $file->getRootPath() . $name;

        if (!file_exists($path)) {
            $this->doCrop($file, $coordinates, $path);
        }

        return $name;
    }

public function crop ( array $ croppable , $ index = 0 ) { $ coordinates = $ croppable [ 'coordinates' ] [ $ index ] ; $ file = new UploadableFile ( $ this -> root_path , $ croppable [ 'image' ] ) ; $ name = $ this -> makeCropName ( $ file , $ coordinates ) ; $ path = $ file -> getRootPath ( ) . $ name ; if ( ! file_exists ( $ path ) ) { $ this -> doCrop ( $ file , $ coordinates , $ path ) ; } return $ name ; }

Crops a file and returns crop's web path

@param array $croppable
@param int $index
@return mixed

Crops a file and returns crop s web path


protected function makeCropName(UploadableFile $file, $coordinates)
    {
        $ext    = $file->getExtension();
        $suffix = implode('_', $coordinates);

        return preg_replace('/\.'. $ext .'$/ui', '_crop_'. $suffix .'.'. $ext, $file->getWebPath());
    }

protected function makeCropName ( UploadableFile $ file , $ coordinates ) { $ ext = $ file -> getExtension ( ) ; $ suffix = implode ( '_' , $ coordinates ) ; return preg_replace ( '/\.' . $ ext . '$/ui' , '_crop_' . $ suffix . '.' . $ ext , $ file -> getWebPath ( ) ) ; }

Returns the name for a cropped file

@param UploadableFile $file
@param $coordinates
@return mixed


protected function doCrop(UploadableFile $file, $coordinates, $path)
    {
        $crop = imagecreatetruecolor($coordinates['min_width'], $coordinates['min_height']);

        switch ($file->getExtension()) {
            case 'gif':
                $source = imagecreatefromgif($file); break;

            case 'png':
                $source = imagecreatefrompng($file); break;

            default:
                $source = imagecreatefromjpeg($file);
        }

        if (preg_match('/^(gif|png)$/', $file->getExtension())) {
            imagecolortransparent($crop, imagecolorallocatealpha($crop, 0, 0, 0, 127));
            imagealphablending($crop, false);
            imagesavealpha($crop, true);
        }

        imagecopyresampled(
            $crop, $source,
            0, 0,
            $coordinates['left'], $coordinates['top'],
            $coordinates['min_width'], $coordinates['min_height'],
            $coordinates['width'], $coordinates['height']
        );

        switch ($file->getExtension()) {
            case 'gif':
                imagegif($crop, $path); break;

            case 'png':
                imagepng($crop, $path); break;

            default:
                imagejpeg($crop, $path, 100);
        }
    }

protected function doCrop ( UploadableFile $ file , $ coordinates , $ path ) { $ crop = imagecreatetruecolor ( $ coordinates [ 'min_width' ] , $ coordinates [ 'min_height' ] ) ; switch ( $ file -> getExtension ( ) ) { case 'gif' : $ source = imagecreatefromgif ( $ file ) ; break ; case 'png' : $ source = imagecreatefrompng ( $ file ) ; break ; default : $ source = imagecreatefromjpeg ( $ file ) ; } if ( preg_match ( '/^(gif|png)$/' , $ file -> getExtension ( ) ) ) { imagecolortransparent ( $ crop , imagecolorallocatealpha ( $ crop , 0 , 0 , 0 , 127 ) ) ; imagealphablending ( $ crop , false ) ; imagesavealpha ( $ crop , true ) ; } imagecopyresampled ( $ crop , $ source , 0 , 0 , $ coordinates [ 'left' ] , $ coordinates [ 'top' ] , $ coordinates [ 'min_width' ] , $ coordinates [ 'min_height' ] , $ coordinates [ 'width' ] , $ coordinates [ 'height' ] ) ; switch ( $ file -> getExtension ( ) ) { case 'gif' : imagegif ( $ crop , $ path ) ; break ; case 'png' : imagepng ( $ crop , $ path ) ; break ; default : imagejpeg ( $ crop , $ path , 100 ) ; } }

Crops a file

@param UploadableFile $file
@param $coordinates
@param $path


public function getSize($image, $relative = false)
    {
        if (!$image instanceof File) {
            if ($relative) {
                $image = $this->root_path . $image;
            }

            $image = new File($image);
        }

        return getimagesize($image->getRealPath());
    }

public function getSize ( $ image , $ relative = false ) { if ( ! $ image instanceof File ) { if ( $ relative ) { $ image = $ this -> root_path . $ image ; } $ image = new File ( $ image ) ; } return getimagesize ( $ image -> getRealPath ( ) ) ; }

Returns image size info

@param $image
@param bool $relative
@return array


public function getPermutations($file)
    {
        $paths = $this->_appendFileToPaths($this->_paths, $file);

        return $this->_appendExtensionsToPaths($paths, $this->_extensions);
    }

public function getPermutations ( $ file ) { $ paths = $ this -> _appendFileToPaths ( $ this -> _paths , $ file ) ; return $ this -> _appendExtensionsToPaths ( $ paths , $ this -> _extensions ) ; }

Gets the permutations of paths to the given file.

@param string $file The file to build paths to.
@return array The permutations of file paths.

Gets the permutations of paths to the given file .


public function getAnnotations(string $docString): array
    {
        $annotations = [];

        // Get all matches of @ Annotations
        $matches = $this->getAnnotationMatches($docString);

        // If there are any matches iterate through them and create new
        // annotations
        if ($matches && isset($matches[0], $matches[1])) {
            foreach ($matches[0] as $index => $match) {
                $this->setAnnotation($matches, $index, $annotations);
            }
        }

        return $annotations;
    }

Get annotations from a given string.

@param string $docString The doc string

@throws \Valkyrja\Annotations\Exceptions\InvalidAnnotationKeyArgument

@return \Valkyrja\Annotations\Annotation[]


protected function getAnnotationMatches(string $docString): ? array
    {
        preg_match_all($this->getRegex(), $docString, $matches);

        return $matches ?? null;
    }

protected function getAnnotationMatches ( string $ docString ) : ? array { preg_match_all ( $ this -> getRegex ( ) , $ docString , $ matches ) ; return $ matches ?? null ; }

Get annotation matches.

@param string $docString The doc string

@return array[]


protected function setAnnotation(array $matches, int $index, array &$annotations): void
    {
        $properties = $this->getAnnotationProperties($matches, $index);

        // Get the annotation model from the annotations map
        $annotation = $this->getAnnotationFromMap($properties['annotation']);

        // Set the annotation's type
        $annotation->setAnnotationType($properties['annotation']);

        // If there are arguments
        if (null !== $properties['arguments'] && $properties['arguments']) {
            // Filter the arguments and set them in the annotation
            $annotation->setAnnotationArguments(
                $this->getArguments($properties['arguments'])
            );

            // Having set the arguments there's no need to retain this key in
            // the properties
            unset($properties['arguments']);

            // Set the annotation's arguments to setters if they exist
            $this->setAnnotationArguments($annotation);

            // If all arguments have been set to their own properties in the
            // annotation model
            if (empty($annotation->getAnnotationArguments())) {
                // Set the arguments to null
                $annotation->setAnnotationArguments();
            }
        }

        // Set all the matches
        $annotation->setMatches($properties);

        // Set the annotation in the list
        $annotations[] = $annotation;
    }

Set a matched annotation.

@param array $matches     The matches
[
0 => matches,
1 => annotation,
2 => type,
3 => args,
4 => var,
5 => desc
]
@param int   $index       The index
@param array $annotations The annotations list

@throws \Valkyrja\Annotations\Exceptions\InvalidAnnotationKeyArgument

@return void


protected function setAnnotationArguments(Annotation $annotation): void
    {
        $arguments = $annotation->getAnnotationArguments();

        // Iterate through the arguments
        foreach ($annotation->getAnnotationArguments() as $key => $argument) {
            $methodName = 'set' . ucfirst($key);

            // Check if there is a setter function for this argument
            if (method_exists($annotation, $methodName)) {
                // Set the argument using the setter
                $annotation->{$methodName}($argument);

                // Unset from the arguments array
                unset($arguments[$key]);
            }
        }

        $annotation->setAnnotationArguments($arguments);
    }

Set the annotation's arguments.

@param Annotation $annotation The annotation

@return void


protected function getAnnotationProperties(array $matches, int $index): array
    {
        $properties = [];

        // Written like this to appease the code coverage gods
        $properties['annotation']  = $matches[1][$index] ?? null;
        $properties['arguments']   = $matches[2][$index] ?? null;
        $properties['type']        = $matches[3][$index] ?? null;
        $properties['variable']    = $matches[4][$index] ?? null;
        $properties['description'] = $matches[5][$index] ?? null;

        return $this->processAnnotationProperties($properties);
    }

Get the properties for a matched annotation.

@param array $matches The matches
@param int   $index   The index

@return array

Get the properties for a matched annotation .


protected function processAnnotationProperties(array $properties): array
    {
        // If the type and description exist by the variable does not
        // then that means the variable regex group captured the
        // first word of the description
        if (
            $properties['type']
            && $properties['description']
            && ! $properties['variable']
        ) {
            // Rectify this by concatenating the type and description
            $properties['description'] =
                $properties['type'] . $properties['description'];

            // Then unset the type
            unset($properties['type']);
        }

        // Iterate through the properties
        foreach ($properties as &$property) {
            // Clean each one
            $property = $this->cleanMatch($property);
        }

        return $properties;
    }

Process the properties.

@param array $properties The properties

@return array


public function getArguments(string $arguments = null): ? array
    {
        $argumentsList = null;

        // If a valid arguments list was passed in
        if (null !== $arguments && $arguments) {
            $testArgs      = str_replace('=', ':', $arguments);
            $argumentsList = json_decode('{' . $testArgs . '}', true);

            if (\is_array($argumentsList)) {
                foreach ($argumentsList as &$value) {
                    $value = $this->determineValue($value);
                }

                unset($value);
            }

            return $argumentsList;
        }

        return $argumentsList;
    }

Filter a string of arguments into an key => value array.

@param string $arguments The arguments

@throws \Valkyrja\Annotations\Exceptions\InvalidAnnotationKeyArgument

@return array

Filter a string of arguments into an key = > value array .


protected function determineValue($value)
    {
        if (\is_array($value)) {
            foreach ($value as &$item) {
                $item = $this->determineValue($item);
            }

            unset($item);

            return $value;
        }

        // Trim the value of spaces
        $value = trim($value);

        // If there was no double colon found there's no need to go further
        if (strpos($value, '::') === false) {
            return $value;
        }

        // Determine if the value is a constant
        if (\defined($value)) {
            // Set the value as the constant's value
            return \constant($value);
        }

        [$class, $member] = explode('::', $value);

        // Check for static property
        if (property_exists($class, $member)) {
            return $class::$$member;
        }

        // Check for static method
        if (method_exists($class, $member)) {
            return $class::$member();
        }

        return $value;
    }

Determine if a value is a defined constant.

@param mixed $value The value to check

@return mixed

Determine if a value is a defined constant .


public function getAnnotationFromMap(string $annotationType): Annotation
    {
        // Get the annotations map (annotation name to annotation class)
        $annotationsMap = $this->getAnnotationsMap();

        // If an annotation is mapped to a class
        if ($annotationType && array_key_exists(
                $annotationType,
                $annotationsMap
            )
        ) {
            // Set a new class based on the match found
            $annotation = new $annotationsMap[$annotationType]();
        } else {
            // Otherwise set a new base annotation model
            $annotation = new Annotation();
        }

        return $annotation;
    }

Get an annotation model from the annotations map.

@param string $annotationType The annotation type

@return \Valkyrja\Annotations\Annotation

Get an annotation model from the annotations map .


protected function cleanMatch(string $match = null): ? string
    {
        if (! $match) {
            return $match;
        }

        return trim(str_replace('*', '', $match));
    }

protected function cleanMatch ( string $ match = null ) : ? string { if ( ! $ match ) { return $ match ; } return trim ( str_replace ( '*' , '' , $ match ) ) ; }

Clean a match from asterisks and new lines.

@param string $match The match

@return string

Clean a match from asterisks and new lines .


public function getSubscribedEvents()
    {
        $subscribedEvents = array();
        foreach ($this->validProviders as $provider => $class) {
            $subscribedEvents['command.' . $provider] = 'handleCommand';
            $subscribedEvents['command.' . $provider . '.help'] = 'handleCommandHelp';
        }
        return $subscribedEvents;
    }

public function getSubscribedEvents ( ) { $ subscribedEvents = array ( ) ; foreach ( $ this -> validProviders as $ provider => $ class ) { $ subscribedEvents [ 'command.' . $ provider ] = 'handleCommand' ; $ subscribedEvents [ 'command.' . $ provider . '.help' ] = 'handleCommandHelp' ; } return $ subscribedEvents ; }

Return array of subscribed events

@return array


public function handleCommand(Event $event, Queue $queue)
    {
        $provider = $this->getProvider($event->getCustomCommand());
        if ($provider->validateParams($event->getCustomParams())) {
            $request = $this->getApiRequest($event, $queue);
            $this->getEventEmitter()->emit('http.request', array($request));
        } else {
            $this->handleCommandhelp($event, $queue);
        }
    }

public function handleCommand ( Event $ event , Queue $ queue ) { $ provider = $ this -> getProvider ( $ event -> getCustomCommand ( ) ) ; if ( $ provider -> validateParams ( $ event -> getCustomParams ( ) ) ) { $ request = $ this -> getApiRequest ( $ event , $ queue ) ; $ this -> getEventEmitter ( ) -> emit ( 'http.request' , array ( $ request ) ) ; } else { $ this -> handleCommandhelp ( $ event , $ queue ) ; } }

Handler for the main commands

@param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
@param \Phergie\Irc\Bot\React\EventQueueInterface $queue


public function handleCommandHelp(Event $event, Queue $queue)
    {
        $provider = $this->getProvider($event->getCustomCommand());
        $this->sendIrcResponse($event, $queue, $provider->getHelpLines());
    }

public function handleCommandHelp ( Event $ event , Queue $ queue ) { $ provider = $ this -> getProvider ( $ event -> getCustomCommand ( ) ) ; $ this -> sendIrcResponse ( $ event , $ queue , $ provider -> getHelpLines ( ) ) ; }

Handler for the help command

@param \Phergie\Irc\Plugin\React\Command\CommandEvent $event
@param \Phergie\Irc\Bot\React\EventQueueInterface $queue


public function getProvider($command)
    {
        return (isset($this->validProviders[$command])) ? $this->validProviders[$command] : false;
    }

public function getProvider ( $ command ) { return ( isset ( $ this -> validProviders [ $ command ] ) ) ? $ this -> validProviders [ $ command ] : false ; }

Get a single provider class by command

@param string $command
@return \Chrismou\Phergie\Plugin\Audioscrobbler\Provider\AudioscrobblerProviderInterface $provider|false


public function leftJoin($table, $firstColumn, $operator = null, $secondColumn = null) {
		return $this->join($table, $firstColumn, $operator, $secondColumn, 'left');
	}

public function leftJoin ( $ table , $ firstColumn , $ operator = null , $ secondColumn = null ) { return $ this -> join ( $ table , $ firstColumn , $ operator , $ secondColumn , 'left' ) ; }

Add a left join to the query.

@param string $table
@param string $firstColumn
@param string $operator
@param string $secondColumn
@return \wiggum\db\Builder


public function rightJoin($table, $firstColumn, $operator = null, $secondColumn = null) {
		return $this->join($table, $firstColumn, $operator, $secondColumn, 'right');
	}

public function rightJoin ( $ table , $ firstColumn , $ operator = null , $ secondColumn = null ) { return $ this -> join ( $ table , $ firstColumn , $ operator , $ secondColumn , 'right' ) ; }

Add a right join to the query.

@param string $table
@param string $firstColumn
@param string $operator
@param string $secondColumn
@return \wiggum\db\Builder


public function rightJoinWhere($table, $firstColumn, $operator, $value) {
		return $this->joinWhere($table, $firstColumn, $operator, $value, 'right');
	}

public function rightJoinWhere ( $ table , $ firstColumn , $ operator , $ value ) { return $ this -> joinWhere ( $ table , $ firstColumn , $ operator , $ value , 'right' ) ; }

Add a "right join where" clause to the query.

@param string $table
@param string $firstColumn
@param string $operator
@param string $secondColumn
@return \wiggum\db\Builder

Add a right join where clause to the query .


public function toSql() {

		if ($this->type == 'insert') {
			return $this->grammar->compileInsert($this);
		} else if ($this->type == 'update') {
			return $this->grammar->compileUpdate($this);
		} else if ($this->type == 'delete') {
			return $this->grammar->compileDelete($this);
		} else {
			return $this->grammar->compileSelect($this);
		}

	}

public function toSql ( ) { if ( $ this -> type == 'insert' ) { return $ this -> grammar -> compileInsert ( $ this ) ; } else if ( $ this -> type == 'update' ) { return $ this -> grammar -> compileUpdate ( $ this ) ; } else if ( $ this -> type == 'delete' ) { return $ this -> grammar -> compileDelete ( $ this ) ; } else { return $ this -> grammar -> compileSelect ( $ this ) ; } }

Get the SQL representation of the query.

@return string

Get the SQL representation of the query .


public function fetchAllColumn() {
		return $this->db->fetchRows($this->toSql(), $this->getBindings(), PDO::FETCH_COLUMN);
	}

public function fetchAllColumn ( ) { return $ this -> db -> fetchRows ( $ this -> toSql ( ) , $ this -> getBindings ( ) , PDO :: FETCH_COLUMN ) ; }

Fetch all values of a single column from the result set into an array.

@return array

Fetch all values of a single column from the result set into an array .


public function setName($name = null)
    {
        if (empty($name) || !is_string($name)) {
            throw new \InvalidArgumentException(
                sprintf('Object name is invalid! (must be a string, got "%s")', var_export($name,1))
            );
        }
        $this->object_table_name = $name;
        return $this;
    }

Set the object name
@param string $name The object name to set
@return self Return the object for method chaining


public function setStructure($structure = null)
    {
        if (empty($structure) || !is_array($structure)) {
            throw new \InvalidArgumentException(
                sprintf('Object structure is invalid! (must be an array, got "%s")', gettype($structure))
            );
        }
        $this->object_structure = $structure;
        return $this;
    }

Set the object structure
@param string $name The object structure to set
@return self Return the object for method chaining


public function setDatabaseName($name = null)
    {
        if (empty($name) || !is_string($name)) {
            throw new \InvalidArgumentException(
                sprintf('Object database name is invalid! (must be a string, got "%s")', var_export($name,1))
            );
        }
        $this->object_database_name = $name;
        return $this;
    }

Set the object database name
@param string $name The object database name to set
@return self Return the object for method chaining


public function setModelName($name = null)
    {
        if (empty($name) || !is_string($name)) {
            throw new \InvalidArgumentException(
                sprintf('Object model name is invalid! (must be a string, got "%s")', var_export($name,1))
            );
        }
        if (false===\CarteBlanche\App\Loader::classExists($name)) {
            throw new \InvalidArgumentException(
                sprintf('Object model\'s class can\'t be found! (got "%s")', var_export($name,1))
            );
        }
        $this->object_model_name = $name;
        return $this;
    }

Set the object model name
@param string $name The object model name to set
@return self Return the object for method chaining


protected function _buildModel($auto_populate = true, $advanced_search = false)
    {
        if (\CarteBlanche\App\Loader::classExists($this->object_model_name)) {
            try {
                $this->object_model = new $this->object_model_name(
                    $this->getTableName(),
                    $this->getFields(),
                    $this->getStructure(),
                    $auto_populate, $advanced_search
                );
                $db = CarteBlanche::getContainer()->get('entity_manager')
                    ->getStorageEngine($this->getDatabaseName());
                $this->object_model->setStorageEngine($db);

            } catch ( \Exception $e ) {
                throw new \Exception(
                    sprintf('Model "%s" constructor seems not compliant with the "\CarteBlanche\Interfaces\ModelInterface" interface!', $this->object_model_name)
                );
            }
        } else {
            trigger_error( sprintf('Model "%s" can\'t be found!', $this->object_model_name), E_USER_ERROR);
        }
    }


protected function _buildFields()
    {
        $db = CarteBlanche::getContainer()->get('entity_manager')
            ->getStorageEngine($this->getDatabaseName());
        foreach ($this->getStructureEntry('structure') as $_field=>$_data)  {
            $_f = null;
            if (preg_match('/^(.*)_id$/i', $_field, $matches)) {
                if (isset($matches[1]) && is_string($matches[1])) {
                    $related_object = $matches[1];
                    if ($related_object=='parent')
                        $related_object = $this->getTableName();
                    $table = AutoObjectMapper::getAutoObject($related_object, $this->getDatabaseName());
                    $_f = new Relation(
                        $_field, $_data, $db, $related_object, $table->getModel()
                    );
                }
            } else {
                $_f = new Field( $_field, $_data, $db );
            }

            if (!is_null($_f))
                $this->object_fields->setEntry( $_field, $_f );
        }
    }

protected function _buildFields ( ) { $ db = CarteBlanche :: getContainer ( ) -> get ( 'entity_manager' ) -> getStorageEngine ( $ this -> getDatabaseName ( ) ) ; foreach ( $ this -> getStructureEntry ( 'structure' ) as $ _field => $ _data ) { $ _f = null ; if ( preg_match ( '/^(.*)_id$/i' , $ _field , $ matches ) ) { if ( isset ( $ matches [ 1 ] ) && is_string ( $ matches [ 1 ] ) ) { $ related_object = $ matches [ 1 ] ; if ( $ related_object == 'parent' ) $ related_object = $ this -> getTableName ( ) ; $ table = AutoObjectMapper :: getAutoObject ( $ related_object , $ this -> getDatabaseName ( ) ) ; $ _f = new Relation ( $ _field , $ _data , $ db , $ related_object , $ table -> getModel ( ) ) ; } } else { $ _f = new Field ( $ _field , $ _data , $ db ) ; } if ( ! is_null ( $ _f ) ) $ this -> object_fields -> setEntry ( $ _field , $ _f ) ; } }

Build an array of the object fields
@return void


protected function registerValidationFactory() {
        $this->app->singleton('validator', function ($app) {
            $validator = new Factory($app['translator'], $app);

            // The validation presence verifier is responsible for determining the existence
            // of values in a given data collection, typically a relational database or
            // other persistent data stores. And it is used to check for uniqueness.
            if(isset($app['validation.presence'])) {
                $validator->setPresenceVerifier($app['validation.presence']);
            }

            return $validator;
        });
    }

Register the validation factory.

@return void


public function load(): array
    {
        return [
            ServiceLocatorInterface::class => [
                FactoryResolver::class => [
                    LoggerInterface::class => LoggerFactory::class,
                ],
                StaticFactoryResolver::class => [
                    BacktraceDecorator::class => BacktraceDecorator::class,
                    PriorityFilter::class => PriorityFilter::class,
                    AlertPriority::class => AlertPriority::class,
                    CriticalPriority::class => CriticalPriority::class,
                    DebugPriority::class => DebugPriority::class,
                    EmergencyPriority::class => EmergencyPriority::class,
                    ErrorPriority::class => ErrorPriority::class,
                    InformationalPriority::class => InformationalPriority::class,
                    NoticePriority::class => NoticePriority::class,
                    WarningPriority::class => WarningPriority::class,
                    FileWriter::class => FileWriter::class,
                    PdoWriter::class => PdoWriter::class,
                ],
                ReflectionResolver::class => [
                    LoggerMiddleware::class => LoggerMiddleware::class,
                ],
            ],
            LoggerInterface::class => [
                'writers' => [],
            ],
        ];
    }

public function load ( ) : array { return [ ServiceLocatorInterface :: class => [ FactoryResolver :: class => [ LoggerInterface :: class => LoggerFactory :: class , ] , StaticFactoryResolver :: class => [ BacktraceDecorator :: class => BacktraceDecorator :: class , PriorityFilter :: class => PriorityFilter :: class , AlertPriority :: class => AlertPriority :: class , CriticalPriority :: class => CriticalPriority :: class , DebugPriority :: class => DebugPriority :: class , EmergencyPriority :: class => EmergencyPriority :: class , ErrorPriority :: class => ErrorPriority :: class , InformationalPriority :: class => InformationalPriority :: class , NoticePriority :: class => NoticePriority :: class , WarningPriority :: class => WarningPriority :: class , FileWriter :: class => FileWriter :: class , PdoWriter :: class => PdoWriter :: class , ] , ReflectionResolver :: class => [ LoggerMiddleware :: class => LoggerMiddleware :: class , ] , ] , LoggerInterface :: class => [ 'writers' => [ ] , ] , ] ; }

Service locator config for Logger component.

@return array

Service locator config for Logger component .


protected function targetSiteId(ElementInterface $element = null): int
    {
        /** @var Element $element */
        if (Craft::$app->getIsMultiSite() === true && $element !== null) {
            return $element->siteId;
        }

        return Craft::$app->getSites()->currentSite->id;
    }

protected
function
targetSiteId
(
ElementInterface
$
element
=
)
:
int
{
/** @var Element $element */
if
(
Craft
::
$
app
->
getIsMultiSite
(
)
===
true
&&
$
element
!==
)
{
return
$
element
->
siteId
;
}
return
Craft
::
$
app
->
getSites
(
)
->
currentSite
->
id
;
}

Returns the site ID that target elements should have.

@param ElementInterface|Element|null $element

@return int

Returns the site ID that target elements should have .


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

        $tableName = $this->table->getTableName();
        $relations = $this->table->getTableManager()->metadata()->getForeignKeys($tableName);
        //$rels = array();
        foreach ($relations as $column => $parent) {
            if ($parent['referenced_table'] == $parent_table) {
                // @todo, check the case when
                // table has many relations to the same parent
                // we'll have to throw an exception
                $record = $this->table->getTableManager()->table($parent_table)->findOneBy([
                    $parent['referenced_column'] => $record->offsetGet($column)
                ]);
                return $record;
            }
        }
        throw new Exception\RelationNotFoundException(__METHOD__ . ": Cannot find parent relation between table '$tableName' and '$parent_table'");
    }

Return parent record

@throws Exception\LogicException
@throws Exception\RelationNotFoundException

@param Record $record
@param string $parent_table
@return Record|false


public function renderItem($item, $index)
    {
        $header = $item['label'];
        if (array_key_exists('content', $item)) {
            $id = $this->options['id'] . '-collapse-' . $index;
            $options = ArrayHelper::getValue($item, 'contentOptions', []);
            $options['id'] = $id;
            Html::addCssClass($options, ['widget' => 'collapse']);

            $encodeLabel = isset($item['encode']) ? $item['encode'] : $this->encodeLabels;
            if ($encodeLabel) {
                $header = $this->htmlHlp->encode($header);
            }

            $headerOptions = [
                'class' => 'collapse-toggle',
                'data-toggle' => 'collapse',
            ];

            $headerToggle = $this->htmlHlp->a($header, '#' . $id, $headerOptions) . "\n";

            if (is_string($item['content']) || is_numeric($item['content']) || is_object($item['content'])) {
                $content = $this->htmlHlp->tag('div', $item['content'], ['class' => 'card-body']) . "\n";
            } elseif (is_array($item['content'])) {
                $content = $this->htmlHlp->ul($item['content'], [
                    'class' => 'list-group list-group-flush',
                    'itemOptions' => [
                        'class' => 'list-group-item'
                    ],
                    'encode' => false,
                ]) . "\n";
            } else {
                throw new InvalidConfigException('The "content" option should be a string, array or object.');
            }
        } else {
            throw new InvalidConfigException('The "content" option is required.');
        }

        if ($this->autoCloseItems) {
            $options['data-parent'] = '#' . $this->options['id'];
        }
        $contentCollapse = $this->htmlHlp->tag('div', $content, $options);

        $cardConfig = [
            'app' => $this->app,
            'options' => [
                'id' => $this->id . '-collapse-card-' . $index,
            ],
            'body' => $contentCollapse,
            'bodyOptions' => null,
            'header' => $headerToggle,
            'footer' => isset($item['footer']) ? $item['footer'] : null,
        ];

        return Card::widget($cardConfig);
    }

Renders a single collapsible item group
@param string $header a label of the item group [[items]]
@param array $item a single item from [[items]]
@param int $index the item index as each item group content must have an id
@return string the rendering result
@throws InvalidConfigException


public function all($db = null)
    {
        if ($this->emulateExecution) {
            return new LazyPromise(function() { return resolve([]); });
        }
        return $this->createCommand($db)->queryAll()->thenLazy(
            function($results) {
                return $this->populate($results);
            }
        );
    }

public function all ( $ db = null ) { if ( $ this -> emulateExecution ) { return new LazyPromise ( function ( ) { return resolve ( [ ] ) ; } ) ; } return $ this -> createCommand ( $ db ) -> queryAll ( ) -> thenLazy ( function ( $ results ) { return $ this -> populate ( $ results ) ; } ) ; }

Executes the query and returns all results as an array.
@param DatabaseInterface|DbConnectionGetterInterface $db the database connection used to generate the SQL statement.
If this parameter is not given, the `db` application component will be used.
@return LazyPromiseInterface with array the query results. If the query results in nothing, an empty array will be returned.

Executes the query and returns all results as an array .


public function one($db = null)
    {
        if ($this->emulateExecution) {
            return new LazyPromise(function() { return reject(null); });
        }

        return $this->createCommand($db)->queryOne();
    }

public function one ( $ db = null ) { if ( $ this -> emulateExecution ) { return new LazyPromise ( function ( ) { return reject ( null ) ; } ) ; } return $ this -> createCommand ( $ db ) -> queryOne ( ) ; }

Executes the query and returns a single row of result.
@param DatabaseInterface|DbConnectionGetterInterface $db the database connection used to generate the SQL statement.
If this parameter is not given, the `db` application component will be used.
@return LazyPromiseInterface with array the first row (in terms of an array) of the query result. Rejects if the query
results in nothing.

Executes the query and returns a single row of result .


public function column($db = null)
    {
        if ($this->emulateExecution) {
            return new LazyPromise(function() { return resolve([]); });
        }

        if ($this->indexBy === null) {
            return $this->createCommand($db)->queryColumn();
        }

        if (is_string($this->indexBy) && is_array($this->select) && count($this->select) === 1) {
            if (strpos($this->indexBy, '.') === false && count($tables = $this->getTablesUsedInFrom()) > 0) {
                $this->select[] = key($tables) . '.' . $this->indexBy;
            } else {
                $this->select[] = $this->indexBy;
            }
        }
        return $this->createCommand($db)->queryAll()->thenLazy(
            function($results) {
                $rows = [];
                foreach ($results as $row) {
                    $value = reset($row);

                    if ($this->indexBy instanceof \Closure) {
                        $rows[call_user_func($this->indexBy, $row)] = $value;
                    } else {
                        $rows[$row[$this->indexBy]] = $value;
                    }
                }

                return $rows;
            }
        );
    }

public function column ( $ db = null ) { if ( $ this -> emulateExecution ) { return new LazyPromise ( function ( ) { return resolve ( [ ] ) ; } ) ; } if ( $ this -> indexBy === null ) { return $ this -> createCommand ( $ db ) -> queryColumn ( ) ; } if ( is_string ( $ this -> indexBy ) && is_array ( $ this -> select ) && count ( $ this -> select ) === 1 ) { if ( strpos ( $ this -> indexBy , '.' ) === false && count ( $ tables = $ this -> getTablesUsedInFrom ( ) ) > 0 ) { $ this -> select [ ] = key ( $ tables ) . '.' . $ this -> indexBy ; } else { $ this -> select [ ] = $ this -> indexBy ; } } return $ this -> createCommand ( $ db ) -> queryAll ( ) -> thenLazy ( function ( $ results ) { $ rows = [ ] ; foreach ( $ results as $ row ) { $ value = reset ( $ row ) ; if ( $ this -> indexBy instanceof \ Closure ) { $ rows [ call_user_func ( $ this -> indexBy , $ row ) ] = $ value ; } else { $ rows [ $ row [ $ this -> indexBy ] ] = $ value ; } } return $ rows ; } ) ; }

Executes the query and returns the first column of the result.
@param DatabaseInterface|DbConnectionGetterInterface $db the database connection used to generate the SQL statement.
If this parameter is not given, the `db` application component will be used.
@return LazyPromiseInterface with array the first column of the query result. An empty array is returned if the query results in nothing.

Executes the query and returns the first column of the result .


public function count($q = '*', $db = null)
    {
        if ($this->emulateExecution) {
            return new LazyPromise(function() { return resolve(0); });
        }

        return $this->queryScalar("COUNT($q)", $db);
    }

public function count ( $ q = '*' , $ db = null ) { if ( $ this -> emulateExecution ) { return new LazyPromise ( function ( ) { return resolve ( 0 ) ; } ) ; } return $ this -> queryScalar ( "COUNT($q)" , $ db ) ; }

Returns the number of records.
@param string $q the COUNT expression. Defaults to '*'.
Make sure you properly [quote](guide:db-dao#quoting-table-and-column-names) column names in the expression.
@param DatabaseInterface|DbConnectionGetterInterface $db the database connection used to generate the SQL statement.
If this parameter is not given (or null), the `db` application component will be used.
@return LazyPromiseInterface with int|string number of records. The result may be a string depending on the
underlying database engine and to support integer values higher than a 32bit PHP integer can handle.


public function exists($db = null)
    {
        if ($this->emulateExecution) {
            return reject(false);
        }
        $command = $this->createCommand($db);
        $params = $command->params;
        $command->setSql($command->db->getQueryBuilder()->selectExists($command->getSql()));
        $command->bindValues($params);
        return $command->queryScalar()
            ->thenLazy(function($count = 0) {
                return $count > 0 ? true : reject(new Error("Does not exist"));
            });
    }

public
function
exists
(
$
db
=
)
{
if
(
$
this
->
emulateExecution
)
{
return
reject
(
false
)
;
}
$
command
=
$
this
->
createCommand
(
$
db
)
;
$
params
=
$
command
->
params
;
$
command
->
setSql
(
$
command
->
db
->
getQueryBuilder
(
)
->
selectExists
(
$
command
->
getSql
(
)
)
)
;
$
command
->
bindValues
(
$
params
)
;
return
$
command
->
queryScalar
(
)
->
thenLazy
(
function
(
$
count
=
0
)
{
return
$
count
>
0
true
:
reject
(
new
Error
(
"Does not exist"
)
)
;
}
)
;
}

Returns a value indicating whether the query result contains any row of data.
@param DatabaseInterface|DbConnectionGetterInterface $db the database connection used to generate the SQL statement.
If this parameter is not given, the `db` application component will be used.
@return ExtendedPromiseInterface with bool whether the query result contains any row of data.

Returns a value indicating whether the query result contains any row of data .


public function makeCall(NamespaceProphecy $prophecy, $name, array $arguments)
    {
        // For efficiency exclude 'args' from the generated backtrace
        // Limit backtrace to last 3 calls as we don't use the rest
        $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 4);

        $file = $line = null;
        if (isset($backtrace[3]) && isset($backtrace[3]['file'])) {
            $file = $backtrace[3]['file'];
            $line = $backtrace[3]['line'];
        }

        // There are method prophecies, so it's a fake/stub. Searching prophecy for this call
        $matches = [];
        foreach ($prophecy->getProphecies() as $methodProphecy) {
            if ($methodProphecy->getName() !== $name) {
                continue;
            }

            if (0 < $score = $methodProphecy->getArgumentsWildcard()->scoreArguments($arguments)) {
                $matches[] = [$score, $methodProphecy];
            }
        }

        // If fake/stub doesn't have method prophecy for this call - throw exception
        if (!count($matches)) {
            throw $this->createUnexpectedCallException($prophecy, $name, $arguments);
        }

        // Sort matches by their score value
        @usort($matches, function ($match1, $match2) {
            return $match2[0] - $match1[0];
        });

        // If Highest rated method prophecy has a promise - execute it or return null instead
        $returnValue = null;
        $exception = null;
        if ($promise = $matches[0][1]->getPromise()) {
            try {
                $returnValue = $promise->execute($arguments, $matches[0][1]);
            } catch (\Exception $e) {
                $exception = $e;
            }
        }

        $this->recordedCalls[] = new Call($name, $arguments, $returnValue, $exception, $file, $line);

        if (null !== $exception) {
            throw $exception;
        }

        return $returnValue;
    }

Makes and records specific method call for object prophecy.

@param NamespaceProphecy $prophecy
@param string $name
@param array $arguments

@return mixed Returns null if no promise for prophecy found or promise return value.

@throws UnexpectedCallException If no appropriate method prophecy found
@throws \Exception

Makes and records specific method call for object prophecy .


public function findCalls($functionName, ArgumentsWildcard $wildcard)
    {
        return array_values(
            array_filter($this->recordedCalls, function (Call $call) use ($wildcard, $functionName) {
                return $call->getMethodName() === $functionName &&
                    0 < $wildcard->scoreArguments($call->getArguments());
            })
        );
    }

public function findCalls ( $ functionName , ArgumentsWildcard $ wildcard ) { return array_values ( array_filter ( $ this -> recordedCalls , function ( Call $ call ) use ( $ wildcard , $ functionName ) { return $ call -> getMethodName ( ) === $ functionName && 0 < $ wildcard -> scoreArguments ( $ call -> getArguments ( ) ) ; } ) ) ; }

Searches for calls by method name & arguments wildcard.

@param string            $functionName
@param ArgumentsWildcard $wildcard

@return Call[]

Searches for calls by method name & arguments wildcard .


function PEAR_Registry($pear_install_dir = PEAR_INSTALL_DIR, $pear_channel = false,
                           $pecl_channel = false)
    {
        parent::PEAR();
        $this->setInstallDir($pear_install_dir);
        $this->_pearChannel = $pear_channel;
        $this->_peclChannel = $pecl_channel;
        $this->_config      = false;
    }

function PEAR_Registry ( $ pear_install_dir = PEAR_INSTALL_DIR , $ pear_channel = false , $ pecl_channel = false ) { parent :: PEAR ( ) ; $ this -> setInstallDir ( $ pear_install_dir ) ; $ this -> _pearChannel = $ pear_channel ; $ this -> _peclChannel = $ pecl_channel ; $ this -> _config = false ; }

PEAR_Registry constructor.

@param string (optional) PEAR install directory (for .php files)
@param PEAR_ChannelFile PEAR_ChannelFile object representing the PEAR channel, if
default values are not desired.  Only used the very first time a PEAR
repository is initialized
@param PEAR_ChannelFile PEAR_ChannelFile object representing the PECL channel, if
default values are not desired.  Only used the very first time a PEAR
repository is initialized

@access public


function _assertStateDir($channel = false)
    {
        if ($channel && $this->_getChannelFromAlias($channel) != 'pear.php.net') {
            return $this->_assertChannelStateDir($channel);
        }

        static $init = false;
        if (!file_exists($this->statedir)) {
            if (!$this->hasWriteAccess()) {
                return false;
            }

            require_once 'System.php';
            if (!System::mkdir(array('-p', $this->statedir))) {
                return $this->raiseError("could not create directory '{$this->statedir}'");
            }
            $init = true;
        } elseif (!is_dir($this->statedir)) {
            return $this->raiseError('Cannot create directory ' . $this->statedir . ', ' .
                'it already exists and is not a directory');
        }

        $ds = DIRECTORY_SEPARATOR;
        if (!file_exists($this->channelsdir)) {
            if (!file_exists($this->channelsdir . $ds . 'pear.php.net.reg') ||
                  !file_exists($this->channelsdir . $ds . 'pecl.php.net.reg') ||
                  !file_exists($this->channelsdir . $ds . 'doc.php.net.reg') ||
                  !file_exists($this->channelsdir . $ds . '__uri.reg')) {
                $init = true;
            }
        } elseif (!is_dir($this->channelsdir)) {
            return $this->raiseError('Cannot create directory ' . $this->channelsdir . ', ' .
                'it already exists and is not a directory');
        }

        if ($init) {
            static $running = false;
            if (!$running) {
                $running = true;
                $this->_initializeDirs();
                $running = false;
                $init = false;
            }
        } else {
            $this->_initializeDepDB();
        }

        return true;
    }

Make sure the directory where we keep registry files exists.

@return bool TRUE if directory exists, FALSE if it could not be
created

@access private

Make sure the directory where we keep registry files exists .


function _assertChannelStateDir($channel)
    {
        $ds = DIRECTORY_SEPARATOR;
        if (!$channel || $this->_getChannelFromAlias($channel) == 'pear.php.net') {
            if (!file_exists($this->channelsdir . $ds . 'pear.php.net.reg')) {
                $this->_initializeChannelDirs();
            }
            return $this->_assertStateDir($channel);
        }

        $channelDir = $this->_channelDirectoryName($channel);
        if (!is_dir($this->channelsdir) ||
              !file_exists($this->channelsdir . $ds . 'pear.php.net.reg')) {
            $this->_initializeChannelDirs();
        }

        if (!file_exists($channelDir)) {
            if (!$this->hasWriteAccess()) {
                return false;
            }

            require_once 'System.php';
            if (!System::mkdir(array('-p', $channelDir))) {
                return $this->raiseError("could not create directory '" . $channelDir .
                    "'");
            }
        } elseif (!is_dir($channelDir)) {
            return $this->raiseError("could not create directory '" . $channelDir .
                "', already exists and is not a directory");
        }

        return true;
    }

Make sure the directory where we keep registry files exists for a non-standard channel.

@param string channel name
@return bool TRUE if directory exists, FALSE if it could not be
created

@access private

Make sure the directory where we keep registry files exists for a non - standard channel .


function _assertChannelDir()
    {
        if (!file_exists($this->channelsdir)) {
            if (!$this->hasWriteAccess()) {
                return false;
            }

            require_once 'System.php';
            if (!System::mkdir(array('-p', $this->channelsdir))) {
                return $this->raiseError("could not create directory '{$this->channelsdir}'");
            }
        } elseif (!is_dir($this->channelsdir)) {
            return $this->raiseError("could not create directory '{$this->channelsdir}" .
                "', it already exists and is not a directory");
        }

        if (!file_exists($this->channelsdir . DIRECTORY_SEPARATOR . '.alias')) {
            if (!$this->hasWriteAccess()) {
                return false;
            }

            require_once 'System.php';
            if (!System::mkdir(array('-p', $this->channelsdir . DIRECTORY_SEPARATOR . '.alias'))) {
                return $this->raiseError("could not create directory '{$this->channelsdir}/.alias'");
            }
        } elseif (!is_dir($this->channelsdir . DIRECTORY_SEPARATOR . '.alias')) {
            return $this->raiseError("could not create directory '{$this->channelsdir}" .
                "/.alias', it already exists and is not a directory");
        }

        return true;
    }

Make sure the directory where we keep registry files for channels exists

@return bool TRUE if directory exists, FALSE if it could not be
created

@access private


function _channelFileName($channel, $noaliases = false)
    {
        if (!$noaliases) {
            if (file_exists($this->_getChannelAliasFileName($channel))) {
                $channel = implode('', file($this->_getChannelAliasFileName($channel)));
            }
        }
        return $this->channelsdir . DIRECTORY_SEPARATOR . str_replace('/', '_',
            strtolower($channel)) . '.reg';
    }

function _channelFileName ( $ channel , $ noaliases = false ) { if ( ! $ noaliases ) { if ( file_exists ( $ this -> _getChannelAliasFileName ( $ channel ) ) ) { $ channel = implode ( '' , file ( $ this -> _getChannelAliasFileName ( $ channel ) ) ) ; } } return $ this -> channelsdir . DIRECTORY_SEPARATOR . str_replace ( '/' , '_' , strtolower ( $ channel ) ) . '.reg' ; }

Get the name of the file where data for a given channel is stored.
@param string channel name
@return string registry file name

Get the name of the file where data for a given channel is stored .


function _getChannelFromAlias($channel)
    {
        if (!$this->_channelExists($channel)) {
            if ($channel == 'pear.php.net') {
                return 'pear.php.net';
            }

            if ($channel == 'pecl.php.net') {
                return 'pecl.php.net';
            }

            if ($channel == 'doc.php.net') {
                return 'doc.php.net';
            }

            if ($channel == '__uri') {
                return '__uri';
            }

            return false;
        }

        $channel = strtolower($channel);
        if (file_exists($this->_getChannelAliasFileName($channel))) {
            // translate an alias to an actual channel
            return implode('', file($this->_getChannelAliasFileName($channel)));
        }

        return $channel;
    }

Get the name of a channel from its alias


function _getAlias($channel)
    {
        if (!$this->_channelExists($channel)) {
            if ($channel == 'pear.php.net') {
                return 'pear';
            }

            if ($channel == 'pecl.php.net') {
                return 'pecl';
            }

            if ($channel == 'doc.php.net') {
                return 'phpdocs';
            }

            return false;
        }

        $channel = $this->_getChannel($channel);
        if (PEAR::isError($channel)) {
            return $channel;
        }

        return $channel->getAlias();
    }

function _getAlias ( $ channel ) { if ( ! $ this -> _channelExists ( $ channel ) ) { if ( $ channel == 'pear.php.net' ) { return 'pear' ; } if ( $ channel == 'pecl.php.net' ) { return 'pecl' ; } if ( $ channel == 'doc.php.net' ) { return 'phpdocs' ; } return false ; } $ channel = $ this -> _getChannel ( $ channel ) ; if ( PEAR :: isError ( $ channel ) ) { return $ channel ; } return $ channel -> getAlias ( ) ; }

Get the alias of a channel from its alias or its name


function _lock($mode = LOCK_EX)
    {
        if (stristr(php_uname(), 'Windows 9')) {
            return true;
        }

        if ($mode != LOCK_UN && is_resource($this->lock_fp)) {
            // XXX does not check type of lock (LOCK_SH/LOCK_EX)
            return true;
        }

        if (!$this->_assertStateDir()) {
            if ($mode == LOCK_EX) {
                return $this->raiseError('Registry directory is not writeable by the current user');
            }

            return true;
        }

        $open_mode = 'w';
        // XXX People reported problems with LOCK_SH and 'w'
        if ($mode === LOCK_SH || $mode === LOCK_UN) {
            if (!file_exists($this->lockfile)) {
                touch($this->lockfile);
            }
            $open_mode = 'r';
        }

        if (!is_resource($this->lock_fp)) {
            $this->lock_fp = @fopen($this->lockfile, $open_mode);
        }

        if (!is_resource($this->lock_fp)) {
            $this->lock_fp = null;
            return $this->raiseError("could not create lock file" .
                                     (isset($php_errormsg) ? ": " . $php_errormsg : ""));
        }

        if (!(int)flock($this->lock_fp, $mode)) {
            switch ($mode) {
                case LOCK_SH: $str = 'shared';    break;
                case LOCK_EX: $str = 'exclusive'; break;
                case LOCK_UN: $str = 'unlock';    break;
                default:      $str = 'unknown';   break;
            }

            //is resource at this point, close it on error.
            fclose($this->lock_fp);
            $this->lock_fp = null;
            return $this->raiseError("could not acquire $str lock ($this->lockfile)",
                                     PEAR_REGISTRY_ERROR_LOCK);
        }

        return true;
    }

Lock the registry.

@param integer lock mode, one of LOCK_EX, LOCK_SH or LOCK_UN.
See flock manual for more information.

@return bool TRUE on success, FALSE if locking failed, or a
PEAR error if some other error occurs (such as the
lock file not being writable).

@access private


function _channelExists($channel, $noaliases = false)
    {
        $a = file_exists($this->_channelFileName($channel, $noaliases));
        if (!$a && $channel == 'pear.php.net') {
            return true;
        }

        if (!$a && $channel == 'pecl.php.net') {
            return true;
        }

        if (!$a && $channel == 'doc.php.net') {
            return true;
        }

        return $a;
    }

function _channelExists ( $ channel , $ noaliases = false ) { $ a = file_exists ( $ this -> _channelFileName ( $ channel , $ noaliases ) ) ; if ( ! $ a && $ channel == 'pear.php.net' ) { return true ; } if ( ! $ a && $ channel == 'pecl.php.net' ) { return true ; } if ( ! $ a && $ channel == 'doc.php.net' ) { return true ; } return $ a ; }

Determine whether a channel exists in the registry

@param string Channel name
@param bool if true, then aliases will be ignored
@return boolean


function _mirrorExists($channel, $mirror)
    {
        $data = $this->_channelInfo($channel);
        if (!isset($data['servers']['mirror'])) {
            return false;
        }

        foreach ($data['servers']['mirror'] as $m) {
            if ($m['attribs']['host'] == $mirror) {
                return true;
            }
        }

        return false;
    }

function _mirrorExists ( $ channel , $ mirror ) { $ data = $ this -> _channelInfo ( $ channel ) ; if ( ! isset ( $ data [ 'servers' ] [ 'mirror' ] ) ) { return false ; } foreach ( $ data [ 'servers' ] [ 'mirror' ] as $ m ) { if ( $ m [ 'attribs' ] [ 'host' ] == $ mirror ) { return true ; } } return false ; }

Determine whether a mirror exists within the deafult channel in the registry

@param string Channel name
@param string Mirror name

@return boolean


function isAlias($alias)
    {
        if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
            return $e;
        }
        $ret = $this->_isChannelAlias($alias);
        $this->_unlock();
        return $ret;
    }

function isAlias ( $ alias ) { if ( PEAR :: isError ( $ e = $ this -> _lock ( LOCK_SH ) ) ) { return $ e ; } $ ret = $ this -> _isChannelAlias ( $ alias ) ; $ this -> _unlock ( ) ; return $ ret ; }

Determines whether the parameter is an alias of a channel
@param string
@return bool


function channelInfo($channel = null, $noaliases = false)
    {
        if (PEAR::isError($e = $this->_lock(LOCK_SH))) {
            return $e;
        }
        $ret = $this->_channelInfo($channel, $noaliases);
        $this->_unlock();
        return $ret;
    }

function channelInfo ( $ channel = null , $ noaliases = false ) { if ( PEAR :: isError ( $ e = $ this -> _lock ( LOCK_SH ) ) ) { return $ e ; } $ ret = $ this -> _channelInfo ( $ channel , $ noaliases ) ; $ this -> _unlock ( ) ; return $ ret ; }

Retrieve a raw array of channel data.

Do not use this, instead use {@link getChannel()} for normal
operations.  Array structure is undefined in this method
@param string channel name
@param bool whether to strictly retrieve information only on non-aliases
@return array|null|PEAR_Error


function updateChannel($channel, $lastmodified = null)
    {
        if ($channel->getName() == '__uri') {
            return false;
        }
        return $this->addChannel($channel, $lastmodified, true);
    }

function updateChannel ( $ channel , $ lastmodified = null ) { if ( $ channel -> getName ( ) == '__uri' ) { return false ; } return $ this -> addChannel ( $ channel , $ lastmodified , true ) ; }

For future expandibility purposes, separate this
@param PEAR_ChannelFile

For future expandibility purposes separate this


public function matches(array $data)
    {
        return (isset($data[$this->property]) &&
            call_user_func($this->function, $data[$this->property]));
    }

public function matches ( array $ data ) { return ( isset ( $ data [ $ this -> property ] ) && call_user_func ( $ this -> function , $ data [ $ this -> property ] ) ) ; }

Does this filter match?

@param array $data

@return bool


public function tinyMCEfile()
  {
    $reflector = new \ReflectionClass('Jin2\Form\Components\Wysiwyg');
    $tinyMCEUrl = dirname($reflector->getFileName());
    $tinyMCEUrl .= '..'
      . DIRECTORY_SEPARATOR .'..'
      . DIRECTORY_SEPARATOR .'..'
      . DIRECTORY_SEPARATOR .'..'
      . DIRECTORY_SEPARATOR .'assets'
      . DIRECTORY_SEPARATOR. 'wysiwyg';
    $tinyMCEUrl = preg_replace('#^.*(\\'. DIRECTORY_SEPARATOR .'vendor\\'. DIRECTORY_SEPARATOR .'.+)$#', '$1', $tinyMCEUrl);
    $tinyMCEUrl = str_replace(DIRECTORY_SEPARATOR, '/', $tinyMCEUrl);
    return $tinyMCEUrl . '/tinymce/tinymce.min.js';
  }

public function tinyMCEfile ( ) { $ reflector = new \ ReflectionClass ( 'Jin2\Form\Components\Wysiwyg' ) ; $ tinyMCEUrl = dirname ( $ reflector -> getFileName ( ) ) ; $ tinyMCEUrl .= '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'assets' . DIRECTORY_SEPARATOR . 'wysiwyg' ; $ tinyMCEUrl = preg_replace ( '#^.*(\\' . DIRECTORY_SEPARATOR . 'vendor\\' . DIRECTORY_SEPARATOR . '.+)$#' , '$1' , $ tinyMCEUrl ) ; $ tinyMCEUrl = str_replace ( DIRECTORY_SEPARATOR , '/' , $ tinyMCEUrl ) ; return $ tinyMCEUrl . '/tinymce/tinymce.min.js' ; }

Retourne l'url de TinyMCE

@return string


public static function InitWith($value) {
        $instance = new Str();
        $instance->value = $value;
        $instance->IsValid();
        return $instance;
    }

public static function InitWith ( $ value ) { $ instance = new Str ( ) ; $ instance -> value = $ value ; $ instance -> IsValid ( ) ; return $ instance ; }

Create an instance of the class, sets the value property and returns the object.
@param string $value
@return \Puzzlout\Objects\Str
@throws \Exception

Create an instance of the class sets the value property and returns the object .


public function getEntityManager($name = null)
	{

		$entityManager = $this->getDoctrine()->getManager($name);
		if (!$entityManager->isOpen()) {
			$entityManager = $entityManager->create($entityManager->getConnection(), $entityManager->getConfiguration());
		}

		return $entityManager;

	}

public function getEntityManager ( $ name = null ) { $ entityManager = $ this -> getDoctrine ( ) -> getManager ( $ name ) ; if ( ! $ entityManager -> isOpen ( ) ) { $ entityManager = $ entityManager -> create ( $ entityManager -> getConnection ( ) , $ entityManager -> getConfiguration ( ) ) ; } return $ entityManager ; }

Get Doctrine Entity Manager

@return ObjectManager


public function resolve($className)
    {
        $trimmed = ltrim($className, '\\');

        if (!$this->canResolve($trimmed)) return $className;

        return $this->implementations[$trimmed];
    }

public function resolve ( $ className ) { $ trimmed = ltrim ( $ className , '\\' ) ; if ( ! $ this -> canResolve ( $ trimmed ) ) return $ className ; return $ this -> implementations [ $ trimmed ] ; }

Resolve a given class name.

If the resolved class does not exist return the original class.

@param string $className
@return string


public function validateHashesTo($attribute, $value, $parameters) {
        $this->requireParameterCount(1, $parameters, 'hashes_to');

        return $this->hasher->check($value, $parameters[0]);
    }

public function validateHashesTo ( $ attribute , $ value , $ parameters ) { $ this -> requireParameterCount ( 1 , $ parameters , 'hashes_to' ) ; return $ this -> hasher -> check ( $ value , $ parameters [ 0 ] ) ; }

Check the field is the given value.

@param  string  $attribute
@param  mixed   $value
@param  array   $parameters
@return bool


public function validateRouteExists($attribute, $value, $parameters) {
        $method = 'getBy' . studly_case(isset($parameters[0]) ? $parameters[0] : 'name');
        $routes = $this->router->getRoutes();
        return $routes->$method($value) !== null;
    }

public function validateRouteExists ( $ attribute , $ value , $ parameters ) { $ method = 'getBy' . studly_case ( isset ( $ parameters [ 0 ] ) ? $ parameters [ 0 ] : 'name' ) ; $ routes = $ this -> router -> getRoutes ( ) ; return $ routes -> $ method ( $ value ) !== null ; }

Determines if the given route exists.
If a parameter is provided it will determine whether the routes are fetched by name or action.

@param  string  $attribute
@param  mixed   $value
@param  array   $parameters
@return bool

Determines if the given route exists . If a parameter is provided it will determine whether the routes are fetched by name or action .


private function _hardCopy($originDir, $targetDir)
    {
        $filesystem = $this->getApplication()->getService('filesystem');

        $filesystem->mkdir($targetDir, 0777);
        // We use a custom iterator to ignore VCS files
        $filesystem->mirror(
            $originDir, $targetDir,
            Finder::create()->ignoreDotFiles(false)->in($originDir)
        );
    }

Creates a directory hard copy

@param string $originDir Source directory
@param string $targetDir Target directory

@return void


public function init()
    {
        parent::init();
        $this->clientOptions = false;
        $this->htmlHlp->addCssClass($this->options, ['widget' => 'btn']);
    }

public function init ( ) { parent :: init ( ) ; $ this -> clientOptions = false ; $ this -> htmlHlp -> addCssClass ( $ this -> options , [ 'widget' => 'btn' ] ) ; }

Initializes the widget.
If you override this method, make sure you call the parent implementation first.

Initializes the widget . If you override this method make sure you call the parent implementation first .


public static function getNextDay($dt, $format = "Y-m-d")
    {
        $dtObj = \DateTime::createFromFormat($format, $dt);

        if (!$dtObj) {
            return "";
        }

        return $dtObj->add(date_interval_create_from_date_string('1 days'))->format($format);
    }

public
static
function
getNextDay
(
$
dt
,
$
format
=
"Y-m-d"
)
{
$
dtObj
=
\
DateTime
::
createFromFormat
(
$
format
,
$
dt
)
;
if
(
!
$
dtObj
)
{
return
""
;
}
return
$
dtObj
->
add
(
date_interval_create_from_date_string
(
'1 days'
)
)
->
format
(
$
format
)
;
}

Returns next date of given date in given format
@param  string $dt     Source date
@param  string $format Source date format
@return string Destination date or empty string if source date can't be parsed


public static function getPrevDay($dt, $format = "Y-m-d")
    {
        $dtObj = \DateTime::createFromFormat($format, $dt);

        if (!$dtObj) {
            return "";
        }

        return $dtObj->sub(date_interval_create_from_date_string('1 days'))->format($format);
    }

public
static
function
getPrevDay
(
$
dt
,
$
format
=
"Y-m-d"
)
{
$
dtObj
=
\
DateTime
::
createFromFormat
(
$
format
,
$
dt
)
;
if
(
!
$
dtObj
)
{
return
""
;
}
return
$
dtObj
->
sub
(
date_interval_create_from_date_string
(
'1 days'
)
)
->
format
(
$
format
)
;
}

Returns previous date of given date in given format
@param  string $dt     Source date
@param  string $format Source date format
@return string Destination date or empty string if source date can't be parsed


public static function createDateRande($from, $amount, $dtFormat='Y-m-d')
    {
        $range = [ $from ];
        $curDt = $from;

        for($i=1; $i<$amount; $i++) {
            $curDt = \KsUtils\Dt::getNextDay($curDt, $dtFormat);
            $range[] = $curDt;
        }

        return $range;
    }

public static function createDateRande ( $ from , $ amount , $ dtFormat = 'Y-m-d' ) { $ range = [ $ from ] ; $ curDt = $ from ; for ( $ i = 1 ; $ i < $ amount ; $ i ++ ) { $ curDt = \ KsUtils \ Dt :: getNextDay ( $ curDt , $ dtFormat ) ; $ range [ ] = $ curDt ; } return $ range ; }

Creates an array of consecutive dates
@param string $from Starting date
@param integer $amount Range's length
@param string $dtFormat Format of starting and resulting dates, default: Y-m-d
@return array List of dates


public static function file(&$filePath)
    {
        $filePath = \Reaction::$app->getAlias($filePath);
        $filePath = FileHelper::normalizePath($filePath);
        return static::getFs()->file($filePath);
    }

public static function file ( & $ filePath ) { $ filePath = \ Reaction :: $ app -> getAlias ( $ filePath ) ; $ filePath = FileHelper :: normalizePath ( $ filePath ) ; return static :: getFs ( ) -> file ( $ filePath ) ; }

Get file object
@param string $filePath
@return FileInterface|File


public static function dir(&$dirPath)
    {
        $dirPath = \Reaction::$app->getAlias($dirPath);
        $dirPath = FileHelper::normalizePath($dirPath);
        return static::getFs()->dir($dirPath);
    }

public static function dir ( & $ dirPath ) { $ dirPath = \ Reaction :: $ app -> getAlias ( $ dirPath ) ; $ dirPath = FileHelper :: normalizePath ( $ dirPath ) ; return static :: getFs ( ) -> dir ( $ dirPath ) ; }

Get dir object
@param string $dirPath
@return DirectoryInterface|Directory


public static function open($filePath, $flags = 'r')
    {
        $file = static::ensureFileObject($filePath);
        $createMode = FileHelper::permissionsAsString(static::$fileCreateMode);
        return $file->open($flags, $createMode);
    }

public static function open ( $ filePath , $ flags = 'r' ) { $ file = static :: ensureFileObject ( $ filePath ) ; $ createMode = FileHelper :: permissionsAsString ( static :: $ fileCreateMode ) ; return $ file -> open ( $ flags , $ createMode ) ; }

Open file with given flags
@param string $filePath
@param string $flags c - create, w - write, r - read, t - truncate
@return \React\Promise\PromiseInterface


public static function create($filePath, $mode = null, $time = null)
    {
        $mode = isset($mode) ? $mode : static::$fileCreateMode;
        $modeStr = static::permissionsAsString($mode);
        $time = is_int($time) ? $time : time();
        $file = static::file($filePath);
        return $file->create($modeStr, $time)
            ->then(function() use ($file, $mode) {
                return $file->chmod($mode);
            });
    }

public static function create ( $ filePath , $ mode = null , $ time = null ) { $ mode = isset ( $ mode ) ? $ mode : static :: $ fileCreateMode ; $ modeStr = static :: permissionsAsString ( $ mode ) ; $ time = is_int ( $ time ) ? $ time : time ( ) ; $ file = static :: file ( $ filePath ) ; return $ file -> create ( $ modeStr , $ time ) -> then ( function ( ) use ( $ file , $ mode ) { return $ file -> chmod ( $ mode ) ; } ) ; }

Create a file
@param string $filePath
@param int|null   $mode
@param int|null   $time
@return \React\Promise\PromiseInterface


public static function putContents($filePath, $contents, $openFlags = 'cwt', $lock = true, $createMode = null)
    {
        $lockTimeout = is_int($lock) && !empty($lock) ? $lock : null;
        $lock = !empty($lock);
        $file = static::ensureFileObject($filePath);
        $createMode = isset($createMode) ? $createMode : static::$fileCreateMode;
        $createModeStr = FileHelper::permissionsAsString($createMode);
        $unlockCallback = function ($result = null) use ($filePath, $lock) {
            if ($lock) {
                static::unlock($filePath);
            }
            if (is_object($result) && $result instanceof \Throwable) {
                throw $result;
            }
            return $result;
        };
        return static::onUnlock($filePath)
            ->then(function() use (&$file, $filePath, $lockTimeout, $openFlags, $createModeStr, $lock) {
                if ($lock) {
                    static::lock($filePath, $lockTimeout);
                }
                return $file->open($openFlags, $createModeStr);
            })->then(function(WritableStreamInterface $stream) use (&$file, $contents) {
                $stream->write($contents);
                return $file->close();
            })->then($unlockCallback, $unlockCallback);
    }

public static function putContents ( $ filePath , $ contents , $ openFlags = 'cwt' , $ lock = true , $ createMode = null ) { $ lockTimeout = is_int ( $ lock ) && ! empty ( $ lock ) ? $ lock : null ; $ lock = ! empty ( $ lock ) ; $ file = static :: ensureFileObject ( $ filePath ) ; $ createMode = isset ( $ createMode ) ? $ createMode : static :: $ fileCreateMode ; $ createModeStr = FileHelper :: permissionsAsString ( $ createMode ) ; $ unlockCallback = function ( $ result = null ) use ( $ filePath , $ lock ) { if ( $ lock ) { static :: unlock ( $ filePath ) ; } if ( is_object ( $ result ) && $ result instanceof \ Throwable ) { throw $ result ; } return $ result ; } ; return static :: onUnlock ( $ filePath ) -> then ( function ( ) use ( & $ file , $ filePath , $ lockTimeout , $ openFlags , $ createModeStr , $ lock ) { if ( $ lock ) { static :: lock ( $ filePath , $ lockTimeout ) ; } return $ file -> open ( $ openFlags , $ createModeStr ) ; } ) -> then ( function ( WritableStreamInterface $ stream ) use ( & $ file , $ contents ) { $ stream -> write ( $ contents ) ; return $ file -> close ( ) ; } ) -> then ( $ unlockCallback , $ unlockCallback ) ; }

Put contents into file
@param string|File $filePath
@param string      $contents
@param string      $openFlags
@param bool|int    $lock Lock file for operation and check for a lock OR lock timeout
@param int|null    $createMode
@return ExtendedPromiseInterface


public static function getContents($filePath, $lock = true)
    {
        $lockTimeout = is_int($lock) && !empty($lock) ? $lock : null;
        $lock = !empty($lock);
        $file = static::ensureFileObject($filePath);
        $unlockCallback = function ($result = null) use ($lock, $filePath) {
            if ($lock) {
                static::unlock($filePath);
            }
            if (is_object($result) && $result instanceof \Throwable) {
                throw $result;
            }
            return $result;
        };
        return static::onUnlock($filePath)->then(
            function () use (&$file, $filePath, $lock, $lockTimeout) {
                if ($lock) {
                    static::lock($filePath, $lockTimeout);
                }
                return $file->exists();
            }
        )
            ->then(function () use (&$file, $filePath) {
                return $file->getContents();
            })->then($unlockCallback, $unlockCallback);
    }

public static function getContents ( $ filePath , $ lock = true ) { $ lockTimeout = is_int ( $ lock ) && ! empty ( $ lock ) ? $ lock : null ; $ lock = ! empty ( $ lock ) ; $ file = static :: ensureFileObject ( $ filePath ) ; $ unlockCallback = function ( $ result = null ) use ( $ lock , $ filePath ) { if ( $ lock ) { static :: unlock ( $ filePath ) ; } if ( is_object ( $ result ) && $ result instanceof \ Throwable ) { throw $ result ; } return $ result ; } ; return static :: onUnlock ( $ filePath ) -> then ( function ( ) use ( & $ file , $ filePath , $ lock , $ lockTimeout ) { if ( $ lock ) { static :: lock ( $ filePath , $ lockTimeout ) ; } return $ file -> exists ( ) ; } ) -> then ( function ( ) use ( & $ file , $ filePath ) { return $ file -> getContents ( ) ; } ) -> then ( $ unlockCallback , $ unlockCallback ) ; }

Get file contents
@param string|File $filePath
@param bool|int    $lock Lock file for operation OR lock timeout
@return ExtendedPromiseInterface


public static function chmod($path, $mode = 0755)
    {
        if ($path instanceof GenericOperationInterface) {
            return $path->chmod($mode);
        }
        return static::file($path)->chmod($mode);
    }

public static function chmod ( $ path , $ mode = 0755 ) { if ( $ path instanceof GenericOperationInterface ) { return $ path -> chmod ( $ mode ) ; } return static :: file ( $ path ) -> chmod ( $ mode ) ; }

Perform 'chmod' operation
@param string|GenericOperationInterface $path File or Directory
@param int                              $mode
@return \React\Promise\PromiseInterface


public static function lock($filePath, $timeout = null)
    {
        $filePath = FileHelper::normalizePath($filePath);
        $timeout = isset($timeout) ? $timeout : static::$LockTimeout;
        $expire = time() + $timeout;
        if (isset(static::$_lockedFiles[$filePath])) {
            $expire = static::$_lockedFiles[$filePath] <= $expire ? $expire : static::$_lockedFiles[$filePath];
        }
        static::$_lockedFiles[$filePath] = $expire;
        static::checkUnlockTimer();
    }

public static function lock ( $ filePath , $ timeout = null ) { $ filePath = FileHelper :: normalizePath ( $ filePath ) ; $ timeout = isset ( $ timeout ) ? $ timeout : static :: $ LockTimeout ; $ expire = time ( ) + $ timeout ; if ( isset ( static :: $ _lockedFiles [ $ filePath ] ) ) { $ expire = static :: $ _lockedFiles [ $ filePath ] <= $ expire ? $ expire : static :: $ _lockedFiles [ $ filePath ] ; } static :: $ _lockedFiles [ $ filePath ] = $ expire ; static :: checkUnlockTimer ( ) ; }

Lock file for some time or until some operation is not finished
@param string $filePath
@param int $timeout


public static function onUnlock($filePath) {
        $filePath = FileHelper::normalizePath($filePath);
        if (!static::isLocked($filePath)) {
            return resolve(true);
        }
        $deferred = new Deferred();
        if (!isset(static::$_lockedFilesQueue[$filePath])) {
            static::$_lockedFilesQueue[$filePath] = [];
        }
        static::$_lockedFilesQueue[$filePath][] = $deferred;
        return $deferred->promise();
    }

public static function onUnlock ( $ filePath ) { $ filePath = FileHelper :: normalizePath ( $ filePath ) ; if ( ! static :: isLocked ( $ filePath ) ) { return resolve ( true ) ; } $ deferred = new Deferred ( ) ; if ( ! isset ( static :: $ _lockedFilesQueue [ $ filePath ] ) ) { static :: $ _lockedFilesQueue [ $ filePath ] = [ ] ; } static :: $ _lockedFilesQueue [ $ filePath ] [ ] = $ deferred ; return $ deferred -> promise ( ) ; }

Get promise of unlocking file
@param string $filePath
@return ExtendedPromiseInterface


protected static function ensureFileObject(&$pathOrObject)
    {
        if ($pathOrObject instanceof FileInterface) {
            return $pathOrObject;
        } elseif ($pathOrObject instanceof DirectoryInterface) {
            return static::file($pathOrObject->getPath());
        } elseif (is_string($pathOrObject)) {
            return static::file($pathOrObject);
        }
        return $pathOrObject;
    }

protected static function ensureFileObject ( & $ pathOrObject ) { if ( $ pathOrObject instanceof FileInterface ) { return $ pathOrObject ; } elseif ( $ pathOrObject instanceof DirectoryInterface ) { return static :: file ( $ pathOrObject -> getPath ( ) ) ; } elseif ( is_string ( $ pathOrObject ) ) { return static :: file ( $ pathOrObject ) ; } return $ pathOrObject ; }

Ensure that object is implementing FileInterface
@param File|Directory|string $pathOrObject
@return File


protected static function ensureDirObject(&$pathOrObject)
    {
        if ($pathOrObject instanceof DirectoryInterface) {
            return $pathOrObject;
        } elseif ($pathOrObject instanceof FileInterface) {
            return static::dir($pathOrObject->getPath());
        } elseif (is_string($pathOrObject)) {
            return static::dir($pathOrObject);
        }
        return $pathOrObject;
    }

protected static function ensureDirObject ( & $ pathOrObject ) { if ( $ pathOrObject instanceof DirectoryInterface ) { return $ pathOrObject ; } elseif ( $ pathOrObject instanceof FileInterface ) { return static :: dir ( $ pathOrObject -> getPath ( ) ) ; } elseif ( is_string ( $ pathOrObject ) ) { return static :: dir ( $ pathOrObject ) ; } return $ pathOrObject ; }

Ensure that object is implementing DirectoryInterface
@param FileInterface|DirectoryInterface|string $pathOrObject
@return DirectoryInterface


protected static function checkUnlockTimer() {
        if (static::$_unlockTimer instanceof TimerInterface) {
            return;
        }
        static::$_unlockTimer = \Reaction::$app->loop->addPeriodicTimer(1, function () {
            $now = time();
            foreach (static::$_lockedFiles as $filePath => $timeout) {
                if ($timeout <= $now) {
                    static::unlock($filePath);
                }
            }
        });
    }

protected static function checkUnlockTimer ( ) { if ( static :: $ _unlockTimer instanceof TimerInterface ) { return ; } static :: $ _unlockTimer = \ Reaction :: $ app -> loop -> addPeriodicTimer ( 1 , function ( ) { $ now = time ( ) ; foreach ( static :: $ _lockedFiles as $ filePath => $ timeout ) { if ( $ timeout <= $ now ) { static :: unlock ( $ filePath ) ; } } } ) ; }

Check if unlock timer is set or create it


public static function globals()
    {
        static $globals;
        if(!$globals) {

            $globals = new static(Uri::current());
            $globals->servers = &$_SERVER;
            $globals->envs = &$_ENV;
            $globals->values = &$_POST;
            $globals->cookies = &$_COOKIE;

            $globals->accept = Request\Accept::from(
                $globals->server('HTTP_ACCEPT'),
                $globals->server('HTTP_ACCEPT_LANGUAGE'),
                $globals->server('HTTP_ACCEPT_ENCODING'),
                $globals->server('HTTP_ACCEPT_CHARSET')
            );

            $globals->method = $globals->server('REQUEST_METHOD');
            $globals->secure = ($globals->server('HTTPS') == 'on');
            $globals->ajax = $globals->server('HTTP_X_REQUESTED_WITH')
                && strtolower($globals->server('HTTP_X_REQUESTED_WITH')) == 'xmlhttprequest';

            $globals->root = dirname($globals->server('SCRIPT_FILENAME'));
            $globals->root = rtrim($globals->root, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR;

            if(function_exists('http_response_code')) {
                $globals->code = http_response_code();
            }
            if(function_exists('http_get_request_body')) {
                $globals->body = http_get_request_body();
            }
            if(function_exists('apache_request_headers')) {
                $globals->headers = apache_request_headers();
            }

            foreach($_FILES as $index => $file) {
                $globals->files[$index] = new Request\File($file);
            }

            $globals->cli = (php_sapi_name() === 'cli');
            $globals->agent = $globals->server('HTTP_USER_AGENT');
            $globals->ip = $globals->server('REMOTE_ADDR');
            $globals->time = $globals->server('REQUEST_TIME');
        }

        return $globals;
    }

public static function globals ( ) { static $ globals ; if ( ! $ globals ) { $ globals = new static ( Uri :: current ( ) ) ; $ globals -> servers = & $ _SERVER ; $ globals -> envs = & $ _ENV ; $ globals -> values = & $ _POST ; $ globals -> cookies = & $ _COOKIE ; $ globals -> accept = Request \ Accept :: from ( $ globals -> server ( 'HTTP_ACCEPT' ) , $ globals -> server ( 'HTTP_ACCEPT_LANGUAGE' ) , $ globals -> server ( 'HTTP_ACCEPT_ENCODING' ) , $ globals -> server ( 'HTTP_ACCEPT_CHARSET' ) ) ; $ globals -> method = $ globals -> server ( 'REQUEST_METHOD' ) ; $ globals -> secure = ( $ globals -> server ( 'HTTPS' ) == 'on' ) ; $ globals -> ajax = $ globals -> server ( 'HTTP_X_REQUESTED_WITH' ) && strtolower ( $ globals -> server ( 'HTTP_X_REQUESTED_WITH' ) ) == 'xmlhttprequest' ; $ globals -> root = dirname ( $ globals -> server ( 'SCRIPT_FILENAME' ) ) ; $ globals -> root = rtrim ( $ globals -> root , DIRECTORY_SEPARATOR ) . DIRECTORY_SEPARATOR ; if ( function_exists ( 'http_response_code' ) ) { $ globals -> code = http_response_code ( ) ; } if ( function_exists ( 'http_get_request_body' ) ) { $ globals -> body = http_get_request_body ( ) ; } if ( function_exists ( 'apache_request_headers' ) ) { $ globals -> headers = apache_request_headers ( ) ; } foreach ( $ _FILES as $ index => $ file ) { $ globals -> files [ $ index ] = new Request \ File ( $ file ) ; } $ globals -> cli = ( php_sapi_name ( ) === 'cli' ) ; $ globals -> agent = $ globals -> server ( 'HTTP_USER_AGENT' ) ; $ globals -> ip = $ globals -> server ( 'REMOTE_ADDR' ) ; $ globals -> time = $ globals -> server ( 'REQUEST_TIME' ) ; } return $ globals ; }

Create from global environment

@return static


public function render()
    {
        if (!file_exists($this->template)):
            throw new \Exception("Template of section is not defined.");
        endif;

        $func = $this->closedRender($this->template, $this->data);
        $func();
    }

public
function
render
(
)
{
if
(
!
file_exists
(
$
this
->
template
)
)
:
throw
new
\
Exception
(
"Template of section is not defined."
)
;
endif
;
$
func
=
$
this
->
closedRender
(
$
this
->
template
,
$
this
->
data
)
;
$
func
(
)
;
}


public function on($firstColumn, $operator, $secondColumn, $boolean = 'and', $where = false) {

		if ($where)
			$this->bindings[] = $secondColumn;

		if ($where && ($operator === 'in' || $operator === 'not in') && is_array($secondColumn)) {
			$secondColumn = count($secondColumn);
		}

		$this->clauses[] = compact('firstColumn', 'operator', 'secondColumn', 'boolean', 'where');

		return $this;
	}

public
function
on
(
$
firstColumn
,
$
operator
,
$
secondColumn
,
$
boolean
=
'and'
,
$
where
=
false
)
{
if
(
$
where
)
$
this
->
bindings
[
]
=
$
secondColumn
;
if
(
$
where
&&
(
$
operator
===
'in'
||
$
operator
===
'not in'
)
&&
is_array
(
$
secondColumn
)
)
{
$
secondColumn
=
count
(
$
secondColumn
)
;
}
$
this
->
clauses
[
]
=
compact
(
'firstColumn'
,
'operator'
,
'secondColumn'
,
'boolean'
,
'where'
)
;
return
$
this
;
}

Add an "on" clause to the join.

@param string $first
@param string $operator
@param string $second
@param string $boolean
@param bool $where
@return \queryBuilder\JoinClause


public function where($firstColumn, $operator, $secondColumn, $boolean = 'and') {
		return $this->on($firstColumn, $operator, $secondColumn, $boolean, true);
	}

public function where ( $ firstColumn , $ operator , $ secondColumn , $ boolean = 'and' ) { return $ this -> on ( $ firstColumn , $ operator , $ secondColumn , $ boolean , true ) ; }

Add an "on where" clause to the join.

@param string $firstColumn
@param string $operator
@param string $second
@param string $boolean
@return \queryBuilder\JoinClause


public function whereNull($column, $boolean = 'and', $not = false) {
		$null = $not ? 'not null' : 'null';

		return $this->on($column, 'is', $null, $boolean, false);
	}

public
function
whereNull
(
$
column
,
$
boolean
=
'and'
,
$
not
=
false
)
{
$
=
$
not
'not null'
:
'null'
;
return
$
this
->
on
(
$
column
,
'is'
,
$
,
$
boolean
,
false
)
;
}

Add an "on where is null" clause to the join.

@param string $column
@param string $boolean
@return \queryBuilder\JoinClause

Add an on where is null clause to the join .


public function arrayToCollection(array $source, $collectionClass)
    {
        $manager = $this->manager;
        if ($manager instanceof ArrayCasterManagerInterface) {
            return $manager->process($source, $collectionClass);
        }

        throw new \LogicException(
            "The manager must be set to cast array in collection"
        );
    }

Array to collection

This method inject an array into specific collection type.

@param array  $source          The array source to inject
@param string $collectionClass The collection class name

@throws \ParseError if the array cannot be cast
@return CollectionInterface


public function it_could_be_normal()
    {
        $this->isNormal()->shouldBeBool();
        $this->isNormal()->shouldBe(true);
        $this->isSpecial()->shouldBe(false);
        $this->isSuper()->shouldBe(false);
    }

public function it_could_be_normal ( ) { $ this -> isNormal ( ) -> shouldBeBool ( ) ; $ this -> isNormal ( ) -> shouldBe ( true ) ; $ this -> isSpecial ( ) -> shouldBe ( false ) ; $ this -> isSuper ( ) -> shouldBe ( false ) ; }

Specifies if the move is a normal, special or super.

@return bool

Specifies if the move is a normal special or super .


protected function getInternal($id, $unserialize = true)
    {
        return $this->selectQuery()->where(['sid' => $id])
            ->one($this->db)
            ->then(function($row) use ($unserialize) {
                return $unserialize ? $this->getHandler()->unserializeData($row['data']) : $row;
            });
    }

protected function getInternal ( $ id , $ unserialize = true ) { return $ this -> selectQuery ( ) -> where ( [ 'sid' => $ id ] ) -> one ( $ this -> db ) -> then ( function ( $ row ) use ( $ unserialize ) { return $ unserialize ? $ this -> getHandler ( ) -> unserializeData ( $ row [ 'data' ] ) : $ row ; } ) ; }

Get entry from DB
@param string $id
@param bool $unserialize
@return ExtendedPromiseInterface


protected function updateInternal($row, $existingRow = null)
    {
        $equal = isset($existingRow) && isset($existingRow['data']) && $row['data'] === $existingRow['data'];
        $id = $row['sid'];
        unset($row['sid']);
        //If data not changed then just update timestamp
        if ($equal) {
            unset($row['data']);
        }
        return $this->createCommand()
            ->update($this->table, $row, ['sid' => $id])
            ->execute();
    }

Update existing entry in DB
@param array      $row
@param array|null $existingRow
@return ExtendedPromiseInterface|\Reaction\Promise\LazyPromiseInterface


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

        return $this->getMigrationHistory($limit)->then(
            function($migrations) {
                if (empty($migrations)) {
                    $this->stdout("No migration has been done before.\n", Console::FG_YELLOW);

                    return true;
                }
                $migrations = array_keys($migrations);
                $n = count($migrations);
                $this->stdout("Total $n " . ($n === 1 ? 'migration' : 'migrations') . " to be reverted:\n", Console::FG_YELLOW);
                foreach ($migrations as $migration) {
                    $this->stdout("\t$migration\n");
                }
                $this->stdout("\n");

                $reverted = 0;

                return $this->confirm('Revert the above ' . ($n === 1 ? 'migration' : 'migrations') . '?')->then(
                    function() use ($migrations, $n, &$reverted) {
                        $promises = [];
                        foreach ($migrations as $migration) {
                            $promises[] = $this->migrateDown($migration)->thenLazy(
                                function() use (&$reverted) {
                                    $reverted++;
                                    return true;
                                },
                                function($error = null) use ($reverted, $n) {
                                    $this->stdout("\n$reverted from $n " . ($reverted === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_RED);
                                    $this->stdout("\nMigration failed. The rest of the migrations are canceled.\n", Console::FG_RED);
                                    return reject($error);
                                }
                            );
                        }
                        return allInOrder($promises)->then(
                            function() use ($n) {
                                $this->stdout("\n$n " . ($n === 1 ? 'migration was' : 'migrations were') . " reverted.\n", Console::FG_GREEN);
                                $this->stdout("\nMigrated down successfully.\n", Console::FG_GREEN);
                            }
                        );
                    }
                );
            }
        );
    }

Downgrades the application by reverting old migrations.

For example,

```
console migrate/down     # revert the last migration
console migrate/down 3   # revert the last 3 migrations
console migrate/down all # revert all migrations
```

@param RequestApplicationInterface $app
@param int|string                  $limit the number of migrations to be reverted. Defaults to 1,
meaning the last applied migration will be reverted. When value is "all", all migrations will be reverted.
@return ExtendedPromiseInterface
@throws Exception if the number of the steps specified is less than 1.

Downgrades the application by reverting old migrations .


public function actionFresh(RequestApplicationInterface $app)
    {
        if (\Reaction::isProd()) {
            $this->stdout("App env is set to 'production'.\nRefreshing migrations is not possible on production systems.\n");
            return resolve(true);
        }

        $confirmMessage = "Are you sure you want to reset the database and start the migration from the beginning?\nAll data will be lost irreversibly!";
        return $this->confirm($confirmMessage)->then(
            function() {
                return $this->truncateDatabase();
            },
            function() {
                $this->stdout('Action was cancelled by user. Nothing has been performed.');
                return resolve(true);
            }
        )->then(
            function() use ($app) {
                return $this->actionUp($app);
            }
        );
    }

Truncates the whole database and starts the migration from the beginning.

```
console migrate/fresh
```

@param RequestApplicationInterface $app
@return ExtendedPromiseInterface

Truncates the whole database and starts the migration from the beginning .