protected function createActingAs(array $properties = [], string $userModel = null): Authenticatable
    {
        $userClass = $userModel ?: config('auth.providers.users.model');

        $this->actingAs = factory($userClass)->create($properties);
        $this->actingAs($this->actingAs);
        return $this->actingAs;
    }

protected function createActingAs ( array $ properties = [ ] , string $ userModel = null ) : Authenticatable { $ userClass = $ userModel ? : config ( 'auth.providers.users.model' ) ; $ this -> actingAs = factory ( $ userClass ) -> create ( $ properties ) ; $ this -> actingAs ( $ this -> actingAs ) ; return $ this -> actingAs ; }

Create an acting as user, save it, and return it

Note that this uses the config option but it can be overridden by the other option

@param array $properties
@param string|null $userModel
@return Authenticatable

Create an acting as user save it and return it


public function init()
    {
        parent::init();
        $self = $this;
        //Close session on end of request
        $this->app->once(Reaction\RequestApplicationInterface::EVENT_REQUEST_END, function() use (&$self) {
            return $self->close();
        });

        if ($this->getIsActive()) {
            Reaction::warning('Session is already started');
            $this->updateFlashCounters();
        }
    }

public
function
init
(
)
{
parent
::
init
(
)
;
$
self
=
$
this
;
//Close session on end of request
$
this
->
app
->
once
(
Reaction
\
RequestApplicationInterface
::
EVENT_REQUEST_END
,
function
(
)
use
(
&
$
self
)
{
return
$
self
->
close
(
)
;
}
)
;
if
(
$
this
->
getIsActive
(
)
)
{
Reaction
::
warning
(
'Session is already started'
)
;
$
this
->
updateFlashCounters
(
)
;
}
}

Initializes the application component.
This method is required by IApplicationComponent and is invoked by application.

Initializes the application component . This method is required by IApplicationComponent and is invoked by application .


public function open()
    {
        if ($this->getIsActive()) {
            return \Reaction\Promise\resolve(true);
        }

        $this->registerSessionHandler();

        $self = $this;
        return $this->openInternal()->then(
            function() use ($self) {
                if (Reaction::isDebug()) {
                    //Reaction::info('Session started');
                }
                $self->updateFlashCounters();
            }
        );
    }

public
function
open
(
)
{
if
(
$
this
->
getIsActive
(
)
)
{
return
\
Reaction
\
Promise
\
resolve
(
true
)
;
}
$
this
->
registerSessionHandler
(
)
;
$
self
=
$
this
;
return
$
this
->
openInternal
(
)
->
then
(
function
(
)
use
(
$
self
)
{
if
(
Reaction
::
isDebug
(
)
)
{
//Reaction::info('Session started');
}
$
self
->
updateFlashCounters
(
)
;
}
)
;
}

Starts the session.
@return ExtendedPromiseInterface


protected function openInternal()
    {
        $self = $this;
        if (!$this->getId()) {
            $self = $this;
            return $this->handler->createId($this->app)
                ->then(function($id = null) use ($self) {
                    $self->_isActive = true;
                    $self->setId($id);
                    $cookie = $self->createSessionCookie();
                    $self->app->response->cookies->add($cookie);
                    return true;
                });
        } else {
            $this->_isActive = true;
            return $this->readSession()->then(
                function($data) use ($self) {
                    $self->data = is_array($data) ? $data : [];
                    return true;
                },
                function($error = null) use ($self) {
                    $self->data = [];
                    return false;
                }
            )->always(function() {
                //Write initial data state for future needs
                $this->_dataInitial = $this->data;
            });
        }
    }

Open session internal method
@return ExtendedPromiseInterface


protected function registerSessionHandler()
    {
        if ($this->handler !== null) {
            if (!is_object($this->handler)) {
                if (is_string($this->handler) && Reaction::$app->has($this->handler)) {
                    $this->handler = Reaction::$app->get($this->handler);
                } else {
                    $this->handler = Reaction::create($this->handler);
                }
            }
            if (!$this->handler instanceof SessionHandlerInterface) {
                throw new InvalidConfigException('"' . get_class($this) . '::handler" must implement the \Reaction\Web\Sessions\SessionHandlerInterface.');
            }
        } else {
            throw new InvalidConfigException('"' . get_class($this) . '::handler" can not be empty.');
        }
    }

Registers session handler.
@throws \Reaction\Exceptions\InvalidConfigException


public function close($destroy = false)
    {
        if ($this->getIsActive()) {
            if (Reaction::isDebug()) {
                //Reaction::info('Session closed');
            }
            return $destroy || $this->isEmpty() ? $this->destroySession() : $this->writeSession();
        }
        $this->_isActive = false;
        return \Reaction\Promise\resolve(true);
    }

public
function
close
(
$
destroy
=
false
)
{
if
(
$
this
->
getIsActive
(
)
)
{
if
(
Reaction
::
isDebug
(
)
)
{
//Reaction::info('Session closed');
}
return
$
destroy
||
$
this
->
isEmpty
(
)
$
this
->
destroySession
(
)
:
$
this
->
writeSession
(
)
;
}
$
this
->
_isActive
=
false
;
return
\
Reaction
\
Promise
\
resolve
(
true
)
;
}

Ends the current session and store session data.
@param bool $destroy
@return ExtendedPromiseInterface

Ends the current session and store session data .


public function destroy()
    {
        if ($this->getIsActive()) {
            $sessionId = $this->getId();
            return $this->close(true)
                ->otherwise(function() { return true; })
                ->then(function() use ($sessionId) {
                    $this->setId($sessionId);
                    return $this->open();
                });
        }
        return Reaction\Promise\resolve(true);
    }

public function destroy ( ) { if ( $ this -> getIsActive ( ) ) { $ sessionId = $ this -> getId ( ) ; return $ this -> close ( true ) -> otherwise ( function ( ) { return true ; } ) -> then ( function ( ) use ( $ sessionId ) { $ this -> setId ( $ sessionId ) ; return $ this -> open ( ) ; } ) ; } return Reaction \ Promise \ resolve ( true ) ; }

Frees all session variables and destroys all data registered to a session.

This method has no effect when session is not [[getIsActive()|active]].
Make sure to call [[open()]] before calling it.
@see open()
@see isActive

Frees all session variables and destroys all data registered to a session .


public function regenerateID($deleteOldSession = false)
    {
        if ($this->getIsActive()) {
            return $this->handler->regenerateId($this->id, $this->app, $deleteOldSession);
        }
        return \Reaction\Promise\reject(new Reaction\Exceptions\SessionException('Session is not active'));
    }

public
function
regenerateID
(
$
deleteOldSession
=
false
)
{
if
(
$
this
->
getIsActive
(
)
)
{
return
$
this
->
handler
->
regenerateId
(
$
this
->
id
,
$
this
->
app
,
$
deleteOldSession
)
;
}
return
\
Reaction
\
Promise
\
reject
(
new
Reaction
\
Exceptions
\
SessionException
(
'Session is not active'
)
)
;
}

Updates the current session ID with a newly generated one.

Please refer to <http://php.net/session_regenerate_id> for more details.

This method has no effect when session is not [[getIsActive()|active]].
Make sure to call [[open()]] before calling it.

@param bool $deleteOldSession Whether to delete the old associated session file or not.
@see open()
@see isActive
@return \React\Promise\PromiseInterface

Updates the current session ID with a newly generated one .


public function readSession($id = null)
    {
        $id = !isset($id) && isset($this->_sessionId) ? $this->_sessionId : $id;
        if (!isset($id)) {
            return \Reaction\Promise\reject(new Reaction\Exceptions\ErrorException('Param "$id" must be specified in "' . __METHOD__ . '"'));
        }
        return $this->handler->read($id);
    }

public
function
readSession
(
$
id
=
)
{
$
id
=
!
isset
(
$
id
)
&&
isset
(
$
this
->
_sessionId
)
$
this
->
_sessionId
:
$
id
;
if
(
!
isset
(
$
id
)
)
{
return
\
Reaction
\
Promise
\
reject
(
new
Reaction
\
Exceptions
\
ErrorException
(
'Param "$id" must be specified in "'
.
__METHOD__
.
'"'
)
)
;
}
return
$
this
->
handler
->
read
(
$
id
)
;
}

Session read handler.
@internal Do not call this method directly.
@param string $id session ID
@return ExtendedPromiseInterface with array the session data


public function writeSession($data = null, $id = null)
    {
        $id = !isset($id) && isset($this->_sessionId) ? $this->_sessionId : $id;
        if (!isset($id)) {
            return \Reaction\Promise\reject(new Reaction\Exceptions\ErrorException('Param "$id" must be specified in "' . __METHOD__ . '"'));
        }
        if (!isset($data)) {
            $data = $this->data;
        }
        return $this->handler->write($id, $data);
    }

public
function
writeSession
(
$
data
=
,
$
id
=
)
{
$
id
=
!
isset
(
$
id
)
&&
isset
(
$
this
->
_sessionId
)
$
this
->
_sessionId
:
$
id
;
if
(
!
isset
(
$
id
)
)
{
return
\
Reaction
\
Promise
\
reject
(
new
Reaction
\
Exceptions
\
ErrorException
(
'Param "$id" must be specified in "'
.
__METHOD__
.
'"'
)
)
;
}
if
(
!
isset
(
$
data
)
)
{
$
data
=
$
this
->
data
;
}
return
$
this
->
handler
->
write
(
$
id
,
$
data
)
;
}

Session write handler.
@internal Do not call this method directly.
@param string $id session ID
@param array  $data session data
@return ExtendedPromiseInterface with bool whether session write is successful


public function destroySession($id = null)
    {
        $id = !isset($id) && isset($this->_sessionId) ? $this->_sessionId : $id;
        if (!isset($id)) {
            return \Reaction\Promise\reject(new Reaction\Exceptions\ErrorException('Param "$id" must be specified in "' . __METHOD__ . '"'));
        }
        return $this->handler->destroy($id, true);
    }

public
function
destroySession
(
$
id
=
)
{
$
id
=
!
isset
(
$
id
)
&&
isset
(
$
this
->
_sessionId
)
$
this
->
_sessionId
:
$
id
;
if
(
!
isset
(
$
id
)
)
{
return
\
Reaction
\
Promise
\
reject
(
new
Reaction
\
Exceptions
\
ErrorException
(
'Param "$id" must be specified in "'
.
__METHOD__
.
'"'
)
)
;
}
return
$
this
->
handler
->
destroy
(
$
id
,
true
)
;
}

Session destroy handler.
@internal Do not call this method directly.
@param string $id session ID
@return ExtendedPromiseInterface with bool whether session is destroyed successfully


public function set($key, $value)
    {
        $this->open();
        $data = $this->data;
        $data[$key] = $value;
        $this->data = $data;
    }

public function set ( $ key , $ value ) { $ this -> open ( ) ; $ data = $ this -> data ; $ data [ $ key ] = $ value ; $ this -> data = $ data ; }

Adds a session variable.
If the specified name already exists, the old value will be overwritten.
@param string $key session variable name
@param mixed  $value session variable value

Adds a session variable . If the specified name already exists the old value will be overwritten .


public function remove($key)
    {
        $this->open();
        $data = $this->data;
        if (isset($data[$key])) {
            unset($data[$key]);
        }
        $this->data = $data;
    }

public function remove ( $ key ) { $ this -> open ( ) ; $ data = $ this -> data ; if ( isset ( $ data [ $ key ] ) ) { unset ( $ data [ $ key ] ) ; } $ this -> data = $ data ; }

Removes a session variable.
@param string $key the name of the session variable to be removed


public function removeAll()
    {
        $this->open();
        $data = $this->data;
        foreach (array_keys($data) as $key) {
            unset($data[$key]);
        }
        $this->data = $data;
        return $this->writeSession();
    }

public function removeAll ( ) { $ this -> open ( ) ; $ data = $ this -> data ; foreach ( array_keys ( $ data ) as $ key ) { unset ( $ data [ $ key ] ) ; } $ this -> data = $ data ; return $ this -> writeSession ( ) ; }

Removes all session variables.
@return PromiseInterface with bool when write process ends


public function getFlash($key, $defaultValue = null, $delete = false)
    {
        $counters = $this->get($this->flashParam, []);
        if (isset($counters[$key])) {
            $value = $this->get($key, $defaultValue);
            if ($delete) {
                $this->removeFlash($key);
            } elseif ($counters[$key] < 0) {
                // mark for deletion in the next request
                $counters[$key] = 1;
                $this->data[$this->flashParam] = $counters;
            }

            return $value;
        }

        return $defaultValue;
    }

Returns a flash message.
@param string $key the key identifying the flash message
@param mixed $defaultValue value to be returned if the flash message does not exist.
@param bool $delete whether to delete this flash message right after this method is called.
If false, the flash message will be automatically deleted in the next request.
@return mixed the flash message or an array of messages if addFlash was used
@see setFlash()
@see addFlash()
@see hasFlash()
@see getAllFlashes()
@see removeFlash()


public function getAllFlashes($delete = false)
    {
        $counters = $this->get($this->flashParam, []);
        $flashes = [];
        foreach (array_keys($counters) as $key) {
            if (array_key_exists($key, $this->data)) {
                $flashes[$key] = $this->data[$key];
                if ($delete) {
                    unset($counters[$key], $this->data[$key]);
                } elseif ($counters[$key] < 0) {
                    // mark for deletion in the next request
                    $counters[$key] = 1;
                }
            } else {
                unset($counters[$key]);
            }
        }

        $this->data[$this->flashParam] = $counters;

        return $flashes;
    }

Returns all flash messages.

You may use this method to display all the flash messages in a view file:

```php
<?php
foreach ($app->session->getAllFlashes() as $key => $message) {
echo '<div class="alert alert-' . $key . '">' . $message . '</div>';
} ?>
```

With the above code you can use the [bootstrap alert][] classes such as `success`, `info`, `danger`
as the flash message key to influence the color of the div.

Note that if you use [[addFlash()]], `$message` will be an array, and you will have to adjust the above code.

[bootstrap alert]: http://getbootstrap.com/components/#alerts

@param bool $delete whether to delete the flash messages right after this method is called.
If false, the flash messages will be automatically deleted in the next request.
@return array flash messages (key => message or key => [message1, message2]).
@see setFlash()
@see addFlash()
@see getFlash()
@see hasFlash()
@see removeFlash()


public function setFlash($key, $value = true, $removeAfterAccess = true)
    {
        $counters = $this->get($this->flashParam, []);
        $counters[$key] = $removeAfterAccess ? -1 : 0;
        $this->data[$key] = $value;
        $this->data[$this->flashParam] = $counters;
    }

public function setFlash ( $ key , $ value = true , $ removeAfterAccess = true ) { $ counters = $ this -> get ( $ this -> flashParam , [ ] ) ; $ counters [ $ key ] = $ removeAfterAccess ? - 1 : 0 ; $ this -> data [ $ key ] = $ value ; $ this -> data [ $ this -> flashParam ] = $ counters ; }

Sets a flash message.
A flash message will be automatically deleted after it is accessed in a request and the deletion will happen
in the next request.
If there is already an existing flash message with the same key, it will be overwritten by the new one.
@param string $key the key identifying the flash message. Note that flash messages
and normal session variables share the same name space. If you have a normal
session variable using the same name, its value will be overwritten by this method.
@param mixed $value flash message
@param bool $removeAfterAccess whether the flash message should be automatically removed only if
it is accessed. If false, the flash message will be automatically removed after the next request,
regardless if it is accessed or not. If true (default value), the flash message will remain until after
it is accessed.
@see getFlash()
@see addFlash()
@see removeFlash()

Sets a flash message . A flash message will be automatically deleted after it is accessed in a request and the deletion will happen in the next request . If there is already an existing flash message with the same key it will be overwritten by the new one .


public function addFlash($key, $value = true, $removeAfterAccess = true)
    {
        $counters = $this->get($this->flashParam, []);
        $counters[$key] = $removeAfterAccess ? -1 : 0;
        $this->data[$this->flashParam] = $counters;
        if (empty($this->data[$key])) {
            $this->data[$key] = [$value];
        } else {
            if (is_array($this->data[$key])) {
                $this->data[$key][] = $value;
            } else {
                $this->data[$key] = [$this->data[$key], $value];
            }
        }
    }

public function addFlash ( $ key , $ value = true , $ removeAfterAccess = true ) { $ counters = $ this -> get ( $ this -> flashParam , [ ] ) ; $ counters [ $ key ] = $ removeAfterAccess ? - 1 : 0 ; $ this -> data [ $ this -> flashParam ] = $ counters ; if ( empty ( $ this -> data [ $ key ] ) ) { $ this -> data [ $ key ] = [ $ value ] ; } else { if ( is_array ( $ this -> data [ $ key ] ) ) { $ this -> data [ $ key ] [ ] = $ value ; } else { $ this -> data [ $ key ] = [ $ this -> data [ $ key ] , $ value ] ; } } }

Adds a flash message.
If there are existing flash messages with the same key, the new one will be appended to the existing message array.
@param string $key the key identifying the flash message.
@param mixed $value flash message
@param bool $removeAfterAccess whether the flash message should be automatically removed only if
it is accessed. If false, the flash message will be automatically removed after the next request,
regardless if it is accessed or not. If true (default value), the flash message will remain until after
it is accessed.
@see getFlash()
@see setFlash()
@see removeFlash()

Adds a flash message . If there are existing flash messages with the same key the new one will be appended to the existing message array .


public function removeFlash($key)
    {
        $counters = $this->get($this->flashParam, []);
        $value = isset($this->data[$key], $counters[$key]) ? $this->data[$key] : null;
        unset($counters[$key], $this->data[$key]);
        $this->data[$this->flashParam] = $counters;

        return $value;
    }

public function removeFlash ( $ key ) { $ counters = $ this -> get ( $ this -> flashParam , [ ] ) ; $ value = isset ( $ this -> data [ $ key ] , $ counters [ $ key ] ) ? $ this -> data [ $ key ] : null ; unset ( $ counters [ $ key ] , $ this -> data [ $ key ] ) ; $ this -> data [ $ this -> flashParam ] = $ counters ; return $ value ; }

Removes a flash message.
@param string $key the key identifying the flash message. Note that flash messages
and normal session variables share the same name space.  If you have a normal
session variable using the same name, it will be removed by this method.
@return mixed the removed flash message. Null if the flash message does not exist.
@see getFlash()
@see setFlash()
@see addFlash()
@see removeAllFlashes()


public function removeAllFlashes()
    {
        $counters = $this->get($this->flashParam, []);
        foreach (array_keys($counters) as $key) {
            unset($this->data[$key]);
        }
        unset($this->data[$this->flashParam]);
    }

public function removeAllFlashes ( ) { $ counters = $ this -> get ( $ this -> flashParam , [ ] ) ; foreach ( array_keys ( $ counters ) as $ key ) { unset ( $ this -> data [ $ key ] ) ; } unset ( $ this -> data [ $ this -> flashParam ] ) ; }

Removes all flash messages.
Note that flash messages and normal session variables share the same name space.
If you have a normal session variable using the same name, it will be removed
by this method.
@see getFlash()
@see setFlash()
@see addFlash()
@see removeFlash()

Removes all flash messages . Note that flash messages and normal session variables share the same name space . If you have a normal session variable using the same name it will be removed by this method .


protected function freeze()
    {
        if ($this->getIsActive()) {
            if (isset($this->data)) {
                $this->frozenSessionData = $this->data;
            }
            //$this->close();
            if (Reaction::isDebug()) {
                Reaction::info('Session frozen');
            }
        }
    }

protected
function
freeze
(
)
{
if
(
$
this
->
getIsActive
(
)
)
{
if
(
isset
(
$
this
->
data
)
)
{
$
this
->
frozenSessionData
=
$
this
->
data
;
}
//$this->close();
if
(
Reaction
::
isDebug
(
)
)
{
Reaction
::
info
(
'Session frozen'
)
;
}
}
}

If session is started it's not possible to edit session ini settings. In PHP7.2+ it throws exception.
This function saves session data to temporary variable and stop session.

If session is started it s not possible to edit session ini settings . In PHP7 . 2 + it throws exception . This function saves session data to temporary variable and stop session .


protected function unfreeze()
    {
        if (null !== $this->frozenSessionData) {

            //$this->open();

            if ($this->getIsActive()) {
                Reaction::info('Session unfrozen');
            } else {
                $error = error_get_last();
                $message = isset($error['message']) ? $error['message'] : 'Failed to unfreeze session.';
                Reaction::error($message);
            }

            $this->data = $this->frozenSessionData;
            $this->frozenSessionData = null;
            $this->writeSession();
        }
    }

protected
function
unfreeze
(
)
{
if
(
!==
$
this
->
frozenSessionData
)
{
//$this->open();
if
(
$
this
->
getIsActive
(
)
)
{
Reaction
::
info
(
'Session unfrozen'
)
;
}
else
{
$
error
=
error_get_last
(
)
;
$
message
=
isset
(
$
error
[
'message'
]
)
$
error
[
'message'
]
:
'Failed to unfreeze session.'
;
Reaction
::
error
(
$
message
)
;
}
$
this
->
data
=
$
this
->
frozenSessionData
;
$
this
->
frozenSessionData
=
;
$
this
->
writeSession
(
)
;
}
}

Starts session and restores data from temporary variable


protected function createSessionCookie() {
        $_params = $this->getCookieParams();
        $config = [
            'class' => 'Reaction\Web\Cookie',
        ];
        foreach ($_params as $key => $value) {
            if ($key === 'httponly') {
                $key = 'httpOnly';
            } elseif ($key === 'lifetime') {
                $expireValue = intval($value);
                if (empty($expireValue)) {
                    continue;
                }
                $key = 'expire';
                $value = time() + $expireValue;
            }
            $config[$key] = $value;
        }
        $config['value'] = $this->id;
        $config['name'] = $this->getName();
        return Reaction::create($config);
    }

protected function createSessionCookie ( ) { $ _params = $ this -> getCookieParams ( ) ; $ config = [ 'class' => 'Reaction\Web\Cookie' , ] ; foreach ( $ _params as $ key => $ value ) { if ( $ key === 'httponly' ) { $ key = 'httpOnly' ; } elseif ( $ key === 'lifetime' ) { $ expireValue = intval ( $ value ) ; if ( empty ( $ expireValue ) ) { continue ; } $ key = 'expire' ; $ value = time ( ) + $ expireValue ; } $ config [ $ key ] = $ value ; } $ config [ 'value' ] = $ this -> id ; $ config [ 'name' ] = $ this -> getName ( ) ; return Reaction :: create ( $ config ) ; }

Create session cookie
@return Reaction\Web\Cookie


protected function _validateAfter($attribute, $value, $parameters)
    {
        $this->_requireParameterCount(1, $parameters, 'after');

        if (! is_string($value)) {
            return false;
        }

        if ($format = $this->_getDateFormat($attribute)) {
            return $this->_validateAfterWithFormat($format, $value, $parameters);
        }

        if (! ($date = strtotime($parameters[0]))) {
            return strtotime($value) > strtotime($this->_getValue($parameters[0]));
        }

        return strtotime($value) > $date;
    }

protected function _validateAfter ( $ attribute , $ value , $ parameters ) { $ this -> _requireParameterCount ( 1 , $ parameters , 'after' ) ; if ( ! is_string ( $ value ) ) { return false ; } if ( $ format = $ this -> _getDateFormat ( $ attribute ) ) { return $ this -> _validateAfterWithFormat ( $ format , $ value , $ parameters ) ; } if ( ! ( $ date = strtotime ( $ parameters [ 0 ] ) ) ) { return strtotime ( $ value ) > strtotime ( $ this -> _getValue ( $ parameters [ 0 ] ) ) ; } return strtotime ( $ value ) > $ date ; }

Validate the date is after a given date.

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

Validate the date is after a given date .


protected function _validateAfterWithFormat($format, $value, $parameters)
    {
        $param = $this->_getValue($parameters[0]) ?: $parameters[0];

        return $this->_checkDateTimeOrder($format, $param, $value);
    }

protected function _validateAfterWithFormat ( $ format , $ value , $ parameters ) { $ param = $ this -> _getValue ( $ parameters [ 0 ] ) ? : $ parameters [ 0 ] ; return $ this -> _checkDateTimeOrder ( $ format , $ param , $ value ) ; }

Validate the date is after a given date with a given format.

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

Validate the date is after a given date with a given format .


protected function _validateDateFormat($attribute, $value, $parameters)
    {
        $this->_requireParameterCount(1, $parameters, 'date_format');

        if (! is_string($value)) {
            return false;
        }

        $parsed = date_parse_from_format($parameters[0], $value);

        return $parsed['error_count'] === 0 && $parsed['warning_count'] === 0;
    }

protected function _validateDateFormat ( $ attribute , $ value , $ parameters ) { $ this -> _requireParameterCount ( 1 , $ parameters , 'date_format' ) ; if ( ! is_string ( $ value ) ) { return false ; } $ parsed = date_parse_from_format ( $ parameters [ 0 ] , $ value ) ; return $ parsed [ 'error_count' ] === 0 && $ parsed [ 'warning_count' ] === 0 ; }

Validate that an attribute matches a date format.

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

Validate that an attribute matches a date format .


public function checkPredictions()
    {
        $exception = new AggregateException(sprintf("%s:\n", $this->name));

        foreach ($this->prophecies as $prophecy) {
            try {
                $prophecy->checkPrediction();
            } catch (PredictionException $e) {
                $exception->append($e);
            }
        }

        if (count($exception->getExceptions())) {
            throw $exception;
        }
    }

public function checkPredictions ( ) { $ exception = new AggregateException ( sprintf ( "%s:\n" , $ this -> name ) ) ; foreach ( $ this -> prophecies as $ prophecy ) { try { $ prophecy -> checkPrediction ( ) ; } catch ( PredictionException $ e ) { $ exception -> append ( $ e ) ; } } if ( count ( $ exception -> getExceptions ( ) ) ) { throw $ exception ; } }

Checks that registered method predictions do not fail.

@throws \Prophecy\Exception\Prediction\AggregateException If any of registered predictions fail

Checks that registered method predictions do not fail .


function assign(array &$arr, string $path, $value, string $separator = '.')
    {
        $keys = explode($separator, $path);

        foreach ($keys as $key) {
            $arr = &$arr[$key];
        }

        $arr = $value;
    }

function assign ( array & $ arr , string $ path , $ value , string $ separator = '.' ) { $ keys = explode ( $ separator , $ path ) ; foreach ( $ keys as $ key ) { $ arr = & $ arr [ $ key ] ; } $ arr = $ value ; }

Creates an multidimensional array out of an string notation and adds a value to the last element.

@param array $arr
Reference to the array to fill
@param string $path
Path to create array from
@param mixed $value
The value to assign to the last key
@param string $separator
Optional seperator to be used while splittint the path into key values (Default: '.')

Creates an multidimensional array out of an string notation and adds a value to the last element .


public function getControllerPluginConfig()
    {
        return [
            'factories' => [
                'resource' => function(\Zend\Mvc\Controller\PluginManager $sm) {
                        $event = new ResourceEvent();
                        $event->setIdentity($sm->getServiceLocator()->get('api-identity'));
                        $sm->get('');
                    }
            ]
        ];
    }

public function getControllerPluginConfig ( ) { return [ 'factories' => [ 'resource' => function ( \ Zend \ Mvc \ Controller \ PluginManager $ sm ) { $ event = new ResourceEvent ( ) ; $ event -> setIdentity ( $ sm -> getServiceLocator ( ) -> get ( 'api-identity' ) ) ; $ sm -> get ( '' ) ; } ] ] ; }

Expected to return \Zend\ServiceManager\Config object or array to
seed such an object.

@return array|\Zend\ServiceManager\Config

Expected to return \ Zend \ ServiceManager \ Config object or array to seed such an object .


protected function executeRule($user, $item, $params)
    {
        if ($item->ruleName === null) {
            return resolve(true);
        }
        return $this->getRule($item->ruleName)->then(
            function($rule) use ($user, $item, $params) {
                if ($rule instanceof Rule) {
                    return $rule->execute($user, $item, $params);
                }
                return reject(false);
            }
        )->then(null, function() use ($item) {
            throw new InvalidConfigException("Rule not found: {$item->ruleName}");
        });
    }

protected
function
executeRule
(
$
user
,
$
item
,
$
params
)
{
if
(
$
item
->
ruleName
===
)
{
return
resolve
(
true
)
;
}
return
$
this
->
getRule
(
$
item
->
ruleName
)
->
then
(
function
(
$
rule
)
use
(
$
user
,
$
item
,
$
params
)
{
if
(
$
rule
instanceof
Rule
)
{
return
$
rule
->
execute
(
$
user
,
$
item
,
$
params
)
;
}
return
reject
(
false
)
;
}
)
->
then
(
,
function
(
)
use
(
$
item
)
{
throw
new
InvalidConfigException
(
"Rule not found: {$item->ruleName}"
)
;
}
)
;
}

Executes the rule associated with the specified auth item.

If the item does not specify a rule, this method will return true. Otherwise, it will
return the value of [[Rule::execute()]].

@param string|int $user the user ID. This should be either an integer or a string representing
the unique identifier of a user. See [[\yii\web\User::id]].
@param Item $item the auth item that needs to execute its rule
@param array $params parameters passed to [[CheckAccessInterface::checkAccess()]] and will be passed to the rule
@return ExtendedPromiseInterface with bool the return value of [[Rule::execute()]]. If the auth item does not specify a rule, true will be returned.

Executes the rule associated with the specified auth item .


function _processMultipleDepsName($deps)
    {
        $ret = $tests = array();
        foreach ($deps as $name => $dep) {
            foreach ($dep as $d) {
                $tests[$name][] = $this->_processDep($d);
            }
        }

        foreach ($tests as $name => $test) {
            $max = $min = $php = array();
            $php['name'] = $name;
            foreach ($test as $dep) {
                if (!$dep) {
                    continue;
                }
                if (isset($dep['channel'])) {
                    $php['channel'] = 'pear.php.net';
                }
                if (isset($dep['conflicts']) && $dep['conflicts'] == 'yes') {
                    $php['conflicts'] = 'yes';
                }
                if (isset($dep['min'])) {
                    $min[$dep['min']] = count($min);
                }
                if (isset($dep['max'])) {
                    $max[$dep['max']] = count($max);
                }
            }
            if (count($min) > 0) {
                uksort($min, 'version_compare');
            }
            if (count($max) > 0) {
                uksort($max, 'version_compare');
            }
            if (count($min)) {
                // get the highest minimum
                $min = array_pop($a = array_flip($min));
            } else {
                $min = false;
            }
            if (count($max)) {
                // get the lowest maximum
                $max = array_shift($a = array_flip($max));
            } else {
                $max = false;
            }
            if ($min) {
                $php['min'] = $min;
            }
            if ($max) {
                $php['max'] = $max;
            }
            $exclude = array();
            foreach ($test as $dep) {
                if (!isset($dep['exclude'])) {
                    continue;
                }
                $exclude[] = $dep['exclude'];
            }
            if (count($exclude)) {
                $php['exclude'] = $exclude;
            }
            $ret[] = $php;
        }
        return $ret;
    }

function
_processMultipleDepsName
(
$
deps
)
{
$
ret
=
$
tests
=
array
(
)
;
foreach
(
$
deps
as
$
name
=>
$
dep
)
{
foreach
(
$
dep
as
$
d
)
{
$
tests
[
$
name
]
[
]
=
$
this
->
_processDep
(
$
d
)
;
}
}
foreach
(
$
tests
as
$
name
=>
$
test
)
{
$
max
=
$
min
=
$
php
=
array
(
)
;
$
php
[
'name'
]
=
$
name
;
foreach
(
$
test
as
$
dep
)
{
if
(
!
$
dep
)
{
continue
;
}
if
(
isset
(
$
dep
[
'channel'
]
)
)
{
$
php
[
'channel'
]
=
'pear.php.net'
;
}
if
(
isset
(
$
dep
[
'conflicts'
]
)
&&
$
dep
[
'conflicts'
]
==
'yes'
)
{
$
php
[
'conflicts'
]
=
'yes'
;
}
if
(
isset
(
$
dep
[
'min'
]
)
)
{
$
min
[
$
dep
[
'min'
]
]
=
count
(
$
min
)
;
}
if
(
isset
(
$
dep
[
'max'
]
)
)
{
$
max
[
$
dep
[
'max'
]
]
=
count
(
$
max
)
;
}
}
if
(
count
(
$
min
)
>
0
)
{
uksort
(
$
min
,
'version_compare'
)
;
}
if
(
count
(
$
max
)
>
0
)
{
uksort
(
$
max
,
'version_compare'
)
;
}
if
(
count
(
$
min
)
)
{
// get the highest minimum
$
min
=
array_pop
(
$
a
=
array_flip
(
$
min
)
)
;
}
else
{
$
min
=
false
;
}
if
(
count
(
$
max
)
)
{
// get the lowest maximum
$
max
=
array_shift
(
$
a
=
array_flip
(
$
max
)
)
;
}
else
{
$
max
=
false
;
}
if
(
$
min
)
{
$
php
[
'min'
]
=
$
min
;
}
if
(
$
max
)
{
$
php
[
'max'
]
=
$
max
;
}
$
exclude
=
array
(
)
;
foreach
(
$
test
as
$
dep
)
{
if
(
!
isset
(
$
dep
[
'exclude'
]
)
)
{
continue
;
}
$
exclude
[
]
=
$
dep
[
'exclude'
]
;
}
if
(
count
(
$
exclude
)
)
{
$
php
[
'exclude'
]
=
$
exclude
;
}
$
ret
[
]
=
$
php
;
}
return
$
ret
;
}

process multiple dependencies that have a name, like package deps
@param array
@return array
@access private

process multiple dependencies that have a name like package deps


public static function parseFragments(array $rawData = [])
    {
        $fragments = [];
        foreach ($rawData as $type => $value) {
            // Skipp Custom values
            if(!is_array($value)) continue;

            $fragments[] = RichText::asHtml($value);
        }

        return $fragments;
    }

public
static
function
parseFragments
(
array
$
rawData
=
[
]
)
{
$
fragments
=
[
]
;
foreach
(
$
rawData
as
$
type
=>
$
value
)
{
// Skipp Custom values
if
(
!
is_array
(
$
value
)
)
continue
;
$
fragments
[
]
=
RichText
::
asHtml
(
$
value
)
;
}
return
$
fragments
;
}

Parse fragments from a json document. For internal usage.

@param array $rawData

@return array

Parse fragments from a json document . For internal usage .


public function make(string $template = null, array $variables = []): View
    {
        return new static($this->app, $template, $variables);
    }

public function make ( string $ template = null , array $ variables = [ ] ) : View { return new static ( $ this -> app , $ template , $ variables ) ; }

Make a new View.

@param string $template  [optional] The template to set
@param array  $variables [optional] The variables to set

@throws InvalidConfigPath

@return \Valkyrja\View\View


public function setVariables(array $variables = []): View
    {
        $this->variables = array_merge($this->variables, $variables);

        return $this;
    }

public function setVariables ( array $ variables = [ ] ) : View { $ this -> variables = array_merge ( $ this -> variables , $ variables ) ; return $ this ; }

Set the variables.

@param array $variables [optional] The variables to set

@return \Valkyrja\View\View


public function setVariable(string $key, $value): View
    {
        $this->variables[$key] = $value;

        return $this;
    }

public function setVariable ( string $ key , $ value ) : View { $ this -> variables [ $ key ] = $ value ; return $ this ; }

Set a single variable.

@param string $key   The variable key to set
@param mixed  $value The value to set

@return \Valkyrja\View\View


public function escape(string $value): string
    {
        $value = mb_convert_encoding($value, 'UTF-8', 'UTF-8');
        $value = htmlentities($value, ENT_QUOTES, 'UTF-8');

        return $value;
    }

public function escape ( string $ value ) : string { $ value = mb_convert_encoding ( $ value , 'UTF-8' , 'UTF-8' ) ; $ value = htmlentities ( $ value , ENT_QUOTES , 'UTF-8' ) ; return $ value ; }

Escape a value for output.

@param string $value The value to escape

@return string


public function getTemplateDir(string $path = null): string
    {
        return $this->templateDir . ($path
                ? Directory::DIRECTORY_SEPARATOR . $path
                : $path);
    }

public function getTemplateDir ( string $ path = null ) : string { return $ this -> templateDir . ( $ path ? Directory :: DIRECTORY_SEPARATOR . $ path : $ path ) ; }

Get the template directory.

@param string $path [optional] The path to append

@return string


public function layout(string $layout = null): View
    {
        // If no layout has been set
        if (null === $layout) {
            // Set to null
            return $this->withoutLayout();
        }

        // If we should be tracking layout changes
        if ($this->trackLayoutChanges) {
            // Set the flag
            $this->hasLayoutChanged = true;
        }

        $this->layout     = $layout;
        $this->layoutPath = $this->getFullPath($layout);

        return $this;
    }

Set the layout for the view template.

@param string $layout [optional] The layout to set

@throws InvalidConfigPath

@return \Valkyrja\View\View


public function template(string $template): View
    {
        $this->template     = $template;
        $this->templatePath = $this->getFullPath($template);

        return $this;
    }

public function template ( string $ template ) : View { $ this -> template = $ template ; $ this -> templatePath = $ this -> getFullPath ( $ template ) ; return $ this ; }

Set the template for the view.

@param string $template The template

@throws InvalidConfigPath

@return \Valkyrja\View\View


public function partial(string $partial, array $variables = []): string
    {
        return $this->renderTemplate($this->getFullPath($partial), $variables);
    }

public function partial ( string $ partial , array $ variables = [ ] ) : string { return $ this -> renderTemplate ( $ this -> getFullPath ( $ partial ) , $ variables ) ; }

Output a partial.

@param string $partial   The partial
@param array  $variables [optional]

@throws InvalidConfigPath

@return string


public function endBlock(string $name): string
    {
        unset($this->blockStatus[$name]);

        return $this->blocks[$name] = ob_get_clean();
    }

public function endBlock ( string $ name ) : string { unset ( $ this -> blockStatus [ $ name ] ) ; return $ this -> blocks [ $ name ] = ob_get_clean ( ) ; }

End a block.

@param string $name The block's name

@return string


public function render(array $variables = []): string
    {
        // Set the variables with the new variables and this view instance
        $this->variables = array_merge(
            $this->variables,
            $variables,
            ['view' => $this]
        );

        // Render the template
        $template = $this->renderTemplate($this->templatePath);

        // Check if a layout has been set
        if (null === $this->layout) {
            return $template;
        }

        // Begin tracking layout changes for recursive layout
        $this->trackLayoutChanges = true;

        return $this->renderTemplate($this->layoutPath);
    }

Render the templates and view.

@param array $variables [optional] The variables to set

@return string


protected function getFullPath(string $template): string
    {
        // If the first character of the template is an @ symbol
        // Then this is a template from a path in the config
        if (strpos($template, '@') === 0) {
            $explodeOn = Directory::DIRECTORY_SEPARATOR;
            $parts     = explode($explodeOn, $template);
            $path      = config('views.paths.' . $parts[0]);

            // If there is no path
            if ($path === null) {
                // Then throw an exception
                throw new InvalidConfigPath(
                    'Invalid path '
                    . $parts[0]
                    . ' specified for template '
                    . $template
                );
            }

            // Remove any trailing slashes
            $parts[0] = $explodeOn . trim($path, $explodeOn);

            $path = implode($explodeOn, $parts);
        } else {
            $path = $this->getTemplateDir($template);
        }

        return $path . $this->getFileExtension();
    }

Get the full path for a given template.

@param string $template The template

@throws InvalidConfigPath

@return string

Get the full path for a given template .


protected function renderTemplate(string $templatePath, array $variables = []): string
    {
        $variables = array_merge($this->variables, $variables);

        extract($variables, EXTR_OVERWRITE);

        ob_start();
        include $templatePath;

        return ob_get_clean();
    }

protected function renderTemplate ( string $ templatePath , array $ variables = [ ] ) : string { $ variables = array_merge ( $ this -> variables , $ variables ) ; extract ( $ variables , EXTR_OVERWRITE ) ; ob_start ( ) ; include $ templatePath ; return ob_get_clean ( ) ; }

Render a template.

@param string $templatePath The template path
@param array  $variables    [optional] The variables to set

@return string


protected function renderLayout(string $layoutPath): string
    {
        // Render the layout
        $renderedLayout = $this->renderTemplate($layoutPath);

        // Check if the layout has changed
        if ($this->hasLayoutChanged) {
            // Reset the flag
            $this->hasLayoutChanged = false;
            // Render the new layout
            $renderedLayout = $this->renderLayout($this->layoutPath);
        }

        return $renderedLayout;
    }

protected
function
renderLayout
(
string
$
layoutPath
)
:
string
{
// Render the layout
$
renderedLayout
=
$
this
->
renderTemplate
(
$
layoutPath
)
;
// Check if the layout has changed
if
(
$
this
->
hasLayoutChanged
)
{
// Reset the flag
$
this
->
hasLayoutChanged
=
false
;
// Render the new layout
$
renderedLayout
=
$
this
->
renderLayout
(
$
this
->
layoutPath
)
;
}
return
$
renderedLayout
;
}

Render a layout path.

@param string $layoutPath The layout path

@return string


protected function setRoute(Route $route, array &$routes, array &$lengths): void
    {
        $requestMethod = implode(' | ', $route->getRequestMethods());
        $dispatch      = 'Closure';

        if (null !== $route->getFunction()) {
            $dispatch = $route->getFunction();
        } elseif (null !== $route->getClass()) {
            $dispatch = $route->getClass()
                . ($route->isStatic() ? '::' : '->')
                . ($route->getMethod()
                    ? $route->getMethod() . '()'
                    : $route->getProperty());
        }

        $lengths[0] = max($lengths[0], \strlen($requestMethod));
        $lengths[1] = max($lengths[1], \strlen($route->getPath()));
        $lengths[2] = max($lengths[2], \strlen($route->getName()));
        $lengths[3] = max($lengths[3], \strlen($dispatch));

        $routes[] = [
            $requestMethod,
            $route->getPath(),
            $route->getName() ?? '',
            $dispatch,
        ];
    }

protected
function
setRoute
(
Route
$
route
,
array
&
$
routes
,
array
&
$
lengths
)
:
void
{
$
requestMethod
=
implode
(
' | '
,
$
route
->
getRequestMethods
(
)
)
;
$
dispatch
=
'Closure'
;
if
(
!==
$
route
->
getFunction
(
)
)
{
$
dispatch
=
$
route
->
getFunction
(
)
;
}
elseif
(
!==
$
route
->
getClass
(
)
)
{
$
dispatch
=
$
route
->
getClass
(
)
.
(
$
route
->
isStatic
(
)
'::'
:
'->'
)
.
(
$
route
->
getMethod
(
)
$
route
->
getMethod
(
)
.
'()'
:
$
route
->
getProperty
(
)
)
;
}
$
lengths
[
0
]
=
max
(
$
lengths
[
0
]
,
\
strlen
(
$
requestMethod
)
)
;
$
lengths
[
1
]
=
max
(
$
lengths
[
1
]
,
\
strlen
(
$
route
->
getPath
(
)
)
)
;
$
lengths
[
2
]
=
max
(
$
lengths
[
2
]
,
\
strlen
(
$
route
->
getName
(
)
)
)
;
$
lengths
[
3
]
=
max
(
$
lengths
[
3
]
,
\
strlen
(
$
dispatch
)
)
;
$
routes
[
]
=
[
$
requestMethod
,
$
route
->
getPath
(
)
,
$
route
->
getName
(
)
??
''
,
$
dispatch
,
]
;
}

Set a route as an array from a route object.

@param Route $route   The route object
@param array $routes  The flat routes
@param array $lengths The longest string lengths

@throws \InvalidArgumentException

@return void

Set a route as an array from a route object .


protected function getSepLine(array $lengths): string
    {
        return '+-' . str_repeat('-', $lengths[0])
            . '-+-' . str_repeat('-', $lengths[1])
            . '-+-' . str_repeat('-', $lengths[2])
            . '-+-' . str_repeat('-', $lengths[3])
            . '-+';
    }

protected function getSepLine ( array $ lengths ) : string { return '+-' . str_repeat ( '-' , $ lengths [ 0 ] ) . '-+-' . str_repeat ( '-' , $ lengths [ 1 ] ) . '-+-' . str_repeat ( '-' , $ lengths [ 2 ] ) . '-+-' . str_repeat ( '-' , $ lengths [ 3 ] ) . '-+' ; }

Get the separation line.

@param array $lengths The longest lengths

@return string


protected function headerMessage(array $headerTexts, array $lengths): void
    {
        $headerMessage = '| ' . $headerTexts[0]
            . str_repeat(' ', $lengths[0] - \strlen($headerTexts[0]))
            . ' | ' . $headerTexts[1]
            . str_repeat(' ', $lengths[1] - \strlen($headerTexts[1]))
            . ' | ' . $headerTexts[2]
            . str_repeat(' ', $lengths[2] - \strlen($headerTexts[2]))
            . ' | ' . $headerTexts[3]
            . str_repeat(' ', $lengths[3] - \strlen($headerTexts[3]))
            . ' |';

        output()->writeMessage($headerMessage, true);
    }

protected
function
headerMessage
(
array
$
headerTexts
,
array
$
lengths
)
:
void
{
$
headerMessage
=
'| '
.
$
headerTexts
[
0
]
.
str_repeat
(
' '
,
$
lengths
[
0
]
\
strlen
(
$
headerTexts
[
0
]
)
)
.
' | '
.
$
headerTexts
[
1
]
.
str_repeat
(
' '
,
$
lengths
[
1
]
\
strlen
(
$
headerTexts
[
1
]
)
)
.
' | '
.
$
headerTexts
[
2
]
.
str_repeat
(
' '
,
$
lengths
[
2
]
\
strlen
(
$
headerTexts
[
2
]
)
)
.
' | '
.
$
headerTexts
[
3
]
.
str_repeat
(
' '
,
$
lengths
[
3
]
\
strlen
(
$
headerTexts
[
3
]
)
)
.
' |'
;
output
(
)
->
writeMessage
(
$
headerMessage
,
true
)
;
}

Output the header message.

@param array $headerTexts The header texts
@param array $lengths     The longest lengths

@return void


public static function getNotification()
    {
        $notificationClassList = ClassMapGenerator::createMap(base_path().'/vendor/abuseio');
        /** @noinspection PhpUnusedParameterInspection */
        $notificationClassListFiltered = array_where(
            array_keys($notificationClassList),
            function ($value, $key) {
                // Get all notifications, ignore all other packages.
                if (strpos($value, 'AbuseIO\Notification\\') !== false) {
                    return $value;
                }
                return false;
            }
        );

        $notifications = [];
        $notificationList = array_map('class_basename', $notificationClassListFiltered);
        foreach ($notificationList as $notification) {
            if (!in_array($notification, ['Factory', 'Notification'])) {
                $notifications[] = $notification;
            }
        }
        return $notifications;
    }

Get a list of installed AbuseIO notifications and return as an array

@return array


public static function create($requiredName)
    {
        /**
         * Loop through the notification list and try to find a match by name
         */
        $notifications = Factory::getNotification();
        foreach ($notifications as $notificationName) {

            if ($notificationName === ucfirst($requiredName)) {
                $notificationClass = 'AbuseIO\\Notification\\' . $notificationName;

                // Collector is enabled, then return its object
                if (config("notifications.{$notificationName}.notification.enabled") === true) {

                    return new $notificationClass();

                } else {
                    Log::info(
                        'AbuseIO\Notification\Factory: ' .
                        "The notification {$notificationName} has been disabled and will not be used."
                    );

                    return false;
                }
            }
        }

        // No valid notifications found
        Log::info(
            'AbuseIO\Notification\Factory: ' .
            "The notification {$requiredName} is not present on this system"
        );
        return false;
    }

Create and return a Collector object and it's configuration

@param string $requiredName
@return object

Create and return a Collector object and it s configuration


public function setKey($key)
    {
        $this->key = $key;

        if (0 < strlen($this->key) && !$this->hasRename()) {
            if ($this->hasPath()) {
                $this->rename = pathinfo($this->path, PATHINFO_BASENAME);
            } else {
                $this->rename = pathinfo($this->key, PATHINFO_BASENAME);
            }
            $this->setUpdatedAt(new \DateTime());
        }

        return $this;
    }

public function setKey ( $ key ) { $ this -> key = $ key ; if ( 0 < strlen ( $ this -> key ) && ! $ this -> hasRename ( ) ) { if ( $ this -> hasPath ( ) ) { $ this -> rename = pathinfo ( $ this -> path , PATHINFO_BASENAME ) ; } else { $ this -> rename = pathinfo ( $ this -> key , PATHINFO_BASENAME ) ; } $ this -> setUpdatedAt ( new \ DateTime ( ) ) ; } return $ this ; }

Sets the key.

@param string $key
@return UploadableTrait


public function shouldBeRenamed()
    {
        return (bool) ($this->hasPath() && $this->guessFilename() != pathinfo($this->getPath(), PATHINFO_BASENAME));
    }

public function shouldBeRenamed ( ) { return ( bool ) ( $ this -> hasPath ( ) && $ this -> guessFilename ( ) != pathinfo ( $ this -> getPath ( ) , PATHINFO_BASENAME ) ) ; }

Returns whether the uploadable should be renamed or not.

@return boolean

Returns whether the uploadable should be renamed or not .


public function guessExtension()
    {
        $extension = null;
        if ($this->hasFile()) {
            $extension = $this->file->guessExtension();
        } elseif ($this->hasKey()) {
            $extension = pathinfo($this->getKey(), PATHINFO_EXTENSION);
        } elseif ($this->hasPath()) {
            $extension = pathinfo($this->getPath(), PATHINFO_EXTENSION);
        }
        $extension = strtolower($extension);
        return $extension;
    }

public function guessExtension ( ) { $ extension = null ; if ( $ this -> hasFile ( ) ) { $ extension = $ this -> file -> guessExtension ( ) ; } elseif ( $ this -> hasKey ( ) ) { $ extension = pathinfo ( $ this -> getKey ( ) , PATHINFO_EXTENSION ) ; } elseif ( $ this -> hasPath ( ) ) { $ extension = pathinfo ( $ this -> getPath ( ) , PATHINFO_EXTENSION ) ; } $ extension = strtolower ( $ extension ) ; return $ extension ; }


public function guessFilename()
    {
        // Extension
        $extension = $this->guessExtension();

        // Filename
        $filename = null;
        if ($this->hasRename()) {
            $filename = Transliterator::urlize(pathinfo($this->rename, PATHINFO_FILENAME));
        } elseif ($this->hasFile()) {
            $filename = pathinfo($this->file->getFilename(), PATHINFO_FILENAME);
        } elseif ($this->hasKey()) {
            $filename = pathinfo($this->getKey(), PATHINFO_FILENAME);
        } elseif ($this->hasPath()) {
            $filename = pathinfo($this->path, PATHINFO_FILENAME);
        }

        if ($filename !== null && $extension !== null) {
            return $filename . '.' . $extension;
        }

        return null;
    }

public
function
guessFilename
(
)
{
// Extension
$
extension
=
$
this
->
guessExtension
(
)
;
// Filename
$
filename
=
;
if
(
$
this
->
hasRename
(
)
)
{
$
filename
=
Transliterator
::
urlize
(
pathinfo
(
$
this
->
rename
,
PATHINFO_FILENAME
)
)
;
}
elseif
(
$
this
->
hasFile
(
)
)
{
$
filename
=
pathinfo
(
$
this
->
file
->
getFilename
(
)
,
PATHINFO_FILENAME
)
;
}
elseif
(
$
this
->
hasKey
(
)
)
{
$
filename
=
pathinfo
(
$
this
->
getKey
(
)
,
PATHINFO_FILENAME
)
;
}
elseif
(
$
this
->
hasPath
(
)
)
{
$
filename
=
pathinfo
(
$
this
->
path
,
PATHINFO_FILENAME
)
;
}
if
(
$
filename
!==
&&
$
extension
!==
)
{
return
$
filename
.
'.'
.
$
extension
;
}
return
;
}


public function setRename($rename)
    {
        if ($rename !== $this->rename) {
            $this->updatedAt = new \DateTime();
        }
        $this->rename = strtolower($rename);

        return $this;
    }

public function setRename ( $ rename ) { if ( $ rename !== $ this -> rename ) { $ this -> updatedAt = new \ DateTime ( ) ; } $ this -> rename = strtolower ( $ rename ) ; return $ this ; }

Set rename.

@param string $rename
@return UploadableTrait|$this


public function downloadAction(Request $request)
    {
        $key = $request->attributes->get('key');
        if (0 < strlen($key)) {
            $fs = $this->get('local_upload_filesystem');
            if ($fs->has($key)) {
                $file = $fs->get($key);

                // TODO 304 not modified

                $response = new StreamedResponse();

                // Set the headers
                $response->headers->set('Content-Type', $file->getMimetype());
                $response->headers->set('Content-Length', $file->getSize());

                // TODO http cache
                /*$this->setHttpCacheHeaders(
                    $lastModified,
                    md5($this->getCachePath() . $lastModified->getTimestamp()),
                    $this->maxAge
                );*/

                $response->setCallback(function () use ($file) {
                    fpassthru($file->readStream());
                });

                return $response;
            }
        }

        throw new NotFoundHttpException('File not found');
    }

Download local file.

@param Request $request
@return BinaryFileResponse
@throws NotFoundHttpException


public function tinymceUploadAction(Request $request)
    {
        // TODO check admin ?

        if (!$request->isXmlHttpRequest()) {
            throw new NotFoundHttpException();
        }

        $name = $request->request->get('name');
        $base64 = $request->request->get('data');

        $filename = md5(time().uniqid()).".jpg";
        $data = explode(',', $base64);
        if (2 != count($data)) {
            throw new \InvalidArgumentException('Invalid image data.');
        }

        $fs = $this->get('local_tinymce_filesystem');
        if (!$fs->put($filename, base64_decode($data[1]))) {
            throw new \Exception('Failed to create image.');
        }

        return new JsonResponse([
            'location' => '/tinymce/' . $filename,
        ]);
    }

public
function
tinymceUploadAction
(
Request
$
request
)
{
// TODO check admin ?
if
(
!
$
request
->
isXmlHttpRequest
(
)
)
{
throw
new
NotFoundHttpException
(
)
;
}
$
name
=
$
request
->
request
->
get
(
'name'
)
;
$
base64
=
$
request
->
request
->
get
(
'data'
)
;
$
filename
=
md5
(
time
(
)
.
uniqid
(
)
)
.
".jpg"
;
$
data
=
explode
(
','
,
$
base64
)
;
if
(
2
!=
count
(
$
data
)
)
{
throw
new
\
InvalidArgumentException
(
'Invalid image data.'
)
;
}
$
fs
=
$
this
->
get
(
'local_tinymce_filesystem'
)
;
if
(
!
$
fs
->
put
(
$
filename
,
base64_decode
(
$
data
[
1
]
)
)
)
{
throw
new
\
Exception
(
'Failed to create image.'
)
;
}
return
new
JsonResponse
(
[
'location'
=>
'/tinymce/'
.
$
filename
,
]
)
;
}

Handle tinymce upload.

@param Request $request
@return JsonResponse
@throws \Exception


public function onKernelException(GetResponseForExceptionEvent $event)
    {
        $exception = $event->getException();

        if ($exception instanceof NotFoundHttpException) {

            $request = $event->getRequest();
            $registry = $this->container->get('ekyna_core.redirection.provider_registry');
            foreach ($registry->getProviders() as $provider) {
                if ($provider->supports($request) && false !== $response = $provider->redirect($request)) {
                    if ($response instanceof RedirectResponse) {
                        $event->setResponse($response);
                    } elseif (is_string($response) && 0 < strlen($response)) {
                        $response = $this->container
                            ->get('security.http_utils')
                            ->createRedirectResponse($request, $response, 301)
                        ;
                        $event->setResponse($response);
                    }
                    return;
                }
            }

        } elseif ($exception instanceof RedirectException) {

            // Check path
            $path = $exception->getPath();
            if (0 === strlen($path)) {
                return;
            }

            // Build the response
            $request = $event->getRequest();
            $response = $this->container
                ->get('security.http_utils')
                ->createRedirectResponse($request, $path)
            ;
            $event->setResponse($response);

            // Add flash
            if (0 < strlen($message = $exception->getMessage())) {
                $this->container
                    ->get('session')
                    ->getFlashBag()
                    ->add($exception->getMessageType(), $message)
                ;
            }

        } elseif ($exception instanceof HttpException) {

            // Don't send log about http exceptions.
            return;

        } elseif(!$this->container->getParameter('kernel.debug')) {

            $template = new TemplateReference('EkynaCoreBundle', 'Exception', 'exception', 'html', 'twig');
            $code = $exception->getCode();
            $email = $this->container->getParameter('error_report_mail');
            $request = $this->container->get('request_stack')->getMasterRequest();

            $content = $this->container->get('twig')->render(
                (string) $template,
                [
                    'status_code' => $code,
                    'status_text' => isset(Response::$statusTexts[$code]) ? Response::$statusTexts[$code] : '',
                    'exception' => FlattenException::create($exception),
                    'request' => $request,
                    'logger' => null,
                    'currentContent' => null,
                ]
            );

            $report = \Swift_Message::newInstance('Error report', $content, 'text/html');
            $report->setFrom($email)->setTo($email);
            $this->container->get('mailer')->send($report);
        }
    }

Kernel exception event handler.

@param GetResponseForExceptionEvent $event


private function getCurl(string $url, int $return = 1, int $timeout = 10, string $lang = 'de-DE')
    {
        // Define useragent
        $agent = 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ' . $lang . '; rv:1.9.2.12) Gecko/20101026 Firefox/3.6.12';

        // Url encode
        $url = urlencode($url);

        // Language of request
        $lang = array(
            'Accept-Language: ' . $lang
        );

        $curl = curl_init();

        curl_setopt($curl, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $lang);
        curl_setopt($curl, CURLOPT_USERAGENT, $agent);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, $return);
        curl_setopt($curl, CURLOPT_URL, $url);

        $result = curl_exec($curl);

        curl_close($curl);

        return $result;
    }

Fetches an url and returns the returned data

@param string $url
Url to load
@param number $return
Flag to expect return value
@param number $timeout
Max timeout
@param string $lang
Language of useragent to send

@return mixed


public function execute() {
        if ($this->isMulti) {
            return;
        }
        $this->applyMethod();
        $this->responseText = curl_exec($this->curl);
        self::log('HTTP RESPONSE: '.$this->responseText);
        return $this->parseResponse();
    }

public
function
execute
(
)
{
if
(
$
this
->
isMulti
)
{
return
;
}
$
this
->
applyMethod
(
)
;
$
this
->
responseText
=
curl_exec
(
$
this
->
curl
)
;
self
::
log
(
'HTTP RESPONSE: '
.
$
this
->
responseText
)
;
return
$
this
->
parseResponse
(
)
;
}

EXECUTE AND CLOSE
@return mixed|null
@throws \Exception


public function setCookieFile($file) {
        $file = (string)$file;
        return $this->setOption(CURLOPT_COOKIEJAR, $file)
            ->setOption(CURLOPT_COOKIEFILE, $file);
    }

public function setCookieFile ( $ file ) { $ file = ( string ) $ file ; return $ this -> setOption ( CURLOPT_COOKIEJAR , $ file ) -> setOption ( CURLOPT_COOKIEFILE , $ file ) ; }

SET COOKIE FILE
@param string|File $file
@return $this


protected static function chooseParameters(array $item, array $args) {
        $data = static::getMapParameters($item, $args);
        if (empty($data)) {
            throw new Exception('ONE OF MANY IS NEED!');
        }
        return $data;
    }

protected
static
function
chooseParameters
(
array
$
item
,
array
$
args
)
{
$
data
=
static
::
getMapParameters
(
$
item
,
$
args
)
;
if
(
empty
(
$
data
)
)
{
throw
new
Exception
(
'ONE OF MANY IS NEED!'
)
;
}
return
$
data
;
}

MANY CHOOSE ONE
@param array $item
@param array $args
@return array
@throws Exception


public function actionIndex()
    {
        $items = Item::updateAll(Yii::$app->request->post('Item'));
        if ($items === true) {
            Yii::$app->session->setFlash('info', Yii::t('modules/module', 'Updated'));
            return $this->refresh();
        } else if (!$items) {
            $items = Item::findAll();
        }
        return $this->render('index', [
            'dataProvider' =>  new ArrayDataProvider([
                'allModels' => $items, 'key' => 'id'
            ]),
        ]);
    }

public function actionIndex ( ) { $ items = Item :: updateAll ( Yii :: $ app -> request -> post ( 'Item' ) ) ; if ( $ items === true ) { Yii :: $ app -> session -> setFlash ( 'info' , Yii :: t ( 'modules/module' , 'Updated' ) ) ; return $ this -> refresh ( ) ; } else if ( ! $ items ) { $ items = Item :: findAll ( ) ; } return $ this -> render ( 'index' , [ 'dataProvider' => new ArrayDataProvider ( [ 'allModels' => $ items , 'key' => 'id' ] ) , ] ) ; }


protected function initOptions()
    {
        $this->htmlHlp->addCssClass($this->options, ['alert']);

        if ($this->closeButton !== false) {
            $this->htmlHlp->addCssClass($this->options, ['alert-dismissible', 'fade', 'show']);
            $this->closeButton = array_merge([
                'data-dismiss' => 'alert',
                'aria-hidden' => 'true',
                'aria-label' => 'Close',
                'class' => 'close',
            ], $this->closeButton);
        }
    }

protected function initOptions ( ) { $ this -> htmlHlp -> addCssClass ( $ this -> options , [ 'alert' ] ) ; if ( $ this -> closeButton !== false ) { $ this -> htmlHlp -> addCssClass ( $ this -> options , [ 'alert-dismissible' , 'fade' , 'show' ] ) ; $ this -> closeButton = array_merge ( [ 'data-dismiss' => 'alert' , 'aria-hidden' => 'true' , 'aria-label' => 'Close' , 'class' => 'close' , ] , $ this -> closeButton ) ; } }

Initializes the widget options.
This method sets the default values for various options.

Initializes the widget options . This method sets the default values for various options .


public function write($filename = null, Zend_Config $config = null, $exclusiveLock = null)
    {
        if ($filename !== null) {
            $this->setFilename($filename);
        }

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

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

        if ($this->_filename === null) {

            throw new Zend_Config_Exception('No filename was set');
        }

        if ($this->_config === null) {

            throw new Zend_Config_Exception('No config was set');
        }

        $configString = $this->render();

        $flags = 0;

        if ($this->_exclusiveLock) {
            $flags |= LOCK_EX;
        }

        $result = @file_put_contents($this->_filename, $configString, $flags);

        if ($result === false) {

            throw new Zend_Config_Exception('Could not write to file "' . $this->_filename . '"');
        }
    }

public
function
write
(
$
filename
=
,
Zend_Config
$
config
=
,
$
exclusiveLock
=
)
{
if
(
$
filename
!==
)
{
$
this
->
setFilename
(
$
filename
)
;
}
if
(
$
config
!==
)
{
$
this
->
setConfig
(
$
config
)
;
}
if
(
$
exclusiveLock
!==
)
{
$
this
->
setExclusiveLock
(
$
exclusiveLock
)
;
}
if
(
$
this
->
_filename
===
)
{
throw
new
Zend_Config_Exception
(
'No filename was set'
)
;
}
if
(
$
this
->
_config
===
)
{
throw
new
Zend_Config_Exception
(
'No config was set'
)
;
}
$
configString
=
$
this
->
render
(
)
;
$
flags
=
0
;
if
(
$
this
->
_exclusiveLock
)
{
$
flags
|=
LOCK_EX
;
}
$
result
=
@
file_put_contents
(
$
this
->
_filename
,
$
configString
,
$
flags
)
;
if
(
$
result
===
false
)
{
throw
new
Zend_Config_Exception
(
'Could not write to file "'
.
$
this
->
_filename
.
'"'
)
;
}
}

Write configuration to file.

@param string $filename
@param Zend_Config $config
@param bool $exclusiveLock
@return void


protected function getExceptionFromContext(array $context)
    {
        $exception = $context['exception'] ?? null;

        if ($exception instanceof \Exception) {
            return $exception;
        }

        if ($exception instanceof \Error) {
            return new \ErrorException(
                $exception->getMessage(),
                0,
                $exception->getCode(),
                $exception->getFile(),
                $exception->getLine()
            );
        }

        return null;
    }

protected function getExceptionFromContext ( array $ context ) { $ exception = $ context [ 'exception' ] ?? null ; if ( $ exception instanceof \ Exception ) { return $ exception ; } if ( $ exception instanceof \ Error ) { return new \ ErrorException ( $ exception -> getMessage ( ) , 0 , $ exception -> getCode ( ) , $ exception -> getFile ( ) , $ exception -> getLine ( ) ) ; } return null ; }

Extracts and returns the exception value from the given context.

@param array $context Any extraneous log information that does not fit well in a string.

@return \Exception|null

Extracts and returns the exception value from the given context .


protected function convertExceptionToArray($exception)
    {
        if (!Reaction::isDebug() && !$exception instanceof UserException && !$exception instanceof HttpException) {
            $exception = new HttpException(500, Reaction::t('rct', 'An internal server error occurred.'));
        }

        $array = [
            'name' => ($exception instanceof Exception || $exception instanceof ErrorException) ? $exception->getName() : 'Exception',
            'message' => $exception->getMessage(),
            'code' => $exception->getCode(),
        ];
        if ($exception instanceof HttpException) {
            $array['status'] = $exception->statusCode;
        }
        if (Reaction::isDebug()) {
            $array['type'] = get_class($exception);
            if (!$exception instanceof UserException) {
                $array['file'] = $exception->getFile();
                $array['line'] = $exception->getLine();
                $array['stack-trace'] = explode("\n", $exception->getTraceAsString());
            }
        }
        if (($prev = $exception->getPrevious()) !== null) {
            $array['previous'] = $this->convertExceptionToArray($prev);
        }

        return $array;
    }

protected
function
convertExceptionToArray
(
$
exception
)
{
if
(
!
Reaction
::
isDebug
(
)
&&
!
$
exception
instanceof
UserException
&&
!
$
exception
instanceof
HttpException
)
{
$
exception
=
new
HttpException
(
500
,
Reaction
::
t
(
'rct'
,
'An internal server error occurred.'
)
)
;
}
$
array
=
[
'name'
=>
(
$
exception
instanceof
Exception
||
$
exception
instanceof
ErrorException
)
$
exception
->
getName
(
)
:
'Exception'
,
'message'
=>
$
exception
->
getMessage
(
)
,
'code'
=>
$
exception
->
getCode
(
)
,
]
;
if
(
$
exception
instanceof
HttpException
)
{
$
array
[
'status'
]
=
$
exception
->
statusCode
;
}
if
(
Reaction
::
isDebug
(
)
)
{
$
array
[
'type'
]
=
get_class
(
$
exception
)
;
if
(
!
$
exception
instanceof
UserException
)
{
$
array
[
'file'
]
=
$
exception
->
getFile
(
)
;
$
array
[
'line'
]
=
$
exception
->
getLine
(
)
;
$
array
[
'stack-trace'
]
=
explode
(
"\n"
,
$
exception
->
getTraceAsString
(
)
)
;
}
}
if
(
(
$
prev
=
$
exception
->
getPrevious
(
)
)
!==
)
{
$
array
[
'previous'
]
=
$
this
->
convertExceptionToArray
(
$
prev
)
;
}
return
$
array
;
}

Converts an exception into an array.
@param \Exception|\Error $exception the exception being converted
@return array the array representation of the exception.


public function renderFile($_file_, $_params_)
    {
        $_params_['handler'] = $this;
        if ($this->exception instanceof ErrorException || !$this->app->has('view')) {
            ob_start();
            ob_implicit_flush(false);
            extract($_params_, EXTR_OVERWRITE);
            require Reaction::getAlias($_file_);

            return ob_get_clean();
        }

        return $this->app->view->renderFile($_file_, $_params_, $this);
    }

public function renderFile ( $ _file_ , $ _params_ ) { $ _params_ [ 'handler' ] = $ this ; if ( $ this -> exception instanceof ErrorException || ! $ this -> app -> has ( 'view' ) ) { ob_start ( ) ; ob_implicit_flush ( false ) ; extract ( $ _params_ , EXTR_OVERWRITE ) ; require Reaction :: getAlias ( $ _file_ ) ; return ob_get_clean ( ) ; } return $ this -> app -> view -> renderFile ( $ _file_ , $ _params_ , $ this ) ; }

Renders a view file as a PHP script.
@param string $_file_ the view file.
@param array $_params_ the parameters (name-value pairs) that will be extracted and made available in the view file.
@return string the rendering result


public function isCoreFile($file)
    {
        $corePath = Reaction::getAlias('@reaction');
        return $file === null || strpos(realpath($file), $corePath . DIRECTORY_SEPARATOR) === 0;
    }

public function isCoreFile ( $ file ) { $ corePath = Reaction :: getAlias ( '@reaction' ) ; return $ file === null || strpos ( realpath ( $ file ) , $ corePath . DIRECTORY_SEPARATOR ) === 0 ; }

Determines whether given name of the file belongs to the framework.
@param string $file name to be checked.
@return bool whether given name of the file belongs to the framework.

Determines whether given name of the file belongs to the framework .


public function getExceptionName($exception)
    {
        if (
            $exception instanceof \Reaction\Exceptions\Exception
            || $exception instanceof \Reaction\Exceptions\InvalidCallException
            || $exception instanceof \Reaction\Exceptions\InvalidParamException
            || $exception instanceof \Reaction\Exceptions\UnknownMethodException
        ) {
            return $exception->getName();
        }

        return null;
    }

public function getExceptionName ( $ exception ) { if ( $ exception instanceof \ Reaction \ Exceptions \ Exception || $ exception instanceof \ Reaction \ Exceptions \ InvalidCallException || $ exception instanceof \ Reaction \ Exceptions \ InvalidParamException || $ exception instanceof \ Reaction \ Exceptions \ UnknownMethodException ) { return $ exception -> getName ( ) ; } return null ; }

Returns human-readable exception name.
@param \Exception $exception
@return string|null human-readable exception name or null if it cannot be determined

Returns human - readable exception name .


public function beforeOutput() {
        if (!($this->response instanceof jResponseHtml))
            return;

        $conf = &jApp::config()->jResponseHtml;
        $basePath = jApp::urlBasePath();
        if (isset($conf['minifyCSS']) && $conf['minifyCSS']) {
            if (isset($conf['minifyExcludeCSS']) && $conf['minifyExcludeCSS']) {
                $this->excludeCSS = preg_split( '/\s*,\s*/', $conf['minifyExcludeCSS'] );
                foreach($this->excludeCSS as $k=>$url) {
                    if (substr($url,0,1) != '/')
                        $this->excludeCSS[$k]= $basePath.$url;
                }
            }

            $this->response->setCSSLinks($this->generateMinifyList($this->response->getCSSLinks(), 'excludeCSS'));
            $this->response->setCSSIELinks($this->generateMinifyList($this->response->getCSSIELinks(), 'excludeCSS'));
        }

        if (isset($conf['minifyJS']) && $conf['minifyJS']) {
            if(isset($conf['minifyExcludeJS']) && $conf['minifyExcludeJS'] ) {
                $this->excludeJS = preg_split( '/\s*,\s*/', $conf['minifyExcludeJS'] );
                foreach($this->excludeJS as $k=>$url) {
                    if (substr($url,0,1) != '/')
                        $this->excludeJS[$k]= $basePath.$url;
                }
            }
            $this->response->setJSLinks($this->generateMinifyList($this->response->getJSLinks(), 'excludeJS'));
            $this->response->setJSIELinks($this->generateMinifyList($this->response->getJSIELinks(), 'excludeJS'));
        }
    }

public function beforeOutput ( ) { if ( ! ( $ this -> response instanceof jResponseHtml ) ) return ; $ conf = & jApp :: config ( ) -> jResponseHtml ; $ basePath = jApp :: urlBasePath ( ) ; if ( isset ( $ conf [ 'minifyCSS' ] ) && $ conf [ 'minifyCSS' ] ) { if ( isset ( $ conf [ 'minifyExcludeCSS' ] ) && $ conf [ 'minifyExcludeCSS' ] ) { $ this -> excludeCSS = preg_split ( '/\s*,\s*/' , $ conf [ 'minifyExcludeCSS' ] ) ; foreach ( $ this -> excludeCSS as $ k => $ url ) { if ( substr ( $ url , 0 , 1 ) != '/' ) $ this -> excludeCSS [ $ k ] = $ basePath . $ url ; } } $ this -> response -> setCSSLinks ( $ this -> generateMinifyList ( $ this -> response -> getCSSLinks ( ) , 'excludeCSS' ) ) ; $ this -> response -> setCSSIELinks ( $ this -> generateMinifyList ( $ this -> response -> getCSSIELinks ( ) , 'excludeCSS' ) ) ; } if ( isset ( $ conf [ 'minifyJS' ] ) && $ conf [ 'minifyJS' ] ) { if ( isset ( $ conf [ 'minifyExcludeJS' ] ) && $ conf [ 'minifyExcludeJS' ] ) { $ this -> excludeJS = preg_split ( '/\s*,\s*/' , $ conf [ 'minifyExcludeJS' ] ) ; foreach ( $ this -> excludeJS as $ k => $ url ) { if ( substr ( $ url , 0 , 1 ) != '/' ) $ this -> excludeJS [ $ k ] = $ basePath . $ url ; } } $ this -> response -> setJSLinks ( $ this -> generateMinifyList ( $ this -> response -> getJSLinks ( ) , 'excludeJS' ) ) ; $ this -> response -> setJSIELinks ( $ this -> generateMinifyList ( $ this -> response -> getJSIELinks ( ) , 'excludeJS' ) ) ; } }

called when the content is generated, and potentially sent, except
the body end tag and the html end tags. This method can output
directly some contents.

called when the content is generated and potentially sent except the body end tag and the html end tags . This method can output directly some contents .


protected function generateMinifyList($list, $exclude) {
        $pendingList = array();
        $pendingParameters = false;
        $resultList = array();

        foreach ($list as $url=>$parameters) {
            if(preg_match('#^https?\://#', $url) || in_array($url, $this->$exclude) ) {
                // for absolute or exculded url, we put directly in the result
                // we won't try to minify it or combine it with an other file
                $resultList[$url] = $parameters;
                continue;
            }
            ksort($parameters);
            if ($pendingParameters === false) {
                $pendingParameters = $parameters;
                $pendingList[] = $url;
                continue;
            }
            if ($pendingParameters == $parameters) {
                $pendingList[] = $url;
            }
            else {
                $resultList[$this->generateMinifyUrl($pendingList)] = $pendingParameters;
                $pendingList = array($url);
                $pendingParameters = $parameters;
            }
        }
        if ($pendingParameters !== false && count($pendingList)) {
            $resultList[$this->generateMinifyUrl($pendingList)] = $pendingParameters;
        }
        return $resultList;
    }

generate a list of urls for minify. It combines urls if possible
@param array $list  key=url, values = attributes/parameters
@param string $exclude  name of the property containing the list of excluded files
@return array list of urls to insert in the html page

generate a list of urls for minify . It combines urls if possible


public function setAmountDefault($amountDefault)
    {
        $amountDefault = (float) $amountDefault;

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

        $this->amountDefault = $amountDefault;

        return $this;
    }

public function setAmountDefault ( $ amountDefault ) { $ amountDefault = ( float ) $ amountDefault ; if ( $ this -> exists ( ) && $ this -> amountDefault !== $ amountDefault ) { $ this -> updated [ 'amountDefault' ] = true ; } $ this -> amountDefault = $ amountDefault ; return $ this ; }

Set value for field "budget_amount_default"

@param  float $amountDefault
@return $this

Set value for field budget_amount_default


public function setDateStart($dateStart)
    {
        $dateStart = (string) $dateStart;

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

        $this->dateStart = $dateStart;

        return $this;
    }

public function setDateStart ( $ dateStart ) { $ dateStart = ( string ) $ dateStart ; if ( $ this -> exists ( ) && $ this -> dateStart !== $ dateStart ) { $ this -> updated [ 'dateStart' ] = true ; } $ this -> dateStart = $ dateStart ; return $ this ; }

Set value for field "budget_date_start"

@param  string $dateStart
@return $this


public function setDateEnd($dateEnd)
    {
        $dateEnd = ($dateEnd === null ? $dateEnd : (string) $dateEnd);

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

        $this->dateEnd = $dateEnd;

        return $this;
    }

public function setDateEnd ( $ dateEnd ) { $ dateEnd = ( $ dateEnd === null ? $ dateEnd : ( string ) $ dateEnd ) ; if ( $ this -> exists ( ) && $ this -> dateEnd !== $ dateEnd ) { $ this -> updated [ 'dateEnd' ] = true ; } $ this -> dateEnd = $ dateEnd ; return $ this ; }

Set value for field "budget_date_end"

@param  string $dateEnd
@return $this


public function setIsRecurrent($isRecurrent)
    {
        $isRecurrent = (bool) $isRecurrent;

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

        $this->isRecurrent = $isRecurrent;

        return $this;
    }

public function setIsRecurrent ( $ isRecurrent ) { $ isRecurrent = ( bool ) $ isRecurrent ; if ( $ this -> exists ( ) && $ this -> isRecurrent !== $ isRecurrent ) { $ this -> updated [ 'isRecurrent' ] = true ; } $ this -> isRecurrent = $ isRecurrent ; return $ this ; }

Set value for field "budget_is_recurrent"

@param  bool $isRecurrent
@return $this


public function setMonthBitmask($monthBitmask)
    {
        $monthBitmask = (int) $monthBitmask;

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

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

        $this->monthBitmask = $monthBitmask;

        return $this;
    }

Set value for field "budget_month_bitmask"

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

Set value for field budget_month_bitmask


public function getAllBudgetCategory($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinManyCacheBudgetCategory) {
            $mapper = new BudgetCategoryMapper($this->dependencyContainer->getDatabase('money'));
            $mapper->addWhere('budget_id', $this->getId());

            $this->joinManyCacheBudgetCategory = $mapper->select();
        }

        return $this->joinManyCacheBudgetCategory;
    }

public function getAllBudgetCategory ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinManyCacheBudgetCategory ) { $ mapper = new BudgetCategoryMapper ( $ this -> dependencyContainer -> getDatabase ( 'money' ) ) ; $ mapper -> addWhere ( 'budget_id' , $ this -> getId ( ) ) ; $ this -> joinManyCacheBudgetCategory = $ mapper -> select ( ) ; } return $ this -> joinManyCacheBudgetCategory ; }

Get list of BudgetCategory data objects.

@param  bool $isForceReload
@return BudgetCategory[]

Get list of BudgetCategory data objects .


public function getAllBudgetMonth($isForceReload = false)
    {
        if ($isForceReload || null === $this->joinManyCacheBudgetMonth) {
            $mapper = new BudgetMonthMapper($this->dependencyContainer->getDatabase('money'));
            $mapper->addWhere('budget_id', $this->getId());

            $this->joinManyCacheBudgetMonth = $mapper->select();
        }

        return $this->joinManyCacheBudgetMonth;
    }

public function getAllBudgetMonth ( $ isForceReload = false ) { if ( $ isForceReload || null === $ this -> joinManyCacheBudgetMonth ) { $ mapper = new BudgetMonthMapper ( $ this -> dependencyContainer -> getDatabase ( 'money' ) ) ; $ mapper -> addWhere ( 'budget_id' , $ this -> getId ( ) ) ; $ this -> joinManyCacheBudgetMonth = $ mapper -> select ( ) ; } return $ this -> joinManyCacheBudgetMonth ; }

Get list of BudgetMonth data objects.

@param  bool $isForceReload
@return BudgetMonth[]


protected function execute($sql, array $values = [], \Closure $callback = null)
    {
        if($statement = $this->pdo->prepare($sql)) {
            if($statement->execute($values)) {

                // format output
                $return = $callback ? $callback($statement) : true;

                // close statement connection
                $statement->closeCursor();
                unset($statement);

                return $return;
            }

            throw $this->error($sql, $statement);
        }

        throw $this->error($sql);
    }

protected
function
execute
(
$
sql
,
array
$
values
=
[
]
,
\
Closure
$
callback
=
)
{
if
(
$
statement
=
$
this
->
pdo
->
prepare
(
$
sql
)
)
{
if
(
$
statement
->
execute
(
$
values
)
)
{
// format output
$
return
=
$
callback
$
callback
(
$
statement
)
:
true
;
// close statement connection
$
statement
->
closeCursor
(
)
;
unset
(
$
statement
)
;
return
$
return
;
}
throw
$
this
->
error
(
$
sql
,
$
statement
)
;
}
throw
$
this
->
error
(
$
sql
)
;
}

Safe SQL execution

@param string $sql
@param array $values
@param \Closure $callback
@return \PDOStatement


protected function error($sql, \PDOStatement $statement = null)
    {
        $error = $this->pdo->errorInfo();
        if(!$error[1] and $statement) {
            $error = $statement->errorInfo();
            $statement->closeCursor();
            unset($statement);
        }

        $code = is_int($error[0]) ? $error[0] : null;
        return new \PDOException('[' . $error[0] . '] ' . $error[2] . ', in query (' . $sql . ')', $code);
    }

protected
function
error
(
$
sql
,
\
PDOStatement
$
statement
=
)
{
$
error
=
$
this
->
pdo
->
errorInfo
(
)
;
if
(
!
$
error
[
1
]
and
$
statement
)
{
$
error
=
$
statement
->
errorInfo
(
)
;
$
statement
->
closeCursor
(
)
;
unset
(
$
statement
)
;
}
$
code
=
is_int
(
$
error
[
0
]
)
$
error
[
0
]
:
;
return
new
\
PDOException
(
'['
.
$
error
[
0
]
.
'] '
.
$
error
[
2
]
.
', in query ('
.
$
sql
.
')'
,
$
code
)
;
}

Generate PDO error

@param string $sql
@param \PDOStatement $statement
@return \PDOException


public static function path($path)
	{
		$loaders = spl_autoload_functions();
		$loader = require $path;

		// Check whether autoloader is registered at all
		if ($loaders and in_array(array($loader, 'loadClass'), $loaders))
		{
			// Create new loader first using the previous one
			$newLoader = new Loader($loader);

			$loader->unregister();

			return spl_autoload_register(array($newLoader, 'loadClass'));
		}

		return false;
	}

Searches for an autoloader instance in the given path

@param string $path

@return boolean


public function up()
    {
        $transaction = $this->db->createTransaction();
        return $transaction->begin()->thenLazy(
            function($connection) {
                //Set transaction connection
                $this->_connection = $connection;
                $promise = $this->safeUp($connection);
                return is_array($promise) ? allInOrder($promise) : $promise;
            }
        )->thenLazy(
            function() use ($transaction) {
                return $transaction->commit();
            },
            function($error) use ($transaction) {
                $this->printException($error);
                return $transaction->rollBack()
                    ->always(function() {
                        //Remove transaction connection
                        $this->_connection = null;
                    })
                    ->then(
                    function() use ($error) { throw $error; },
                    function($e) { throw $e; }
                );
            }
        );
    }

public
function
up
(
)
{
$
transaction
=
$
this
->
db
->
createTransaction
(
)
;
return
$
transaction
->
begin
(
)
->
thenLazy
(
function
(
$
connection
)
{
//Set transaction connection
$
this
->
_connection
=
$
connection
;
$
promise
=
$
this
->
safeUp
(
$
connection
)
;
return
is_array
(
$
promise
)
allInOrder
(
$
promise
)
:
$
promise
;
}
)
->
thenLazy
(
function
(
)
use
(
$
transaction
)
{
return
$
transaction
->
commit
(
)
;
}
,
function
(
$
error
)
use
(
$
transaction
)
{
$
this
->
printException
(
$
error
)
;
return
$
transaction
->
rollBack
(
)
->
always
(
function
(
)
{
//Remove transaction connection
$
this
->
_connection
=
;
}
)
->
then
(
function
(
)
use
(
$
error
)
{
throw
$
error
;
}
,
function
(
$
e
)
{
throw
$
e
;
}
)
;
}
)
;
}

This method contains the logic to be executed when applying this migration.
Child classes may override this method to provide actual migration logic.
@return ExtendedPromiseInterface
Resolved promise mean the migration succeeds and rejected - not.

This method contains the logic to be executed when applying this migration . Child classes may override this method to provide actual migration logic .


public function down()
    {
        $transaction = $this->db->createTransaction();
        return $transaction->begin()->thenLazy(
            function($connection) {
                $promise = $this->safeDown($connection);
                return is_array($promise) ? allInOrder($promise) : $promise;
            }
        )->thenLazy(
            function() use ($transaction) {
                return $transaction->commit();
            },
            function($error) use ($transaction) {
                $this->printException($error);
                return $transaction->rollBack()->then(
                    function() use ($error) { throw $error; },
                    function($e) { throw $e; }
                );
            }
        );
    }

public function down ( ) { $ transaction = $ this -> db -> createTransaction ( ) ; return $ transaction -> begin ( ) -> thenLazy ( function ( $ connection ) { $ promise = $ this -> safeDown ( $ connection ) ; return is_array ( $ promise ) ? allInOrder ( $ promise ) : $ promise ; } ) -> thenLazy ( function ( ) use ( $ transaction ) { return $ transaction -> commit ( ) ; } , function ( $ error ) use ( $ transaction ) { $ this -> printException ( $ error ) ; return $ transaction -> rollBack ( ) -> then ( function ( ) use ( $ error ) { throw $ error ; } , function ( $ e ) { throw $ e ; } ) ; } ) ; }

This method contains the logic to be executed when removing this migration.
The default implementation throws an exception indicating the migration cannot be removed.
Child classes may override this method if the corresponding migrations can be removed.
@return ExtendedPromiseInterface
Resolved promise mean the migration succeeds and rejected - not.

This method contains the logic to be executed when removing this migration . The default implementation throws an exception indicating the migration cannot be removed . Child classes may override this method if the corresponding migrations can be removed .


public function insert($table, $columns)
    {
        $cmdPromise = $this->createCommand()->insert($table, $columns)->execute();
        return $this->execPromise($cmdPromise, "insert into $table");
    }

public
function
insert
(
$
table
,
$
columns
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
insert
(
$
table
,
$
columns
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"insert into $table"
)
;
}

Creates and executes an INSERT SQL statement.
The method will properly escape the column names, and bind the values to be inserted.
@param string $table the table that new rows will be inserted into.
@param array  $columns the column data (name => value) to be inserted into the table.
@return LazyPromiseInterface

Creates and executes an INSERT SQL statement . The method will properly escape the column names and bind the values to be inserted .


public function batchInsert($table, $columns, $rows)
    {
        $cmdPromise = $this->createCommand()->batchInsert($table, $columns, $rows)->execute();
        return $this->execPromise($cmdPromise, "insert into $table");
    }

public
function
batchInsert
(
$
table
,
$
columns
,
$
rows
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
batchInsert
(
$
table
,
$
columns
,
$
rows
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"insert into $table"
)
;
}

Creates and executes a batch INSERT SQL statement.
The method will properly escape the column names, and bind the values to be inserted.
@param string $table the table that new rows will be inserted into.
@param array $columns the column names.
@param array $rows the rows to be batch inserted into the table
@return LazyPromiseInterface

Creates and executes a batch INSERT SQL statement . The method will properly escape the column names and bind the values to be inserted .


public function update($table, $columns, $condition = '', $params = [])
    {
        $cmdPromise = $this->createCommand()->update($table, $columns, $condition, $params)->execute();
        return $this->execPromise($cmdPromise, "update $table");
    }

public
function
update
(
$
table
,
$
columns
,
$
condition
=
''
,
$
params
=
[
]
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
update
(
$
table
,
$
columns
,
$
condition
,
$
params
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"update $table"
)
;
}

Creates and executes an UPDATE SQL statement.
The method will properly escape the column names and bind the values to be updated.
@param string $table the table to be updated.
@param array $columns the column data (name => value) to be updated.
@param array|string $condition the conditions that will be put in the WHERE part. Please
refer to [[Query::where()]] on how to specify conditions.
@param array $params the parameters to be bound to the query.
@return LazyPromiseInterface

Creates and executes an UPDATE SQL statement . The method will properly escape the column names and bind the values to be updated .


public function delete($table, $condition = '', $params = [])
    {
        $cmdPromise = $this->createCommand()->delete($table, $condition, $params)->execute();
        return $this->execPromise($cmdPromise, "delete from $table");
    }

public
function
delete
(
$
table
,
$
condition
=
''
,
$
params
=
[
]
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
delete
(
$
table
,
$
condition
,
$
params
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"delete from $table"
)
;
}

Creates and executes a DELETE SQL statement.
@param string $table the table where the data will be deleted from.
@param array|string $condition the conditions that will be put in the WHERE part. Please
refer to [[Query::where()]] on how to specify conditions.
@param array $params the parameters to be bound to the query.
@return LazyPromiseInterface

Creates and executes a DELETE SQL statement .


public function renameTable($table, $newName)
    {
        $cmdPromise = $this->createCommand()->renameTable($table, $newName)->execute();
        return $this->execPromise($cmdPromise, "rename table $table to $newName");
    }

public
function
renameTable
(
$
table
,
$
newName
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
renameTable
(
$
table
,
$
newName
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"rename table $table to $newName"
)
;
}

Builds and executes a SQL statement for renaming a DB table.
@param string $table the table to be renamed. The name will be properly quoted by the method.
@param string $newName the new table name. The name will be properly quoted by the method.
@return LazyPromiseInterface

Builds and executes a SQL statement for renaming a DB table .


public function dropTable($table)
    {
        $cmdPromise = $this->createCommand()->dropTable($table)->execute();
        return $this->execPromise($cmdPromise, "drop table $table");
    }

public
function
dropTable
(
$
table
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
dropTable
(
$
table
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"drop table $table"
)
;
}

Builds and executes a SQL statement for dropping a DB table.
@param string $table the table to be dropped. The name will be properly quoted by the method.
@return LazyPromiseInterface

Builds and executes a SQL statement for dropping a DB table .


public function truncateTable($table)
    {
        $cmdPromise = $this->createCommand()->truncateTable($table)->execute();
        return $this->execPromise($cmdPromise, "truncate table $table");
    }

public
function
truncateTable
(
$
table
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
truncateTable
(
$
table
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"truncate table $table"
)
;
}

Builds and executes a SQL statement for truncating a DB table.
@param string $table the table to be truncated. The name will be properly quoted by the method.
@return LazyPromiseInterface

Builds and executes a SQL statement for truncating a DB table .


public function dropColumn($table, $column)
    {
        $cmdPromise = $this->createCommand()->dropColumn($table, $column)->execute();
        return $this->execPromise($cmdPromise, "drop column $column from table $table");
    }

public
function
dropColumn
(
$
table
,
$
column
)
{
$
cmdPromise
=
$
this
->
createCommand
(
)
->
dropColumn
(
$
table
,
$
column
)
->
execute
(
)
;
return
$
this
->
execPromise
(
$
cmdPromise
,
"drop column $column from table $table"
)
;
}

Builds and executes a SQL statement for dropping a DB column.
@param string $table the table whose column is to be dropped. The name will be properly quoted by the method.
@param string $column the name of the column to be dropped. The name will be properly quoted by the method.
@return LazyPromiseInterface

Builds and executes a SQL statement for dropping a DB column .


public function renameColumn($table, $name, $newName)
    {
        $cmdPromise = $this->createCommand()->renameColumn($table, $name, $newName)->execute();
        return $this->execPromise($cmdPromise, "rename column $name in table $table to $newName");
    }

Builds and executes a SQL statement for renaming a column.
@param string $table the table whose column is to be renamed. The name will be properly quoted by the method.
@param string $name the old name of the column. The name will be properly quoted by the method.
@param string $newName the new name of the column. The name will be properly quoted by the method.
@return LazyPromiseInterface

Builds and executes a SQL statement for renaming a column .


public function alterColumn($table, $column, $type)
    {
        $promises = [];
        $promises[] = $this->createCommand()->alterColumn($table, $column, $type)->execute();
        if ($type instanceof ColumnSchemaBuilder && $type->comment !== null) {
            $promises[] = $this->createCommand()->addCommentOnColumn($table, $column, $type->comment)->execute();
        }
        return $this->execPromise($promises, "alter column $column in table $table to $type");
    }

Builds and executes a SQL statement for changing the definition of a column.
@param string $table the table whose column is to be changed. The table name will be properly quoted by the method.
@param string $column the name of the column to be changed. The name will be properly quoted by the method.
@param string $type the new column type. The [[QueryBuilder::getColumnType()]] method will be invoked to convert abstract column type (if any)
into the physical one. Anything that is not recognized as abstract type will be kept in the generated SQL.
For example, 'string' will be turned into 'varchar(255)', while 'string not null' will become 'varchar(255) not null'.
@return LazyPromiseInterface

Builds and executes a SQL statement for changing the definition of a column .