protected function compareValues($field_name, $reference_value, $allow_null, callable $compare_with, $validation_failed_message)
    {
        if (empty($field_name)) {
            throw new InvalidArgumentException("Value '$field_name' is not a valid field name");
        }

        if (array_key_exists($field_name, $this->field_values)) {
            if ($this->field_values[$field_name] === null) {
                if ($allow_null) {
                    return true;
                } else {
                    return $this->failPresenceValidation($field_name);
                }
            }

            if (call_user_func($compare_with, $this->field_values[$field_name], $reference_value)) {
                return true;
            } else {
                $this->addFieldError($field_name, $validation_failed_message);

                return false;
            }
        } else {
            return $this->failPresenceValidation($field_name);
        }
    }

Validate field value by comparing it to a reference value using a closure.

@param  string   $field_name
@param  mixed    $reference_value
@param  bool     $allow_null
@param  callable $compare_with
@param  string   $validation_failed_message
@return bool

Validate field value by comparing it to a reference value using a closure .


public function generateUri(string $name, array $substitutions = [], array $options = []): string
    {
        $this->injectRoutes();

        if (! $this->router->hasNamedRoute($name)) {
            throw new Exception\RuntimeException(sprintf(
                'Cannot generate URI based on route "%s"; route not found',
                $name
            ));
        }

        return $this->router->urlFor($name, $substitutions);
    }

Generate a URI from the named route.

Takes the named route and any substitutions, and attempts to generate a
URI from it. Additional router-dependent options may be passed.

The URI generated MUST NOT be escaped. If you wish to escape any part of
the URI, this should be performed afterwards; consider passing the URI
to league/uri to encode it.

@see https://github.com/auraphp/Aura.Router#generating-a-route-path
@see http://framework.zend.com/manual/current/en/modules/zend.mvc.routing.html
@param string $name
@param array $substitutions
@param array $options
@return string
@throws Exception\RuntimeException if unable to generate the given URI.


public function storeSucceed(Role $role)
    {
        $message = trans('antares/acl::response.roles.created', ['name' => $role->name]);
        return $this->redirectWithMessage(handles('antares::acl/index/roles'), $message);
    }

public function storeSucceed ( Role $ role ) { $ message = trans ( 'antares/acl::response.roles.created' , [ 'name' => $ role -> name ] ) ; return $ this -> redirectWithMessage ( handles ( 'antares::acl/index/roles' ) , $ message ) ; }

Response when storing user succeed.

@param  \Antares\Model\Role  $role

@return mixed


public function getFieldErrors($field)
    {
        return isset($this->errors[$field]) ? $this->errors[$field] : null;
    }

public function getFieldErrors ( $ field ) { return isset ( $ this -> errors [ $ field ] ) ? $ this -> errors [ $ field ] : null ; }

Return field errors.

@param  string $field
@return array


public function hasError($field)
    {
        return isset($this->errors[$field]) && count($this->errors[$field]);
    }

public function hasError ( $ field ) { return isset ( $ this -> errors [ $ field ] ) && count ( $ this -> errors [ $ field ] ) ; }

Check if a specific field has reported errors.

@param  string $field
@return bool

Check if a specific field has reported errors .


public function &addError($error, $field = self::ANY_FIELD)
    {
        if (empty($field)) {
            $field = self::ANY_FIELD;
        }

        if (empty($this->errors[$field])) {
            $this->errors[$field] = [];
        }

        $this->errors[$field][] = $error;

        return $this;
    }

public function & addError ( $ error , $ field = self :: ANY_FIELD ) { if ( empty ( $ field ) ) { $ field = self :: ANY_FIELD ; } if ( empty ( $ this -> errors [ $ field ] ) ) { $ this -> errors [ $ field ] = [ ] ; } $ this -> errors [ $ field ] [ ] = $ error ; return $ this ; }

Add error to array.

@param  string $error
@param  string $field
@return $this


public function prepareProductTitle($product)
    {
        $title = $product->oxarticles__oxtitle->value;
        if ($product->oxarticles__oxvarselect->value) {
            $title .= ' ' . $product->oxarticles__oxvarselect->value;
        }

        return $title;
    }

public
function
prepareProductTitle
(
$
product
)
{
$
title
=
$
product
->
oxarticles__oxtitle
->
value
;
if
(
$
product
->
oxarticles__oxvarselect
->
value
)
{
$
title
.=
' '
.
$
product
->
oxarticles__oxvarselect
->
value
;
}
return
$
title
;
}

Returns formatted product title.

@param \OxidEsales\Eshop\Application\Model\Article $product product which title must be prepared.

@return string


protected function modifyByContactController()
    {
        /** @var \OxidEsales\Eshop\Application\Controller\ContactController $currentController */
        $currentController = Registry::getConfig()->getActiveView();
        if ($currentController->getContactSendStatus()) {
            $this->activePageEntity->setContactsMessage('Kontaktformular gesendet');
        }
    }


protected function modifyByNewsletterController()
    {
        /** @var \OxidEsales\Eshop\Application\Controller\NewsletterController $currentController */
        $currentController = Registry::getConfig()->getActiveView();
        if ($currentController->getNewsletterStatus()) {
            $this->activePageEntity->setNewsletterMessage('Newsletter registriert');
        }
    }

Sets if newsletter have been subscribed.

Sets if newsletter have been subscribed .


protected function modifyWithUserRegistrationAction($user)
    {
        $errorCode = Registry::getRequest()->getRequestEscapedParameter('newslettererror');
        $successCode = Registry::getRequest()->getRequestEscapedParameter('success');

        if ($errorCode && $errorCode < 0) {
            $this->activePageEntity->setRegisteredUserId($user ? md5($user->getId()) : 'NULL');
            $this->activePageEntity->setRegisteredUserResult(abs($errorCode));
        }

        if ($successCode && $successCode > 0 && $user) {
            $this->activePageEntity->setRegisteredUserId(md5($user->getId()));
            $this->activePageEntity->setRegisteredUserResult(0);

            $this->activePageEntity->setLoginUserId($this->activeUserDataProvider->getActiveUserHashedId());
            $this->activePageEntity->setLoginResult($this->activeUserDataProvider->isLoaded() ? 0 : 1);
        }
    }

protected function modifyWithUserRegistrationAction ( $ user ) { $ errorCode = Registry :: getRequest ( ) -> getRequestEscapedParameter ( 'newslettererror' ) ; $ successCode = Registry :: getRequest ( ) -> getRequestEscapedParameter ( 'success' ) ; if ( $ errorCode && $ errorCode < 0 ) { $ this -> activePageEntity -> setRegisteredUserId ( $ user ? md5 ( $ user -> getId ( ) ) : 'NULL' ) ; $ this -> activePageEntity -> setRegisteredUserResult ( abs ( $ errorCode ) ) ; } if ( $ successCode && $ successCode > 0 && $ user ) { $ this -> activePageEntity -> setRegisteredUserId ( md5 ( $ user -> getId ( ) ) ) ; $ this -> activePageEntity -> setRegisteredUserResult ( 0 ) ; $ this -> activePageEntity -> setLoginUserId ( $ this -> activeUserDataProvider -> getActiveUserHashedId ( ) ) ; $ this -> activePageEntity -> setLoginResult ( $ this -> activeUserDataProvider -> isLoaded ( ) ? 0 : 1 ) ; } }

Sets user registration action to an object.

@param User $user

Sets user registration action to an object .


public function disableEventSubscriber($subscriberClass)
    {
        $subscriberClass = $this->getSubscriberClassName($subscriberClass);
        $eventManager = $this->getEventManager();

        /* @var EventSubscriber[] $subscribers */
        foreach ($this->getEventListeners() as $subscribers) {
            while ($subscriber = \array_shift($subscribers)) {
                if ($subscriber instanceof $subscriberClass) {
                    $this->disabledSubscribers[] = $subscriber;

                    $eventManager->removeEventSubscriber($subscriber);

                    return;
                }
            }
        }
    }

Disable event subscriber.

@param \Doctrine\Common\EventSubscriber|string $subscriberClass


public function restoreEventSubscribers()
    {
        $eventManager = $this->getEventManager();

        foreach ($this->disabledSubscribers as $subscriber) {
            $eventManager->addEventSubscriber($subscriber);
        }

        $this->disabledSubscribers = [];
    }

public function restoreEventSubscribers ( ) { $ eventManager = $ this -> getEventManager ( ) ; foreach ( $ this -> disabledSubscribers as $ subscriber ) { $ eventManager -> addEventSubscriber ( $ subscriber ) ; } $ this -> disabledSubscribers = [ ] ; }


public function disableEventListeners(string $event)
    {
        $eventManager = $this->getEventManager();

        if (!\array_key_exists($event, $this->disabledListeners)) {
            $this->disabledListeners[$event] = [];
        }

        foreach ($this->getEventListeners($event) as $listener) {
            $eventManager->removeEventListener($event, $listener);

            $this->disabledListeners[$event][] = $listener;
        }
    }

public function disableEventListeners ( string $ event ) { $ eventManager = $ this -> getEventManager ( ) ; if ( ! \ array_key_exists ( $ event , $ this -> disabledListeners ) ) { $ this -> disabledListeners [ $ event ] = [ ] ; } foreach ( $ this -> getEventListeners ( $ event ) as $ listener ) { $ eventManager -> removeEventListener ( $ event , $ listener ) ; $ this -> disabledListeners [ $ event ] [ ] = $ listener ; } }

Disable all listeners for an event.

@param string $event


public function disableEventListener(string $event, $subscriberClass)
    {
        $subscriberClass = $this->getSubscriberClassName($subscriberClass);

        if (!\array_key_exists($event, $this->disabledListeners)) {
            $this->disabledListeners[$event] = [];
        }

        $eventManager = $this->getEventManager();

        foreach ($this->getEventListeners($event) as $listener) {
            if ($listener instanceof $subscriberClass) {
                $this->disabledListeners[$event][] = $listener;

                $eventManager->removeEventListener($event, $listener);
                break;
            }
        }
    }

public function disableEventListener ( string $ event , $ subscriberClass ) { $ subscriberClass = $ this -> getSubscriberClassName ( $ subscriberClass ) ; if ( ! \ array_key_exists ( $ event , $ this -> disabledListeners ) ) { $ this -> disabledListeners [ $ event ] = [ ] ; } $ eventManager = $ this -> getEventManager ( ) ; foreach ( $ this -> getEventListeners ( $ event ) as $ listener ) { if ( $ listener instanceof $ subscriberClass ) { $ this -> disabledListeners [ $ event ] [ ] = $ listener ; $ eventManager -> removeEventListener ( $ event , $ listener ) ; break ; } } }

Disable listener for an event.

@param string                 $event
@param string|EventSubscriber $subscriberClass

@throws \InvalidArgumentException


public function restoreAllEventListeners()
    {
        $eventManager = $this->getEventManager();

        foreach ($this->disabledListeners as $event => $listeners) {
            /* @var EventSubscriber[] $listeners */
            foreach ($listeners as $listener) {
                $eventManager->addEventListener($event, $listener);
            }

            $this->disabledListeners[$event] = [];
        }
    }

public
function
restoreAllEventListeners
(
)
{
$
eventManager
=
$
this
->
getEventManager
(
)
;
foreach
(
$
this
->
disabledListeners
as
$
event
=>
$
listeners
)
{
/* @var EventSubscriber[] $listeners */
foreach
(
$
listeners
as
$
listener
)
{
$
eventManager
->
addEventListener
(
$
event
,
$
listener
)
;
}
$
this
->
disabledListeners
[
$
event
]
=
[
]
;
}
}


public function restoreEventListeners(string $event)
    {
        if (!\array_key_exists($event, $this->disabledListeners) || empty($this->disabledListeners[$event])) {
            return;
        }

        $eventManager = $this->getEventManager();

        /* @var EventSubscriber[] $listeners */
        $listeners = $this->disabledListeners[$event];
        foreach ($listeners as $listener) {
            $eventManager->addEventListener($event, $listener);
        }

        $this->disabledListeners[$event] = [];
    }

public
function
restoreEventListeners
(
string
$
event
)
{
if
(
!
\
array_key_exists
(
$
event
,
$
this
->
disabledListeners
)
||
empty
(
$
this
->
disabledListeners
[
$
event
]
)
)
{
return
;
}
$
eventManager
=
$
this
->
getEventManager
(
)
;
/* @var EventSubscriber[] $listeners */
$
listeners
=
$
this
->
disabledListeners
[
$
event
]
;
foreach
(
$
listeners
as
$
listener
)
{
$
eventManager
->
addEventListener
(
$
event
,
$
listener
)
;
}
$
this
->
disabledListeners
[
$
event
]
=
[
]
;
}

Restore disabled listeners for an event.

@param string $event

Restore disabled listeners for an event .


protected function getSubscriberClassName($subscriberClass): string
    {
        if ($this->isEventSubscriber($subscriberClass)) {
            return \is_object($subscriberClass) ? \get_class($subscriberClass) : $subscriberClass;
        }

        throw new \InvalidArgumentException('subscriberClass must be an EventSubscriber');
    }

Get subscriber class name.

@param string|EventSubscriber $subscriberClass

@throws \InvalidArgumentException

@return string


private function isEventSubscriber($subscriberClass): bool
    {
        return \is_object($subscriberClass) || (\is_string($subscriberClass) && \class_exists($subscriberClass))
            ? \in_array(EventSubscriber::class, \class_implements($subscriberClass), true)
            : false;
    }

private function isEventSubscriber ( $ subscriberClass ) : bool { return \ is_object ( $ subscriberClass ) || ( \ is_string ( $ subscriberClass ) && \ class_exists ( $ subscriberClass ) ) ? \ in_array ( EventSubscriber :: class , \ class_implements ( $ subscriberClass ) , true ) : false ; }

Is an event subscriber.

@param $subscriberClass

@return bool


protected function getEventListeners($event = null): array
    {
        $eventManager = $this->getEventManager();

        return $event !== null && !$eventManager->hasListeners($event) ? [] : $eventManager->getListeners($event);
    }

protected function getEventListeners ( $ event = null ) : array { $ eventManager = $ this -> getEventManager ( ) ; return $ event !== null && ! $ eventManager -> hasListeners ( $ event ) ? [ ] : $ eventManager -> getListeners ( $ event ) ; }

Get event listeners.

@param string|null $event

@return EventSubscriber[]


public function getActiveUserHashedId()
    {
        $id = null;
        if ($this->isLoaded()) {
            $id = md5($this->user->oxuser__oxid->value);
        }

        return $id;
    }

public function getActiveUserHashedId ( ) { $ id = null ; if ( $ this -> isLoaded ( ) ) { $ id = md5 ( $ this -> user -> oxuser__oxid -> value ) ; } return $ id ; }

Hashes active user ID and returns it.

@return null|string


public function getActiveUserHashedEmail()
    {
        $email = null;
        if ($this->isLoaded()) {
            $email = md5($this->user->oxuser__oxusername->value);
        }

        return $email;
    }

public function getActiveUserHashedEmail ( ) { $ email = null ; if ( $ this -> isLoaded ( ) ) { $ email = md5 ( $ this -> user -> oxuser__oxusername -> value ) ; } return $ email ; }

Hashes active user email and returns it.

@return null|string

Hashes active user email and returns it .


public static function generateCacheKey()
    {
        $args = func_get_args();
        if (empty($args)) {
            throw new \InvalidArgumentException('At least one argument must be passed to generate cache key.');
        }
        $const = $args[0] . '::VERSION';
        $version = defined($const) ? self::$delimiter . constant($const) : '';
        return self::$prefix . self::$delimiter . implode(self::$delimiter, $args) . $version;
    }

Generate cache key.
Optionally you can pass a class name as the first parameter and if
this class will contain constant named "VERSION" than it will be mixed up
with the result key.
@throws \InvalidArgumentException
@return string

Generate cache key . Optionally you can pass a class name as the first parameter and if this class will contain constant named VERSION than it will be mixed up with the result key .


public static function generateCacheKeys()
    {
        $args = func_get_args();
        if (empty($args)) {
            throw new \InvalidArgumentException('At least one argument must be passed to generate cache key.');
        }
        $ids = array_pop($args);
        if (!is_array($ids)) {
            throw new \InvalidArgumentException('The last parameter must be an array.');
        }
        $commonKey = call_user_func_array(['self', 'generateCacheKey'], $args);
        $result = [];
        foreach ($ids as $id) {
            $result[] = $commonKey . self::$delimiter . $id;
        }
        return $result;
    }

Generate cache keys.
The last parameter must be an array
@return array
@throws \InvalidArgumentException

Generate cache keys . The last parameter must be an array


public function send()
    {
        $cc = curl_init($this->url);
        $this->logger->log("API connection established");

        curl_setopt($cc, CURLOPT_HTTPHEADER,
            array('Authorization: Bearer ' . $this->apiKey, 'Content-type: application/json'));
        curl_setopt($cc, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($cc, CURLOPT_VERBOSE, 0);
        curl_setopt($cc, CURLOPT_HEADER, 1);

        // Execute the cURL, fetch the XML
        $result = curl_exec($cc);
        $this->result = $result;
        $this->headerSize = curl_getinfo($cc, CURLINFO_HEADER_SIZE);

        // Close connection
        curl_close($cc);
    }

public
function
send
(
)
{
$
cc
=
curl_init
(
$
this
->
url
)
;
$
this
->
logger
->
log
(
"API connection established"
)
;
curl_setopt
(
$
cc
,
CURLOPT_HTTPHEADER
,
array
(
'Authorization: Bearer '
.
$
this
->
apiKey
,
'Content-type: application/json'
)
)
;
curl_setopt
(
$
cc
,
CURLOPT_RETURNTRANSFER
,
true
)
;
curl_setopt
(
$
cc
,
CURLOPT_VERBOSE
,
0
)
;
curl_setopt
(
$
cc
,
CURLOPT_HEADER
,
1
)
;
// Execute the cURL, fetch the XML
$
result
=
curl_exec
(
$
cc
)
;
$
this
->
result
=
$
result
;
$
this
->
headerSize
=
curl_getinfo
(
$
cc
,
CURLINFO_HEADER_SIZE
)
;
// Close connection
curl_close
(
$
cc
)
;
}

Sends a get request and recieves results


public function exists($key)
    {
        $index = explode('.', $key);
        self::getValue($this->item, $index, false, $err);

        return !$err;
    }

public function exists ( $ key ) { $ index = explode ( '.' , $ key ) ; self :: getValue ( $ this -> item , $ index , false , $ err ) ; return ! $ err ; }

Check if property exists

@param string $key The index to fetch in dot notation
@return boolean


public function get($key)
    {
        $index = explode('.', $key);
        $ret = self::getValue($this->item, $index, true, $err);

        if ($err) {
            $invalidPath = join('.', array_slice($index, 0, -1 * $err->incomplete));
            trigger_error("Unable to get '$key': '$invalidPath' is a {$err->var}", E_USER_WARNING);
        } // @codeCoverageIgnore

        return $ret;
    }

Get a value

@param string $key The index to fetch in dot notation
@return mixed


protected static function getValue($item, $index, $ignore = false, &$err = null)
    {
        $err = null;

        if (empty($index)) return $item;

        $key = array_shift($index);

        if ((is_array($item) || $item instanceof \Traversable) && isset($item[$key])) {
            return static::getValue($item[$key], $index, $ignore, $err);
        }

        if (is_object($item) && isset($item->$key)) {
            return static::getValue($item->$key, $index, $ignore, $err);
        }

        if ((!is_object($item) && !is_array($item)) || !$ignore) {
            $err = (object)['var' => isset($item) ? gettype($item) : null, 'incomplete' => count($index) + 1];
        }

        return null;
    }

protected static function getValue ( $ item , $ index , $ ignore = false , & $ err = null ) { $ err = null ; if ( empty ( $ index ) ) return $ item ; $ key = array_shift ( $ index ) ; if ( ( is_array ( $ item ) || $ item instanceof \ Traversable ) && isset ( $ item [ $ key ] ) ) { return static :: getValue ( $ item [ $ key ] , $ index , $ ignore , $ err ) ; } if ( is_object ( $ item ) && isset ( $ item -> $ key ) ) { return static :: getValue ( $ item -> $ key , $ index , $ ignore , $ err ) ; } if ( ( ! is_object ( $ item ) && ! is_array ( $ item ) ) || ! $ ignore ) { $ err = ( object ) [ 'var' => isset ( $ item ) ? gettype ( $ item ) : null , 'incomplete' => count ( $ index ) + 1 ] ; } return null ; }

Navigate through the item and get the value

@param array  $item
@param array  $index   The index sequence we are navigating to
@param array  $ignore  Don't raise an error if not exists
@param object $err     Error object [OUTPUT]
@return mixed


public function set($key, $value)
    {
        $index = explode('.', $key);
        self::setValue($this->item, $index, $value, false, $err);

        if ($err) {
            $invalidPath = join('.', array_slice($index, 0, -1 * $err->incomplete));
            $reason = isset($err->var) ? "'$invalidPath' is a {$err->var}" : "'$invalidPath' doesn't exist";
            trigger_error("Unable to set '$key': $reason", E_USER_WARNING);
        } // @codeCoverageIgnore

        return $this->item;
    }

public
function
set
(
$
key
,
$
value
)
{
$
index
=
explode
(
'.'
,
$
key
)
;
self
::
setValue
(
$
this
->
item
,
$
index
,
$
value
,
false
,
$
err
)
;
if
(
$
err
)
{
$
invalidPath
=
join
(
'.'
,
array_slice
(
$
index
,
0
,
1
*
$
err
->
incomplete
)
)
;
$
reason
=
isset
(
$
err
->
var
)
"'$invalidPath' is a {$err->var}"
:
"'$invalidPath' doesn't exist"
;
trigger_error
(
"Unable to set '$key': $reason"
,
E_USER_WARNING
)
;
}
// @codeCoverageIgnore
return
$
this
->
item
;
}

Set a value

@param string $key    The index to fetch in dot notation
@param mixed  $value
@return object|array


public function put($key, $value)
    {
        $index = explode('.', $key);
        $err = null;

        self::setValue($this->item, $index, $value, $this->assoc ? 'array' : 'object', $err);

        if ($err) {
            $invalidPath = join('.', array_slice($index, 0, -1 * $err->incomplete));
            trigger_error("Unable to put '$key': '$invalidPath' is a {$err->var}", E_USER_WARNING);
        } // @codeCoverageIgnore

        return $this->item;
    }

Set a value, creating the structure if required

@param string  $key    The index to fetch in dot notation
@param mixed   $value
@return object|array

Set a value creating the structure if required


protected static function setValue(&$item, $index, $value, $create = false, &$err = null)
    {
        $err = null;

        $key = array_shift($index);

        if (is_array($item) || $item instanceof \Traversable) {
            if (empty($index)) {
                $item[$key] = $value;
                return;
            }

            if (!isset($item[$key]) && $create) {
                $item[$key] = $create === 'array' ? [] : (object)[];
            }

            if (isset($item[$key])) {
                return static::setValue($item[$key], $index, $value, $create, $err);
            }
        } elseif (is_object($item)) {
            if (empty($index)) {
                $item->$key = $value;
                return;
            }

            if (!isset($item->$key) && $create) {
                $item->$key = $create === 'array' ? [] : (object)[];
            }

            if (isset($item->$key)) {
                return static::setValue($item->$key, $index, $value, $create, $err);
            }
        } else {
            $err = (object)['var' => gettype($item), 'incomplete' => count($index) + 1];
            return;
        }

        $err = (object)['var' => null, 'incomplete' => count($index)];
    }

protected static function setValue ( & $ item , $ index , $ value , $ create = false , & $ err = null ) { $ err = null ; $ key = array_shift ( $ index ) ; if ( is_array ( $ item ) || $ item instanceof \ Traversable ) { if ( empty ( $ index ) ) { $ item [ $ key ] = $ value ; return ; } if ( ! isset ( $ item [ $ key ] ) && $ create ) { $ item [ $ key ] = $ create === 'array' ? [ ] : ( object ) [ ] ; } if ( isset ( $ item [ $ key ] ) ) { return static :: setValue ( $ item [ $ key ] , $ index , $ value , $ create , $ err ) ; } } elseif ( is_object ( $ item ) ) { if ( empty ( $ index ) ) { $ item -> $ key = $ value ; return ; } if ( ! isset ( $ item -> $ key ) && $ create ) { $ item -> $ key = $ create === 'array' ? [ ] : ( object ) [ ] ; } if ( isset ( $ item -> $ key ) ) { return static :: setValue ( $ item -> $ key , $ index , $ value , $ create , $ err ) ; } } else { $ err = ( object ) [ 'var' => gettype ( $ item ) , 'incomplete' => count ( $ index ) + 1 ] ; return ; } $ err = ( object ) [ 'var' => null , 'incomplete' => count ( $ index ) ] ; }

Navigate through the item and set the value

@param array        $item
@param array        $index   The index sequence we are navigating to
@param mixed        $value
@param string|false $create  Create structure if required: 'object', 'array' or false
@param object       $err     Error object [OUTPUT]


public function remove($key)
    {
        $index = explode('.', $key);
        self::removeValue($this->item, $index, $err);

        if ($err) {
            $invalidPath = join('.', array_slice($index, 0, -1 * $err->incomplete));
            trigger_error("Unable to remove '$key': '$invalidPath' is a {$err->var}", E_USER_WARNING);
        } // @codeCoverageIgnore

        return $this->item;
    }

Get a particular value back from the config array

@param string $key The index to fetch in dot notation
@return object|array


protected static function removeValue(&$item, $index, &$err = null)
    {
        $err = null;

        if (!is_object($item) && !is_array($item)) {
            $err = (object)['var' => gettype($item), 'incomplete' => count($index)];
            return;
        }

        $key = array_shift($index);

        if (empty($index)) {
            if (is_object($item) && isset($item->$key)) unset($item->$key);
            if (is_array($item) && isset($item[$key])) unset($item[$key]);
            return;
        }

        if (is_object($item) && isset($item->$key)) return static::removeValue($item->$key, $index, $err);
        if (is_array($item) && isset($item[$key])) return static::removeValue($item[$key], $index, $err);
    }

protected static function removeValue ( & $ item , $ index , & $ err = null ) { $ err = null ; if ( ! is_object ( $ item ) && ! is_array ( $ item ) ) { $ err = ( object ) [ 'var' => gettype ( $ item ) , 'incomplete' => count ( $ index ) ] ; return ; } $ key = array_shift ( $ index ) ; if ( empty ( $ index ) ) { if ( is_object ( $ item ) && isset ( $ item -> $ key ) ) unset ( $ item -> $ key ) ; if ( is_array ( $ item ) && isset ( $ item [ $ key ] ) ) unset ( $ item [ $ key ] ) ; return ; } if ( is_object ( $ item ) && isset ( $ item -> $ key ) ) return static :: removeValue ( $ item -> $ key , $ index , $ err ) ; if ( is_array ( $ item ) && isset ( $ item [ $ key ] ) ) return static :: removeValue ( $ item [ $ key ] , $ index , $ err ) ; }

Navigate through the item and remove the value

@param array  $item
@param array  $index  The index sequence we are navigating to
@param object $err    Error object [OUTPUT]
@return mixed


public function setLogger($loggerClass, $loggerFunc) {

        if(empty($loggerClass)) {
            $this->helper->setLogger($loggerFunc);
        } else {
            $this->helper->setLogger(array($loggerClass, $loggerFunc));
        }
    }

public function setLogger ( $ loggerClass , $ loggerFunc ) { if ( empty ( $ loggerClass ) ) { $ this -> helper -> setLogger ( $ loggerFunc ) ; } else { $ this -> helper -> setLogger ( array ( $ loggerClass , $ loggerFunc ) ) ; } }

Creates the logger functionality in Helper


public function boot()
    {
        $this->registerTranslations();
        $this->registerConfig();
        $this->registerViews();
        $this->registerFactories();
        $this->setMailConfig();
    }

public function boot ( ) { $ this -> registerTranslations ( ) ; $ this -> registerConfig ( ) ; $ this -> registerViews ( ) ; $ this -> registerFactories ( ) ; $ this -> setMailConfig ( ) ; }

Boot the application events.

@return void


private function setMailConfig()
    {
        try {
            config([
                'mail.host' => setting()->get('mail.mail_host', ''),
                'mail.port' => setting()->get('mail.mail_port', '2525'),
                'mail.username' => setting()->get('mail.mail_user', ''),
                'mail.password' => setting()->get('mail.mail_password', ''),
                'mail.from.address' => setting()->get('mail.mail_from_address', ''),
                'mail.from.name' => setting()->get('mail.mail_from_name', '')
            ]);
        } catch (\Exception $e) {}
    }

private function setMailConfig ( ) { try { config ( [ 'mail.host' => setting ( ) -> get ( 'mail.mail_host' , '' ) , 'mail.port' => setting ( ) -> get ( 'mail.mail_port' , '2525' ) , 'mail.username' => setting ( ) -> get ( 'mail.mail_user' , '' ) , 'mail.password' => setting ( ) -> get ( 'mail.mail_password' , '' ) , 'mail.from.address' => setting ( ) -> get ( 'mail.mail_from_address' , '' ) , 'mail.from.name' => setting ( ) -> get ( 'mail.mail_from_name' , '' ) ] ) ; } catch ( \ Exception $ e ) { } }


public function get($key)
    {
        if (!isset($this->setFields[$key]))
            return null;

        return $this->setFields[$key];
    }

public function get ( $ key ) { if ( ! isset ( $ this -> setFields [ $ key ] ) ) return null ; return $ this -> setFields [ $ key ] ; }

Checks if the key is set, returns it if true

@param $key
@return $setFields

Checks if the key is set returns it if true


protected function convertValue($value)
    {
        if (!is_array($value)) {
            return $value;
        }

        $result = 'array(';
        $values = array();
        foreach ($value as $key => $val) {
            $values[] .= sprintf("'%s' => %s", $key, $this->convertValue($val));
        }

        $result .= implode(",", $values);
        $result .= ')';

        return $result;
    }

protected
function
convertValue
(
$
value
)
{
if
(
!
is_array
(
$
value
)
)
{
return
$
value
;
}
$
result
=
'array('
;
$
values
=
array
(
)
;
foreach
(
$
value
as
$
key
=>
$
val
)
{
$
values
[
]
.=
sprintf
(
"'%s' => %s"
,
$
key
,
$
this
->
convertValue
(
$
val
)
)
;
}
$
result
.=
implode
(
","
,
$
values
)
;
$
result
.=
')'
;
return
$
result
;
}

Converts a value to its php representation.

@param mixed $value

@return object|integer|double|string|null|boolean

Converts a value to its php representation .


public function getPageSize(Request $request): int
    {
        $pageSize = $request->get('pageSize', 50);

        if ($pageSize > 5000) {
            return 5000;
        }

        return (int) $pageSize;
    }

public function getPageSize ( Request $ request ) : int { $ pageSize = $ request -> get ( 'pageSize' , 50 ) ; if ( $ pageSize > 5000 ) { return 5000 ; } return ( int ) $ pageSize ; }

Get the page size for pagination

@param Request $request
@return int


public function register(Application $app)
    {

    	$app['capsule.connection_defaults'] = array(
    			'driver' => 'mysql',
    			'host' => 'localhost',
    			'database' => null,
    			'username' => 'root',
    			'password' => null,
    			'charset' => 'utf8',
    			'collation' => 'utf8_unicode_ci',
    			'prefix' => null,
    			'logging' => false,
    	);

    	$app['capsule.global'] = true;
    	$app['capsule.eloquent'] = true;
    	$app['capsule.container'] = $app->share(function() {
    		return new Container;
    	});

    	$app['capsule.dispatcher'] = $app->share(function() use($app) {
    		return new Dispatcher($app['capsule.container']);
    	});

    	if (class_exists('Illuminate\Cache\CacheManager')) {
    		$app['capsule.cache_manager'] = $app->share(function() use($app) {
    			return new CacheManager($app['capsule.container']);
    		});
    	}

    	$app['capsule'] = $app->share(function($name) use ($app) {

    		$capsule = new Capsule($app['capsule.container']);
    		$capsule->setEventDispatcher($app['capsule.dispatcher']);
    		if (isset($app['capsule.cache_manager']) && isset($app['capsule.cache'])) {
    			$capsule->setCacheManager($app['capsule.cache_manager']);
    			foreach ($app['capsule.cache'] as $key => $value) {
    				$app['capsule.container']->offsetGet('config')->offsetSet('cache.' . $key, $value);
    			}
    		}
    		if ($app['capsule.global']) {
    			$capsule->setAsGlobal();
    		}
    		if ($app['capsule.eloquent']) {
    			$capsule->bootEloquent();
    		}
    		if (! isset($app['capsule.connections'])) {
    			$app['capsule.connections'] = array(
    					'default' => (isset($app['capsule.connection']) ? $app['capsule.connection'] : array()),
    			);
    		}
    		foreach ($app['capsule.connections'] as $connection => $options) {
    			$options = array_replace($app['capsule.connection_defaults'], $options);
    			$logging = $options['logging'];
    			unset($options['logging']);
    			$capsule->addConnection($options, $connection);
    			if ($logging) {
    				$capsule->connection($connection)->enableQueryLog();
    			} else {
    				$capsule->connection($connection)->disableQueryLog();
    			}
    		}

    		return $capsule;

    	});

    }

public function register ( Application $ app ) { $ app [ 'capsule.connection_defaults' ] = array ( 'driver' => 'mysql' , 'host' => 'localhost' , 'database' => null , 'username' => 'root' , 'password' => null , 'charset' => 'utf8' , 'collation' => 'utf8_unicode_ci' , 'prefix' => null , 'logging' => false , ) ; $ app [ 'capsule.global' ] = true ; $ app [ 'capsule.eloquent' ] = true ; $ app [ 'capsule.container' ] = $ app -> share ( function ( ) { return new Container ; } ) ; $ app [ 'capsule.dispatcher' ] = $ app -> share ( function ( ) use ( $ app ) { return new Dispatcher ( $ app [ 'capsule.container' ] ) ; } ) ; if ( class_exists ( 'Illuminate\Cache\CacheManager' ) ) { $ app [ 'capsule.cache_manager' ] = $ app -> share ( function ( ) use ( $ app ) { return new CacheManager ( $ app [ 'capsule.container' ] ) ; } ) ; } $ app [ 'capsule' ] = $ app -> share ( function ( $ name ) use ( $ app ) { $ capsule = new Capsule ( $ app [ 'capsule.container' ] ) ; $ capsule -> setEventDispatcher ( $ app [ 'capsule.dispatcher' ] ) ; if ( isset ( $ app [ 'capsule.cache_manager' ] ) && isset ( $ app [ 'capsule.cache' ] ) ) { $ capsule -> setCacheManager ( $ app [ 'capsule.cache_manager' ] ) ; foreach ( $ app [ 'capsule.cache' ] as $ key => $ value ) { $ app [ 'capsule.container' ] -> offsetGet ( 'config' ) -> offsetSet ( 'cache.' . $ key , $ value ) ; } } if ( $ app [ 'capsule.global' ] ) { $ capsule -> setAsGlobal ( ) ; } if ( $ app [ 'capsule.eloquent' ] ) { $ capsule -> bootEloquent ( ) ; } if ( ! isset ( $ app [ 'capsule.connections' ] ) ) { $ app [ 'capsule.connections' ] = array ( 'default' => ( isset ( $ app [ 'capsule.connection' ] ) ? $ app [ 'capsule.connection' ] : array ( ) ) , ) ; } foreach ( $ app [ 'capsule.connections' ] as $ connection => $ options ) { $ options = array_replace ( $ app [ 'capsule.connection_defaults' ] , $ options ) ; $ logging = $ options [ 'logging' ] ; unset ( $ options [ 'logging' ] ) ; $ capsule -> addConnection ( $ options , $ connection ) ; if ( $ logging ) { $ capsule -> connection ( $ connection ) -> enableQueryLog ( ) ; } else { $ capsule -> connection ( $ connection ) -> disableQueryLog ( ) ; } } return $ capsule ; } ) ; }

Register the Capsule service.

@param Application $app


public function validate()
    {
        $resultingData = array_merge($this->defaultFields, $this->setFields);
        return $this->_arrayKeysExists($this->requiredFields, $resultingData);
    }

public function validate ( ) { $ resultingData = array_merge ( $ this -> defaultFields , $ this -> setFields ) ; return $ this -> _arrayKeysExists ( $ this -> requiredFields , $ resultingData ) ; }

Validates the user input data

@return bool


public static function instance() {

		if ( ! isset( self::$instance ) && ! ( self::$instance instanceof WP_Notice ) ) {
			self::$instance = new WP_Notice;
			self::$instance->init();
		}

		return self::$instance;

	}

public static function instance ( ) { if ( ! isset ( self :: $ instance ) && ! ( self :: $ instance instanceof WP_Notice ) ) { self :: $ instance = new WP_Notice ; self :: $ instance -> init ( ) ; } return self :: $ instance ; }


private function init() {
		add_action( 'admin_notices', array( self::$instance, 'display' ) );
		add_action( 'admin_print_scripts', array( self::$instance, 'load_script' ) );
		add_action( 'wp_ajax_tdp_dismiss_notice', array( self::$instance, 'dismiss_notice_ajax' ) );
	}

private function init ( ) { add_action ( 'admin_notices' , array ( self :: $ instance , 'display' ) ) ; add_action ( 'admin_print_scripts' , array ( self :: $ instance , 'load_script' ) ) ; add_action ( 'wp_ajax_tdp_dismiss_notice' , array ( self :: $ instance , 'dismiss_notice_ajax' ) ) ; }


public function load_script() {
		wp_register_script( 'tdp', trailingslashit( plugin_dir_url( __FILE__ ) ) . 'assets/js/main.js', array( 'jquery' ), self::$instance->version, true );
		wp_enqueue_script( 'tdp' );
	}

public function load_script ( ) { wp_register_script ( 'tdp' , trailingslashit ( plugin_dir_url ( __FILE__ ) ) . 'assets/js/main.js' , array ( 'jquery' ) , self :: $ instance -> version , true ) ; wp_enqueue_script ( 'tdp' ) ; }

Load script to dismiss notices.

@return void


public function display() {

		if ( is_null( self::$instance->notices ) || empty( self::$instance->notices ) ) {
			return;
		}

		foreach ( self::$instance->notices as $id => $notice ) {

			$id = self::$instance->get_id( $id );

			// Check if the notice was dismissed.
			if ( self::$instance->is_dismissed( $id ) ) {
				continue;
			}

			if ( ! empty( $notice['cap'] ) && ! current_user_can( $notice['cap'] ) ) {
					continue;
			}

			$class = array(
				'notice',
				'notice-' . $notice['type'],
				$notice['dismissible'] ? 'is-dismissible' : false,
				$notice['class'],
			);

			printf( '

%2$s

', trim( implode( ' ', $class ) ), $notice['content'], "tdp-$id" );

		}

	}


public function register_notice( $id, $type, $content, $args = array() ) {
		if ( is_null( self::$instance->notices ) ) {
			self::$instance->notices = array();
		}

		$id      = self::$instance->get_id( $id );
		$type    = in_array( $t = sanitize_text_field( $type ), self::$instance->get_types() ) ? $t : 'updated';
		$content = wp_kses_post( $content );
		$args    = wp_parse_args( $args, self::$instance->default_args() );

		$notice = array(
			'type'    => $type,
			'content' => $content,
		);

		$notice                         = array_merge( $notice, $args );
		self::$instance->notices[ $id ] = $notice;

		return true;
	}

public function register_notice ( $ id , $ type , $ content , $ args = array ( ) ) { if ( is_null ( self :: $ instance -> notices ) ) { self :: $ instance -> notices = array ( ) ; } $ id = self :: $ instance -> get_id ( $ id ) ; $ type = in_array ( $ t = sanitize_text_field ( $ type ) , self :: $ instance -> get_types ( ) ) ? $ t : 'updated' ; $ content = wp_kses_post ( $ content ) ; $ args = wp_parse_args ( $ args , self :: $ instance -> default_args ( ) ) ; $ notice = array ( 'type' => $ type , 'content' => $ content , ) ; $ notice = array_merge ( $ notice , $ args ) ; self :: $ instance -> notices [ $ id ] = $ notice ; return true ; }

Register a notice.

@param string $id
@param string $type
@param string $content
@param array $args
@return void


public function dismiss_notice_ajax() {
		if ( ! isset( $_POST['id'] ) ) {
			echo 0;
			exit;
		}
		if ( empty( $_POST['id'] ) || false === strpos( $_POST['id'], 'tdp-' ) ) {
			echo 0;
			exit;
		}

		$id = self::$instance->get_id( str_replace( 'tdp-', '', $_POST['id'] ) );
		echo self::$instance->dismiss_notice( $id );
		exit;

	}

public function dismiss_notice_ajax ( ) { if ( ! isset ( $ _POST [ 'id' ] ) ) { echo 0 ; exit ; } if ( empty ( $ _POST [ 'id' ] ) || false === strpos ( $ _POST [ 'id' ] , 'tdp-' ) ) { echo 0 ; exit ; } $ id = self :: $ instance -> get_id ( str_replace ( 'tdp-' , '' , $ _POST [ 'id' ] ) ) ; echo self :: $ instance -> dismiss_notice ( $ id ) ; exit ; }

Dismiss a notice via ajax.

@return void


public function dismiss_notice( $id ) {
		$notice = self::$instance->get_notice( self::$instance->get_id( $id ) );
		if ( self::$instance->is_dismissed( $id ) ) {
			return false;
		}
		return 'user' === $notice['scope'] ? self::$instance->dismiss_user( $id ) : self::$instance->dismiss_global( $id );
	}

public function dismiss_notice ( $ id ) { $ notice = self :: $ instance -> get_notice ( self :: $ instance -> get_id ( $ id ) ) ; if ( self :: $ instance -> is_dismissed ( $ id ) ) { return false ; } return 'user' === $ notice [ 'scope' ] ? self :: $ instance -> dismiss_user ( $ id ) : self :: $ instance -> dismiss_global ( $ id ) ; }

Dismiss notice into the database.

@param string $id
@return void


private function dismiss_user( $id ) {
		$dismissed = self::$instance->dismissed_user();
		if ( in_array( $id, $dismissed ) ) {
			return false;
		}
		array_push( $dismissed, $id );
		return update_user_meta( get_current_user_id(), 'tdp_dismissed_notices', $dismissed );
	}

private function dismiss_user ( $ id ) { $ dismissed = self :: $ instance -> dismissed_user ( ) ; if ( in_array ( $ id , $ dismissed ) ) { return false ; } array_push ( $ dismissed , $ id ) ; return update_user_meta ( get_current_user_id ( ) , 'tdp_dismissed_notices' , $ dismissed ) ; }

Dismiss notice for an user.

@param string $id the notice id.
@return void


private function dismiss_global( $id ) {
		$dismissed = self::$instance->dismissed_global();
		if ( in_array( $id, $dismissed ) ) {
			return false;
		}
		array_push( $dismissed, $id );
		return update_option( 'tdp_dismissed_notices', $dismissed );
	}

private function dismiss_global ( $ id ) { $ dismissed = self :: $ instance -> dismissed_global ( ) ; if ( in_array ( $ id , $ dismissed ) ) { return false ; } array_push ( $ dismissed , $ id ) ; return update_option ( 'tdp_dismissed_notices' , $ dismissed ) ; }

Dismiss a global notice.

@param string $id the id of the notice.
@return void


public function restore_notice( $id ) {
		$id     = self::$instance->get_id( $id );
		$notice = self::$instance->get_notice( $id );
		if ( false === $notice ) {
			return false;
		}
		return 'user' === $notice['scope'] ? self::$instance->restore_user( $id ) : self::$instance->restore_global( $id );
	}

public function restore_notice ( $ id ) { $ id = self :: $ instance -> get_id ( $ id ) ; $ notice = self :: $ instance -> get_notice ( $ id ) ; if ( false === $ notice ) { return false ; } return 'user' === $ notice [ 'scope' ] ? self :: $ instance -> restore_user ( $ id ) : self :: $ instance -> restore_global ( $ id ) ; }

Restore a notice previously dismissed.

@param string $id the id of the notice.
@return void


private function restore_user( $id ) {
		$id     = self::$instance->get_id( $id );
		$notice = self::$instance->get_notice( $id );

		if ( false === $notice ) {
			return false;
		}

		$dismissed = self::$instance->dismissed_user();
		if ( ! in_array( $id, $dismissed ) ) {
			return false;
		}

		$flip = array_flip( $dismissed );
		$key  = $flip[ $id ];
		unset( $dismissed[ $key ] );

		return update_user_meta( get_current_user_id(), 'tdp_dismissed_notices', $dismissed );
	}

private function restore_user ( $ id ) { $ id = self :: $ instance -> get_id ( $ id ) ; $ notice = self :: $ instance -> get_notice ( $ id ) ; if ( false === $ notice ) { return false ; } $ dismissed = self :: $ instance -> dismissed_user ( ) ; if ( ! in_array ( $ id , $ dismissed ) ) { return false ; } $ flip = array_flip ( $ dismissed ) ; $ key = $ flip [ $ id ] ; unset ( $ dismissed [ $ key ] ) ; return update_user_meta ( get_current_user_id ( ) , 'tdp_dismissed_notices' , $ dismissed ) ; }

Restore a notice for the current user.

@param string $id the id of the notice.
@return void


private function restore_global( $id ) {
		$id     = self::$instance->get_id( $id );
		$notice = self::$instance->get_notice( $id );

		if ( false === $notice ) {
			return false;
		}

		$dismissed = self::$instance->dismissed_global();

		if ( ! in_array( $id, $dismissed ) ) {
			return false;
		}

		$flip = array_flip( $dismissed );
		$key  = $flip[ $id ];

		unset( $dismissed[ $key ] );
		return update_option( 'tdp_dismissed_notices', $dismissed );
	}

private function restore_global ( $ id ) { $ id = self :: $ instance -> get_id ( $ id ) ; $ notice = self :: $ instance -> get_notice ( $ id ) ; if ( false === $ notice ) { return false ; } $ dismissed = self :: $ instance -> dismissed_global ( ) ; if ( ! in_array ( $ id , $ dismissed ) ) { return false ; } $ flip = array_flip ( $ dismissed ) ; $ key = $ flip [ $ id ] ; unset ( $ dismissed [ $ key ] ) ; return update_option ( 'tdp_dismissed_notices' , $ dismissed ) ; }

Restore a globally dismissed notice.

@param string $id
@return void


public function dismissed_notices() {
		$user   = self::$instance->dismissed_user();
		$global = self::$instance->dismissed_global();

		return array_merge( $user, $global );
	}

public function dismissed_notices ( ) { $ user = self :: $ instance -> dismissed_user ( ) ; $ global = self :: $ instance -> dismissed_global ( ) ; return array_merge ( $ user , $ global ) ; }

Get list of dismissed notices.

@return array


public function is_dismissed( $id ) {
		$dismissed = self::$instance->dismissed_notices();
		if ( ! in_array( self::$instance->get_id( $id ), $dismissed ) ) {
			return false;
		}
		return true;
	}

public function is_dismissed ( $ id ) { $ dismissed = self :: $ instance -> dismissed_notices ( ) ; if ( ! in_array ( self :: $ instance -> get_id ( $ id ) , $ dismissed ) ) { return false ; } return true ; }

Check if a notice is dismissed.

@param string $id
@return boolean


public function get_notice( $id ) {
		$id = self::$instance->get_id( $id );
		if ( ! is_array( self::$instance->notices ) || ! array_key_exists( $id, self::$instance->notices ) ) {
			return false;
		}
		return self::$instance->notices[ $id ];
	}

public function get_notice ( $ id ) { $ id = self :: $ instance -> get_id ( $ id ) ; if ( ! is_array ( self :: $ instance -> notices ) || ! array_key_exists ( $ id , self :: $ instance -> notices ) ) { return false ; } return self :: $ instance -> notices [ $ id ] ; }

Get a registered notice.

@param string $id the id of the notice.
@return void


public function refineItem($raw)
    {
        $refined = $this->setTemplate($raw);

        if ( ! empty($this->attachments)) {
            $refined = $this->merge($refined, $this->includeAttachments($raw));
        }

        return $refined;
    }

public function refineItem ( $ raw ) { $ refined = $ this -> setTemplate ( $ raw ) ; if ( ! empty ( $ this -> attachments ) ) { $ refined = $ this -> merge ( $ refined , $ this -> includeAttachments ( $ raw ) ) ; } return $ refined ; }

Refine a single item using the supplied callback.

@param  mixed $raw
@return mixed

Refine a single item using the supplied callback .


public function refineCollection($raw, $retainKey = false)
    {
        $refined = [];

        foreach ($raw as $key => $item) {
            if ($retainKey) {
                $this->key = $key;
                $refined[ $key ] = $this->refineItem($item);
            } else {
                $refined[] = $this->refineItem($item);
            }
        }

        return $refined;
    }

public function refineCollection ( $ raw , $ retainKey = false ) { $ refined = [ ] ; foreach ( $ raw as $ key => $ item ) { if ( $ retainKey ) { $ this -> key = $ key ; $ refined [ $ key ] = $ this -> refineItem ( $ item ) ; } else { $ refined [ ] = $ this -> refineItem ( $ item ) ; } } return $ refined ; }

Refine a collection of raw items.

@param mixed $raw
@param boolean $retainKey
@return array


protected function includeAttachments($raw)
    {
        $attachments = [];

        foreach ($this->attachments as $attachment => $refinery) {
            if (isset($refinery['raw'])) {
                $attachments[$attachment] = $refinery['raw']($raw);
            } else {
                $class = $refinery['class'];
                $callback = $refinery['callback'];

                if ( ! $callback) {
                    $items = $this->getItems($raw, $class, $attachment);
                } else {
                    $items = $this->getItemsUsingCallback($raw, $class, $callback);
                }

                $attachments[$attachment] = ! is_null($items) ? $class->refine($items) : null;
            }
        }

        return $attachments;
    }

protected function includeAttachments ( $ raw ) { $ attachments = [ ] ; foreach ( $ this -> attachments as $ attachment => $ refinery ) { if ( isset ( $ refinery [ 'raw' ] ) ) { $ attachments [ $ attachment ] = $ refinery [ 'raw' ] ( $ raw ) ; } else { $ class = $ refinery [ 'class' ] ; $ callback = $ refinery [ 'callback' ] ; if ( ! $ callback ) { $ items = $ this -> getItems ( $ raw , $ class , $ attachment ) ; } else { $ items = $ this -> getItemsUsingCallback ( $ raw , $ class , $ callback ) ; } $ attachments [ $ attachment ] = ! is_null ( $ items ) ? $ class -> refine ( $ items ) : null ; } } return $ attachments ; }

Return any required attachments. Check if the attachment needs to
be filtered, if so they run the callback and then return the
attachments.

@param  mixed $raw
@return mixed

Return any required attachments . Check if the attachment needs to be filtered if so they run the callback and then return the attachments .


protected function getItems($raw, $class, $attachment)
    {
        if ($class->hasFilter()) {
            $query = $class->getFilter();

            return call_user_func_array($query, [$raw->$attachment()]);
        } else {
            return is_object($raw) ? $raw->$attachment : $raw[$attachment];
        }
    }

protected function getItems ( $ raw , $ class , $ attachment ) { if ( $ class -> hasFilter ( ) ) { $ query = $ class -> getFilter ( ) ; return call_user_func_array ( $ query , [ $ raw -> $ attachment ( ) ] ) ; } else { return is_object ( $ raw ) ? $ raw -> $ attachment : $ raw [ $ attachment ] ; } }

Get the items to be refined from the raw object.

@param mixed  $raw
@param mixed  $class
@param string $attachment
@return mixed

Get the items to be refined from the raw object .


public function bring($attachments)
    {
        if (is_string($attachments)) {
            $attachments = func_get_args();
        }

        $this->attachments = $this->parseAttachments($attachments);

        return $this;
    }

public function bring ( $ attachments ) { if ( is_string ( $ attachments ) ) { $ attachments = func_get_args ( ) ; } $ this -> attachments = $ this -> parseAttachments ( $ attachments ) ; return $ this ; }

Set the attachments you want to bring with the refined items.

@param  string|array $attachments
@return $this

Set the attachments you want to bring with the refined items .


protected function parseAttachments(array $relations)
    {
        $parsedRelations = [];

        foreach ($relations as $key => $relation) {
            if ( ! is_numeric($key)) {
                if (is_callable($relation)) {
                    $parsedRelations[$key] = $this->attachItem($key);
                    $parsedRelations[$key]['class']->with($this->attributes)->filter($relation);
                } else {
                    $parsedRelations[$key] = $this->attachItem($key);
                    $parsedRelations[$key]['class']->with($this->attributes)->bring($relation);
                }
            } else {
                $parsedRelations[$relation] = $this->attachItem($relation);

                if (isset($parsedRelations[$relation]['class'])) {
                    $parsedRelations[$relation]['class']->with($this->attributes);
                }
            }
        }

        return $parsedRelations;
    }

protected function parseAttachments ( array $ relations ) { $ parsedRelations = [ ] ; foreach ( $ relations as $ key => $ relation ) { if ( ! is_numeric ( $ key ) ) { if ( is_callable ( $ relation ) ) { $ parsedRelations [ $ key ] = $ this -> attachItem ( $ key ) ; $ parsedRelations [ $ key ] [ 'class' ] -> with ( $ this -> attributes ) -> filter ( $ relation ) ; } else { $ parsedRelations [ $ key ] = $ this -> attachItem ( $ key ) ; $ parsedRelations [ $ key ] [ 'class' ] -> with ( $ this -> attributes ) -> bring ( $ relation ) ; } } else { $ parsedRelations [ $ relation ] = $ this -> attachItem ( $ relation ) ; if ( isset ( $ parsedRelations [ $ relation ] [ 'class' ] ) ) { $ parsedRelations [ $ relation ] [ 'class' ] -> with ( $ this -> attributes ) ; } } } return $ parsedRelations ; }

Get the classes needed for each attachment.

@param  array $relations
@return array

Get the classes needed for each attachment .


protected function attachItem($attachment)
    {
        if ( ! method_exists($this, $attachment)) {
            throw new RefineryMethodNotFound(
                "No attachment set with the name '{$attachment}' on '" . get_class($this) . "'."
            );
        }

        return $this->$attachment();
    }

Check the attachment method exists on the class being attached, if it
does then run the method.

@param  string $attachment
@return mixed
@throws RefineryMethodNotFound

Check the attachment method exists on the class being attached if it does then run the method .


public function attach($className, callable $callback = null)
    {
        // If the user has passed through a callable item then we want
        // to attach the raw result of that call.
        if (is_callable($className)) {
            return ['raw' => $className];
        }

        if ( ! class_exists($className)) {
            throw new AttachmentClassNotFound("No class found with the name '{$className}'.");
        }

        return ['class' => new $className, 'callback' => $callback];
    }

Set the class to be used for the attachment.

@param string|callable $className
@param callable|bool   $callback
@return array
@throws AttachmentClassNotFound

Set the class to be used for the attachment .


protected function merge($original, $merge)
    {
        if (is_array($original) && is_array($merge)) {
            return array_merge($original, $merge);
        }

        if (is_array($original)) {
            foreach ($merge as $key => $value) {
                $original[$key] = $value;
            }
        } else {
            foreach ($merge as $key => $value) {
                $original->$key = $value;
            }
        }

        return $original;
    }

protected function merge ( $ original , $ merge ) { if ( is_array ( $ original ) && is_array ( $ merge ) ) { return array_merge ( $ original , $ merge ) ; } if ( is_array ( $ original ) ) { foreach ( $ merge as $ key => $ value ) { $ original [ $ key ] = $ value ; } } else { foreach ( $ merge as $ key => $ value ) { $ original -> $ key = $ value ; } } return $ original ; }

Merge a set of data into another.

@param mixed $original
@param mixed $merge
@return mixed


public function getResponseHeaders()
    {
        $headers = array();

        $header_text = substr($this->result, 0, $this->headerSize);

        foreach (explode("\r\n", $header_text) as $i => $line)
            if (strlen($line) > 4 && substr($line, 0, 4) === "HTTP") {
                $headers['http_code'] = $line;
            } else {
                list ($key, $value) = array_pad(explode(': ', $line, 2), 2, null);
                $headers[$key] = $value;
            }

        return $headers;
    }

public
function
getResponseHeaders
(
)
{
$
headers
=
array
(
)
;
$
header_text
=
substr
(
$
this
->
result
,
0
,
$
this
->
headerSize
)
;
foreach
(
explode
(
"\r\n"
,
$
header_text
)
as
$
i
=>
$
line
)
if
(
strlen
(
$
line
)
>
4
&&
substr
(
$
line
,
0
,
4
)
===
"HTTP"
)
{
$
headers
[
'http_code'
]
=
$
line
;
}
else
{
list
(
$
key
,
$
value
)
=
array_pad
(
explode
(
': '
,
$
line
,
2
)
,
2
,
)
;
$
headers
[
$
key
]
=
$
value
;
}
return
$
headers
;
}

Returns the headers from a response

@return $headers


public function getCardReference()
    {
        if (isset($this->data['response']['token'])) {
            return $this->data['response']['token'];
        }
        if (isset($this->data['response']['card_token'])) {
            return $this->data['response']['card_token'];
        }
    }

public function getCardReference ( ) { if ( isset ( $ this -> data [ 'response' ] [ 'token' ] ) ) { return $ this -> data [ 'response' ] [ 'token' ] ; } if ( isset ( $ this -> data [ 'response' ] [ 'card_token' ] ) ) { return $ this -> data [ 'response' ] [ 'card_token' ] ; } }

Get Card Reference

This is used after createCard or createCustomer to get the credit card token to be
used in future transactions.

@return string


public function getCustomerReference()
    {
        if (isset($this->data['response']['customer'])) {
            return $this->data['response']['customer'];
        }
        if (isset($this->data['response']['id'])) {
            return $this->data['response']['id'];
        }
    }

public function getCustomerReference ( ) { if ( isset ( $ this -> data [ 'response' ] [ 'customer' ] ) ) { return $ this -> data [ 'response' ] [ 'customer' ] ; } if ( isset ( $ this -> data [ 'response' ] [ 'id' ] ) ) { return $ this -> data [ 'response' ] [ 'id' ] ; } }

Get Customer Reference

This is used after createCustomer to get the customer token to be
used in future transactions.

@return string


public static function getClassName($class)
    {
        if (!is_object($class) && !is_string($class)) {
            throw new InvalidArgumentException(sprintf('$object must be a string or an object, %s given', gettype($class)));
        }

        $className = is_string($class) ? $class : get_class($class);
        $pos = strrpos($className, '\\');

        if ($pos !== false) {
            $className = substr($className, ($pos + 1));
        }

        return $className;
    }

Strip the namespace from a given class or object and get only the class name.

@param mixed $class

@throws \InvalidArgumentException
@return bool|string

Strip the namespace from a given class or object and get only the class name .


public static function getNamespace($class)
    {
        if (!is_object($class) && !is_string($class)) {
            throw new InvalidArgumentException('$object must be a string or an object');
        }

        $class = (is_string($class) ? $class : get_class($class));
        $pos = strrpos($class, '\\');

        return substr($class, 0, $pos);
    }

public
static
function
getNamespace
(
$
class
)
{
if
(
!
is_object
(
$
class
)
&&
!
is_string
(
$
class
)
)
{
throw
new
InvalidArgumentException
(
'$object must be a string or an object'
)
;
}
$
class
=
(
is_string
(
$
class
)
$
class
:
get_class
(
$
class
)
)
;
$
pos
=
strrpos
(
$
class
,
'\\'
)
;
return
substr
(
$
class
,
0
,
$
pos
)
;
}

Get the namespace from a given class or object.

@param mixed $class

@return string
@throws \InvalidArgumentException

Get the namespace from a given class or object .


private function findAdderMethod($obj, $key)
    {
        if (method_exists($obj, $method = 'add'.$key)) {
            return $method;
        }

        foreach ((array) StringUtil::singularify($key) as $singularForm) {
            if (method_exists($obj, $method = 'add'.$singularForm)) {
                return $method;
            }
        }

        if (method_exists($obj, $method = 'add'.rtrim($key, 's'))) {
            return $method;
        }

        if (substr($key, -3) === 'ies' && method_exists($obj, $method = 'add'.substr($key, 0, -3).'y')) {
            return $method;
        }
    }

private function findAdderMethod ( $ obj , $ key ) { if ( method_exists ( $ obj , $ method = 'add' . $ key ) ) { return $ method ; } foreach ( ( array ) StringUtil :: singularify ( $ key ) as $ singularForm ) { if ( method_exists ( $ obj , $ method = 'add' . $ singularForm ) ) { return $ method ; } } if ( method_exists ( $ obj , $ method = 'add' . rtrim ( $ key , 's' ) ) ) { return $ method ; } if ( substr ( $ key , - 3 ) === 'ies' && method_exists ( $ obj , $ method = 'add' . substr ( $ key , 0 , - 3 ) . 'y' ) ) { return $ method ; } }

Finds an adder method for the given object.
Thanks to the alice library for this code snippet.

@param mixed  $obj
@param string $key

@return string|null

Finds an adder method for the given object . Thanks to the alice library for this code snippet .


protected function initMappings()
    {
        if ($this->initialized) {
            return $this;
        }

        foreach ($this->classMetadata->fieldMappings as $key => $mapping) {
            if (isset($mapping['reference'])) {
                $this->associationMappings[$key] = $mapping;
            } else {
                $this->fieldMappings[$key] = $mapping;
            }
        }

        $this->initialized = true;

        return $this;
    }

protected function initMappings ( ) { if ( $ this -> initialized ) { return $ this ; } foreach ( $ this -> classMetadata -> fieldMappings as $ key => $ mapping ) { if ( isset ( $ mapping [ 'reference' ] ) ) { $ this -> associationMappings [ $ key ] = $ mapping ; } else { $ this -> fieldMappings [ $ key ] = $ mapping ; } } $ this -> initialized = true ; return $ this ; }

Initialize the mappings from the class metadata.
The mapping will be split in field mappings and association mappings.

@return ClassMetadataProxy

Initialize the mappings from the class metadata . The mapping will be split in field mappings and association mappings .


public function setTranslationLang($lang)
    {
        global $translationData;
        $translationData = array();
        $file = realpath(dirname(dirname(__FILE__)) . "/etc/lang/en-" . strtolower($lang) . ".csv");
        if (file_exists($file)) {
            if (($handle = fopen($file, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if (count($data) == 2) {
                        $translationData[$data[0]] = $data[1];
                    }
                }
                fclose($handle);
            }

        }
    }

public function setTranslationLang ( $ lang ) { global $ translationData ; $ translationData = array ( ) ; $ file = realpath ( dirname ( dirname ( __FILE__ ) ) . "/etc/lang/en-" . strtolower ( $ lang ) . ".csv" ) ; if ( file_exists ( $ file ) ) { if ( ( $ handle = fopen ( $ file , "r" ) ) !== FALSE ) { while ( ( $ data = fgetcsv ( $ handle , 1000 , "," ) ) !== FALSE ) { if ( count ( $ data ) == 2 ) { $ translationData [ $ data [ 0 ] ] = $ data [ 1 ] ; } } fclose ( $ handle ) ; } } }

Sets data used for translations

@param $lang


protected function readProperty($object, $property)
    {
        foreach ($this->propertyReader as $reader) {
            /** @var PropertyReaderInterface $reader */
            if ($reader->supports($object, $property)) {
                return $reader->getValue($object, $property);
            }
        }

        $camelProp = ucfirst($property);
        $getter = 'get'.$camelProp;
        $isser = 'is'.$camelProp;

        if (method_exists($object, $getter)) {
            return $object->$getter();
        } elseif (method_exists($object, $isser)) {
            return $object->$isser();
        } elseif (property_exists($object, $property)) {
            $reflectionProperty = new \ReflectionProperty($object, $property);
            $reflectionProperty->setAccessible(true);

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

        throw new InvalidPropertyException(sprintf('Neither property "%s" nor method "%s()" nor method "%s()" exists in class "%s"', $property, $getter, $isser, get_class($object)));
    }

Reads a property from an object.

@param $object
@param $property

@return mixed
@throws InvalidPropertyException


public function defaultAction($name = null, $selfedit = 'false', $installMode = null)
    {
        $this->selfedit = $selfedit;
        $this->installMode = $installMode;
        $name = $name ? $name : 'entityManager';

        $this->instanceName = $name;

        if ($selfedit == 'true') {
            $this->moufManager = MoufManager::getMoufManager();
        } else {
            $this->moufManager = MoufManager::getMoufManagerHiddenInstance();
        }

        $classNameMapper = ClassNameMapper::createFromComposerFile(__DIR__.'/../../../../../../composer.json');
        $managedNamespaces = $classNameMapper->getManagedNamespaces();

        $this->autoloadDetected = true;
        if ($this->moufManager->instanceExists($name)) {
            $instance = $this->moufManager->getInstanceDescriptor($name);
            $this->entitiesNamespace = $instance->getSetterProperty('setEntitiesNamespace')->getValue();
            $this->proxyNamespace = $instance->getSetterProperty('setProxyNamespace')->getValue();
            $this->daoNamespace = $instance->getSetterProperty('setDaoNamespace')->getValue();
        } else {
            if ($managedNamespaces) {
                $rootNamespace = $classNameMapper->getManagedNamespaces()[0];
                $this->entitiesNamespace = $rootNamespace."Model\\Entities";
                $this->proxyNamespace = $rootNamespace."Model\\Proxies";
                $this->daoNamespace = $rootNamespace."Model\\DAOs";
            } else {
                $this->autoloadDetected = false;
                $this->entitiesPath = 'src/path_to_entities';
                $this->proxyDir = 'src/path_to_proxies';
                $this->proxyNamespace = "YOUR_APP_NAMESPACE\\PATH\\TO\\PROXIES";
            }
        }

        $this->contentBlock->addFile(__DIR__.'/../views/install.php', $this);
        $this->template->toHtml();
    }

public function defaultAction ( $ name = null , $ selfedit = 'false' , $ installMode = null ) { $ this -> selfedit = $ selfedit ; $ this -> installMode = $ installMode ; $ name = $ name ? $ name : 'entityManager' ; $ this -> instanceName = $ name ; if ( $ selfedit == 'true' ) { $ this -> moufManager = MoufManager :: getMoufManager ( ) ; } else { $ this -> moufManager = MoufManager :: getMoufManagerHiddenInstance ( ) ; } $ classNameMapper = ClassNameMapper :: createFromComposerFile ( __DIR__ . '/../../../../../../composer.json' ) ; $ managedNamespaces = $ classNameMapper -> getManagedNamespaces ( ) ; $ this -> autoloadDetected = true ; if ( $ this -> moufManager -> instanceExists ( $ name ) ) { $ instance = $ this -> moufManager -> getInstanceDescriptor ( $ name ) ; $ this -> entitiesNamespace = $ instance -> getSetterProperty ( 'setEntitiesNamespace' ) -> getValue ( ) ; $ this -> proxyNamespace = $ instance -> getSetterProperty ( 'setProxyNamespace' ) -> getValue ( ) ; $ this -> daoNamespace = $ instance -> getSetterProperty ( 'setDaoNamespace' ) -> getValue ( ) ; } else { if ( $ managedNamespaces ) { $ rootNamespace = $ classNameMapper -> getManagedNamespaces ( ) [ 0 ] ; $ this -> entitiesNamespace = $ rootNamespace . "Model\\Entities" ; $ this -> proxyNamespace = $ rootNamespace . "Model\\Proxies" ; $ this -> daoNamespace = $ rootNamespace . "Model\\DAOs" ; } else { $ this -> autoloadDetected = false ; $ this -> entitiesPath = 'src/path_to_entities' ; $ this -> proxyDir = 'src/path_to_proxies' ; $ this -> proxyNamespace = "YOUR_APP_NAMESPACE\\PATH\\TO\\PROXIES" ; } } $ this -> contentBlock -> addFile ( __DIR__ . '/../views/install.php' , $ this ) ; $ this -> template -> toHtml ( ) ; }

Displays the first install screen.

@Action
@Logged

@param string $selfedit If true, the name of the component must be a component from the Mouf framework itself (internal use only)


final public function before(string $action, Record $record, Record $previous = null): bool
    {
        $action = ucfirst($action);
        $method = "before{$action}";
        $container = Container::instance();
        if ($container->exists($this, $method)) {
            return $container->invoke($this, $method, ['record' => $record, 'previous' => $previous]);
        }
        return true;
    }

final public function before ( string $ action , Record $ record , Record $ previous = null ) : bool { $ action = ucfirst ( $ action ) ; $ method = "before{$action}" ; $ container = Container :: instance ( ) ; if ( $ container -> exists ( $ this , $ method ) ) { return $ container -> invoke ( $ this , $ method , [ 'record' => $ record , 'previous' => $ previous ] ) ; } return true ; }

This method is called before the operation be executed, the changes made in Record will be save
@param string $action
@param Record $record
@param Record $previous
@return bool
@throws SimplesRunTimeError

This method is called before the operation be executed the changes made in Record will be save


final public function after(string $action, Record $record, $extra = true)
    {
        $data = is_array($extra) ? $extra : [];

        $data = $this->afterDefault($action, $record, $data);

        $name = ucfirst($action);
        $method = "after{$name}";
        $container = Container::instance();
        if ($container->exists($this, $method)) {
            return $container->invoke($this, $method, ['record' => $record, 'data' => $data]);
        }

        if ($action === Action::READ) {
            return $data;
        }

        return $extra;
    }

final public function after ( string $ action , Record $ record , $ extra = true ) { $ data = is_array ( $ extra ) ? $ extra : [ ] ; $ data = $ this -> afterDefault ( $ action , $ record , $ data ) ; $ name = ucfirst ( $ action ) ; $ method = "after{$name}" ; $ container = Container :: instance ( ) ; if ( $ container -> exists ( $ this , $ method ) ) { return $ container -> invoke ( $ this , $ method , [ 'record' => $ record , 'data' => $ data ] ) ; } if ( $ action === Action :: READ ) { return $ data ; } return $ extra ; }

Triggered after operation be executed, the changes made in Record has no effect in storage
@param string $action
@param Record $record
@param mixed $extra
@return bool|array
@throws SimplesRunTimeError

Triggered after operation be executed the changes made in Record has no effect in storage


public function extend(Collection $collection)
    {
        foreach ($collection as $entity) {
            $this->append($entity);
        }
        return $this;
    }

public function extend ( Collection $ collection ) { foreach ( $ collection as $ entity ) { $ this -> append ( $ entity ) ; } return $ this ; }

Extend collection with entities from another one

@param Collection $data
@access public

@return static


public function append($data)
    {
        if (is_array($data) || $data instanceof \Traversable) {
            foreach ($data as $entity) {
                if (!$entity instanceof Entity) {
                    throw new InvalidArgumentException('Collection can contain only Entities class');
                }
                parent::append($entity);
            }
        } else {
            parent::append($data);
        }
        return $this;
    }

Append entities to collection

@param Entity|Collection|Traversable|array $data entity or list of entities to append
@access public

@return static


public function prepend($entity)
    {
        $collection = $this->getNewCollection();
        $collection->append($entity);
        foreach ($this as $entity) {
            $collection->append($entity);
        }
        $this->clear();
        $this->append($collection);
        return $this;
    }

public function prepend ( $ entity ) { $ collection = $ this -> getNewCollection ( ) ; $ collection -> append ( $ entity ) ; foreach ( $ this as $ entity ) { $ collection -> append ( $ entity ) ; } $ this -> clear ( ) ; $ this -> append ( $ collection ) ; return $ this ; }

Prepand entity to the begining of collection

@param Entity $entity

@return static


public function __isset($name)
    {
        if ($this->count() > 1) {
            throw new LogicException(
                'Collection has more then one element, you cannot get entity property directly'
            );
        }
        $current = $this->first();
        if (!$current) {
            return false;
        }
        return isset($current->$name);
    }

Returns isset on entity property when collection has only one element

@param string $name property name

@throws LogicException when collection has more then one element

@return mixed


public function last()
    {
        $this->seek($this->count() - 1);
        $entity = $this->current();
        $this->rewind();
        return $entity;
    }

public function last ( ) { $ this -> seek ( $ this -> count ( ) - 1 ) ; $ entity = $ this -> current ( ) ; $ this -> rewind ( ) ; return $ entity ; }

Returns last entity from collection

@return Entity


private function getElementMovedByOffset($offset)
    {
        if (!is_int($this->key())) {
            throw new LogicException(sprintf("Can't get element moved by %s as current key is not numeric", $offset));
        }
        $oldPosition = $this->key();
        $newPosition = $oldPosition + $offset;
        $this->seek($newPosition);
        if (!is_int($this->key())) {
            throw new LogicException(sprintf("Can't get element moved by %s as next key is not numeric", $offset));
        }
        $value = $this->current();
        $this->seek($oldPosition);
        return $value;
    }

Returns element moved by offset from the current key

@param integer $offset offset

@return Entity


public function has($field, $value, $strict = false)
    {
        return !(false === $this->search($field, $value, $strict));
    }

public function has ( $ field , $ value , $ strict = false ) { return ! ( false === $ this -> search ( $ field , $ value , $ strict ) ) ; }

Checks if collection has entity with field equals to given value

@param string $field field
@param mixed $value value

@return bool


public function search($field, $value, $strict = false)
    {
        $value = is_array($value) ? $value : array($value);
        foreach ($this as $key => $entity) {
            if (isset($entity->$field) && in_array($entity->$field, $value, $strict)) {
                return $key;
            }
        }

        return false;
    }

public function search ( $ field , $ value , $ strict = false ) { $ value = is_array ( $ value ) ? $ value : array ( $ value ) ; foreach ( $ this as $ key => $ entity ) { if ( isset ( $ entity -> $ field ) && in_array ( $ entity -> $ field , $ value , $ strict ) ) { return $ key ; } } return false ; }

Search for an element with given property and value

@param string $field name of property
@param mixed $value value to compare
@param bool $strict compare value and type of property

@return integer|string|false


public function shift()
    {
        $slice = $this->slice(0, 1);
        $offset = $slice->getKeys();
        $this->offsetUnset($offset[0]);
        return $slice->first();
    }

public function shift ( ) { $ slice = $ this -> slice ( 0 , 1 ) ; $ offset = $ slice -> getKeys ( ) ; $ this -> offsetUnset ( $ offset [ 0 ] ) ; return $ slice -> first ( ) ; }

Shift an entity off the begining of collection

@return Entity


public function filter(\Closure $callback)
    {
        $offsetToRemove = [];
        foreach ($this as $offset => $entity) {
            if (!$callback($entity)) {
                $offsetToRemove[] = $offset;
            }
        }
        $this->offsetUnset($offsetToRemove);
        return $this;
    }

public function filter ( \ Closure $ callback ) { $ offsetToRemove = [ ] ; foreach ( $ this as $ offset => $ entity ) { if ( ! $ callback ( $ entity ) ) { $ offsetToRemove [ ] = $ offset ; } } $ this -> offsetUnset ( $ offsetToRemove ) ; return $ this ; }

Filter collection from entities not matching criteria given in callback

@param \Closure $callback callback

@return static


public function getBy(\Closure $callback)
    {
        $instanceCopy = $this->getNewCollection();
        foreach ($this as $offset => $entity) {
            if ($callback($entity)) {
                $instanceCopy->append($entity);
            }
        }

        return $instanceCopy;
    }

public function getBy ( \ Closure $ callback ) { $ instanceCopy = $ this -> getNewCollection ( ) ; foreach ( $ this as $ offset => $ entity ) { if ( $ callback ( $ entity ) ) { $ instanceCopy -> append ( $ entity ) ; } } return $ instanceCopy ; }

Get collection of entities matching criteria given in callback

Usage example:

$colleciton->getBy(function($entity) {
return $entity->name == 'John';
});

@param Closure $callback
@return static


public function chunk($size)
    {
        $collection = $this->getNewCollection();

        foreach (array_chunk($this->getKeys(), $size) as $chunkIndex => $keys) {
            $collection[$chunkIndex] = $this->getNewCollection();

            foreach ($keys as $key) {
                $collection[$chunkIndex]->append($this[$key]);
            }
        }

        return $collection;
    }

public function chunk ( $ size ) { $ collection = $ this -> getNewCollection ( ) ; foreach ( array_chunk ( $ this -> getKeys ( ) , $ size ) as $ chunkIndex => $ keys ) { $ collection [ $ chunkIndex ] = $ this -> getNewCollection ( ) ; foreach ( $ keys as $ key ) { $ collection [ $ chunkIndex ] -> append ( $ this [ $ key ] ) ; } } return $ collection ; }

Splits collection into chunks

@param integer $size

@return static


public function slice($offset, $length = null)
    {
        $keys = $this->getKeys();

        $keys = array_slice($keys, $offset, $length);

        $collection = $this->getNewCollection();

        foreach ($this as $key => $entity) {
            if (in_array($key, $keys)) {
                $collection[$key] = $entity;
            }
        }

        return $collection;
    }

public function slice ( $ offset , $ length = null ) { $ keys = $ this -> getKeys ( ) ; $ keys = array_slice ( $ keys , $ offset , $ length ) ; $ collection = $ this -> getNewCollection ( ) ; foreach ( $ this as $ key => $ entity ) { if ( in_array ( $ key , $ keys ) ) { $ collection [ $ key ] = $ entity ; } } return $ collection ; }

Extract a slice of the collection

@param integer $offset
@param integer|null $length

@return static


public function split($parts)
    {
        $elementsPerChunk = ceil($this->count() / $parts);

        return $this->chunk($elementsPerChunk);
    }

public function split ( $ parts ) { $ elementsPerChunk = ceil ( $ this -> count ( ) / $ parts ) ; return $ this -> chunk ( $ elementsPerChunk ) ; }

Returns collection of collections created by spliting first Collection to a parts

Example:

When collection has 10 element and we would like to split to 3 separate collections:

$splitted = $collection->split(3);
$splitted->count(); // = 3
$splitted[0]->count(); // = 4
$splitted[1]->count(); // = 4
$splitted[3]->count(); // = 2

@param integer $parts

@return static


public function offsetUnset($index)
    {
        $index = is_array($index) ? $index : (array)$index;
        foreach ($index as $key) {
            parent::offsetUnset($key);
        }
        return $this;
    }

public function offsetUnset ( $ index ) { $ index = is_array ( $ index ) ? $ index : ( array ) $ index ; foreach ( $ index as $ key ) { parent :: offsetUnset ( $ key ) ; } return $ this ; }

Unset values from an offset or offsets

@param string|array $index Offsets to remove

@return static


public function distinctOn($propertyName)
    {
        $values = [];
        $keys = [];
        foreach ($this as $key => $entity) {
            if (in_array($entity->$propertyName, $values)) {
                $keys[] = $key;
            } else {
                $values[] = $entity->$propertyName;
            }
        }
        $this->offsetUnset($keys);
        return $this;
    }

public function distinctOn ( $ propertyName ) { $ values = [ ] ; $ keys = [ ] ; foreach ( $ this as $ key => $ entity ) { if ( in_array ( $ entity -> $ propertyName , $ values ) ) { $ keys [ ] = $ key ; } else { $ values [ ] = $ entity -> $ propertyName ; } } $ this -> offsetUnset ( $ keys ) ; return $ this ; }

Eliminates entities that contains the same value in given property

@param string $propertyName Name of the property

@return static


public function reverse()
    {
        $positions = array_flip($this->getKeys());
        $this->uksort(
            function ($a, $b) use ($positions) {
                return ($positions[$a] < $positions[$b] ? 1 : -1);
            }
        );

        return $this;
    }

public function reverse ( ) { $ positions = array_flip ( $ this -> getKeys ( ) ) ; $ this -> uksort ( function ( $ a , $ b ) use ( $ positions ) { return ( $ positions [ $ a ] < $ positions [ $ b ] ? 1 : - 1 ) ; } ) ; return $ this ; }

Return an collection with elements in reverse order

@return static


public function getAllValuesForProperty($name)
    {
        $values = [];
        foreach ($this as $entity) {
            if (isset($entity->$name)) {
                $value = $entity->$name;
                if (!($value === null || $value instanceof Collection && $value->isEmpty())) {
                    if (is_scalar($value)) {
                        $values[$value] = $value;
                    } else {
                        $values[] = $value;
                    }
                }
            }
        }

        return array_values($values);
    }

public function getAllValuesForProperty ( $ name ) { $ values = [ ] ; foreach ( $ this as $ entity ) { if ( isset ( $ entity -> $ name ) ) { $ value = $ entity -> $ name ; if ( ! ( $ value === null || $ value instanceof Collection && $ value -> isEmpty ( ) ) ) { if ( is_scalar ( $ value ) ) { $ values [ $ value ] = $ value ; } else { $ values [ ] = $ value ; } } } } return array_values ( $ values ) ; }

Return values from all entities from given property

@param string $name name

@return array


public function bindCollection(Collection $collection, array $compareKeys, $propertyName)
    {
        $reflection = new \ReflectionClass($collection);

        $fromKey = key($compareKeys);
        $toKey = $compareKeys[$fromKey];

        $collection = $collection->groupByField($fromKey);

        foreach ($this as $entity) {
            if (!isset($entity->$propertyName)) {
                $entity->$propertyName = new $reflection->name;
            }

            if (!isset($entity->$toKey) || ($value = $entity->$toKey) === null) {
                continue; //do not try to bind to null or non existing property
            }

            if (isset($collection[$value])) {
                $entity->$propertyName->append($collection[$value]);
            }
        }
        return $this;
    }

Bind two collections

@param Collection $collection collection
@param array $compareKeys The name of the key to compare with from target Collection
@param string $propertyName The nae of new property that will be created in source Collection

@return static


private function groupByField($name)
    {
        $collection = $this->getNewCollection();
        foreach ($this as $entity) {
            if (!isset($entity->$name) || $entity->$name === null) {
                continue; //when entity dosen't have set property it will be omitted
            }

            $value = $entity->$name;

            if (!isset($collection[$value])) {
                $collection[$value] = $this->getNewCollection();
            }
            $collection[$value]->append($entity);
        }
        return $collection;
    }

Group entities inside collection to sepearate Collections

@param string $name Property name to group by

@return static


public function prepareScopes()
    {
        $result = [];

        foreach ($this->scopes as $key => $scope) {
            // If no scope configuration has been provided, just make scope's name to be its alias
            if (!is_array($scope)) {
                $result[$scope] = ['alias' => $scope];
                continue;
            }

            $result[$key] = $scope;

            // If no alias has been provided, make it to be scope's name
            if (!isset($scope['alias'])) {
                $result[$key]['alias'] = $key;
            }
        }

        return $result;
    }

Parse scope configuration passed as a second argument for applyScopes method

@return array


public function parseScopeArguments(array $scope)
    {
        $scope = new MosaicArray($scope);
        $result = [];

        // If "type" key has been provided, we have to typecast the result
        $type = $scope->getItem('type');

        // Get default scope argument value
        $default = $scope->getItem('default');

        // Get request parameter value
        $value = $this->getInputManager()->get($scope['alias'], null);

        // If there are no parameters with the scope name:
        // 1) in a case when no default value is set, return null to ignore this scope
        // 2) if default value is set, return it
        if (is_null($value)) {
            return !is_null($default) ? [$default] : null;
        }

        // If "keys" configuration key has been provided, we are dealing with an array parameter (e.g. <input name="somename[somekey]">)
        $keys = $scope->getItem('keys');

        // If "keys" are empty, we have to perform some DRY actions
        if (is_null($keys)) {
            $keys = ['default'];
            $value = ['default' => $value];
        }

        foreach ((array) $keys as $key) {
            $arg = $this->setType($value[$key], $type);

            // Empty arguments are not allowed by default in order to allow default scope argument values
            // Set allowEmpty option to `true` if you want to change this behavior
            if ($arg !== '' or $scope->getItem('allowEmpty')) {
                $result[] = $arg;
            }
        }

        return $result;
    }

Parse scope arguments from request parameters

@param  array $scope
@return array


protected function setType($variable, $type)
    {
        // Do nothing if $type is not a string
        if (is_string($type)) {
            if (in_array($type, ['bool', 'boolean'])) {
                // Only 1, '1', true and 'true' values will be converted to boolean true
                // Any other value will be converted to boolean false
                $variable = in_array($variable, [1, '1', true, 'true'], true);
            } else {
                settype($variable, $type);
            }
        }

        return $variable;
    }

Typecast a variable

@param  mixed       $variable
@param  string|null $type
@return mixed


public function registerAnnotationBasedEntities($namespace, $directory) {
        $mappingDriver = InstallUtils::getOrCreateInstance('mappingDriver.'.$namespace, null, $this->moufManager);
        $mappingDriver->setCode('return new Doctrine\\ORM\\Mapping\\Driver\\AnnotationDriver($container->get(\'annotationReader\'), [ROOT_PATH . "'.$directory.'"]);');

        $this->addDriverToChain($namespace, $mappingDriver);
    }

Registers a set of annotation-based entities.

@param string $namespace
@param string $directory Directory where the annotations are stored, relative to ROOT_PATH.

Registers a set of annotation - based entities .


public function convert($string)
    {
        $stringToCamelCase = new StringToCamelCase();
        $parts = [];

        foreach (explode('/', trim($string, '/')) as $part) {
            $parts[] = ucfirst($stringToCamelCase->convert($part, '-'));
        }

        return implode('\\', $parts);
    }

public function convert ( $ string ) { $ stringToCamelCase = new StringToCamelCase ( ) ; $ parts = [ ] ; foreach ( explode ( '/' , trim ( $ string , '/' ) ) as $ part ) { $ parts [ ] = ucfirst ( $ stringToCamelCase -> convert ( $ part , '-' ) ) ; } return implode ( '\\' , $ parts ) ; }

convert path to namespaced classname

@param string $string
@return string


private function prepareDataForInsert($data)
    {
        $items = [];
        foreach ($data as $key => $value) {
            $items[] = ['key' => $key, 'value' => $value];
        }

        return $items;
    }

private function prepareDataForInsert ( $ data ) { $ items = [ ] ; foreach ( $ data as $ key => $ value ) { $ items [ ] = [ 'key' => $ key , 'value' => $ value ] ; } return $ items ; }

Prepare data for insert

@param array $data
@return array


private function updateData($data)
    {
        $this->data = $data;

        $cache = Yii::$app->{$this->cache};
        $cache->delete($this->cacheName);

        if (is_array($this->data) && count($this->data)) {
            $cache->set($this->cacheName, serialize($this->data));
        }
    }

private function updateData ( $ data ) { $ this -> data = $ data ; $ cache = Yii :: $ app -> { $ this -> cache } ; $ cache -> delete ( $ this -> cacheName ) ; if ( is_array ( $ this -> data ) && count ( $ this -> data ) ) { $ cache -> set ( $ this -> cacheName , serialize ( $ this -> data ) ) ; } }

Update data and cache

@param array $data


protected function parseFilterFields(array $data = []): array
    {
        $filters = [];
        foreach ($data as $name => $value) {
            if (is_array($value) && $name === '__filter__') {
                $filters = $this->parseFilterRules($filters, $value);
                continue;
            }
            if (!$this->has($name)) {
                $class = static::class;
                $json = JSON::encode($data);
                throw new SimplesRunTimeError(
                    "There is no property `{$name}` in `{$class}` parsing {$json}"
                );
            }
            $filters[] = Filter::create($this->get($name), $value);
        }
        return $filters;
    }

Parse the filters of fields

@param array $data
@return array
@throws Exception


protected function parseFilterValues(array $filters = []): array
    {
        $values = [];
        foreach ($filters as $filter) {
            if (is_array($filter)) {
                $values = array_merge($values, $this->parseFilterValues($filter['filter']));
                continue;
            }
            /** @var Filter $filter */
            $value = $filter->getParsedValue($this->getDriver());
            if (!is_array($value)) {
                $values[] = $value;
                continue;
            }
            $values = array_merge($values, $value);
        }
        return $values;
    }

protected
function
parseFilterValues
(
array
$
filters
=
[
]
)
:
array
{
$
values
=
[
]
;
foreach
(
$
filters
as
$
filter
)
{
if
(
is_array
(
$
filter
)
)
{
$
values
=
array_merge
(
$
values
,
$
this
->
parseFilterValues
(
$
filter
[
'filter'
]
)
)
;
continue
;
}
/** @var Filter $filter */
$
value
=
$
filter
->
getParsedValue
(
$
this
->
getDriver
(
)
)
;
if
(
!
is_array
(
$
value
)
)
{
$
values
[
]
=
$
value
;
continue
;
}
$
values
=
array_merge
(
$
values
,
$
value
)
;
}
return
$
values
;
}

Parse the values of the fields

@param array $filters
@return array


public function convert($data)
    {
        if (is_array($data)) {
            if (!is_numeric(key($data))) {
                return (object) array_map(__METHOD__, $data);
            }

            /** @var stdClass $data */
            return $data;
        } else {
            /** @var stdClass $data */
            return $data;
        }
    }

public
function
convert
(
$
data
)
{
if
(
is_array
(
$
data
)
)
{
if
(
!
is_numeric
(
key
(
$
data
)
)
)
{
return
(
object
)
array_map
(
__METHOD__
,
$
data
)
;
}
/** @var stdClass $data */
return
$
data
;
}
else
{
/** @var stdClass $data */
return
$
data
;
}
}

convert array to object

@param array $data
@return stdClass


public function getLabel() {
		if ($this->translationService) {
			return $this->translationService->getTranslation($this->label);
		} else {
			return $this->label;
		}
	}

public function getLabel ( ) { if ( $ this -> translationService ) { return $ this -> translationService -> getTranslation ( $ this -> label ) ; } else { return $ this -> label ; } }

Returns the label for the menu item.
@return string


public function getAdditionalStyleByType($type) {
		$return = null;
		if($this->additionalStyles) {
			foreach ($this->additionalStyles as $additionalStyle) {
				if($additionalStyle instanceof $type) {
					if($return === null)
						$return = $additionalStyle;
					else
						throw new \Exception("MenuItem: There are many instance of $type, please use getAdditionalStylesByType function to get all instance");
				}
			}
		}
		return $return;
	}

Returns the one of additionnal style
@return array<MenuItemStyleInterface>


public function getAdditionalStylesByType($type) {
		$return = array();
		if($this->additionalStyles) {
			foreach ($this->additionalStyles as $additionalStyle) {
				if($additionalStyle instanceof $type) {
					$return[] = $additionalStyle;
				}
			}
		}
		return $return;
	}

public function getAdditionalStylesByType ( $ type ) { $ return = array ( ) ; if ( $ this -> additionalStyles ) { foreach ( $ this -> additionalStyles as $ additionalStyle ) { if ( $ additionalStyle instanceof $ type ) { $ return [ ] = $ additionalStyle ; } } } return $ return ; }

Returns the list of additionnal style
@return array<MenuItemStyleInterface>


public function getLink() {
		if ($this->url === null) {
			return null;
		}
		$link = $this->getLinkWithoutParams();

		$params = array();
		// First, get the list of all parameters to be propagated
		if (is_array($this->propagatedUrlParameters)) {
			foreach ($this->propagatedUrlParameters as $parameter) {
				if (isset($_REQUEST[$parameter])) {
					$params[$parameter] = \get($parameter);
				}
			}
		}

		if (!empty($params)) {
			if (strpos($link, "?") === FALSE) {
				$link .= "?";
			} else {
				$link .= "&";
			}
			$paramsAsStrArray = array();
			foreach ($params as $key=>$value) {
				$paramsAsStrArray[] = urlencode($key).'='.urlencode($value);
			}
			$link .= implode("&", $paramsAsStrArray);
		}

		return $link;
	}

Returns the absolute URL, with parameters if required.
@return string

Returns the absolute URL with parameters if required .


public function convert($data)
    {
        if (is_object($data)) {
            $data = get_object_vars($data);
        }

        if (is_array($data)) {
            return array_map(__METHOD__, $data);
        } else {
            return $data;
        }
    }

public function convert ( $ data ) { if ( is_object ( $ data ) ) { $ data = get_object_vars ( $ data ) ; } if ( is_array ( $ data ) ) { return array_map ( __METHOD__ , $ data ) ; } else { return $ data ; } }

convert object to array

@param mixed $data
@return array


protected function configure(string $collection, string $primaryKey = 'id', string $relationship = '')
    {
        if ($relationship) {
            $reference = get_parent_class($this);
            $call = 'construct';
            if (method_exists($reference, $call)) {
                $reference::$call();
            }
        }

        if ($this->collection) {
            $this->parents[$relationship] = clone $this;
            $this->add($relationship)->integer()->collection($collection)->update(false);
            if (!$relationship) {
                throw new SimplesRunTimeError("When extending one model you need give a name to relationship");
            }
        }
        $this->collection = $collection;
        $this->primaryKey = $primaryKey;

        $this->add($this->hashKey)->hashKey();
        foreach ([$this->destroyKeys, $this->createKeys, $this->updateKeys] as $keys) {
            foreach ($keys as $key => $name) {
                $this->add($name)->type($this->getTimestampType($key))->recover(false);
            }
        }
        $this->add($primaryKey)->primaryKey();

        return $this;
    }

Configure the instance with reference properties
@param string $collection
@param string $primaryKey ('id')
@param string $relationship ('')
@return $this
@throws SimplesRunTimeError


private function connection($connection): string
    {
        $this->connection = !is_null($connection) ? $connection : env('DEFAULT_DATABASE');
        if (!$this->connection) {
            throw new SimplesRunTimeError(
                "There is no `connection` to be used. Check .env file or configure the model property"
            );
        }
        return $this->connection;
    }

Parse the connection name and choose a source to it
@param $connection
@return string
@throws SimplesRunTimeError


protected function import(string $name, string $relationship, array $options = []): Field
    {
        $source = $this->get($relationship);
        $reference = $source->getReferences();

        $class = off($reference, 'class');
        if (!class_exists($class)) {
            throw new SimplesRunTimeError("Cant not import '{$name}' from '{$class}'");
        }

        /** @var DataMapper $class */
        $import = $class::instance()->get($name);

        $options = array_merge($import->getOptions(), $options);

        $from = new Field($import->getCollection(), $name, $import->getType(), $options);
        $this->fields[$name] = $from->from($source);

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

Allow use this field like readonly in read filtering and getting it in record
@param string $name
@param string $relationship
@param array $options
@return Field
@throws SimplesRunTimeError


public function convert($string)
    {
        $parts = [];

        foreach (explode('\\', trim($string, '\\')) as $name) {
            $name = strtolower(preg_replace('/([a-z])([A-Z])/', '$1-$2', $name));
            $parts[] = $name;
        }

        return implode('/', $parts);
    }

public function convert ( $ string ) { $ parts = [ ] ; foreach ( explode ( '\\' , trim ( $ string , '\\' ) ) as $ name ) { $ name = strtolower ( preg_replace ( '/([a-z])([A-Z])/' , '$1-$2' , $ name ) ) ; $ parts [ ] = $ name ; } return implode ( '/' , $ parts ) ; }

convert namespaced classname to path

@param string $string
@return string


public function fire()
    {
        $this->record['attempts'] += 1;
        $this->record['status'] = 'running';
        DB::table($this->table)->where('ID', $this->id)->update([
            'attempts' => $this->record['attempts'],
            'status' => $this->record['status'],
        ]);

        $this->resolveAndFire(array('job' => $this->job, 'data' => $this->data));

        /**
         * Auto delete is implemented.
         * However, WTF is this AUTO DELETE ???
         * None of laravel builtin Job class implements it,
         * nor any document mentions it.
         */
        if ($this->autoDelete()) { $this->delete(); return; }

        /**
         * Auto release if job was not explicitly deleted/released.
         */
        if ($this->record['status'] == 'running') { $this->release(); }
    }