public static function getLinesIntersection(Line $line1, Line $line2)
    {
        $div = ($line1->getSlope() - $line2->getSlope());
        $x = ($div!=0 ?
            (($line2->getYIntercept() - $line1->getYIntercept()) / $div) : ($line2->getYIntercept() - $line1->getYIntercept()));
        $y = $line1->getOrdinateByAbscissa($x);
        return new Point($x, $y);
    }

public static function getLinesIntersection ( Line $ line1 , Line $ line2 ) { $ div = ( $ line1 -> getSlope ( ) - $ line2 -> getSlope ( ) ) ; $ x = ( $ div != 0 ? ( ( $ line2 -> getYIntercept ( ) - $ line1 -> getYIntercept ( ) ) / $ div ) : ( $ line2 -> getYIntercept ( ) - $ line1 -> getYIntercept ( ) ) ) ; $ y = $ line1 -> getOrdinateByAbscissa ( $ x ) ; return new Point ( $ x , $ y ) ; }

Get the intersection point between two lines

y = (A1 * x) + B1  &&  y = (A2 * x) + B2
x = (B2 - B1) / (A1 - A2)

@param   \Maths\Geometry\Line    $line1
@param   \Maths\Geometry\Line    $line2
@return  \Maths\Geometry\Point


public function arePerpendiculars(Line $line1, Line $line2)
    {
        if (self::areParallels($line1, $line2)) {
            return false;
        }
    }

public function arePerpendiculars ( Line $ line1 , Line $ line2 ) { if ( self :: areParallels ( $ line1 , $ line2 ) ) { return false ; } }

Test if two segments are perpendiculars

This will test it two lines are perpendiculars constructing a triangle and
testing if it is perpendicular

@param   \Maths\Geometry\Line     $line1
@param   \Maths\Geometry\Line     $line2
@return  bool


public static function areParallels(Line $line1, Line $line2)
    {
        if (
            ($line1->isHorizontal() && $line2->isHorizontal()) ||
            ($line1->isVertical() && $line2->isVertical())
        ) {
            return true;
        }
        $line1->rearrange();
        $line2->rearrange();
        $abs = array(
            $line1->getPointA()->getAbscissa(),
            $line1->getPointB()->getAbscissa(),
            $line2->getPointA()->getAbscissa(),
            $line2->getPointB()->getAbscissa()
        );
        $ords = array(
            $line1->getPointA()->getOrdinate(),
            $line1->getPointB()->getOrdinate(),
            $line2->getPointA()->getOrdinate(),
            $line2->getPointB()->getOrdinate()
        );
        $e = new Point(
            rand(0, 10) + (max($abs) + abs(min($abs))),
            rand(0, 10) + (max($ords) + abs(min($ords)))
        );
        $segAE = new Segment($line1->getPointA(), $e);
        $segBE = new Segment($line1->getPointB(), $e);

        $intersectCE = self::getLinesIntersection($segAE, $line2);
        $segCE = new Segment($intersectCE, $e);
        $intersectDE = self::getLinesIntersection($segBE, $line2);
        $segDE = new Segment($intersectDE, $e);

/*
echo <<<TYPEOTHER
        var demo1 = brd.create('point', [{$line1->getPointA()->x},{$line1->getPointA()->y}], {
            name: 'a'
        });
        var demo2 = brd.create('point', [{$line1->getPointB()->x},{$line1->getPointB()->y}], {
            name: 'b'
        });
        var segment1 = brd.create('line', [demo1,demo2], {straightFirst:false,straightLast:false});

        var demo3 = brd.create('point', [{$intersectCE->x},{$intersectCE->y}], {
            name: 'c'
        });
        var demo4 = brd.create('point', [{$intersectDE->x},{$intersectDE->y}], {
            name: 'd'
        });
        var segment2 = brd.create('line', [demo3,demo4], {straightFirst:false,straightLast:false});

        var demo5 = brd.create('point', [{$e->x},{$e->y}], {
            name: 'e'
        });
        var segment3 = brd.create('line', [demo1,demo5], {straightFirst:false,straightLast:false,color:'#404040'});
        var segment4 = brd.create('line', [demo2,demo5], {straightFirst:false,straightLast:false,color:'#404040'});
        var segment5 = brd.create('line', [demo3,demo5], {straightFirst:false,straightLast:false,color:'#404040'});
        var segment6 = brd.create('line', [demo4,demo5], {straightFirst:false,straightLast:false,color:'#404040'});
TYPEOTHER;
*/

        return (bool) (($segAE->getLength() / $segCE->getLength()) == ($segBE->getLength() / $segDE->getLength()));
    }

Test if two segments are parallels

This will test if the two lines drawn from the two segments verify the Thales theorem
by comparing [ab] (segment 1), [cd] (segment 2) and a fifth point [e] used to build
triangles:

[ae]/[ce] == [be]/[de] ?

@param   \Maths\Geometry\Line     $line1
@param   \Maths\Geometry\Line     $line2
@return  bool


public static function getDirectionByPoints(PointInterface $point1, PointInterface $point2)
    {
        if (self::areSameSpace($point1, $point2)) {
            $directions = array(
                0 => self::getDirectionByCoordinates($point1->getAbscissa(), $point2->getAbscissa())
            );
            if ($point1->is2D() || $point1->is3D()) {
                $directions[1] = self::getDirectionByCoordinates($point1->getOrdinate(), $point2->getOrdinate());
            }
            if ($point1->is3D()) {
                $directions[2] = self::getDirectionByCoordinates($point1->getApplicate(), $point2->getApplicate());
            }
            return $directions;
        } else {
            throw new \InvalidArgumentException(
                "Can not guess directions between two points of different space types"
            );
        }
    }

Get the directions between two points for each axis

This will return an array with the value `1,-1,0` for each axis.

@param   PointInterface  $point1
@param   PointInterface  $point2
@return  array
@throws  \InvalidArgumentException


public static function getDirectionByCoordinates($a, $b)
    {
        if ($a < $b) {
            return self::DIRECTION_POSITIVE;
        } elseif ($a > $b) {
            return self::DIRECTION_NEGATIVE;
        } else {
            return self::DIRECTION_NULL;
        }
    }

public static function getDirectionByCoordinates ( $ a , $ b ) { if ( $ a < $ b ) { return self :: DIRECTION_POSITIVE ; } elseif ( $ a > $ b ) { return self :: DIRECTION_NEGATIVE ; } else { return self :: DIRECTION_NULL ; } }

Get the directions between two points

This will return:

-    `1` if [a->b] evolves in positive direction
-    `-1` if [a->b] evolves in negative direction
-    `0` if [a->b] does not evolve (same point)

@param   int  $a
@param   int  $b
@return  int


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

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

Executes query and returns all results as an array.
@param DatabaseInterface|DbConnectionGetterInterface|null $db the DB connection used to create the DB command.
If null, the DB connection returned by [[modelClass]] will be used.
@return ExtendedPromiseInterface with array|ActiveRecordInterface[] the query results. If the query results in nothing, an empty array will be returned.

Executes query and returns all results as an array .


protected function prepareAsyncVia() {
        // lazy loading of a relation
        $where = $this->where;

        $promise = new LazyPromise(function() {
            return resolve(true);
        });

        if ($this->via instanceof self) {
            // via junction table
            $promise->thenLazy(
                function() {
                    return $this->via->findJunctionRows([$this->primaryModel]);
                }
            )->thenLazy(
                function($viaModels) {
                    $this->filterByModels($viaModels);
                    return true;
                }
            );
        } elseif (is_array($this->via)) {
            // via relation
            /* @var $viaQuery ActiveQuery */
            list($viaName, $viaQuery) = $this->via;
            $viaModelsPr = $viaQuery->multiple ? $viaQuery->all() : $viaQuery->one();
            $viaModelsPr->otherwise(function() use (&$viaQuery) {
                return $viaQuery->multiple ? [] : null;
            });
            $promise->thenLazy(
                function() use ($viaModelsPr) {
                    return $viaModelsPr;
                }
            )->thenLazy(
                function($viaModels) use ($viaName, &$viaQuery) {
                    $this->primaryModel->populateRelation($viaName, $viaModels);
                    if (!$viaQuery->multiple) {
                        $viaModels = $viaModels === null ? [] : [$viaModels];
                    }
                    return $viaModels;
                }
            )->thenLazy(
                function($viaModels) {
                    $this->filterByModels($viaModels);
                    return true;
                }
            );
        } else {
            $this->filterByModels([$this->primaryModel]);
        }
        return $promise->thenLazy(
            function() use (&$where) {
                $query = Query::create($this);
                $this->where = $where;
                return $query;
            }
        );
    }

protected
function
prepareAsyncVia
(
)
{
// lazy loading of a relation
$
where
=
$
this
->
where
;
$
promise
=
new
LazyPromise
(
function
(
)
{
return
resolve
(
true
)
;
}
)
;
if
(
$
this
->
via
instanceof
self
)
{
// via junction table
$
promise
->
thenLazy
(
function
(
)
{
return
$
this
->
via
->
findJunctionRows
(
[
$
this
->
primaryModel
]
)
;
}
)
->
thenLazy
(
function
(
$
viaModels
)
{
$
this
->
filterByModels
(
$
viaModels
)
;
return
true
;
}
)
;
}
elseif
(
is_array
(
$
this
->
via
)
)
{
// via relation
/* @var $viaQuery ActiveQuery */
list
(
$
viaName
,
$
viaQuery
)
=
$
this
->
via
;
$
viaModelsPr
=
$
viaQuery
->
multiple
$
viaQuery
->
all
(
)
:
$
viaQuery
->
one
(
)
;
$
viaModelsPr
->
otherwise
(
function
(
)
use
(
&
$
viaQuery
)
{
return
$
viaQuery
->
multiple
[
]
:
;
}
)
;
$
promise
->
thenLazy
(
function
(
)
use
(
$
viaModelsPr
)
{
return
$
viaModelsPr
;
}
)
->
thenLazy
(
function
(
$
viaModels
)
use
(
$
viaName
,
&
$
viaQuery
)
{
$
this
->
primaryModel
->
populateRelation
(
$
viaName
,
$
viaModels
)
;
if
(
!
$
viaQuery
->
multiple
)
{
$
viaModels
=
$
viaModels
===
[
]
:
[
$
viaModels
]
;
}
return
$
viaModels
;
}
)
->
thenLazy
(
function
(
$
viaModels
)
{
$
this
->
filterByModels
(
$
viaModels
)
;
return
true
;
}
)
;
}
else
{
$
this
->
filterByModels
(
[
$
this
->
primaryModel
]
)
;
}
return
$
promise
->
thenLazy
(
function
(
)
use
(
&
$
where
)
{
$
query
=
Query
::
create
(
$
this
)
;
$
this
->
where
=
$
where
;
return
$
query
;
}
)
;
}

Prepare query with relations
@return ExtendedPromiseInterface|LazyPromise


private function removeDuplicatedModels($models)
    {
        $hash = [];
        /* @var $class ActiveRecordInterface */
        $class = $this->modelClass;
        $pks = $class::primaryKey();

        if (count($pks) > 1) {
            // composite primary key
            foreach ($models as $i => $model) {
                $key = [];
                foreach ($pks as $pk) {
                    if (!isset($model[$pk])) {
                        // do not continue if the primary key is not part of the result set
                        break 2;
                    }
                    $key[] = $model[$pk];
                }
                $key = serialize($key);
                if (isset($hash[$key])) {
                    unset($models[$i]);
                } else {
                    $hash[$key] = true;
                }
            }
        } elseif (empty($pks)) {
            throw new InvalidConfigException("Primary key of '{$class}' can not be empty.");
        } else {
            // single column primary key
            $pk = reset($pks);
            foreach ($models as $i => $model) {
                if (!isset($model[$pk])) {
                    // do not continue if the primary key is not part of the result set
                    break;
                }
                $key = $model[$pk];
                if (isset($hash[$key])) {
                    unset($models[$i]);
                } elseif ($key !== null) {
                    $hash[$key] = true;
                }
            }
        }

        return array_values($models);
    }

Removes duplicated models by checking their primary key values.
This method is mainly called when a join query is performed, which may cause duplicated rows being returned.
@param array $models the models to be checked
@throws InvalidConfigException if model primary key is empty
@return array|ActiveRecordInterface[] the distinctive models

Removes duplicated models by checking their primary key values . This method is mainly called when a join query is performed which may cause duplicated rows being returned .


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

        return $this->createCommand($db)->thenLazy(
            function(CommandInterface $command) {
                return $command->queryOne();
            }
        )->thenLazy(
            function($row) {
                if ($row !== false) {
                    return $this->populate([$row]);
                }
                return reject(null);
            }
        )->thenLazy(
            function($models) {
                return reset($models) ?: reject(null);
            }
        );
    }

public function one ( $ db = null ) { if ( $ this -> emulateExecution ) { return reject ( false ) ; } return $ this -> createCommand ( $ db ) -> thenLazy ( function ( CommandInterface $ command ) { return $ command -> queryOne ( ) ; } ) -> thenLazy ( function ( $ row ) { if ( $ row !== false ) { return $ this -> populate ( [ $ row ] ) ; } return reject ( null ) ; } ) -> thenLazy ( function ( $ models ) { return reset ( $ models ) ? : reject ( null ) ; } ) ; }

Executes query and returns a single row of result.
@param DatabaseInterface|DbConnectionGetterInterface|null $db the DB connection used to create the DB command.
If `null`, the DB connection returned by [[modelClass]] will be used.
@return ExtendedPromiseInterface with ActiveRecordInterface|array|null a single row of query result. Depending on the setting of [[asArray]],
the query result may be either an array or an ActiveRecord object. `null` will be returned
if the query results in nothing.

Executes query and returns a single row of result .


public static function isValid(string $value): bool
    {
        // Look for:
        // \n not preceded by \r, OR
        // \r not followed by \n, OR
        // \r\n not followed by space or horizontal tab; these are all CRLF attacks
        if (preg_match("#(?:(?:(?<!\r)\n)|(?:\r(?!\n))|(?:\r\n(?![ \t])))#", $value)) {
            return false;
        }

        // Non-visible, non-whitespace characters
        // 9 === horizontal tab
        // 10 === line feed
        // 13 === carriage return
        // 32-126, 128-254 === visible
        // 127 === DEL (disallowed)
        // 255 === null byte (disallowed)
        if (preg_match('/[^\x09\x0a\x0d\x20-\x7E\x80-\xFE]/', $value)) {
            return false;
        }

        return true;
    }

Validate a header value.

Per RFC 7230, only VISIBLE ASCII characters, spaces, and horizontal
tabs are allowed in values; header continuations MUST consist of
a single CRLF sequence followed by a space or horizontal tab.

@see http://en.wikipedia.org/wiki/HTTP_response_splitting

@param string $value

@return bool


public static function assertValid(string $value): void
    {
        if (! self::isValid($value)) {
            throw new InvalidArgumentException(
                sprintf(
                    '"%s" is not valid header value',
                    $value
                )
            );
        }
    }

public
static
function
assertValid
(
string
$
value
)
:
void
{
if
(
!
self
::
isValid
(
$
value
)
)
{
throw
new
InvalidArgumentException
(
sprintf
(
'"%s" is not valid header value'
,
$
value
)
)
;
}
}

Assert a header value is valid.

@param string $value

@throws InvalidArgumentException for invalid values

@return void


public function request()
    {
        if ('' !== $this->defaultOptions['callback']) {
            $msg = 'Cannot run query when callback is set. Get query using getRawRequestUrl().';
            throw new \BadMethodCallException($msg);
        }

        $this->buildSpecificRequestUri();

        try {
            if (null === $content = $this->getHttpClient()->getContent($this->getRawRequestUrl())) {
                throw new \RuntimeException('The request was not successful.');
            }
        } catch (\RuntimeException $e) {
            throw new \RuntimeException('The request was not successful.');
        }

        if (self::RESULT_ARRAY === $this->resultFormat) {
            $resultSet = json_decode($content, true);
            $resultSet = new ResultSet($resultSet['results']);

            return $resultSet;
        } else {
            // convert JSON-string to array
            $jsonString = json_decode($content);

            $this->resultCount = (integer) $jsonString->resultCount;
            $this->results     = json_encode($jsonString->results);

            return $this->results;
        }
    }

Query the service and save result

@throws \BadMethodCallException
@throws \RuntimeException

@return ResultSet|string


protected function buildRequestUri()
    {
        $requestParameters = array();

        // add entity
        if (!empty($this->defaultOptions['entity'])) {
            $tmp = array_keys($this->defaultOptions['entity']);
            $key = array_pop($tmp);
            $requestParameters[] = 'entity=' . $this->defaultOptions['entity'][$key];
        }

        // add media type
        if (!empty($this->defaultOptions['mediaType'])) {
            $requestParameters[] = 'media=' . $this->defaultOptions['mediaType'];
        }

        // add attribute
        if (!empty($this->defaultOptions['attribute'])) {
            $requestParameters[] = 'attribute=' . $this->defaultOptions['attribute'];
        }

        // add language
        if (!empty($this->defaultOptions['language'])) {
            $requestParameters[] = 'lang=' . $this->defaultOptions['language'];
        }

        // add limit
        if ($this->defaultOptions['limit'] <> 100) {
            $requestParameters[] = 'limit=' . $this->defaultOptions['limit'];
        }

        // add country
        if ($this->defaultOptions['country'] != 'us') {
            $requestParameters[] = 'country=' . $this->defaultOptions['country'];
        }

        // add callback
        if (!empty($this->defaultOptions['callback'])) {
            $requestParameters[] = 'callback=' . $this->defaultOptions['callback'];
        }

        // add version
        if ($this->defaultOptions['version'] <> 2) {
            $requestParameters[] = 'version=' . $this->defaultOptions['version'];
        }

        // add explicity
        if ($this->defaultOptions['explicit'] != 'yes') {
            $requestParameters[] = 'explicit=' . $this->defaultOptions['explicit'];
        }

        return implode('&', $requestParameters);
    }

protected
function
buildRequestUri
(
)
{
$
requestParameters
=
array
(
)
;
// add entity
if
(
!
empty
(
$
this
->
defaultOptions
[
'entity'
]
)
)
{
$
tmp
=
array_keys
(
$
this
->
defaultOptions
[
'entity'
]
)
;
$
key
=
array_pop
(
$
tmp
)
;
$
requestParameters
[
]
=
'entity='
.
$
this
->
defaultOptions
[
'entity'
]
[
$
key
]
;
}
// add media type
if
(
!
empty
(
$
this
->
defaultOptions
[
'mediaType'
]
)
)
{
$
requestParameters
[
]
=
'media='
.
$
this
->
defaultOptions
[
'mediaType'
]
;
}
// add attribute
if
(
!
empty
(
$
this
->
defaultOptions
[
'attribute'
]
)
)
{
$
requestParameters
[
]
=
'attribute='
.
$
this
->
defaultOptions
[
'attribute'
]
;
}
// add language
if
(
!
empty
(
$
this
->
defaultOptions
[
'language'
]
)
)
{
$
requestParameters
[
]
=
'lang='
.
$
this
->
defaultOptions
[
'language'
]
;
}
// add limit
if
(
$
this
->
defaultOptions
[
'limit'
]
<>
100
)
{
$
requestParameters
[
]
=
'limit='
.
$
this
->
defaultOptions
[
'limit'
]
;
}
// add country
if
(
$
this
->
defaultOptions
[
'country'
]
!=
'us'
)
{
$
requestParameters
[
]
=
'country='
.
$
this
->
defaultOptions
[
'country'
]
;
}
// add callback
if
(
!
empty
(
$
this
->
defaultOptions
[
'callback'
]
)
)
{
$
requestParameters
[
]
=
'callback='
.
$
this
->
defaultOptions
[
'callback'
]
;
}
// add version
if
(
$
this
->
defaultOptions
[
'version'
]
<>
2
)
{
$
requestParameters
[
]
=
'version='
.
$
this
->
defaultOptions
[
'version'
]
;
}
// add explicity
if
(
$
this
->
defaultOptions
[
'explicit'
]
!=
'yes'
)
{
$
requestParameters
[
]
=
'explicit='
.
$
this
->
defaultOptions
[
'explicit'
]
;
}
return
implode
(
'&'
,
$
requestParameters
)
;
}

Build the request uri for all common parameters

@return string


public function setLanguage($language = 'en_us')
    {
        if (in_array($language, $this->languageList)) {
            $this->defaultOptions['language'] = $language;
        }

        return $this;
    }

public function setLanguage ( $ language = 'en_us' ) { if ( in_array ( $ language , $ this -> languageList ) ) { $ this -> defaultOptions [ 'language' ] = $ language ; } return $ this ; }

Sets the language for the result

@param string $language

@return Tunes


public function setMediaType($mediatype = self::MEDIATYPE_ALL)
    {
        if (in_array($mediatype, $this->mediaTypes)) {
            $this->defaultOptions['mediaType'] = $mediatype;
        }

        return $this;
    }

public function setMediaType ( $ mediatype = self :: MEDIATYPE_ALL ) { if ( in_array ( $ mediatype , $ this -> mediaTypes ) ) { $ this -> defaultOptions [ 'mediaType' ] = $ mediatype ; } return $ this ; }

Set the used mediatype

@param string $mediatype

@return Tunes


public function setResultFormat($format = self::RESULT_ARRAY)
    {
        if (in_array($format, $this->resultFormats)) {
            $this->resultFormat = $format;
        }

        return $this;
    }

public function setResultFormat ( $ format = self :: RESULT_ARRAY ) { if ( in_array ( $ format , $ this -> resultFormats ) ) { $ this -> resultFormat = $ format ; } return $ this ; }

Set the result format

@param string $format

@return Tunes


public function setLimit($limit = 100)
    {
        // the limit must be within the boundaries of the service
        if ($limit <= 0 || $limit > 200) {
            throw new \OutOfBoundsException('The limit must be within 0 and 200.');
        }

        $this->defaultOptions['limit'] = (integer) $limit;

        return $this;
    }

Set the limit

@param integer $limit

@throws \OutOfBoundsException

@return Tunes


public function setEntity($entity = array())
    {
        // check if only one entry is given
        if (count($entity) <> 1) {
            throw new \InvalidArgumentException('Must be set with one key/value-pair!');
        }

        // fetch key from parameter
        $_tmp = array_keys($entity);
        $key  = array_pop($_tmp);

        // check if the key of the given array exists
        if (array_key_exists($key, $this->entityList)) {
            // check if value exists for key
            if (in_array($entity[$key], $this->entityList[$key])) {
                $this->defaultOptions['entity'] = $entity;
            }
        }

        return $this;
    }

Set the entity for the result

@param array $entity

@throws \InvalidArgumentException

@return Tunes


public function setAttribute($attribute = '')
    {
        if ('' === $this->defaultOptions['mediaType']) {
            throw new \InvalidArgumentException('Attribute relates to media type but no media type is set.');
        }

        // check if the attribute is in the set of attributes for media type
        if (in_array($attribute, $this->attributesTypes[$this->defaultOptions['mediaType']])) {
            $this->defaultOptions['attribute'] = $attribute;
        } else {
            throw new \InvalidArgumentException('Attribute is not in the set of attributes for this media type.');
        }
    }

Set the attribute you want to search in the iTunes
store.
This is relative to the set media type.

@param string $attribute

@throws \InvalidArgumentException

Set the attribute you want to search in the iTunes store . This is relative to the set media type .


public function setCallback($callback = '')
    {
        if (self::RESULT_JSON !== $this->getResultFormat()) {
            throw new \BadMethodCallException('Callback can only be set with RESULT_JSON');
        }

        $this->defaultOptions['callback'] = $callback;
    }

Set a custom callback function you want to use
when returning search results.
This setting works only when result format is set to
RESULT_JSON

@param string $callback

@throws \BadMethodCallException

Set a custom callback function you want to use when returning search results . This setting works only when result format is set to RESULT_JSON


public function setExplicit($setting = 'yes')
    {
        if (in_array($setting, $this->explicitTypes)) {
            $this->defaultOptions['explicit'] = $setting;
        }

        return $this;
    }

public function setExplicit ( $ setting = 'yes' ) { if ( in_array ( $ setting , $ this -> explicitTypes ) ) { $ this -> defaultOptions [ 'explicit' ] = $ setting ; } return $ this ; }

Set the flag indicating whether or not you want to include
explicit content in your search result

@param string $setting

@return Tunes


protected function getPhotos($galleryId)
    {
        if (! is_null($ids = $this->fetchIds($galleryId))) {
            return array_map([$this, 'getPhoto'], $ids);
        }
    }

protected function getPhotos ( $ galleryId ) { if ( ! is_null ( $ ids = $ this -> fetchIds ( $ galleryId ) ) ) { return array_map ( [ $ this , 'getPhoto' ] , $ ids ) ; } }

Returns all photo currently available in a gallery.

@return array|null

Returns all photo currently available in a gallery .


function log($level, $msg, $append_crlf = true)
    {
        if ($this->debug >= $level) {
            if (!class_exists('PEAR_Frontend')) {
                require_once 'PEAR/Frontend.php';
            }

            $ui = &PEAR_Frontend::singleton();
            if (is_a($ui, 'PEAR_Frontend')) {
                $ui->log($msg, $append_crlf);
            } else {
                print "$msg\n";
            }
        }
    }

function log ( $ level , $ msg , $ append_crlf = true ) { if ( $ this -> debug >= $ level ) { if ( ! class_exists ( 'PEAR_Frontend' ) ) { require_once 'PEAR/Frontend.php' ; } $ ui = & PEAR_Frontend :: singleton ( ) ; if ( is_a ( $ ui , 'PEAR_Frontend' ) ) { $ ui -> log ( $ msg , $ append_crlf ) ; } else { print "$msg\n" ; } } }

Logging method.

@param int    $level  log level (0 is quiet, higher is noisier)
@param string $msg    message to write to the log

@return void

@access public
@static


function mkTempDir($tmpdir = '')
    {
        $topt = $tmpdir ? array('-t', $tmpdir) : array();
        $topt = array_merge($topt, array('-d', 'pear'));
        if (!class_exists('System')) {
            require_once 'System.php';
        }

        if (!$tmpdir = System::mktemp($topt)) {
            return false;
        }

        $this->addTempFile($tmpdir);
        return $tmpdir;
    }

function mkTempDir ( $ tmpdir = '' ) { $ topt = $ tmpdir ? array ( '-t' , $ tmpdir ) : array ( ) ; $ topt = array_merge ( $ topt , array ( '-d' , 'pear' ) ) ; if ( ! class_exists ( 'System' ) ) { require_once 'System.php' ; } if ( ! $ tmpdir = System :: mktemp ( $ topt ) ) { return false ; } $ this -> addTempFile ( $ tmpdir ) ; return $ tmpdir ; }

Create and register a temporary directory.

@param string $tmpdir (optional) Directory to use as tmpdir.
Will use system defaults (for example
/tmp or c:\windows\temp) if not specified

@return string name of created directory

@access public

Create and register a temporary directory .


function infoFromTgzFile($file)
    {
        $packagefile = &new PEAR_PackageFile($this->config);
        $pf = &$packagefile->fromTgzFile($file, PEAR_VALIDATE_NORMAL);
        return $this->_postProcessChecks($pf);
    }

function infoFromTgzFile ( $ file ) { $ packagefile = & new PEAR_PackageFile ( $ this -> config ) ; $ pf = & $ packagefile -> fromTgzFile ( $ file , PEAR_VALIDATE_NORMAL ) ; return $ this -> _postProcessChecks ( $ pf ) ; }

Returns information about a package file.  Expects the name of
a gzipped tar file as input.

@param string  $file  name of .tgz file

@return array  array with package information

@access public
@deprecated use PEAR_PackageFile->fromTgzFile() instead

Returns information about a package file . Expects the name of a gzipped tar file as input .


function infoFromDescriptionFile($descfile)
    {
        $packagefile = &new PEAR_PackageFile($this->config);
        $pf = &$packagefile->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL);
        return $this->_postProcessChecks($pf);
    }

function infoFromDescriptionFile ( $ descfile ) { $ packagefile = & new PEAR_PackageFile ( $ this -> config ) ; $ pf = & $ packagefile -> fromPackageFile ( $ descfile , PEAR_VALIDATE_NORMAL ) ; return $ this -> _postProcessChecks ( $ pf ) ; }

Returns information about a package file.  Expects the name of
a package xml file as input.

@param string  $descfile  name of package xml file

@return array  array with package information

@access public
@deprecated use PEAR_PackageFile->fromPackageFile() instead

Returns information about a package file . Expects the name of a package xml file as input .


function infoFromString($data)
    {
        $packagefile = &new PEAR_PackageFile($this->config);
        $pf = &$packagefile->fromXmlString($data, PEAR_VALIDATE_NORMAL, false);
        return $this->_postProcessChecks($pf);
    }

function infoFromString ( $ data ) { $ packagefile = & new PEAR_PackageFile ( $ this -> config ) ; $ pf = & $ packagefile -> fromXmlString ( $ data , PEAR_VALIDATE_NORMAL , false ) ; return $ this -> _postProcessChecks ( $ pf ) ; }

Returns information about a package file.  Expects the contents
of a package xml file as input.

@param string  $data  contents of package.xml file

@return array   array with package information

@access public
@deprecated use PEAR_PackageFile->fromXmlstring() instead

Returns information about a package file . Expects the contents of a package xml file as input .


function infoFromAny($info)
    {
        if (is_string($info) && file_exists($info)) {
            $packagefile = &new PEAR_PackageFile($this->config);
            $pf = &$packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL);
            if (PEAR::isError($pf)) {
                $errs = $pf->getUserinfo();
                if (is_array($errs)) {
                    foreach ($errs as $error) {
                        $e = $this->raiseError($error['message'], $error['code'], null, null, $error);
                    }
                }

                return $pf;
            }

            return $this->_postProcessValidPackagexml($pf);
        }

        return $info;
    }

function infoFromAny ( $ info ) { if ( is_string ( $ info ) && file_exists ( $ info ) ) { $ packagefile = & new PEAR_PackageFile ( $ this -> config ) ; $ pf = & $ packagefile -> fromAnyFile ( $ info , PEAR_VALIDATE_NORMAL ) ; if ( PEAR :: isError ( $ pf ) ) { $ errs = $ pf -> getUserinfo ( ) ; if ( is_array ( $ errs ) ) { foreach ( $ errs as $ error ) { $ e = $ this -> raiseError ( $ error [ 'message' ] , $ error [ 'code' ] , null , null , $ error ) ; } } return $ pf ; } return $ this -> _postProcessValidPackagexml ( $ pf ) ; } return $ info ; }

Returns package information from different sources

This method is able to extract information about a package
from a .tgz archive or from a XML package definition file.

@access public
@param  string Filename of the source ('package.xml', '<package>.tgz')
@return string
@deprecated use PEAR_PackageFile->fromAnyFile() instead


public function getWithOffers()
    {
        if ((int) $this->id <= 0) {
            throw new NullPointerException("Id is not set.");
        }

        // build url
        $url = $this->base_url . str_replace("{id}", $this->id, $this->_url_offers);
        // get data from server
        $data = $this->getDataFromUrl($url);
        // parse result set and get data as array
        $result = $this->parseJsonData($data);

        return $result;
    }

get article with defined Id with all stored offer data

@throws NullPointerException
@return mixed|array article with offer data


public function getAllWithOffers()
    {
        // build url
        $url = $this->base_url . $this->_url_all_offers;
        // get data from server
        $data = $this->getDataFromUrl($url);
        // parse result set and get data as array
        $result = $this->parseJsonData($data);

        return $result;
    }

get all articles with all stored offer data

@return mixed|array articles with offer data


public function search()
    {
        if (strlen($this->ean) <= 0) {
            throw new NullPointerException("EAN is not set.");
        }

        $params = array(
            "ean" => $this->ean
        );

        $url = $this->base_url . self::URL_SEARCH . "?" . http_build_query($params);

        // get data from server
        $data = $this->getDataFromUrl($url);
        // parse result set and get data as array
        $result = $this->parseJsonData($data);

        return $result;
    }

search article by EAN and return resultset

@return mixed|array article data


protected function setFileHandler(string $logFile, int $logLevel = null)
    {
        $this->logFile = $logFile;
        $stream = new StreamHandler($logFile, $logLevel);
        $this->pushHandler($stream);
    }

protected function setFileHandler ( string $ logFile , int $ logLevel = null ) { $ this -> logFile = $ logFile ; $ stream = new StreamHandler ( $ logFile , $ logLevel ) ; $ this -> pushHandler ( $ stream ) ; }

Set up a logger to write to logFile
@param string $logFile
@param int $logLevel


protected function setMailHandler(string $emailTo, string $emailSubject, string $emailFrom, int $logLevel)
    {
        $mail = new NativeMailerHandler($emailTo, $emailSubject, $emailFrom, $logLevel);
        $this->pushHandler($mail);
    }

protected function setMailHandler ( string $ emailTo , string $ emailSubject , string $ emailFrom , int $ logLevel ) { $ mail = new NativeMailerHandler ( $ emailTo , $ emailSubject , $ emailFrom , $ logLevel ) ; $ this -> pushHandler ( $ mail ) ; }

Set up the logger to send an email
@param string $emailTo
@param string $emailSubject
@param string $emailFrom
@param int $logLevel


public function getLogs(int $limit = 0)
    {
        if (!file_exists($this->logFile)) {
            return [];
        }
        $lineCount = 0;
        $fileAsc = file($this->logFile);
        $file = array_reverse($fileAsc);
        $arrOutput = [];
        foreach ($file as $row) {
            $currentRow = $this->makeLogRow($row);
            if (!$currentRow) {
                continue;
            }
            $arrOutput[] = $currentRow;
            $lineCount++;
            if ($lineCount > $limit && $limit > 0) {
                break;
            }
        }
        return $arrOutput;
    }

public function getLogs ( int $ limit = 0 ) { if ( ! file_exists ( $ this -> logFile ) ) { return [ ] ; } $ lineCount = 0 ; $ fileAsc = file ( $ this -> logFile ) ; $ file = array_reverse ( $ fileAsc ) ; $ arrOutput = [ ] ; foreach ( $ file as $ row ) { $ currentRow = $ this -> makeLogRow ( $ row ) ; if ( ! $ currentRow ) { continue ; } $ arrOutput [ ] = $ currentRow ; $ lineCount ++ ; if ( $ lineCount > $ limit && $ limit > 0 ) { break ; } } return $ arrOutput ; }

Reads a logfile line by line and makes it into an array
@param int $limit
@return array


protected function makeLogRow(string $row)
    {
        //[2017-07-22 23:06:48]
        $date = substr($row, 1, 19);
        if (!Validator::validateDate($date)) {
            return false;
        }
        $fullMsg = substr($row, 22);
        $arrMsg = explode(":", $fullMsg);
        $logLevel = $arrMsg[0];
        $msg = substr($fullMsg, strpos($fullMsg, ":")+2);
        $out = [
            "date" => $date,
            "level" => $logLevel,
            "msg" => $msg,
        ];
        return $out;
    }

protected
function
makeLogRow
(
string
$
row
)
{
//[2017-07-22 23:06:48]
$
date
=
substr
(
$
row
,
1
,
19
)
;
if
(
!
Validator
::
validateDate
(
$
date
)
)
{
return
false
;
}
$
fullMsg
=
substr
(
$
row
,
22
)
;
$
arrMsg
=
explode
(
":"
,
$
fullMsg
)
;
$
logLevel
=
$
arrMsg
[
0
]
;
$
msg
=
substr
(
$
fullMsg
,
strpos
(
$
fullMsg
,
":"
)
+
2
)
;
$
out
=
[
"date"
=>
$
date
,
"level"
=>
$
logLevel
,
"msg"
=>
$
msg
,
]
;
return
$
out
;
}

Creates an array from one log line
@param string $row
@return boolean|array


public function shutdown(&$arg = null, $callback = null)
    {
        if ($this->getDebug() && false===$this->is_shutdown) {
            return \DevDebug\Debugger::shutdown(true, $callback);
        }
    }

public function shutdown ( & $ arg = null , $ callback = null ) { if ( $ this -> getDebug ( ) && false === $ this -> is_shutdown ) { return \ DevDebug \ Debugger :: shutdown ( true , $ callback ) ; } }


public function handles(Request $request)
    {
        if (!$this->is_booted) {
            $this->boot();
        }
        $this->getContainer()->set('request', $request);
        $this->getContainer()->get('router')->setUrl($request->buildUrl());
        $mode_data = $this->getMode(true);
        if (isset($mode_data['log_requests']) && $mode_data['log_requests']) {
            \CarteBlanche\CarteBlanche::log(
                get_class($request).' :: '.$this->getContainer()->get('request')->getUrl(),
                \Library\Logger::INFO
            );
        }
        return $this;
    }

public
function
handles
(
Request
$
request
)
{
if
(
!
$
this
->
is_booted
)
{
$
this
->
boot
(
)
;
}
$
this
->
getContainer
(
)
->
set
(
'request'
,
$
request
)
;
$
this
->
getContainer
(
)
->
get
(
'router'
)
->
setUrl
(
$
request
->
buildUrl
(
)
)
;
$
mode_data
=
$
this
->
getMode
(
true
)
;
if
(
isset
(
$
mode_data
[
'log_requests'
]
)
&&
$
mode_data
[
'log_requests'
]
)
{
\
CarteBlanche
\
CarteBlanche
::
log
(
get_class
(
$
request
)
.
' :: '
.
$
this
->
getContainer
(
)
->
get
(
'request'
)
->
getUrl
(
)
,
\
Library
\
Logger
::
INFO
)
;
}
return
$
this
;
}

Defines the request to treat

@param   \CarteBlanche\App\Request   $request
@return  self


public function distribute()
    {
        if (!$this->is_booted) {
            $this->boot();
        }
        $req = $this->getContainer()->get('request');
        if (empty($req)) {
            $this->handles(new Request);
        }
        return $this->getContainer()->get('front_controller')
                ->distribute();
    }

public function distribute ( ) { if ( ! $ this -> is_booted ) { $ this -> boot ( ) ; } $ req = $ this -> getContainer ( ) -> get ( 'request' ) ; if ( empty ( $ req ) ) { $ this -> handles ( new Request ) ; } return $ this -> getContainer ( ) -> get ( 'front_controller' ) -> distribute ( ) ; }

Distributes the application actions, controllers and views

If no request is defined yet, this will handle current HTTP request if so.

@return string|void
@see \CarteBlanche\App\FrontController::distribute()

Distributes the application actions controllers and views


public function initBundle($space, $dir)
    {
        $bundle = new \CarteBlanche\App\Bundle($space, $dir);
        return $this->getContainer()->setBundle($space, $bundle);
    }

public function initBundle ( $ space , $ dir ) { $ bundle = new \ CarteBlanche \ App \ Bundle ( $ space , $ dir ) ; return $ this -> getContainer ( ) -> setBundle ( $ space , $ bundle ) ; }

Load a new bundle namespace and map it to its path

@param   string  $space
@param   string  $dir
@return  bool


public function addBootError($string)
    {
        $this->boot_errors[] = $string;
        if ($this->getMode()==='dev') {
            die(
                sprintf("[boot error] : %s", $string)
            );
        }
        return $this;
    }

public
function
addBootError
(
$
string
)
{
$
this
->
boot_errors
[
]
=
$
string
;
if
(
$
this
->
getMode
(
)
===
'dev'
)
{
die
(
sprintf
(
"[boot error] : %s"
,
$
string
)
)
;
}
return
$
this
;
}

Add a booting error

@param string $string
@return self


public function initConstantPath($cst, $path_ref, $must_exists = false, $must_be_writable = false)
    {
        if (defined($cst)) {
            $this->addPath($path_ref, constant($cst), $must_exists, $must_be_writable);
        } else {
            throw new ErrorException(
                sprintf('Missing constant path "%s"!', $cst)
            );
        }
        return $this;
    }

public
function
initConstantPath
(
$
cst
,
$
path_ref
,
$
must_exists
=
false
,
$
must_be_writable
=
false
)
{
if
(
defined
(
$
cst
)
)
{
$
this
->
addPath
(
$
path_ref
,
constant
(
$
cst
)
,
$
must_exists
,
$
must_be_writable
)
;
}
else
{
throw
new
ErrorException
(
sprintf
(
'Missing constant path "%s"!'
,
$
cst
)
)
;
}
return
$
this
;
}

Initialize a path from a constant

@param string $cst               A constant name
@param string $path_ref          The path reference
@param bool $must_exists         Check if concerned path exists
@param bool $must_be_writable    Check if concerned path is writable
@return self

@throws ErrorException if the constant is not defined


public function addPath($name, $value, $must_exists = false, $must_be_writable = false)
    {
        $config = $this->getContainer()->get('config');
        if ($must_exists) {
            $realpath = $this->getAbsolutePath($value);
            if (!empty($realpath)) {
                $value = $realpath;
            } else {
                DirectoryHelper::ensureExists($value);
                if (!file_exists($value)) {
                    $this->addBootError(
                        sprintf('Directory "%s" defined as an application path doesn\'t exist and can\'t be created!', $value)
                    );
/*
                    throw new RuntimeException(
                        sprintf('Directory "%s" defined as an application path doesn\'t exist and can\'t be created!', $value)
                    );
*/
                }
            }
        }
        if ($must_be_writable && !is_writable($value)) {
           $this->addBootError(
                sprintf('Directory "%s" must be writable! (%s)', $value, $name)
            );
/*
            throw new RuntimeException(
                sprintf('Directory "%s" must be writable!', $value)
            );
*/
        }
        $config->getRegistry()
            ->loadStack('paths')
            ->setEntry($name, $value)
            ->saveStack('paths', true);
        return $this;
    }

References a path value

@param string $name              The path reference
@param string $value             The path value
@param bool $must_exists         Check if concerned path exists
@param bool $must_be_writable    Check if concerned path is writable
@return self

@throws RuntimeException if the path does not exists and `$must_exists` is true
@throws ErrorException if the concerned path is not writable while it was required


public function getPath($name, $full_path = false)
    {
        $config = $this->getContainer()->get('config');
        $path = $config->getRegistry()->getStackEntry($name, null, 'paths');
        if (file_exists($path) && is_dir($path)) {
            $path = DirectoryHelper::slashDirname($path);
        }
        if (true===$full_path) {
            return $this->getAbsolutePath($path);
        }
        return $path;
    }

public function getPath ( $ name , $ full_path = false ) { $ config = $ this -> getContainer ( ) -> get ( 'config' ) ; $ path = $ config -> getRegistry ( ) -> getStackEntry ( $ name , null , 'paths' ) ; if ( file_exists ( $ path ) && is_dir ( $ path ) ) { $ path = DirectoryHelper :: slashDirname ( $ path ) ; } if ( true === $ full_path ) { return $ this -> getAbsolutePath ( $ path ) ; } return $ path ; }

Get a path value

@param   string    $name       The path reference
@param   bool      $full_path  Must return an absolute path or not (default)
@return  string|null


public function getAbsolutePath($path)
    {
        $root = $this->getPath('root_path');
        if (empty($root)) {
            return null;
        }
        if (empty($path)) {
            return $root;
        }
        if (0===substr_count($path, $root)) {
            $path = DirectoryHelper::slashDirname($root).$path;
        }
        return file_exists($path) ? DirectoryHelper::slashDirname(realpath($path)) : null;
    }

public function getAbsolutePath ( $ path ) { $ root = $ this -> getPath ( 'root_path' ) ; if ( empty ( $ root ) ) { return null ; } if ( empty ( $ path ) ) { return $ root ; } if ( 0 === substr_count ( $ path , $ root ) ) { $ path = DirectoryHelper :: slashDirname ( $ root ) . $ path ; } return file_exists ( $ path ) ? DirectoryHelper :: slashDirname ( realpath ( $ path ) ) : null ; }

Build an app absolute path

@param   string    $path       The relative path to build
@return  string|null


public function whoAmI()
    {
        $cmd = new \Library\Command;
        $whoami = $cmd->run('whoami');
        return !empty($whoami[0]) ? $whoami[0] : null;
    }

public function whoAmI ( ) { $ cmd = new \ Library \ Command ; $ whoami = $ cmd -> run ( 'whoami' ) ; return ! empty ( $ whoami [ 0 ] ) ? $ whoami [ 0 ] : null ; }

Get current user name running the app

@return  string


private function __setMode($mode = 'dev')
    {
        $config = $this->getContainer()->get('config');
        $mode_data = $config->get('carte_blanche.modes', array(), 'app');

        if (array_key_exists($mode, $mode_data)) {
            $this->mode = strtolower($mode);
        } else {
            $this->mode = isset($mode_data['default']) ? strtolower($mode_data['default']) : 'dev';
        }

        if (isset($mode_data[$this->mode])) {
            $this->mode_data = $mode_data[$this->mode];
            if (isset($this->mode_data['display_errors'])) {
                @ini_set('display_errors',$this->mode_data['display_errors']);
            }
            if (isset($this->mode_data['error_reporting'])) {
                @error_reporting($this->mode_data['error_reporting']);
            }
            if (isset($this->mode_data['debug']) && $this->mode_data['debug']) {
                $this->setDebug(true);
            } else {
                $this->setDebug(false);
            }
        }
        return $this;
    }

private function __setMode ( $ mode = 'dev' ) { $ config = $ this -> getContainer ( ) -> get ( 'config' ) ; $ mode_data = $ config -> get ( 'carte_blanche.modes' , array ( ) , 'app' ) ; if ( array_key_exists ( $ mode , $ mode_data ) ) { $ this -> mode = strtolower ( $ mode ) ; } else { $ this -> mode = isset ( $ mode_data [ 'default' ] ) ? strtolower ( $ mode_data [ 'default' ] ) : 'dev' ; } if ( isset ( $ mode_data [ $ this -> mode ] ) ) { $ this -> mode_data = $ mode_data [ $ this -> mode ] ; if ( isset ( $ this -> mode_data [ 'display_errors' ] ) ) { @ ini_set ( 'display_errors' , $ this -> mode_data [ 'display_errors' ] ) ; } if ( isset ( $ this -> mode_data [ 'error_reporting' ] ) ) { @ error_reporting ( $ this -> mode_data [ 'error_reporting' ] ) ; } if ( isset ( $ this -> mode_data [ 'debug' ] ) && $ this -> mode_data [ 'debug' ] ) { $ this -> setDebug ( true ) ; } else { $ this -> setDebug ( false ) ; } } return $ this ; }

Define the current kernel mode

Launch settings according to the MODE config entry

@param string $mode
@return self


private function __loadDefaultConfig()
    {
        $app_cfgfile = __DIR__.'/../../../config/'.self::CARTE_BLANCHE_CONFIG_FILE;
        if (!file_exists($app_cfgfile)) {
            throw new ErrorException(
                sprintf('Default application configuration file not found in "%s" [%s]!', $this->getPath('config_dir'), $app_cfgfile)
            );
        }
        $this->getContainer()->get('config')->load($app_cfgfile);
    }

Load the default configuration file

@throws \CarteBlanche\Exception\ErrorException


public function init()
    {
        parent::init();
        $this->basePath = Reaction::$app->getAlias($this->basePath);
        if (!is_dir($this->basePath)) {
            throw new InvalidConfigException("The directory does not exist: {$this->basePath}");
        } elseif (!is_writable($this->basePath)) {
            throw new InvalidConfigException("The directory is not writable by the Web process: {$this->basePath}");
        }

        $this->basePath = realpath($this->basePath);
        $this->baseUrl = rtrim(Reaction::$app->getAlias($this->baseUrl), '/');
    }

Initializes the component.
@throws InvalidConfigException if [[basePath]] is invalid


protected function loadBundle($name, $config = [], $publish = true)
    {
        if (!isset($config['class'])) {
            $config['class'] = $name;
        }
        /* @var $bundle AssetBundle */
        $bundle = Reaction::create($config);
        if ($publish) {
            $bundle->publish($this);
        }

        return $bundle;
    }

protected
function
loadBundle
(
$
name
,
$
config
=
[
]
,
$
publish
=
true
)
{
if
(
!
isset
(
$
config
[
'class'
]
)
)
{
$
config
[
'class'
]
=
$
name
;
}
/* @var $bundle AssetBundle */
$
bundle
=
Reaction
::
create
(
$
config
)
;
if
(
$
publish
)
{
$
bundle
->
publish
(
$
this
)
;
}
return
$
bundle
;
}

Loads asset bundle class by name.

@param string $name bundle name
@param array  $config bundle object configuration
@param bool   $publish if bundle should be published
@return AssetBundle
@throws InvalidConfigException if configuration isn't valid
@throws \ReflectionException


public function getConverter()
    {
        if ($this->_converter === null) {
            $this->_converter = Reaction::create(AssetConverter::class);
        } elseif (is_array($this->_converter) || is_string($this->_converter)) {
            if (is_array($this->_converter) && !isset($this->_converter['class'])) {
                $this->_converter['class'] = AssetConverter::class;
            }
            $this->_converter = Reaction::create($this->_converter);
        }

        return $this->_converter;
    }

public function getConverter ( ) { if ( $ this -> _converter === null ) { $ this -> _converter = Reaction :: create ( AssetConverter :: class ) ; } elseif ( is_array ( $ this -> _converter ) || is_string ( $ this -> _converter ) ) { if ( is_array ( $ this -> _converter ) && ! isset ( $ this -> _converter [ 'class' ] ) ) { $ this -> _converter [ 'class' ] = AssetConverter :: class ; } $ this -> _converter = Reaction :: create ( $ this -> _converter ) ; } return $ this -> _converter ; }

Returns the asset converter.
@return AssetConverterInterface the asset converter.


protected function hash($path)
    {
        if (is_callable($this->hashCallback)) {
            return call_user_func($this->hashCallback, $path);
        }
        $path = (is_file($path) ? dirname($path) : $path) . filemtime($path);
        return sprintf('%x', crc32($path . Reaction::getVersion() . '|' . $this->linkAssets));
    }

protected function hash ( $ path ) { if ( is_callable ( $ this -> hashCallback ) ) { return call_user_func ( $ this -> hashCallback , $ path ) ; } $ path = ( is_file ( $ path ) ? dirname ( $ path ) : $ path ) . filemtime ( $ path ) ; return sprintf ( '%x' , crc32 ( $ path . Reaction :: getVersion ( ) . '|' . $ this -> linkAssets ) ) ; }

Generate a CRC32 hash for the directory path. Collisions are higher
than MD5 but generates a much smaller hash string.
@param string $path string to be hashed.
@return string hashed string.

Generate a CRC32 hash for the directory path . Collisions are higher than MD5 but generates a much smaller hash string .


public function addReplytos(array $reply_tos)
    {
        foreach ($reply_tos as $key => $val) {
            if (is_numeric($key)) {
                $this->addReplyto($val);
            } else {
                $this->addReplyto($key, $val);
            }
        }
    }

public function addReplytos ( array $ reply_tos ) { foreach ( $ reply_tos as $ key => $ val ) { if ( is_numeric ( $ key ) ) { $ this -> addReplyto ( $ val ) ; } else { $ this -> addReplyto ( $ key , $ val ) ; } } }

Adds a list of contacts to the replytolist

@param array $reply_tos
List of contacts to add. This array can be an indexed array with only
the contacts mailaddress or an assoc array with mailaddress as key and
the contacts name as value.


public function newUser($user, $pass, $email = '', $fname = '', $sname = '' , $admin = False){
        $hash = password_hash($pass, PASSWORD_BCRYPT);
        return $this->db->insert($this->prefix.'users', ['user' => $user, 'pass' => $hash, 'admin' => $admin, 'email' => $email, 'first_name' => $fname, 'surname' => $sname]) ? $this->db->id() : False;
    }

public function newUser ( $ user , $ pass , $ email = '' , $ fname = '' , $ sname = '' , $ admin = False ) { $ hash = password_hash ( $ pass , PASSWORD_BCRYPT ) ; return $ this -> db -> insert ( $ this -> prefix . 'users' , [ 'user' => $ user , 'pass' => $ hash , 'admin' => $ admin , 'email' => $ email , 'first_name' => $ fname , 'surname' => $ sname ] ) ? $ this -> db -> id ( ) : False ; }

Creates a new user with the provided details


public function resumeSession($authtoken)
    {
        if( $id = $this->db->get($this->prefix.'authtokens', 'user_id', ['token'=>$authtoken]) )
            $this->user = new User($this, $id);
        else
            return False;
    }

public function resumeSession ( $ authtoken ) { if ( $ id = $ this -> db -> get ( $ this -> prefix . 'authtokens' , 'user_id' , [ 'token' => $ authtoken ] ) ) $ this -> user = new User ( $ this , $ id ) ; else return False ; }

Runs when the library is loaded to authenticate and resume the user session


public function calculate($expression)
    {
        $translatedExpression = $this->translate($expression);
        $result = eval('return '.$translatedExpression.';');

        $decimalResult = new Number($result); // this is bad and needs some work

        return $decimalResult->convert($this->numberSystem);
    }

public
function
calculate
(
$
expression
)
{
$
translatedExpression
=
$
this
->
translate
(
$
expression
)
;
$
result
=
eval
(
'return '
.
$
translatedExpression
.
';'
)
;
$
decimalResult
=
new
Number
(
$
result
)
;
// this is bad and needs some work
return
$
decimalResult
->
convert
(
$
this
->
numberSystem
)
;
}

Calculate a mathematical expression that uses pokemath-numbers

@param $expression

@return Number

Calculate a mathematical expression that uses pokemath - numbers


public function urlUserDetails(\League\OAuth2\Client\Token\AccessToken $token)
    {
        return $this->domain . '/api/userinfo?access_token=' . $token;
    }

public function urlUserDetails ( \ League \ OAuth2 \ Client \ Token \ AccessToken $ token ) { return $ this -> domain . '/api/userinfo?access_token=' . $ token ; }

Get provider URL to fetch user details

@param AccessToken $token
@return string


public function raw($sql, array $values = [], $class = null)
    {
        return $this->execute($sql, $values, function(\PDOStatement $statement) use($class)
        {
            if($statement->columnCount() > 0) {
                return $class
                    ? $statement->fetchAll(\PDO::FETCH_CLASS | \PDO::FETCH_PROPS_LATE, $class)
                    : $statement->fetchAll(\PDO::FETCH_OBJ);
            }

            return $statement->rowCount();
        });
    }

public function raw ( $ sql , array $ values = [ ] , $ class = null ) { return $ this -> execute ( $ sql , $ values , function ( \ PDOStatement $ statement ) use ( $ class ) { if ( $ statement -> columnCount ( ) > 0 ) { return $ class ? $ statement -> fetchAll ( \ PDO :: FETCH_CLASS | \ PDO :: FETCH_PROPS_LATE , $ class ) : $ statement -> fetchAll ( \ PDO :: FETCH_OBJ ) ; } return $ statement -> rowCount ( ) ; } ) ; }

Execute raw query

@param string $sql
@param array $values
@param string $class
@return mixed


public static function csrfMetaTags(RequestApplicationInterface $app)
    {
        $encoding = $app->charset;
        if ($app->reqHelper->enableCsrfValidation) {
            return static::tag('meta', '', ['name' => 'csrf-param', 'content' => $app->reqHelper->csrfParam], $encoding) . "\n    "
                . static::tag('meta', '', ['name' => 'csrf-token', 'content' => $app->reqHelper->getCsrfToken()], $encoding) . "\n";
        }

        return '';
    }

public
static
function
csrfMetaTags
(
RequestApplicationInterface
$
app
)
{
$
encoding
=
$
app
->
charset
;
if
(
$
app
->
reqHelper
->
enableCsrfValidation
)
{
return
static
::
tag
(
'meta'
,
''
,
[
'name'
=>
'csrf-param'
,
'content'
=>
$
app
->
reqHelper
->
csrfParam
]
,
$
encoding
)
.
"\n    "
.
static
::
tag
(
'meta'
,
''
,
[
'name'
=>
'csrf-token'
,
'content'
=>
$
app
->
reqHelper
->
getCsrfToken
(
)
]
,
$
encoding
)
.
"\n"
;
}
return
''
;
}

Generates the meta tags containing CSRF token information.
@param RequestApplicationInterface $app
@return string the generated meta tags
@see \Reaction\Web\RequestHelper::enableCsrfValidation

Generates the meta tags containing CSRF token information .


public static function label($content, $for = null, $options = [], $encoding = null)
    {
        $options['for'] = $for;
        return static::tag('label', $content, $options, $encoding);
    }

public static function label ( $ content , $ for = null , $ options = [ ] , $ encoding = null ) { $ options [ 'for' ] = $ for ; return static :: tag ( 'label' , $ content , $ options , $ encoding ) ; }

Generates a label tag.
@param string $content label text. It will NOT be HTML-encoded. Therefore you can pass in HTML code
such as an image tag. If this is is coming from end users, you should [[encode()]]
it to prevent XSS attacks.
@param string $for the ID of the HTML element that this label is associated with.
If this is null, the "for" attribute will not be generated.
@param array  $options the tag options in terms of name-value pairs. These will be rendered as
the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
If a value is null, the corresponding attribute will not be rendered.
See [[renderTagAttributes()]] for details on how attributes are being rendered.
@param string $encoding
@return string the generated label tag


public static function button($content = 'Button', $options = [], $encoding = null)
    {
        if (!isset($options['type'])) {
            $options['type'] = 'button';
        }

        return static::tag('button', $content, $options, $encoding);
    }

public static function button ( $ content = 'Button' , $ options = [ ] , $ encoding = null ) { if ( ! isset ( $ options [ 'type' ] ) ) { $ options [ 'type' ] = 'button' ; } return static :: tag ( 'button' , $ content , $ options , $ encoding ) ; }

Generates a button tag.
@param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
you should consider [[encode()]] it to prevent XSS attacks.
@param array  $options the tag options in terms of name-value pairs. These will be rendered as
the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
If a value is null, the corresponding attribute will not be rendered.
See [[renderTagAttributes()]] for details on how attributes are being rendered.
@param string $encoding
@return string the generated button tag


public static function submitButton($content = 'Submit', $options = [], $encoding = null)
    {
        $options['type'] = 'submit';
        return static::button($content, $options, $encoding);
    }

public static function submitButton ( $ content = 'Submit' , $ options = [ ] , $ encoding = null ) { $ options [ 'type' ] = 'submit' ; return static :: button ( $ content , $ options , $ encoding ) ; }

Generates a submit button tag.

Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.

@param string $content the content enclosed within the button tag. It will NOT be HTML-encoded.
Therefore you can pass in HTML code such as an image tag. If this is is coming from end users,
you should consider [[encode()]] it to prevent XSS attacks.
@param array $options the tag options in terms of name-value pairs. These will be rendered as
the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
If a value is null, the corresponding attribute will not be rendered.
See [[renderTagAttributes()]] for details on how attributes are being rendered.
@param string $encoding
@return string the generated submit button tag


public static function submitInput($label = 'Submit', $options = [], $encoding = null)
    {
        $options['type'] = 'submit';
        $options['value'] = $label;
        return static::tag('input', '', $options, $encoding);
    }

public static function submitInput ( $ label = 'Submit' , $ options = [ ] , $ encoding = null ) { $ options [ 'type' ] = 'submit' ; $ options [ 'value' ] = $ label ; return static :: tag ( 'input' , '' , $ options , $ encoding ) ; }

Generates a submit input button.

Be careful when naming form elements such as submit buttons. According to the [jQuery documentation](https://api.jquery.com/submit/) there
are some reserved names that can cause conflicts, e.g. `submit`, `length`, or `method`.

@param string $label the value attribute. If it is null, the value attribute will not be generated.
@param array  $options the tag options in terms of name-value pairs. These will be rendered as
the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
If a value is null, the corresponding attribute will not be rendered.
See [[renderTagAttributes()]] for details on how attributes are being rendered.
@param string $encoding
@return string the generated button tag


public static function resetInput($label = 'Reset', $options = [], $encoding = null)
    {
        $options['type'] = 'reset';
        $options['value'] = $label;
        return static::tag('input', '', $options, $encoding);
    }

public static function resetInput ( $ label = 'Reset' , $ options = [ ] , $ encoding = null ) { $ options [ 'type' ] = 'reset' ; $ options [ 'value' ] = $ label ; return static :: tag ( 'input' , '' , $ options , $ encoding ) ; }

Generates a reset input button.
@param string $label the value attribute. If it is null, the value attribute will not be generated.
@param array  $options the attributes of the button tag. The values will be HTML-encoded using [[encode()]].
Attributes whose value is null will be ignored and not put in the tag returned.
See [[renderTagAttributes()]] for details on how attributes are being rendered.
@param string $encoding
@return string the generated button tag


public static function hiddenInput($name, $value = null, $options = [], $encoding = null)
    {
        return static::input('hidden', $name, $value, $options, $encoding);
    }

public static function hiddenInput ( $ name , $ value = null , $ options = [ ] , $ encoding = null ) { return static :: input ( 'hidden' , $ name , $ value , $ options , $ encoding ) ; }

Generates a hidden input field.
@param string $name the name attribute.
@param string $value the value attribute. If it is null, the value attribute will not be generated.
@param array $options the tag options in terms of name-value pairs. These will be rendered as
the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
If a value is null, the corresponding attribute will not be rendered.
See [[renderTagAttributes()]] for details on how attributes are being rendered.
@param string $encoding
@return string the generated hidden input tag


public static function passwordInput($name, $value = null, $options = [], $encoding = null)
    {
        return static::input('password', $name, $value, $options, $encoding);
    }

public static function passwordInput ( $ name , $ value = null , $ options = [ ] , $ encoding = null ) { return static :: input ( 'password' , $ name , $ value , $ options , $ encoding ) ; }

Generates a password input field.
@param string $name the name attribute.
@param string $value the value attribute. If it is null, the value attribute will not be generated.
@param array  $options the tag options in terms of name-value pairs. These will be rendered as
the attributes of the resulting tag. The values will be HTML-encoded using [[encode()]].
If a value is null, the corresponding attribute will not be rendered.
See [[renderTagAttributes()]] for details on how attributes are being rendered.
@param string $encoding
@return string the generated password input tag


protected static function processBooleanInputOptions($name, &$options) {
        if(isset($options['label'])) {
            $options['labelOptions'] = isset($options['labelOptions']) ? $options['labelOptions'] : [];
            Html::addCssClass($options['labelOptions'], ['widget' => 'form-check-label']);
        }
        Html::addCssClass($options, ['widget' => 'form-check-input']);
        if(!isset($options['id'])) {
            $idMain = strtolower(str_replace(['[]', '][', '[', ']', ' ', '.'], ['', '-', '-', '', '-', '-'], $name));
            $options['id'] = $idMain . '-opt-' . $options['value'];
        }
    }

protected
static
function
processBooleanInputOptions
(
$
name
,
&
$
options
)
{
if
(
isset
(
$
options
[
'label'
]
)
)
{
$
options
[
'labelOptions'
]
=
isset
(
$
options
[
'labelOptions'
]
)
$
options
[
'labelOptions'
]
:
[
]
;
Html
::
addCssClass
(
$
options
[
'labelOptions'
]
,
[
'widget'
=>
'form-check-label'
]
)
;
}
Html
::
addCssClass
(
$
options
,
[
'widget'
=>
'form-check-input'
]
)
;
if
(
!
isset
(
$
options
[
'id'
]
)
)
{
$
idMain
=
strtolower
(
str_replace
(
[
'[]'
,
']['
,
'['
,
']'
,
' '
,
'.'
]
,
[
''
,
'-'
,
'-'
,
''
,
'-'
,
'-'
]
,
$
name
)
)
;
$
options
[
'id'
]
=
$
idMain
.
'-opt-'
.
$
options
[
'value'
]
;
}
}

Process checkbox and radio options array
@param string $name
@param array $options


public function setHours(int $hours): void
    {
        $this->timeElementsAreValid($hours, $this->minutes, $this->seconds);

        $this->hours = $hours;
    }

public function setHours ( int $ hours ) : void { $ this -> timeElementsAreValid ( $ hours , $ this -> minutes , $ this -> seconds ) ; $ this -> hours = $ hours ; }

Set the hours.

@param integer $hours The hours.


public function setMinutes(int $minutes): void
    {
        $this->timeElementsAreValid($this->hours, $minutes, $this->seconds);

        $this->minutes = $minutes;
    }

public function setMinutes ( int $ minutes ) : void { $ this -> timeElementsAreValid ( $ this -> hours , $ minutes , $ this -> seconds ) ; $ this -> minutes = $ minutes ; }

Set the minutes.

@param integer $minutes The minutes


public function setSeconds(int $seconds): void
    {
        $this->timeElementsAreValid($this->hours, $this->minutes, $seconds);

        $this->seconds = $seconds;
    }

public function setSeconds ( int $ seconds ) : void { $ this -> timeElementsAreValid ( $ this -> hours , $ this -> minutes , $ seconds ) ; $ this -> seconds = $ seconds ; }

Set the seconds.

@param integer $seconds The seconds.


private function timeElementsAreValid($hours, $minutes, $seconds): bool
    {
        $exception = new \InvalidArgumentException(
            \sprintf('Invalid time "%02d:%02d:%02d".', $hours, $minutes, $seconds)
        );

        if ((int)\sprintf('%d%02d%02d', $hours, $minutes, $seconds) > 240000) {
            throw $exception;
        }
        if ($hours < 0 || $minutes < 0 || $seconds < 0) {
            throw $exception;
        }
        if ($hours <= 24 && $minutes <= 59 && $seconds <= 59) {
            return true;
        }

        throw $exception;
    }

private
function
timeElementsAreValid
(
$
hours
,
$
minutes
,
$
seconds
)
:
bool
{
$
exception
=
new
\
InvalidArgumentException
(
\
sprintf
(
'Invalid time "%02d:%02d:%02d".'
,
$
hours
,
$
minutes
,
$
seconds
)
)
;
if
(
(
int
)
\
sprintf
(
'%d%02d%02d'
,
$
hours
,
$
minutes
,
$
seconds
)
>
240000
)
{
throw
$
exception
;
}
if
(
$
hours
<
0
||
$
minutes
<
0
||
$
seconds
<
0
)
{
throw
$
exception
;
}
if
(
$
hours
<=
24
&&
$
minutes
<=
59
&&
$
seconds
<=
59
)
{
return
true
;
}
throw
$
exception
;
}

Check if the time elements are valid.

@param integer $hours The hours.
@param integer $minutes The minutes.
@param integer $seconds The seconds.
@return boolean
@throws \InvalidArgumentException If the elements are not valid.


public function write(string $path, string $contents): bool
    {
        return $this->flySystem->write($path, $contents);
    }

public function write ( string $ path , string $ contents ) : bool { return $ this -> flySystem -> write ( $ path , $ contents ) ; }

Write a file.

@param string $path     The path
@param string $contents The contents

@throws \League\Flysystem\FileExistsException

@return bool


public function writeStream(string $path, $resource): bool
    {
        return $this->flySystem->writeStream($path, $resource);
    }

public function writeStream ( string $ path , $ resource ) : bool { return $ this -> flySystem -> writeStream ( $ path , $ resource ) ; }

Write a file with a stream.

@param string   $path     The path
@param resource $resource The resource

@throws \InvalidArgumentException
@throws \League\Flysystem\FileExistsException

@return bool


public function update(string $path, string $contents): bool
    {
        return $this->flySystem->update($path, $contents);
    }

public function update ( string $ path , string $ contents ) : bool { return $ this -> flySystem -> update ( $ path , $ contents ) ; }

Update an existing file.

@param string $path     The path
@param string $contents The contents

@throws \League\Flysystem\FileNotFoundException

@return bool


public function updateStream(string $path, $resource): bool
    {
        return $this->flySystem->updateStream($path, $resource);
    }

public function updateStream ( string $ path , $ resource ) : bool { return $ this -> flySystem -> updateStream ( $ path , $ resource ) ; }

Update an existing file with a stream.

@param string   $path     The path
@param resource $resource The resource

@throws \InvalidArgumentException
@throws \League\Flysystem\FileNotFoundException

@return bool


public function put(string $path, string $contents): bool
    {
        return $this->flySystem->put($path, $contents);
    }

public function put ( string $ path , string $ contents ) : bool { return $ this -> flySystem -> put ( $ path , $ contents ) ; }

Write a file or update a file depending on existence.

@param string $path     The path
@param string $contents The contents

@return bool

Write a file or update a file depending on existence .


public function putStream(string $path, $resource): bool
    {
        return $this->flySystem->putStream($path, $resource);
    }

public function putStream ( string $ path , $ resource ) : bool { return $ this -> flySystem -> putStream ( $ path , $ resource ) ; }

Write a file or update a file depending on existence with a stream.

@param string   $path     The path
@param resource $resource The resource

@throws \InvalidArgumentException

@return bool

Write a file or update a file depending on existence with a stream .


public function rename(string $path, string $newPath): bool
    {
        return $this->flySystem->rename($path, $newPath);
    }

public function rename ( string $ path , string $ newPath ) : bool { return $ this -> flySystem -> rename ( $ path , $ newPath ) ; }

Rename a file.

@param string $path    The existing path
@param string $newPath The new path

@throws \League\Flysystem\FileExistsException
@throws \League\Flysystem\FileNotFoundException

@return bool


public function copy(string $path, string $newPath): bool
    {
        return $this->flySystem->copy($path, $newPath);
    }

public function copy ( string $ path , string $ newPath ) : bool { return $ this -> flySystem -> copy ( $ path , $ newPath ) ; }

Copy a file.

@param string $path    The existing path
@param string $newPath The new path

@throws \League\Flysystem\FileExistsException
@throws \League\Flysystem\FileNotFoundException

@return bool


public function metadata(string $path): ? array
    {
        $metadata = $this->flySystem->getMetadata($path);

        return false !== $metadata ? $metadata : null;
    }

public function metadata ( string $ path ) : ? array { $ metadata = $ this -> flySystem -> getMetadata ( $ path ) ; return false !== $ metadata ? $ metadata : null ; }

Get a file's meta data.

@param string $path The path

@throws \League\Flysystem\FileNotFoundException

@return array|null An array of meta data or null on failure


public function mimetype(string $path): ? string
    {
        $mimetype = $this->flySystem->getMimetype($path);

        return false !== $mimetype ? $mimetype : null;
    }

public function mimetype ( string $ path ) : ? string { $ mimetype = $ this -> flySystem -> getMimetype ( $ path ) ; return false !== $ mimetype ? $ mimetype : null ; }

Get a file's mime type.

@param string $path The path

@throws \League\Flysystem\FileNotFoundException

@return string|null The mime type or null on failure


public function size(string $path): ? int
    {
        $size = $this->flySystem->getSize($path);

        return false !== $size ? $size : null;
    }

public function size ( string $ path ) : ? int { $ size = $ this -> flySystem -> getSize ( $ path ) ; return false !== $ size ? $ size : null ; }

Get a file's size.

@param string $path The path

@return int|null The size in bytes or null on failure


public function timestamp(string $path): ? int
    {
        $timestamp = $this->flySystem->getTimestamp($path);

        return false !== $timestamp ? $timestamp : null;
    }

public function timestamp ( string $ path ) : ? int { $ timestamp = $ this -> flySystem -> getTimestamp ( $ path ) ; return false !== $ timestamp ? $ timestamp : null ; }

Get a file's timestamp.

@param string $path The path

@throws \League\Flysystem\FileNotFoundException

@return int|null The timestamp or null on failure


public function visibility(string $path): ? string
    {
        $visibility = $this->flySystem->getVisibility($path);

        return false !== $visibility ? $visibility : null;
    }

public function visibility ( string $ path ) : ? string { $ visibility = $ this -> flySystem -> getVisibility ( $ path ) ; return false !== $ visibility ? $ visibility : null ; }

Get a file's visibility.

@param string $path The path

@throws \League\Flysystem\FileNotFoundException

@return string|null
The visibility ('public' or 'private') or null on failure


public function setVisibility(string $path, Visibility $visibility): bool
    {
        return $this->flySystem->setVisibility($path, $visibility->getValue());
    }

public function setVisibility ( string $ path , Visibility $ visibility ) : bool { return $ this -> flySystem -> setVisibility ( $ path , $ visibility -> getValue ( ) ) ; }

Set a file's visibility.

@param string     $path       The path
@param Visibility $visibility The visibility

@return bool


public function setVisibilityPublic(string $path): bool
    {
        return $this->flySystem->setVisibility($path, Visibility::PUBLIC);
    }

public function setVisibilityPublic ( string $ path ) : bool { return $ this -> flySystem -> setVisibility ( $ path , Visibility :: PUBLIC ) ; }

Set a file's visibility to public.

@param string $path The path

@return bool


public function setVisibilityPrivate(string $path): bool
    {
        return $this->flySystem->setVisibility($path, Visibility::PRIVATE);
    }

public function setVisibilityPrivate ( string $ path ) : bool { return $ this -> flySystem -> setVisibility ( $ path , Visibility :: PRIVATE ) ; }

Set a file's visibility to private.

@param string $path The path

@return bool


public function listContents(string $directory = null, bool $recursive = false): array
    {
        return $this->flySystem->listContents($directory ?? '', $recursive);
    }

public function listContents ( string $ directory = null , bool $ recursive = false ) : array { return $ this -> flySystem -> listContents ( $ directory ?? '' , $ recursive ) ; }

List the contents of a directory.

@param string $directory [optional] The directory
@param bool   $recursive [optional] Whether to recurse through the
directory

@return array


protected function localAdapter(): Local
    {
        return self::$adapters['local']
            ?? self::$adapters['local'] = new Local(
                $this->app->config()['filesystem']['adapters']['s3']['dir']
            );
    }

protected function localAdapter ( ) : Local { return self :: $ adapters [ 'local' ] ?? self :: $ adapters [ 'local' ] = new Local ( $ this -> app -> config ( ) [ 'filesystem' ] [ 'adapters' ] [ 's3' ] [ 'dir' ] ) ; }

Get the local flysystem adapter.

@throws \LogicException

@return \League\Flysystem\Adapter\Local


protected function s3Adapter(): AwsS3Adapter
    {
        if (isset(self::$adapters['s3'])) {
            return self::$adapters['s3'];
        }

        $config       = $this->app->config()['filesystem']['adapters']['s3'];
        $clientConfig = [
            'credentials' => [
                'key'    => $config['key'],
                'secret' => $config['secret'],
            ],
            'region'      => $config['region'],
            'version'     => $config['version'],
        ];

        self::$adapters['s3'] = new AwsS3Adapter(
            new S3Client($clientConfig),
            $config['bucket'],
            $config['dir']
        );

        return self::$adapters['s3'];
    }

protected function s3Adapter ( ) : AwsS3Adapter { if ( isset ( self :: $ adapters [ 's3' ] ) ) { return self :: $ adapters [ 's3' ] ; } $ config = $ this -> app -> config ( ) [ 'filesystem' ] [ 'adapters' ] [ 's3' ] ; $ clientConfig = [ 'credentials' => [ 'key' => $ config [ 'key' ] , 'secret' => $ config [ 'secret' ] , ] , 'region' => $ config [ 'region' ] , 'version' => $ config [ 'version' ] , ] ; self :: $ adapters [ 's3' ] = new AwsS3Adapter ( new S3Client ( $ clientConfig ) , $ config [ 'bucket' ] , $ config [ 'dir' ] ) ; return self :: $ adapters [ 's3' ] ; }

Get the s3 flysystem adapter.

@throws \InvalidArgumentException

@return \League\Flysystem\AwsS3v3\AwsS3Adapter


protected function processRequest()
    {
        if (!Reaction::$app->getI18n()->detectLanguageByUrl) {
            return;
        }
        $langPrefixes = Reaction::$app->getI18n()->languagePrefixes;
        $rawUrl = trim($this->app->reqHelper->getPathInfo(), '/');
        $requestPrefix = '';
        $rawUrlParts = explode('/', $rawUrl);
        if (!empty($rawUrlParts) && isset($langPrefixes[$rawUrlParts[0]])) {
            $requestPrefix = $rawUrlParts[0];
            $this->baseUrl = $requestPrefix;
            array_shift($rawUrlParts);
        }
        $rawUrl = '/' . trim(implode('/', $rawUrlParts), '/');
        $requestLanguage = $langPrefixes[$requestPrefix];
        $this->app->reqHelper->setPathInfo($rawUrl);
        $this->app->language = $requestLanguage;
    }

protected function processRequest ( ) { if ( ! Reaction :: $ app -> getI18n ( ) -> detectLanguageByUrl ) { return ; } $ langPrefixes = Reaction :: $ app -> getI18n ( ) -> languagePrefixes ; $ rawUrl = trim ( $ this -> app -> reqHelper -> getPathInfo ( ) , '/' ) ; $ requestPrefix = '' ; $ rawUrlParts = explode ( '/' , $ rawUrl ) ; if ( ! empty ( $ rawUrlParts ) && isset ( $ langPrefixes [ $ rawUrlParts [ 0 ] ] ) ) { $ requestPrefix = $ rawUrlParts [ 0 ] ; $ this -> baseUrl = $ requestPrefix ; array_shift ( $ rawUrlParts ) ; } $ rawUrl = '/' . trim ( implode ( '/' , $ rawUrlParts ) , '/' ) ; $ requestLanguage = $ langPrefixes [ $ requestPrefix ] ; $ this -> app -> reqHelper -> setPathInfo ( $ rawUrl ) ; $ this -> app -> language = $ requestLanguage ; }


public function deserializeRequest($className)
    {
        $request = $this->app["request_stack"]->getCurrentRequest();

        return $this->app["serializer"]->deserialize(
            $request->getContent(),
            $className,
            $request->getContentType(),
            $this->app["conneg.deserializationContext"]
        );
    }

public function deserializeRequest ( $ className ) { $ request = $ this -> app [ "request_stack" ] -> getCurrentRequest ( ) ; return $ this -> app [ "serializer" ] -> deserialize ( $ request -> getContent ( ) , $ className , $ request -> getContentType ( ) , $ this -> app [ "conneg.deserializationContext" ] ) ; }

This method retrieves the request body in any supported format and deserializes it.

@param string $className
@return object

This method retrieves the request body in any supported format and deserializes it .


private static function checkAccess($object,$errorMessage){

    	if(is_string($object)){
    		$className = $object;
    		$object = null;
    	}else{
    		$className = get_class($object);
    	}

    	if(TransactionManager::isSuperUser()){
    		return true;
    	}

    	$hasAccess = false;
    	$hasAccessChecks = false;
    	try{
    		TransactionManager::startTransaction(null,true);

    		$debugBacktraces = debug_backtrace(false);
    		$args = null;
    		$function = null;
    		foreach($debugBacktraces as $debugBacktrace){
    			if($debugBacktrace["class"] == $className){
    				$args = $debugBacktrace["args"];
    				$function = $debugBacktrace["function"];
    				break;
    			}
    		}

    		$accessAnnotations = self::getAccessAnnotation($className, $function);

    		if(is_array($accessAnnotations) && count($accessAnnotations) > 0){
    			$hasAccessChecks = true;

    			//
    			// access annotations will be of the form
    			// array(
    			//      "key1|value1",
    			//      "key2|value2",
    			//      ...
    			//      "function|functionName"
    			// )
    			//
    			// Access is granted if session contains value for the specified key
    			// "function" is the special reserved key for which a function mentioned as value is called instead of checking for the value in session

    			// group access annotations by key
    			$accessMasks = array();
    			foreach ($accessAnnotations as $accessMask){
    				$accessMaskArr = preg_split('/\|/', $accessMask);
    				$accessMaskKey = $accessMaskArr[0];
    				$accessMaskValue = $accessMaskArr[1];
    				if(!array_key_exists($accessMaskKey, $accessMasks)){
    					$accessMaskValues = array();
    				}else{
    					$accessMaskValues = $accessMasks[$accessMaskKey];
    				}
    				$accessMaskValues[] = $accessMaskValue;
    				$accessMasks[$accessMaskKey] = $accessMaskValues;
    			}

    			$session = Factory::getSession();
    			foreach ($accessMasks as $accessKey=>$accessValues){
    				if($accessKey == "function"){
    					continue;
    				}
    				$sessionValues = $session->get($accessKey);

    				if(count(array_intersect($sessionValues, $accessValues)) > 0){
    					$hasAccess = true;
    					break;
    				}
    			}

    			if(!$hasAccess && array_key_exists("function", $accessMasks)){
    				foreach ($accessMasks["function"] as $function){
    					$result = Reflection::invokeArgs($className, $function, $object, $args);
    					if($result instanceof Expression){
    						$hasAccess = $result;
    						break;
    					}else if(isset($result) && $result){
    						$hasAccess = true;
    						break;
    					}
    				}
    			}
    		}

    		TransactionManager::commitTransaction();
    	}catch (\Exception $e){
    		TransactionManager::abortTransaction();
    		throw $e;
    	}

    	if($hasAccessChecks){
    		if($hasAccess === false){
    			throw new NoAccessException($errorMessage);
    		}
    		return $hasAccess;
    	}
    	return true;
    }

checks the access for this operation based on the annotations defined for this operation
@param string|Model $object on which access needs to be validated
@param string $errorMessage error message to be set as exception message if access is denied
@throws NoAccessException
@return boolean|string True or Valid where expression for Read access on Success otherwise false


protected function parseBlock($block)
    {
        $lines = array_filter(array_map(function($line)
        {
            $line = trim($line);

            if (strpos($line, "/**") !== false or strpos($line, "*/") !== false) {
                return null;
            }

            return trim(substr($line, 1));
        }, explode(PHP_EOL, $block)));

        return array_values($lines);
    }

protected function parseBlock ( $ block ) { $ lines = array_filter ( array_map ( function ( $ line ) { $ line = trim ( $ line ) ; if ( strpos ( $ line , "/**" ) !== false or strpos ( $ line , "*/" ) !== false ) { return null ; } return trim ( substr ( $ line , 1 ) ) ; } , explode ( PHP_EOL , $ block ) ) ) ; return array_values ( $ lines ) ; }

Parses a DocBlock comment into an array of lines.

@param string $block
@return array

Parses a DocBlock comment into an array of lines .


public static function path(string $path = null): ? string
    {
        return $path && $path[0] !== static::DIRECTORY_SEPARATOR
            ? static::DIRECTORY_SEPARATOR . $path
            : $path;
    }

public static function path ( string $ path = null ) : ? string { return $ path && $ path [ 0 ] !== static :: DIRECTORY_SEPARATOR ? static :: DIRECTORY_SEPARATOR . $ path : $ path ; }

Construct a path with the directory separator prepended.

@param string $path The path

@return string

Construct a path with the directory separator prepended .


protected function getAuthenticationObject()
    {
        if ($this->authObject == null) {
            if (strlen($this->login) <= 0 || strlen($this->password) <= 0) {
                throw new NullPointerException("Login or Password is not set.");
            }
            $auth = new Authentication();
            if (! $auth->authenticate()) {
                throw new AuthException("Authentication Problem. Please check Login and Password.");
            }

            $this->authObject = $auth;
        }

        return $this->authObject;
    }

authentication client with defined login and password; return Auth Object

@throws NullPointerException
@throws AuthException
@return \Mamoto\Api\Authentication

authentication client with defined login and password ; return Auth Object


protected function getDataFromUrl($url)
    {
        $auth = $this->getAuthenticationObject();

        $process = curl_init($url);
        curl_setopt($process, CURLOPT_HEADER, 0);
        // setting the authentication header
        curl_setopt($process, CURLOPT_HTTPHEADER, array(
            "Authorization: " . $auth->getTokenType() . " " . $auth->getAccessToken()
        ));
        curl_setopt($process, CURLOPT_TIMEOUT, 30);
        curl_setopt($process, CURLOPT_RETURNTRANSFER, TRUE);
        $returnData = curl_exec($process);
        curl_close($process);

        return $returnData;
    }

protected
function
getDataFromUrl
(
$
url
)
{
$
auth
=
$
this
->
getAuthenticationObject
(
)
;
$
process
=
curl_init
(
$
url
)
;
curl_setopt
(
$
process
,
CURLOPT_HEADER
,
0
)
;
// setting the authentication header
curl_setopt
(
$
process
,
CURLOPT_HTTPHEADER
,
array
(
"Authorization: "
.
$
auth
->
getTokenType
(
)
.
" "
.
$
auth
->
getAccessToken
(
)
)
)
;
curl_setopt
(
$
process
,
CURLOPT_TIMEOUT
,
30
)
;
curl_setopt
(
$
process
,
CURLOPT_RETURNTRANSFER
,
TRUE
)
;
$
returnData
=
curl_exec
(
$
process
)
;
curl_close
(
$
process
)
;
return
$
returnData
;
}

get data from url

@param string $url
@return mixed raw url data


protected function parseJsonData($data)
    {
        if ($data != FALSE) {
            // check, if raw answer is requestedd
            if ($this->getRawAnswer()) {
                return $data;
            }

            $json_data = json_decode($data, TRUE);
            if (isset($json_data["errors"])) {
                $err_msg = array();
                foreach ($json_data["errors"] as $error) {
                    $err_msg[] = $error["Message"];
                }
                throw new JsonException(implode(";", $err_msg));
            } else {
                return $json_data;
            }
        } else {
            throw new ServerException("Get No Data from Server.");
        }
    }

protected
function
parseJsonData
(
$
data
)
{
if
(
$
data
!=
FALSE
)
{
// check, if raw answer is requestedd
if
(
$
this
->
getRawAnswer
(
)
)
{
return
$
data
;
}
$
json_data
=
json_decode
(
$
data
,
TRUE
)
;
if
(
isset
(
$
json_data
[
"errors"
]
)
)
{
$
err_msg
=
array
(
)
;
foreach
(
$
json_data
[
"errors"
]
as
$
error
)
{
$
err_msg
[
]
=
$
error
[
"Message"
]
;
}
throw
new
JsonException
(
implode
(
";"
,
$
err_msg
)
)
;
}
else
{
return
$
json_data
;
}
}
else
{
throw
new
ServerException
(
"Get No Data from Server."
)
;
}
}

parse Json data and return data as array

@param unknown $data
@throws JsonException
@throws ServerException
@return mixed|array resultset as array


public function getAll()
    {
        // build url
        $url = $this->base_url . $this->url;
        // get data from server
        $data = $this->getDataFromUrl($url);
        // parse result set and get data as array
        $result = $this->parseJsonData($data);

        return $result;
    }

get all data from url

@return array|mixed get all data from url


public function getEntityAlias()
    {
        if (!$this->entityAlias) {
            $className       = $this->getClassName();
            $reflectionCLass = new ReflectionClass($className);

            if (is_string($reflectionCLass->getConstant('ALIAS_NAME'))) {
                $entityAlias = $reflectionCLass->getConstant('ALIAS_NAME');
            } else {
                $entityAlias = array_slice(explode('\\', $className), -1, 1)[0];
            }

            $this->entityAlias = preg_replace('/[^a-z]/i', '', $entityAlias);
        }

        return $this->entityAlias;
    }

public function getEntityAlias ( ) { if ( ! $ this -> entityAlias ) { $ className = $ this -> getClassName ( ) ; $ reflectionCLass = new ReflectionClass ( $ className ) ; if ( is_string ( $ reflectionCLass -> getConstant ( 'ALIAS_NAME' ) ) ) { $ entityAlias = $ reflectionCLass -> getConstant ( 'ALIAS_NAME' ) ; } else { $ entityAlias = array_slice ( explode ( '\\' , $ className ) , - 1 , 1 ) [ 0 ] ; } $ this -> entityAlias = preg_replace ( '/[^a-z]/i' , '' , $ entityAlias ) ; } return $ this -> entityAlias ; }

Get related entity alias used in query. Will be used entity class name without namespace.

@return string
@throws \ReflectionException

Get related entity alias used in query . Will be used entity class name without namespace .


public function createQueryBuilder($alias = null, $indexBy = null)
    {
        return $this->createNewQueryBuilderInstance()->selectFromRepositoryEntity($alias, $indexBy);
    }

public function createQueryBuilder ( $ alias = null , $ indexBy = null ) { return $ this -> createNewQueryBuilderInstance ( ) -> selectFromRepositoryEntity ( $ alias , $ indexBy ) ; }

Gets an ExpressionBuilder used for object-oriented construction of query expressions.

@param string $alias
@param string $indexBy The index for the from.

@return EntityQueryBuilder
@throws \ReflectionException

Gets an ExpressionBuilder used for object - oriented construction of query expressions .


public function createResultSetMappingBuilder($alias = null)
    {
        if (!$alias) {
            $alias = $this->getEntityAlias();
        }

        $resultSet = new ResultSetMappingBuilder(
            $this->getEntityManager(), ResultSetMappingBuilder::COLUMN_RENAMING_INCREMENT
        );
        $resultSet->addRootEntityFromClassMetadata($this->getClassName(), $alias);

        return $resultSet;
    }

public function createResultSetMappingBuilder ( $ alias = null ) { if ( ! $ alias ) { $ alias = $ this -> getEntityAlias ( ) ; } $ resultSet = new ResultSetMappingBuilder ( $ this -> getEntityManager ( ) , ResultSetMappingBuilder :: COLUMN_RENAMING_INCREMENT ) ; $ resultSet -> addRootEntityFromClassMetadata ( $ this -> getClassName ( ) , $ alias ) ; return $ resultSet ; }

Creates a new result set mapping builder for this entity. The column naming strategy is "INCREMENT".

@param string $alias

@return ResultSetMappingBuilder
@throws \ReflectionException

Creates a new result set mapping builder for this entity . The column naming strategy is INCREMENT .


public function findAllIdentifiers()
    {
        $metadata    = $this->getClassMetadata();
        $identifiers = $metadata->getIdentifier();
        $qb          = $this->createQueryBuilder();

        foreach ($identifiers as $field) {
            $qb->select($qb->alias($field));
        }

        return $qb->fetchAllScalar();
    }

public function findAllIdentifiers ( ) { $ metadata = $ this -> getClassMetadata ( ) ; $ identifiers = $ metadata -> getIdentifier ( ) ; $ qb = $ this -> createQueryBuilder ( ) ; foreach ( $ identifiers as $ field ) { $ qb -> select ( $ qb -> alias ( $ field ) ) ; } return $ qb -> fetchAllScalar ( ) ; }

Finds entity ids.

@return array
@throws \ReflectionException


public function min($column)
    {
        $qb = $this->createQueryBuilder();

        $qb->select(sprintf('MIN(%s) AS min_%s', $qb->alias($column), $column));

        return $qb->fetchSingleScalar();
    }

public
function
min
(
$
column
)
{
$
qb
=
$
this
->
createQueryBuilder
(
)
;
$
qb
->
select
(
sprintf
(
'MIN(%s) AS min_%s'
,
$
qb
->
alias
(
$
column
)
,
$
column
)
)
;
return
$
qb
->
fetchSingleScalar
(
)
;
}

Retrieve the minimum value of a given column..

@param string $column

@return mixed
@throws \ReflectionException
@throws \Doctrine\ORM\NonUniqueResultException
@throws \Doctrine\ORM\NoResultException
@throws \Xloit\Bridge\Doctrine\ORM\Exception\InvalidArgumentException

Retrieve the minimum value of a given column ..


public function paginate($page = 1, $perPage = null)
    {
        $perPage = $perPage ?: $this->getMaxResults();
        $qb      = $this->createQueryBuilder();

        $qb->paginate($page, $perPage);

        return $this->getPaginator($qb);
    }

public function paginate ( $ page = 1 , $ perPage = null ) { $ perPage = $ perPage ? : $ this -> getMaxResults ( ) ; $ qb = $ this -> createQueryBuilder ( ) ; $ qb -> paginate ( $ page , $ perPage ) ; return $ this -> getPaginator ( $ qb ) ; }

Retrieve paginator.

@param int $page
@param int $perPage

@return Tools\Pagination\Paginator
@throws \ReflectionException
@throws \Xloit\Bridge\Doctrine\ORM\Exception\InvalidArgumentException


public function isEntity($entity)
    {
        return is_object($entity)
               && !$this->getEntityManager()->getMetadataFactory()->isTransient(ClassUtils::getClass($entity));
    }

public function isEntity ( $ entity ) { return is_object ( $ entity ) && ! $ this -> getEntityManager ( ) -> getMetadataFactory ( ) -> isTransient ( ClassUtils :: getClass ( $ entity ) ) ; }

Indicates whether the given argument is an entity.

@param mixed $entity

@return bool

Indicates whether the given argument is an entity .


protected function getIdentifier($entity, $single = false)
    {
        $this->validateEntity($entity, __METHOD__);

        $entityClass   = ClassUtils::getClass($entity);
        $entityManager = $this->getEntityManager();
        $metadata      = $entityManager->getClassMetadata($entityClass);

        $metadata->validateIdentifier();

        $id = $metadata->getIdentifierValues($entity);

        /** @noinspection IsEmptyFunctionUsageInspection */
        if (empty($id)) {
            return $single ? reset($id) : $id;
        }

        foreach ($id as $field => &$idValue) {
            if (is_object($idValue)
                && $entityManager->getMetadataFactory()->hasMetadataFor(ClassUtils::getClass($idValue))
            ) {
                $singleId = $entityManager->getUnitOfWork()->getSingleIdentifierValue($idValue);

                if ($singleId === null) {
                    throw ORMInvalidArgumentException::invalidIdentifierBindingEntity();
                }

                $idValue = $singleId;
            }

            if (!in_array($field, $metadata->identifier, true)) {
                throw ORMException::missingIdentifierField($metadata->name, $field);
            }
        }

        unset($idValue);

        if (count($metadata->identifier) !== count($id)) {
            throw ORMException::unrecognizedIdentifierFields(
                $metadata->name, array_diff($metadata->identifier, $id)
            );
        }

        return $single ? reset($id) : $id;
    }

Get the object identifier, single or composite.

@param mixed $entity
@param bool  $single

@return array|string
@throws \Doctrine\ORM\Mapping\MappingException
@throws \Doctrine\ORM\ORMInvalidArgumentException
@throws \Doctrine\ORM\ORMException
@throws \Xloit\Bridge\Doctrine\ORM\Exception\InvalidArgumentException

Get the object identifier single or composite .


protected function validateEntity($entity, $method)
    {
        if (!$this->isEntity($entity)) {
            throw new Exception\InvalidArgumentException(
                sprintf(
                    '%s expects parameter 1 to be a valid entity instance, %s provided instead', $method,
                    is_object($entity) ? get_class($entity) : gettype($entity)
                )
            );
        }
    }

Indicates whether the given entity is valid.

@param mixed  $entity
@param string $method

@return void
@throws \Xloit\Bridge\Doctrine\ORM\Exception\InvalidArgumentException

Indicates whether the given entity is valid .