static function onImageQuality($string, $image, $fontName, $x = 0, $y = 0, $size = 10, $defaultColor = '000', $precision = 2)
    {
        $defaultColor = Color::StringToRgb24($defaultColor);
        $factor = 1 << ($precision > 31 ? 31 : $precision);

        $tokens = self::parseString($string);
        $rawText = '';
        foreach ($tokens as $token)
            $rawText .= $token->text;
        $maxBBox = imagettfbbox($size, 0, self::$fonts[$fontName]->getFile(), $rawText);

        $brush = imagecreatetruecolor($maxBBox[2] * 2, -$maxBBox[5] + 5);
        imagefill($brush, 0, 0, 0x7fffffff);
        $hugeBrush = imagecreatetruecolor(imagesx($brush) * $factor, imagesy($brush) * $factor);
        imagefill($hugeBrush, 0, 0, 0x7fffffff);

        $xOffset = 0;
        foreach ($tokens as $token)
            $xOffset += $token->onImage($hugeBrush, $fontName, $xOffset, imagesy($hugeBrush) * .75, $factor * $size, $defaultColor, $factor);

        $brushX = $x + imagesx($brush) / 2;
        $brushY = $y - imagesy($brush) * .25;
        imagecopyresampled($brush, $hugeBrush, 0, 0, 0, 0, imagesx($brush), imagesy($brush), imagesx($hugeBrush), imagesy($hugeBrush));
        imagesetbrush($image, $brush);
        imageline($image, $brushX, $brushY, $brushX, $brushY, IMG_COLOR_BRUSHED);
    }

static function onImageQuality ( $ string , $ image , $ fontName , $ x = 0 , $ y = 0 , $ size = 10 , $ defaultColor = '000' , $ precision = 2 ) { $ defaultColor = Color :: StringToRgb24 ( $ defaultColor ) ; $ factor = 1 << ( $ precision > 31 ? 31 : $ precision ) ; $ tokens = self :: parseString ( $ string ) ; $ rawText = '' ; foreach ( $ tokens as $ token ) $ rawText .= $ token -> text ; $ maxBBox = imagettfbbox ( $ size , 0 , self :: $ fonts [ $ fontName ] -> getFile ( ) , $ rawText ) ; $ brush = imagecreatetruecolor ( $ maxBBox [ 2 ] * 2 , - $ maxBBox [ 5 ] + 5 ) ; imagefill ( $ brush , 0 , 0 , 0x7fffffff ) ; $ hugeBrush = imagecreatetruecolor ( imagesx ( $ brush ) * $ factor , imagesy ( $ brush ) * $ factor ) ; imagefill ( $ hugeBrush , 0 , 0 , 0x7fffffff ) ; $ xOffset = 0 ; foreach ( $ tokens as $ token ) $ xOffset += $ token -> onImage ( $ hugeBrush , $ fontName , $ xOffset , imagesy ( $ hugeBrush ) * .75 , $ factor * $ size , $ defaultColor , $ factor ) ; $ brushX = $ x + imagesx ( $ brush ) / 2 ; $ brushY = $ y - imagesy ( $ brush ) * .25 ; imagecopyresampled ( $ brush , $ hugeBrush , 0 , 0 , 0 , 0 , imagesx ( $ brush ) , imagesy ( $ brush ) , imagesx ( $ hugeBrush ) , imagesy ( $ hugeBrush ) ) ; imagesetbrush ( $ image , $ brush ) ; imageline ( $ image , $ brushX , $ brushY , $ brushX , $ brushY , IMG_COLOR_BRUSHED ) ; }

Draw a string with on an image using quality method. Slow with big text size
@param string $string The style-coded string to draw
@param imageResource $image The image to draw on
@param string $fontName The TTF font to use, which has been declared previously
@param int $x X position
@param int $y Y position
@param int $size Font size
@param string $defaultColor Default text color in 3 or 6 hexadecimal characters
@param int $precision Higher value means higher precision (but also longer execution time), usual values are 1 to 3

Draw a string with on an image using quality method . Slow with big text size


public function getRedirectFor(Request $request)
    {
        $this->request = $request;

        collect($this->getRedirectedUrls())->each(function ($redirects, $missingUrl) {
            $this->router->get($missingUrl, function () use ($redirects) {
                return redirect()->to(
                    $this->determineRedirectUrl($redirects),
                    $this->determineRedirectStatusCode($redirects)
                );
            });
        });

        try {
            return $this->router->dispatch($request);
        }
        catch (\Exception $e) {
            return null;
        }
    }

public function getRedirectFor ( Request $ request ) { $ this -> request = $ request ; collect ( $ this -> getRedirectedUrls ( ) ) -> each ( function ( $ redirects , $ missingUrl ) { $ this -> router -> get ( $ missingUrl , function ( ) use ( $ redirects ) { return redirect ( ) -> to ( $ this -> determineRedirectUrl ( $ redirects ) , $ this -> determineRedirectStatusCode ( $ redirects ) ) ; } ) ; } ) ; try { return $ this -> router -> dispatch ( $ request ) ; } catch ( \ Exception $ e ) { return null ; } }

Get the redirect url.

@param  \Illuminate\Http\Request  $request

@return \Illuminate\Http\Response|null


public function getRedirectedUrls()
    {
        return $this->getCachedRedirects()
            ->keyBy('old_url')
            ->transform(function (Redirect $item) {
                return [$item->new_url, $item->status];
            })
            ->toArray();
    }

public function getRedirectedUrls ( ) { return $ this -> getCachedRedirects ( ) -> keyBy ( 'old_url' ) -> transform ( function ( Redirect $ item ) { return [ $ item -> new_url , $ item -> status ] ; } ) -> toArray ( ) ; }


protected function getCachedRedirects()
    {
        return cache()->remember($this->getOption('cache.key'), $this->getOption('cache.duration'), function () {
            return $this->getRedirectModel()->get();
        });
    }

protected function getCachedRedirects ( ) { return cache ( ) -> remember ( $ this -> getOption ( 'cache.key' ) , $ this -> getOption ( 'cache.duration' ) , function ( ) { return $ this -> getRedirectModel ( ) -> get ( ) ; } ) ; }

Get the cached redirection urls.

@return \Illuminate\Database\Eloquent\Collection


function setSize($iconSize = 5, $nullValue = null)
    {
        $this->arrowNext->setSize($iconSize, $iconSize);
        $this->arrowPrev->setSize($iconSize, $iconSize);
        $this->arrowFastNext->setSize($iconSize, $iconSize);
        $this->arrowFastPrev->setSize($iconSize, $iconSize);
        $this->arrowLast->setSize($iconSize, $iconSize);
        $this->arrowFirst->setSize($iconSize, $iconSize);
    }

function setSize ( $ iconSize = 5 , $ nullValue = null ) { $ this -> arrowNext -> setSize ( $ iconSize , $ iconSize ) ; $ this -> arrowPrev -> setSize ( $ iconSize , $ iconSize ) ; $ this -> arrowFastNext -> setSize ( $ iconSize , $ iconSize ) ; $ this -> arrowFastPrev -> setSize ( $ iconSize , $ iconSize ) ; $ this -> arrowLast -> setSize ( $ iconSize , $ iconSize ) ; $ this -> arrowFirst -> setSize ( $ iconSize , $ iconSize ) ; }


function setSelected()
    {
        $this->isSelected = true;

        $this->selectedIcon = new \ManiaLib\Gui\Elements\Icons64x64_1(11);
        $this->selectedIcon->setSubStyle(\ManiaLib\Gui\Elements\Icons64x64_1::ShowRight);
        $this->selectedIcon->setValign('center');
        $this->selectedIcon->setPosX(71);
        $this->addCardElement($this->selectedIcon);
    }

function setSelected ( ) { $ this -> isSelected = true ; $ this -> selectedIcon = new \ ManiaLib \ Gui \ Elements \ Icons64x64_1 ( 11 ) ; $ this -> selectedIcon -> setSubStyle ( \ ManiaLib \ Gui \ Elements \ Icons64x64_1 :: ShowRight ) ; $ this -> selectedIcon -> setValign ( 'center' ) ; $ this -> selectedIcon -> setPosX ( 71 ) ; $ this -> addCardElement ( $ this -> selectedIcon ) ; }

Sets the button selected and change its styles accordingly


public function invoke($from = null, $keyword = null, $to = null, $text = '')
    {
        if(!$from) {
            throw new Exception("\$from parameter cannot be blank");
        }

        if(!$keyword) {
            throw new Exception("\$keyword parameter cannot be blank");
        }

        if(!$to) {
            throw new Exception("\$to parameter cannot be blank");
        }

        if(!$text) {
            throw new Exception("\$text parameter cannot be blank");
        }

        return $this->exec([
            'from' => $from,
            'keyword' => $keyword,
            'to' => $to,
            'text' => $text
        ]);
    }

public
function
invoke
(
$
from
=
,
$
keyword
=
,
$
to
=
,
$
text
=
''
)
{
if
(
!
$
from
)
{
throw
new
Exception
(
"\$from parameter cannot be blank"
)
;
}
if
(
!
$
keyword
)
{
throw
new
Exception
(
"\$keyword parameter cannot be blank"
)
;
}
if
(
!
$
to
)
{
throw
new
Exception
(
"\$to parameter cannot be blank"
)
;
}
if
(
!
$
text
)
{
throw
new
Exception
(
"\$text parameter cannot be blank"
)
;
}
return
$
this
->
exec
(
[
'from'
=>
$
from
,
'keyword'
=>
$
keyword
,
'to'
=>
$
to
,
'text'
=>
$
text
]
)
;
}

Send a marketing message from Nexmo's shared short code.

@param string|int    $from           Required. Nexmo Shared Short Code, can be found on your Dashboard.
@param string        $keyword        Required. The keyword you selected during Shared Short Code sign up process.
@param string|int    $to             Required. Mobile number in international format.
Ex: 447525856424 or 00447525856424 when sending to UK.
@param string        $text           Required. Body of the text message.
@throws \Nexmo\Exception
@return array

Send a marketing message from Nexmo s shared short code .


function setData($filename, $absoluteUrl = false)
    {
        if (!$absoluteUrl) {
            $this->data = \ManiaLib\Gui\Manialink::$mediaURL . $filename;
        } else {
            $this->data = $filename;
        }
    }

function setData ( $ filename , $ absoluteUrl = false ) { if ( ! $ absoluteUrl ) { $ this -> data = \ ManiaLib \ Gui \ Manialink :: $ mediaURL . $ filename ; } else { $ this -> data = $ filename ; } }

Sets the data to play
@param string The data filename (or URL)
@param bool Whether to prefix the filename with the default media dir URL


static function getLimitString($offset, $length)
    {
        $offset = (int)$offset;
        $length = (int)$length;
        if (!$offset && !$length) {
            return '';
        } elseif (!$offset && $length == 1) {
            return 'LIMIT 1';
        } else {
            return 'LIMIT ' . $offset . ', ' . $length;
        }
    }

static
function
getLimitString
(
$
offset
,
$
length
)
{
$
offset
=
(
int
)
$
offset
;
$
length
=
(
int
)
$
length
;
if
(
!
$
offset
&&
!
$
length
)
{
return
''
;
}
elseif
(
!
$
offset
&&
$
length
==
1
)
{
return
'LIMIT 1'
;
}
else
{
return
'LIMIT '
.
$
offset
.
', '
.
$
length
;
}
}

Returns the "LIMIT x,x" string depending on both values

Returns the LIMIT x x string depending on both values


static function getUpdateString(array $values)
    {
        $tmp = array();

        foreach ($values as $key => $value) {
            $tmp[] = $key . '=' . $value;
        }
        return implode(', ', $tmp);
    }

static
function
getUpdateString
(
array
$
values
)
{
$
tmp
=
array
(
)
;
foreach
(
$
values
as
$
key
=>
$
value
)
{
$
tmp
[
]
=
$
key
.
'='
.
$
value
;
}
return
implode
(
', '
,
$
tmp
)
;
}

Returns string like "name1=value1, name2=value2"


function get($name, $default = null)
    {
        if (array_key_exists($name, $this->params)) {
            return $this->params[$name];
        } else {
            return $default;
        }
    }

function get ( $ name , $ default = null ) { if ( array_key_exists ( $ name , $ this -> params ) ) { return $ this -> params [ $ name ] ; } else { return $ default ; } }

Retrieves a GET parameter, or the default value if not found
@param string
@param mixed
@return mixed

Retrieves a GET parameter or the default value if not found


function getStrict($name, $message = null)
    {
        if (array_key_exists($name, $this->params) && $this->params[$name]) {
            return $this->params[$name];
        } elseif ($message) {
            throw new UserException($message);
        } else {
            throw new InvalidArgumentException($name);
        }
    }

function getStrict ( $ name , $ message = null ) { if ( array_key_exists ( $ name , $ this -> params ) && $ this -> params [ $ name ] ) { return $ this -> params [ $ name ] ; } elseif ( $ message ) { throw new UserException ( $ message ) ; } else { throw new InvalidArgumentException ( $ name ) ; } }

Retrieves a GET parameter, or throws an exception if not found or null
@param string
@param string Optional human readable name for error dialog
@return mixed

Retrieves a GET parameter or throws an exception if not found or null


function getPostStrict($name, $message = null)
    {
        if (array_key_exists($name, $_POST) && $_POST[$name]) {
            return $_POST[$name];
        } elseif ($message) {
            throw new UserException($message);
        } else {
            throw new InvalidArgumentException($name);
        }
    }

function getPostStrict ( $ name , $ message = null ) { if ( array_key_exists ( $ name , $ _POST ) && $ _POST [ $ name ] ) { return $ _POST [ $ name ] ; } elseif ( $ message ) { throw new UserException ( $ message ) ; } else { throw new InvalidArgumentException ( $ name ) ; } }

Retrieves a POST parameter, or throws an exception if not found or null
@param string
@param string Optional human readable name for error dialog
@return mixed

Retrieves a POST parameter or throws an exception if not found or null


function restore($name)
    {
        if (array_key_exists($name, $this->requestParams)) {
            $this->params[$name] = $this->requestParams[$name];
        } else {
            $this->delete($name);
        }
    }

function restore ( $ name ) { if ( array_key_exists ( $ name , $ this -> requestParams ) ) { $ this -> params [ $ name ] = $ this -> requestParams [ $ name ] ; } else { $ this -> delete ( $ name ) ; } }

Restores a GET parameter to the value it had when the page was loaded

@param string


function redirectArgList($route = '')
    {
        $args = func_get_args();
        array_shift($args);
        $args = $this->filterArgs($args);
        $manialink = $this->createLinkString($route, $args);
        Response::getInstance()->redirect($manialink);
    }

function redirectArgList ( $ route = '' ) { $ args = func_get_args ( ) ; array_shift ( $ args ) ; $ args = $ this -> filterArgs ( $ args ) ; $ manialink = $ this -> createLinkString ( $ route , $ args ) ; Response :: getInstance ( ) -> redirect ( $ manialink ) ; }

Redirects to the specified route with, with names of GET vars as parameters of the method

Redirects to the specified route with with names of GET vars as parameters of the method


function createLinkArgList($route = '')
    {
        $args = func_get_args();
        array_shift($args);
        $args = $this->filterArgs($args);
        return $this->createLinkString($route, $args);
    }

function createLinkArgList ( $ route = '' ) { $ args = func_get_args ( ) ; array_shift ( $ args ) ; $ args = $ this -> filterArgs ( $ args ) ; return $ this -> createLinkString ( $ route , $ args ) ; }

Creates a link to the specified route with, with names of GET vars as parameters of the method

Creates a link to the specified route with with names of GET vars as parameters of the method


function createAbsoluteLinkArgList($absoluteLink)
    {
        $args = func_get_args();
        array_shift($args);
        $args = $this->filterArgs($args);
        return $absoluteLink . ($args ? '?' . http_build_query($args) : '');
    }

function createAbsoluteLinkArgList ( $ absoluteLink ) { $ args = func_get_args ( ) ; array_shift ( $ args ) ; $ args = $ this -> filterArgs ( $ args ) ; return $ absoluteLink . ( $ args ? '?' . http_build_query ( $ args ) : '' ) ; }

Returns an URL with the request parameters specified as method arguments

@param string The absolute URL
@return string
@deprecated Old code, not sure if it is still used?


function incPosX($posX)
    {
        $oldX = $this->posX;
        $this->posX += $posX;
        $this->onMove($oldX, $this->posY, $this->posZ);
    }

function incPosX ( $ posX ) { $ oldX = $ this -> posX ; $ this -> posX += $ posX ; $ this -> onMove ( $ oldX , $ this -> posY , $ this -> posZ ) ; }


function incPosY($posY)
    {
        $oldY = $this->posY;
        $this->posY += $posY;
        $this->onMove($this->posX, $oldY, $this->posZ);
    }

function incPosY ( $ posY ) { $ oldY = $ this -> posY ; $ this -> posY += $ posY ; $ this -> onMove ( $ this -> posX , $ oldY , $ this -> posZ ) ; }


function incPosZ($posZ)
    {
        $oldZ = $this->posZ;
        $this->posZ += $posZ;
        $this->onMove($this->posX, $this->posY, $oldZ);
    }

function incPosZ ( $ posZ ) { $ oldZ = $ this -> posZ ; $ this -> posZ += $ posZ ; $ this -> onMove ( $ this -> posX , $ this -> posY , $ oldZ ) ; }


function setPosition()
    {
        $oldX = $this->posX;
        $oldY = $this->posY;
        $oldZ = $this->posZ;

        $args = func_get_args();

        if (!empty($args)) $this->posX = array_shift($args);

        if (!empty($args)) $this->posY = array_shift($args);

        if (!empty($args)) $this->posZ = array_shift($args);

        $this->onMove($oldX, $oldY, $oldZ);
    }

function setPosition ( ) { $ oldX = $ this -> posX ; $ oldY = $ this -> posY ; $ oldZ = $ this -> posZ ; $ args = func_get_args ( ) ; if ( ! empty ( $ args ) ) $ this -> posX = array_shift ( $ args ) ; if ( ! empty ( $ args ) ) $ this -> posY = array_shift ( $ args ) ; if ( ! empty ( $ args ) ) $ this -> posZ = array_shift ( $ args ) ; $ this -> onMove ( $ oldX , $ oldY , $ oldZ ) ; }

Sets the position of the element
@param float
@param float
@param float


function setScale($scale)
    {
        $oldScale = $this->scale;
        $this->scale = $scale;
        $this->onScale($oldScale);
    }

function setScale ( $ scale ) { $ oldScale = $ this -> scale ; $ this -> scale = $ scale ; $ this -> onScale ( $ oldScale ) ; }

Sets the scale factor of the element. 1=original size, 2=double size, 0.5
=half size
@param float

Sets the scale factor of the element . 1 = original size 2 = double size 0 . 5 = half size


function setValign($valign)
    {
        $old = $this->valign;
        $this->valign = $valign;
        $this->onAlign($this->halign, $old);
    }

function setValign ( $ valign ) { $ old = $ this -> valign ; $ this -> valign = $ valign ; $ this -> onAlign ( $ this -> halign , $ old ) ; }

Sets the vertical alignment of the element.
@param string Vertical alignment can be either "top", "center" or
"bottom"

Sets the vertical alignment of the element .


function setHalign($halign)
    {
        $old = $this->halign;
        $this->halign = $halign;
        $this->onAlign($old, $this->valign);
    }

function setHalign ( $ halign ) { $ old = $ this -> halign ; $ this -> halign = $ halign ; $ this -> onAlign ( $ old , $ this -> valign ) ; }

Sets the horizontal alignment of the element
@param string Horizontal alignement can be eithe "left", "center" or
"right"


function setAlign($halign = null, $valign = null)
    {
        $oldHalign = $this->halign;
        $oldValign = $this->valign;
        $this->valign = $valign;
        $this->halign = $halign;
        $this->onAlign($oldHalign, $oldValign);
    }

function setAlign ( $ halign = null , $ valign = null ) { $ oldHalign = $ this -> halign ; $ oldValign = $ this -> valign ; $ this -> valign = $ valign ; $ this -> halign = $ halign ; $ this -> onAlign ( $ oldHalign , $ oldValign ) ; }

Sets the alignment of the element
@param string Horizontal alignement can be eithe "left", "center" or
"right"
@param string Vertical alignment can be either "top", "center" or
"bottom"


function setSizeX($sizeX)
    {
        $oldX = $this->sizeX;
        $this->sizeX = $sizeX;
        $this->onResize($oldX, $this->sizeY);
    }

function setSizeX ( $ sizeX ) { $ oldX = $ this -> sizeX ; $ this -> sizeX = $ sizeX ; $ this -> onResize ( $ oldX , $ this -> sizeY ) ; }

Sets the width of the element
@param float


function setSizeY($sizeY)
    {
        $oldY = $this->sizeY;
        $this->sizeY = $sizeY;
        $this->onResize($this->sizeX, $oldY);
    }

function setSizeY ( $ sizeY ) { $ oldY = $ this -> sizeY ; $ this -> sizeY = $ sizeY ; $ this -> onResize ( $ this -> sizeX , $ oldY ) ; }

Sets the height of the element
@param float


function setSize()
    {
        $oldX = $this->sizeX;
        $oldY = $this->sizeY;

        $args = func_get_args();

        if (!empty($args)) $this->sizeX = array_shift($args);

        if (!empty($args)) $this->sizeY = array_shift($args);

        $this->onResize($oldX, $oldY);
    }

function setSize ( ) { $ oldX = $ this -> sizeX ; $ oldY = $ this -> sizeY ; $ args = func_get_args ( ) ; if ( ! empty ( $ args ) ) $ this -> sizeX = array_shift ( $ args ) ; if ( ! empty ( $ args ) ) $ this -> sizeY = array_shift ( $ args ) ; $ this -> onResize ( $ oldX , $ oldY ) ; }

Sets the size of the element
@param float
@param float


function addItem($topItem = self::BUTTONS_TOP)
    {
        $item = new Button();
        $item->setSubStyle(Bgs1::BgEmpty);
        if ($topItem == self::BUTTONS_TOP) {
            $this->items[] = $item;
        } else {
            $this->bottomItems[] = $item;
        }
        $this->lastItem = $item;
    }

function addItem ( $ topItem = self :: BUTTONS_TOP ) { $ item = new Button ( ) ; $ item -> setSubStyle ( Bgs1 :: BgEmpty ) ; if ( $ topItem == self :: BUTTONS_TOP ) { $ this -> items [ ] = $ item ; } else { $ this -> bottomItems [ ] = $ item ; } $ this -> lastItem = $ item ; }


function addGap($gap = 4)
    {
        $item = new \ManiaLib\Gui\Elements\Spacer(1, $gap);
        $this->items[] = $item;
    }

function addGap ( $ gap = 4 ) { $ item = new \ ManiaLib \ Gui \ Elements \ Spacer ( 1 , $ gap ) ; $ this -> items [ ] = $ item ; }

Adds a vertical gap before the next item
@param float


public static function keys()
    {
        return collect([
            Response::HTTP_MOVED_PERMANENTLY,
            Response::HTTP_SEE_OTHER,
            Response::HTTP_TEMPORARY_REDIRECT,
            Response::HTTP_PERMANENTLY_REDIRECT,
        ]);
    }

public static function keys ( ) { return collect ( [ Response :: HTTP_MOVED_PERMANENTLY , Response :: HTTP_SEE_OTHER , Response :: HTTP_TEMPORARY_REDIRECT , Response :: HTTP_PERMANENTLY_REDIRECT , ] ) ; }

Get the all status codes.

@return \Illuminate\Support\Collection


public static function all($locale = null)
    {
        return static::keys()->mapWithKeys(function ($code) use ($locale) {
            return [$code => Seo::getTrans("redirections.statuses.{$code}", [], $locale)];
        });
    }

public static function all ( $ locale = null ) { return static :: keys ( ) -> mapWithKeys ( function ( $ code ) use ( $ locale ) { return [ $ code => Seo :: getTrans ( "redirections.statuses.{$code}" , [ ] , $ locale ) ] ; } ) ; }

Get the all status names.

@param  string|null  $locale

@return \Illuminate\Support\Collection


static function fatalExceptionHandler(\Exception $exception)
    {
        throw $exception;

        file_put_contents(MANIALIB_APP_PATH . 'fatal-error.log', print_r($exception, true),
            FILE_APPEND);
        if (array_key_exists('HTTP_USER_AGENT', $_SERVER) && $_SERVER['HTTP_USER_AGENT'] == 'GameBox') {
            echo '<manialink><timeout>0</timeout></manialink>';
        } else {
            echo '
Oops
';
            echo '
An error occured. Please try again later.
';
            echo '
';
            if (\ManiaLib\Application\Config::getInstance()->debug) {
                var_dump($exception);
            }
        }
    }

'<manialink><timeout>0</timeout><label text="Fatal error." /></manialink>'

Fallback exception handler when nothing works. It tries to dump the
exception in a file at the app root and prints a message.

Fallback exception handler when nothing works . It tries to dump the exception in a file at the app root and prints a message .


final static function computeMessage(\Exception $e, $styles = array(),
                                         $additionalLines = array())
    {
        if (!$styles) {
            $styles = static::$messageConfigs['default'];
        }

        $trace = $e->getTraceAsString();
        $trace = explode("\n", $trace);
        foreach ($trace as $key => $value) {
            $trace[$key] = sprintf($styles['simpleLine'],
                preg_replace('/#[0-9]*\s*/u', '', $value));
        }
        $file = sprintf($styles['simpleLine'], $e->getFile() . ' (' . $e->getLine() . ')');

        $lines[] = sprintf($styles['title'], get_class($e));
        $lines[] = '';
        $lines[] = sprintf($styles['line'], 'Message', print_r($e->getMessage(), true));
        $lines[] = sprintf($styles['line'], 'Code', $e->getCode());
        $lines = array_merge($lines, $additionalLines, array($file), $trace);
        $lines[] = '';
        return implode("\n", $lines);
    }

final
static
function
computeMessage
(
\
Exception
$
e
,
$
styles
=
array
(
)
,
$
additionalLines
=
array
(
)
)
{
if
(
!
$
styles
)
{
$
styles
=
static
::
$
messageConfigs
[
'default'
]
;
}
$
trace
=
$
e
->
getTraceAsString
(
)
;
$
trace
=
explode
(
"\n"
,
$
trace
)
;
foreach
(
$
trace
as
$
key
=>
$
value
)
{
$
trace
[
$
key
]
=
sprintf
(
$
styles
[
'simpleLine'
]
,
preg_replace
(
'/#[0-9]*\s*/u'
,
''
,
$
value
)
)
;
}
$
file
=
sprintf
(
$
styles
[
'simpleLine'
]
,
$
e
->
getFile
(
)
.
' ('
.
$
e
->
getLine
(
)
.
')'
)
;
$
lines
[
]
=
sprintf
(
$
styles
[
'title'
]
,
get_class
(
$
e
)
)
;
$
lines
[
]
=
''
;
$
lines
[
]
=
sprintf
(
$
styles
[
'line'
]
,
'Message'
,
print_r
(
$
e
->
getMessage
(
)
,
true
)
)
;
$
lines
[
]
=
sprintf
(
$
styles
[
'line'
]
,
'Code'
,
$
e
->
getCode
(
)
)
;
$
lines
=
array_merge
(
$
lines
,
$
additionalLines
,
array
(
$
file
)
,
$
trace
)
;
$
lines
[
]
=
''
;
return
implode
(
"\n"
,
$
lines
)
;
}

Computes a human readable log message from any exception
@return string


final static function computeShortMessage(\Exception $e)
    {
        $message = get_class($e) . '  ' . $e->getMessage() . ' (' . $e->getCode() . ') in ' . $e->getFile() . ' at line ' . $e->getLine();
        return $message;
    }

final
static
function
computeShortMessage
(
\
Exception
$
e
)
{
$
message
=
get_class
(
$
e
)
.
'  '
.
$
e
->
getMessage
(
)
.
' ('
.
$
e
->
getCode
(
)
.
') in '
.
$
e
->
getFile
(
)
.
' at line '
.
$
e
->
getLine
(
)
;
return
$
message
;
}

Computes a short human readable log message from any exception
@return string


public function handle(Request $request, Closure $next)
    {
        $response = $next($request);

        if ($response->getStatusCode() !== Response::HTTP_NOT_FOUND)
            return $response;

        return $this->redirector->getRedirectFor($request) ?: $response;
    }

public function handle ( Request $ request , Closure $ next ) { $ response = $ next ( $ request ) ; if ( $ response -> getStatusCode ( ) !== Response :: HTTP_NOT_FOUND ) return $ response ; return $ this -> redirector -> getRedirectFor ( $ request ) ? : $ response ; }

Handle the missing pages redirection.

@param  \Illuminate\Http\Request  $request
@param  \Closure                  $next

@return mixed


static function uploadFile($path, $filename, $maxSize = 2097152)
    {
        $inputFile = file_get_contents('php://input', null, null, null, $maxSize);

        // Else try to get GET data
        if ($inputFile === false && array_key_exists('input', $_GET)) {
            $inputFile = $_GET['input'];
        }

        // Check for error
        if ($inputFile === false) {
            throw new \Exception('Couldn\'t read input file');
        }
        if (!file_put_contents($path . $filename, $inputFile)) {
            throw new \Exception('Couldn\'t save input file to ' . $path . $filename);
        }
        if (filesize($path . $filename) > $maxSize) {
            // Not sure if usefull here
            unlink($path . $filename);
            throw new FileTooLargeException();
        }
    }

static
function
uploadFile
(
$
path
,
$
filename
,
$
maxSize
=
2097152
)
{
$
inputFile
=
file_get_contents
(
'php://input'
,
,
,
,
$
maxSize
)
;
// Else try to get GET data
if
(
$
inputFile
===
false
&&
array_key_exists
(
'input'
,
$
_GET
)
)
{
$
inputFile
=
$
_GET
[
'input'
]
;
}
// Check for error
if
(
$
inputFile
===
false
)
{
throw
new
\
Exception
(
'Couldn\'t read input file'
)
;
}
if
(
!
file_put_contents
(
$
path
.
$
filename
,
$
inputFile
)
)
{
throw
new
\
Exception
(
'Couldn\'t save input file to '
.
$
path
.
$
filename
)
;
}
if
(
filesize
(
$
path
.
$
filename
)
>
$
maxSize
)
{
// Not sure if usefull here
unlink
(
$
path
.
$
filename
)
;
throw
new
FileTooLargeException
(
)
;
}
}

Tries to read the specified file and save it
@param string The path where the file will be saved
@param string filename
@param int The maximum file size in bytes


static function getCurrent()
    {
        $protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 'https://'
            : 'http://';
        $current_uri = $protocol . $_SERVER['HTTP_HOST'] . self::getRequestURI();
        $parts = parse_url($current_uri);

        $query = '';
        if (!empty($parts['query'])) {
            $params = array();
            parse_str($parts['query'], $params);
            $params = array_filter($params);
            if (!empty($params)) {
                $query = '?' . http_build_query($params, '', '&');
            }
        }

        // Use port if non default.
        $port = isset($parts['port']) &&
        (($protocol === 'http://' && $parts['port'] !== 80) || ($protocol === 'https://' && $parts['port'] !== 443))
            ? ':' . $parts['port'] : '';

        // Rebuild.
        return $protocol . $parts['host'] . $port . $parts['path'] . $query;
    }

static
function
getCurrent
(
)
{
$
protocol
=
isset
(
$
_SERVER
[
'HTTPS'
]
)
&&
$
_SERVER
[
'HTTPS'
]
==
'on'
'https://'
:
'http://'
;
$
current_uri
=
$
protocol
.
$
_SERVER
[
'HTTP_HOST'
]
.
self
::
getRequestURI
(
)
;
$
parts
=
parse_url
(
$
current_uri
)
;
$
query
=
''
;
if
(
!
empty
(
$
parts
[
'query'
]
)
)
{
$
params
=
array
(
)
;
parse_str
(
$
parts
[
'query'
]
,
$
params
)
;
$
params
=
array_filter
(
$
params
)
;
if
(
!
empty
(
$
params
)
)
{
$
query
=
'?'
.
http_build_query
(
$
params
,
''
,
'&'
)
;
}
}
// Use port if non default.
$
port
=
isset
(
$
parts
[
'port'
]
)
&&
(
(
$
protocol
===
'http://'
&&
$
parts
[
'port'
]
!==
80
)
||
(
$
protocol
===
'https://'
&&
$
parts
[
'port'
]
!==
443
)
)
':'
.
$
parts
[
'port'
]
:
''
;
// Rebuild.
return
$
protocol
.
$
parts
[
'host'
]
.
$
port
.
$
parts
[
'path'
]
.
$
query
;
}

Returns the Current URL.

@return string The current URI
@see http://code.google.com/p/oauth2-php
@author Originally written by Naitik Shah <naitik@facebook.com>.
@author Update to draft v10 by Edison Wong <hswong3i@pantarei-design.com>


final public static function getAlignedPosX($posX, $sizeX, $halign, $newAlign)
    {
        if (!$halign) {
            $halign = 'left';
        }
        $alignmentString = $halign . '|' . $newAlign;
        switch ($alignmentString) {
            case 'center|center':
            case 'center|center2':
            case 'left|left':
            case 'right|right':
                $factor = 0;
                break;

            case 'center|left':
            case 'right|center':
            case 'right|center2':
                $factor = -0.5;
                break;

            case 'center|right':
            case 'left|center':
            case 'left|center2':
                $factor = 0.5;
                break;

            case 'left|right':
                $factor = 1;
                break;

            case 'right|left':
                $factor = -1;
                break;

            default:
                throw new \Exception('GUITools: Unsupported positions: ' . $alignmentString);
        }
        return $posX + $factor * $sizeX;
    }

final
public
static
function
getAlignedPosX
(
$
posX
,
$
sizeX
,
$
halign
,
$
newAlign
)
{
if
(
!
$
halign
)
{
$
halign
=
'left'
;
}
$
alignmentString
=
$
halign
.
'|'
.
$
newAlign
;
switch
(
$
alignmentString
)
{
case
'center|center'
:
case
'center|center2'
:
case
'left|left'
:
case
'right|right'
:
$
factor
=
0
;
break
;
case
'center|left'
:
case
'right|center'
:
case
'right|center2'
:
$
factor
=
0.5
;
break
;
case
'center|right'
:
case
'left|center'
:
case
'left|center2'
:
$
factor
=
0.5
;
break
;
case
'left|right'
:
$
factor
=
1
;
break
;
case
'right|left'
:
$
factor
=
1
;
break
;
default
:
throw
new
\
Exception
(
'GUITools: Unsupported positions: '
.
$
alignmentString
)
;
}
return
$
posX
+
$
factor
*
$
sizeX
;
}

Returns the X position of an element in relation to another element and
according to their respective alignments

@param int X position of the parent element
@param int Width of the parent element
@param string Horizontal alignement of the parent element
@param string Horizontal alignement of the element you want to place
@return int Calculated X position of the element you want to place


final public static function getAlignedPosY($posY, $sizeY, $valign, $newAlign)
    {
        switch ($valign) {
            case 'top':
            case null:
                $valign = 'right';
                break;

            case 'bottom':
                $valign = 'left';
                break;
        }
        switch ($newAlign) {
            case 'top':
                $newAlign = 'right';
                break;

            case 'bottom':
                $newAlign = 'left';
                break;
        }
        return self::getAlignedPosX($posY, $sizeY, $valign, $newAlign);
    }

final public static function getAlignedPosY ( $ posY , $ sizeY , $ valign , $ newAlign ) { switch ( $ valign ) { case 'top' : case null : $ valign = 'right' ; break ; case 'bottom' : $ valign = 'left' ; break ; } switch ( $ newAlign ) { case 'top' : $ newAlign = 'right' ; break ; case 'bottom' : $ newAlign = 'left' ; break ; } return self :: getAlignedPosX ( $ posY , $ sizeY , $ valign , $ newAlign ) ; }

Returns the Y position of an element in relation to another element and
according to their respective alignments

@param int Y position of the parent element
@param int Height of the parent element
@param string Vertical alignement of the parent element
@param string Vertical alignement of the element you want to place
@return int Calculated Y position of the element you want to place


final public static function getAlignedPos(\ManiaLib\Gui\Element $object,
                                               $newHalign, $newValign)
    {
        $newPosX = self::getAlignedPosX(
            $object->getPosX(), $object->getRealSizeX(), $object->getHalign(),
            $newHalign);
        $newPosY = self::getAlignedPosY(
            $object->getPosY(), $object->getRealSizeY(), $object->getValign(),
            $newValign);
        return array('x' => $newPosX, 'y' => $newPosY);
    }

final public static function getAlignedPos ( \ ManiaLib \ Gui \ Element $ object , $ newHalign , $ newValign ) { $ newPosX = self :: getAlignedPosX ( $ object -> getPosX ( ) , $ object -> getRealSizeX ( ) , $ object -> getHalign ( ) , $ newHalign ) ; $ newPosY = self :: getAlignedPosY ( $ object -> getPosY ( ) , $ object -> getRealSizeY ( ) , $ object -> getValign ( ) , $ newValign ) ; return array ( 'x' => $ newPosX , 'y' => $ newPosY ) ; }

Returns the position of an element in relation to another element and
according to their respective alignments

@param \ManiaLib\Gui\Element Parent element
@param string Horizontal alignement of the element you want to place
@param string Vertical alignement of the element you want to place
@return array Calculated position of the element you want to place. The
array contains 2 elements with "x" and "y" indexes


public function build(\Magento\Framework\DB\Select $source = null)
    {
        /* this is root query builder (started from SELECT) */
        $result = $this->conn->select();

        /* define tables aliases for internal usage (in this method) */
        $asAcc = self::AS_ACC;
        $asTran = self::AS_TRAN;

        /* FROM prxgt_acc_transaction */
        $tbl = $this->resource->getTableName(self::E_TRAN);    // name with prefix
        $as = $asTran;    // alias for 'current table' (currently processed in this block of code)
        $exp = $this->expMin();
        $cols = [
            self::A_MIN_DATE => $exp
        ];
        $result->from([$as => $tbl], $cols);    // standard names for the variables

        /* LEFT JOIN prxgt_acc_account */
        $tbl = $this->resource->getTableName(self::E_ACC);
        $as = $asAcc;
        $cols = [];
        /* bind account to transaction as debit account to bind asset type below (credit acc. has the same type) */
        $cond = "$as." . EAcc::A_ID . "=$asTran." . ETran::A_DEBIT_ACC_ID;
        $result->joinLeft([$as => $tbl], $cond, $cols);

        return $result;
    }

Get base query to select minimal date_applied for transactions by asset type or account IDs.
Add appropriate 'where' clauses after build.

SELECT
MIN(trn.date_applied)
FROM
prxgt_acc_transaction as trn
LEFT JOIN prxgt_acc_account as acc ON
acc.id = trn.debit_acc_id

@inheritdoc

Get base query to select minimal date_applied for transactions by asset type or account IDs . Add appropriate where clauses after build .


private function quote($data)
    {
        $conn = $this->resource->getConnection();
        $result = $conn->quote($data);
        return $result;
    }

private function quote ( $ data ) { $ conn = $ this -> resource -> getConnection ( ) ; $ result = $ conn -> quote ( $ data ) ; return $ result ; }

Quotes string data to use inside SQL queries.

@param string $data
@return string

Quotes string data to use inside SQL queries .


private function resetAll($dateFrom)
    {
        $quoted = $this->quote($dateFrom);
        $where = EBalance::A_DATE . '>' . $quoted;
        $result = (int)$this->daoBalance->delete($where);
        return $result;
    }

private function resetAll ( $ dateFrom ) { $ quoted = $ this -> quote ( $ dateFrom ) ; $ where = EBalance :: A_DATE . '>' . $ quoted ; $ result = ( int ) $ this -> daoBalance -> delete ( $ where ) ; return $ result ; }

Reset all balances starting from date.

@param $dateFrom
@return int


private function queryDeleteByAssets($assetTypeIds, $dateFrom)
    {
        $tblAcc = $this->resource->getTableName(EAccount::ENTITY_NAME);
        $tblBal = $this->resource->getTableName(EBalance::ENTITY_NAME);
        $conn = $this->resource->getConnection();
        $quoted = $conn->quote($dateFrom);
        $in = '';
        foreach ($assetTypeIds as $id) {
            $in .= (int)$id . ',';
        }
        $in = substr($in, 0, strlen($in) - 1);
        $select = "SELECT " . EAccount::A_ID . " FROM $tblAcc";
        $select .= " WHERE " . EAccount::A_ASSET_TYPE_ID . " IN ($in)";
        $result = "DELETE FROM $tblBal WHERE " . EBalance::A_ACCOUNT_ID . " IN ($select)"
            . " AND (" . EBalance::A_DATE . ">$quoted)";
        return $result;
    }

private
function
queryDeleteByAssets
(
$
assetTypeIds
,
$
dateFrom
)
{
$
tblAcc
=
$
this
->
resource
->
getTableName
(
EAccount
::
ENTITY_NAME
)
;
$
tblBal
=
$
this
->
resource
->
getTableName
(
EBalance
::
ENTITY_NAME
)
;
$
conn
=
$
this
->
resource
->
getConnection
(
)
;
$
quoted
=
$
conn
->
quote
(
$
dateFrom
)
;
$
in
=
''
;
foreach
(
$
assetTypeIds
as
$
id
)
{
$
in
.=
(
int
)
$
id
.
','
;
}
$
in
=
substr
(
$
in
,
0
,
strlen
(
$
in
)
1
)
;
$
select
=
"SELECT "
.
EAccount
::
A_ID
.
" FROM $tblAcc"
;
$
select
.=
" WHERE "
.
EAccount
::
A_ASSET_TYPE_ID
.
" IN ($in)"
;
$
result
=
"DELETE FROM $tblBal WHERE "
.
EBalance
::
A_ACCOUNT_ID
.
" IN ($select)"
.
" AND ("
.
EBalance
::
A_DATE
.
">$quoted)"
;
return
$
result
;
}

Compose query to delete balances filtered by asset types and date.

@param int[] $assetTypeIds
@param string $dateFrom
@return string

Compose query to delete balances filtered by asset types and date .


static function configure(ClassLoader $classLoader, string $vendorDirPath, bool $usePrefixes = true): void
    {
        $composerBasePath = $vendorDirPath . '/composer/';

        $classLoader->addClassMap(require $composerBasePath . 'autoload_classmap.php');
        $classLoader->setUsePrefixes($usePrefixes);

        if ($usePrefixes) {
            $classLoader->addPrefixes(require $composerBasePath . 'autoload_psr4.php');
            $classLoader->addPrefixes(require $composerBasePath . 'autoload_namespaces.php', ClassLoader::PSR0);
        }

        $autoloadedFilesPath =  $composerBasePath . 'autoload_files.php';

        if (is_file($autoloadedFilesPath)) {
            foreach (require $autoloadedFilesPath as $file) {
                require $file;
            }
        }
    }

static function configure ( ClassLoader $ classLoader , string $ vendorDirPath , bool $ usePrefixes = true ) : void { $ composerBasePath = $ vendorDirPath . '/composer/' ; $ classLoader -> addClassMap ( require $ composerBasePath . 'autoload_classmap.php' ) ; $ classLoader -> setUsePrefixes ( $ usePrefixes ) ; if ( $ usePrefixes ) { $ classLoader -> addPrefixes ( require $ composerBasePath . 'autoload_psr4.php' ) ; $ classLoader -> addPrefixes ( require $ composerBasePath . 'autoload_namespaces.php' , ClassLoader :: PSR0 ) ; } $ autoloadedFilesPath = $ composerBasePath . 'autoload_files.php' ; if ( is_file ( $ autoloadedFilesPath ) ) { foreach ( require $ autoloadedFilesPath as $ file ) { require $ file ; } } }

Add autoload configuration of packages managed by Composer

- $vendorDirPath should be a path to the vendor directory without a trailing slash
- if $usePrefixes is FALSE, prefixes will not be loaded (use with optimized autoload files)


public function getServiceIds()
    {
        $services  = [];
        $reserved  = ['get', 'getParameter', 'getServiceIds', 'getReturnType'];
        $container = new \ReflectionClass($this);

        foreach ($this->factories as $name => $factory) {
            $services[] = self::underscore($name);
        }

        foreach ($container->getMethods() as $method) {
            if (!in_array($method->name, $reserved) && preg_match('/^get(.+)$/', $method->name, $match)) {
                $services[] = self::underscore($match[1]);
            }
        }

        sort($services);

        return $services;
    }

public function getServiceIds ( ) { $ services = [ ] ; $ reserved = [ 'get' , 'getParameter' , 'getServiceIds' , 'getReturnType' ] ; $ container = new \ ReflectionClass ( $ this ) ; foreach ( $ this -> factories as $ name => $ factory ) { $ services [ ] = self :: underscore ( $ name ) ; } foreach ( $ container -> getMethods ( ) as $ method ) { if ( ! in_array ( $ method -> name , $ reserved ) && preg_match ( '/^get(.+)$/' , $ method -> name , $ match ) ) { $ services [ ] = self :: underscore ( $ match [ 1 ] ) ; } } sort ( $ services ) ; return $ services ; }

Returns all available service ids of this container

@return array
@throws \ReflectionException


public function getReturnType($name)
    {
        $container = new ReflectionClass($this);

        try {
            $method = $container->getMethod('get' . self::normalizeName($name));
            $doc    = $method->getDocComment();

            if (!empty($doc)) {
                preg_match('/@return ([a-zA-Z0-9_\x7f-\xff\x5c]+)/', $doc, $matches);

                if (isset($matches[1])) {
                    return $matches[1];
                }
            }
        } catch (ReflectionException $e) {
            // method does not exist
        }

        // as fallback we get the service and return the used type
        $service = $this->get($name);

        if (is_object($service)) {
            return get_class($service);
        } else {
            return gettype($service);
        }
    }

Tries to determine the return type of a service. At first we try to
determine the type from the return annotation which is in most cases
more useful because it could specify an interface instead of an concrete
implementation. As fallback we get an instance of the service and return
the type

@param string $name
@return string
@throws \ReflectionException
@throws \Psr\Container\NotFoundExceptionInterface

Tries to determine the return type of a service . At first we try to determine the type from the return annotation which is in most cases more useful because it could specify an interface instead of an concrete implementation . As fallback we get an instance of the service and return the type


public function exec($balances, $trans)
    {
        $result = [];
        foreach ($trans as $one) {
            $accDebit = $one->getDebitAccId();
            $accCredit = $one->getCreditAccId();
            $timestamp = $one->getDateApplied();
            $value = $one->getValue();
            /* date_applied is in UTC format */
            $date = $this->hlpPeriod->getPeriodCurrent($timestamp);
            /**
             * Process debit account:
             */
            /** @var EBalance $entry Get balance on the transaction date (calculated or new) */
            $entry = $this->getBalanceEntry($balances, $result, $accDebit, $date);
            /* change total debit for the entry */
            $totalDebit = $entry->getTotalDebit() + $value;
            $entry->setTotalDebit($totalDebit);
            /* change close balance for the entry */
            $balanceClose = $entry->getBalanceClose() - $value;
            $entry->setBalanceClose($balanceClose);
            /* update calculated entries for result balances */
            $result[$accDebit][$date] = $entry;
            /* update current balances in the working var */
            if (isset($balances[$accDebit])) {
                $balances[$accDebit] -= $value;
            } else {
                $balances[$accDebit] = -$value;
            }
            /**
             * Process credit account:
             */
            /* get balance on the transaction date (calculated or new) */
            $entry = $this->getBalanceEntry($balances, $result, $accCredit, $date);
            /* change total credit for the entry */
            $totalCredit = $entry->getTotalCredit() + $value;
            $entry->setTotalCredit($totalCredit);
            /* change close balance for the entry */
            $balanceClose = $entry->getBalanceClose() + $value;
            $entry->setBalanceClose($balanceClose);
            /* update calculated entries for result balances */
            $result[$accCredit][$date] = $entry;
            /* update current balances in the working var */
            if (isset($balances[$accCredit])) {
                $balances[$accCredit] += $value;
            } else {
                $balances[$accCredit] = $value;
            }
        }
        return $result;
    }

/**
             * Process debit account:
             */

/**
             * Process credit account:
             */

Collect transactions and compose daily balances updates.

@param array $balances [accId => balance]
@param ETrans[] $trans
@return array [accId => EBalance[]]
@throws \Exception

Collect transactions and compose daily balances updates .


private function getBalanceEntry($current, $balances, $accId, $datestamp)
    {
        if (isset($balances[$accId][$datestamp])) {
            /* there is data for this account on this date */
            $result = $balances[$accId][$datestamp];
        } else {
            /* there is NO data for this account on this date */
            $result = new EBalance();
            $result->setAccountId($accId);
            $result->setDate($datestamp);
            $result->setBalanceOpen(0);
            $result->setTotalDebit(0);
            $result->setTotalCredit(0);
            $result->setBalanceClose(0);
            if (isset($current[$accId])) {
                /* we need to update entry balances for newly created entry */
                $result->setBalanceOpen($current[$accId]);
                $result->setBalanceClose($current[$accId]);
            }
        }
        return $result;
    }

Extract existing balance on the date or create new empty entity.

@param array $current [accId => balance]
@param EBalance[] $balances
@param $accId
@param $datestamp
@return EBalance
@throws \Exception

Extract existing balance on the date or create new empty entity .


protected final static function hierarchy(){
		$Hierarchy = [get_called_class()];

		while(class_exists($class = get_parent_class($Hierarchy[count($Hierarchy) -1]))){
			array_push($Hierarchy, $class);
		}

		return $Hierarchy;
	}

protected final static function hierarchy ( ) { $ Hierarchy = [ get_called_class ( ) ] ; while ( class_exists ( $ class = get_parent_class ( $ Hierarchy [ count ( $ Hierarchy ) - 1 ] ) ) ) { array_push ( $ Hierarchy , $ class ) ; } return $ Hierarchy ; }

Retrieves hierarchical list of the class ancestors.

@attention The called class name is included.
@return array

Retrieves hierarchical list of the class ancestors .


public function changeContentType($type)
    {

        $mime = [
            'json' => 'application/json',
            'javascript' => 'application/javascript',
            'js' => 'application/javascript',
            'ogg' => 'audio/ogg',
            'mpeg' => 'audio/mpeg',
            'html' => 'text/html',
            'plain' => 'text/plain',
            'urlencoded' => 'application/x-www-form-urlencoded'
        ];

        if (array_key_exists($type, $mime)) {
            $this->unsetHeader('Content-Type');
            $this->setHeader('Content-Type', $mime[$type]);
        }

        return $this;

    }

public function changeContentType ( $ type ) { $ mime = [ 'json' => 'application/json' , 'javascript' => 'application/javascript' , 'js' => 'application/javascript' , 'ogg' => 'audio/ogg' , 'mpeg' => 'audio/mpeg' , 'html' => 'text/html' , 'plain' => 'text/plain' , 'urlencoded' => 'application/x-www-form-urlencoded' ] ; if ( array_key_exists ( $ type , $ mime ) ) { $ this -> unsetHeader ( 'Content-Type' ) ; $ this -> setHeader ( 'Content-Type' , $ mime [ $ type ] ) ; } return $ this ; }

Change header content type

@param string $type

@return $this


private function headerParse($rawHeader)
    {

        $headers = array();

        $headerLine = substr($rawHeader, 0, strpos($rawHeader, "\r\n\r\n"));

        foreach (explode("\r\n", $headerLine) as $i => $line) {
            if ($i === 0) {
                $headers['Status-Line'] = $line;
                continue;
            }

            list ($key, $value) = explode(': ', $line);
            $headers[$key] = $value;
        }

        return $headers;
    }

private
function
headerParse
(
$
rawHeader
)
{
$
headers
=
array
(
)
;
$
headerLine
=
substr
(
$
rawHeader
,
0
,
strpos
(
$
rawHeader
,
"\r\n\r\n"
)
)
;
foreach
(
explode
(
"\r\n"
,
$
headerLine
)
as
$
i
=>
$
line
)
{
if
(
$
i
===
0
)
{
$
headers
[
'Status-Line'
]
=
$
line
;
continue
;
}
list
(
$
key
,
$
value
)
=
explode
(
': '
,
$
line
)
;
$
headers
[
$
key
]
=
$
value
;
}
return
$
headers
;
}

Parser for headers

@param $rawHeader

@return array


public function convertToArray($string, $value)
    {
        $keys = explode('.', $string);

        return $this->buildDimensionalArray($keys, count($keys), $value);
    }

public function convertToArray ( $ string , $ value ) { $ keys = explode ( '.' , $ string ) ; return $ this -> buildDimensionalArray ( $ keys , count ( $ keys ) , $ value ) ; }

Convert dotted string to a nested array.
Append the value to the last nested array.

@param string $string
@param string $value

@return string|array

Convert dotted string to a nested array . Append the value to the last nested array .


private function buildDimensionalArray(array $keys, $dimensions, $value)
    {
        $result = [];

        // add first dimension
        $result[$keys[0]] = [];
        $pointer = &$result[$keys[0]];

        for ($i = 1; $i < $dimensions; $i++) {
            if ($i === ($dimensions - 1)) {
                $pointer[$keys[$i]] = $value;
            } else {
                $pointer[$keys[$i]] = [];
                $pointer = &$pointer[$keys[$i]];
            }
        }

        return $result;
    }

private
function
buildDimensionalArray
(
array
$
keys
,
$
dimensions
,
$
value
)
{
$
result
=
[
]
;
// add first dimension
$
result
[
$
keys
[
0
]
]
=
[
]
;
$
pointer
=
&
$
result
[
$
keys
[
0
]
]
;
for
(
$
i
=
1
;
$
i
<
$
dimensions
;
$
i
++
)
{
if
(
$
i
===
(
$
dimensions
1
)
)
{
$
pointer
[
$
keys
[
$
i
]
]
=
$
value
;
}
else
{
$
pointer
[
$
keys
[
$
i
]
]
=
[
]
;
$
pointer
=
&
$
pointer
[
$
keys
[
$
i
]
]
;
}
}
return
$
result
;
}

Builds nested array with the specified keys.

@param array $keys
@param int $dimensions
@param string $value

@return array

Builds nested array with the specified keys .


private function getAssetTypes($typeIds, $typeCodes)
    {
        $result = [];
        $types = $this->daoTypeAsset->get();
        if (
            empty($typeIds) &&
            empty($typeCodes)
        ) {
            /* return all asset types */
            /** @var ETypeAsset $type */
            foreach ($types as $type) {
                $typeId = $type->getId();
                $typeCode = $type->getCode();
                $result[$typeId] = $typeCode;
            }
        } else {
            /* validate ID for given type ID or convert type code to type ID */
            /** @var ETypeAsset $type */
            foreach ($types as $type) {
                $typeId = $type->getId();
                $typeCode = $type->getCode();
                if (
                    (is_array($typeIds) && in_array($typeId, $typeIds)) ||
                    (is_array($typeCodes) && in_array($typeCode, $typeCodes))
                ) {
                    $result[$typeId] = $typeCode;
                }
            }
        }
        return $result;
    }

Validate given asset type or get all types.

@param int[] $typeIds
@param string[] $typeCodes
@return array [id => code]

Validate given asset type or get all types .


public function exec($assetTypeId)
    {
        /* get the last date with balances for given asset then take previous date */
        $dsLast = $this->getDateBalanceClose($assetTypeId);
        $dsPrev = $this->hlpPeriod->getPeriodPrev($dsLast);
        /* get all closing balances for previous date */
        $balances = $this->getBalances($assetTypeId, $dsPrev);
        /* get all accounts with given asset type */
        $accounts = $this->getAccounts($assetTypeId);
        /* get all transactions starting from "balance close -1 day" for given asset */
        $trans = $this->getTransactions($assetTypeId, $dsPrev);
        /* then validate current balances */
        $this->validate($accounts, $balances, $trans);
    }

Validate balances for one asset type.

@param int $assetTypeId
@throws \Exception


private function getDateBalanceClose($typeId)
    {
        $req = new ARequestLastDate();
        $req->setAssetTypeId($typeId);
        /** @var AResponseLastDate $resp */
        $resp = $this->servLastDate->exec($req);
        $result = $resp->getLastDate();
        return $result;
    }

private
function
getDateBalanceClose
(
$
typeId
)
{
$
req
=
new
ARequestLastDate
(
)
;
$
req
->
setAssetTypeId
(
$
typeId
)
;
/** @var AResponseLastDate $resp */
$
resp
=
$
this
->
servLastDate
->
exec
(
$
req
)
;
$
result
=
$
resp
->
getLastDate
(
)
;
return
$
result
;
}

Get datestamp for the last day of available balances.

@param int $typeId asset type
@return string YYYYMMDD
@throws \Exception

Get datestamp for the last day of available balances .


public function checkAction($strategy)
    {
        $config = $this->get('dcs_opauth.strategy_parser')->get($strategy);
        $opauth = new \Opauth($config, false);

        $this->dispatchEvent(DCSOpauthEvents::BEFORE_PARSE_RESPONSE, new OpauthEvent($opauth));

        $responseData = $this->get('dcs_opauth.response_parser')->parse($opauth);

        // Check if there are errors from the provider
        $isValid = !isset($responseData['error']);

        $event = new OpauthResponseEvent($opauth, $responseData, $isValid);
        $this->dispatchEvent(DCSOpauthEvents::AFTER_PARSE_RESPONSE, $event);

        // If there are no errors, and authentication is enabled, create the token with the data provider
        if ($isValid && $event->getAuthenticate()) {
            $this->get('dcs_opauth.authenticator')->authenticate($responseData);
        }

        // Verify if the response is set
        if (null === $response = $event->getResponse()) {
            if ($isValid) {
                if (null === $routeRedirect = $this->container->getParameter('dcs_opauth.redirect_after_response')) {
                    $url = '/'.ltrim($this->get('request')->getBaseUrl(), '/');
                } else {
                    // Check if route exists
                    try {
                        $url = $this->generateUrl($routeRedirect);
                    } catch (RouteNotFoundException $e) {
                        $url = $routeRedirect;
                    }
                }
                // Create default response
                $response = new RedirectResponse($url);
            } else {
                $response = $this->render($this->container->getParameter('dcs_opauth.error_view'), $responseData['error']);
            }
        }

        return $response;
    }


protected final function mutate(string $prefix, string $name, $value = null) {
		return method_exists($this, $method = Src::tcm(strtolower(Str::join('_', $prefix, $name , 'property'))))
			? call_user_func([$this, $method], $value) : $value;
	}

protected final function mutate ( string $ prefix , string $ name , $ value = null ) { return method_exists ( $ this , $ method = Src :: tcm ( strtolower ( Str :: join ( '_' , $ prefix , $ name , 'property' ) ) ) ) ? call_user_func ( [ $ this , $ method ] , $ value ) : $ value ; }

Checks if mutator exists and returns the mutated value.

@param string $prefix
Any prefix like 'get' or 'set' to separate getters and setters for example.

@param string $name
It will be converted into the camel case
via underscores like a separator.

@param $value
Some parameters if needed.

@return mixed
The value will be returned "as is" if the requested mutator doesn't exist.

Checks if mutator exists and returns the mutated value .


public function fetch($url)
    {
        $this->builder = new Builder(urlencode($url));

        foreach ($this->defaults as $key => $value) {
            if (method_exists($this->builder, $key)) {
                call_user_func([$this->builder, $key], $value);
            }
        }

        return $this;
    }

public function fetch ( $ url ) { $ this -> builder = new Builder ( urlencode ( $ url ) ) ; foreach ( $ this -> defaults as $ key => $ value ) { if ( method_exists ( $ this -> builder , $ key ) ) { call_user_func ( [ $ this -> builder , $ key ] , $ value ) ; } } return $ this ; }

Let the client fetch the given url as image.

@param string $url
@return $this

Let the client fetch the given url as image .


public function url()
    {
        if (!isset($this->config['url'])) {
            throw InvalidConfigurationException::urlNotDefined();
        }

        if (!isset($this->config['client'])) {
            throw InvalidConfigurationException::clientNotDefined();
        }

        return implode('/', array_filter([
            $this->config['url'],
            $this->config['client'],
            $this->getResourceKey(),
            $this->getTypeKey(),
            $this->builder->getManipulations(),
            $this->builder->getKey(),
        ]));
    }

public function url ( ) { if ( ! isset ( $ this -> config [ 'url' ] ) ) { throw InvalidConfigurationException :: urlNotDefined ( ) ; } if ( ! isset ( $ this -> config [ 'client' ] ) ) { throw InvalidConfigurationException :: clientNotDefined ( ) ; } return implode ( '/' , array_filter ( [ $ this -> config [ 'url' ] , $ this -> config [ 'client' ] , $ this -> getResourceKey ( ) , $ this -> getTypeKey ( ) , $ this -> builder -> getManipulations ( ) , $ this -> builder -> getKey ( ) , ] ) ) ; }

Retrieve the imaginary url.

@return string


public function generate()
    {
        // validate doc url and sheets
        if (!$this->validator->validateDocUrl($this->csvUrl)) {
            throw new Exception('Provided doc url is not valid.');
        }

        $this->validator->validateSheets($this->sheets);

        $strings = [];

        foreach ($this->sheets as $locale => $csvId) {
            // create locale directories
            $this->createDirectory($this->target . '/' . $locale);

            $localized = $this->localize($csvId);
            $strings[$locale] = $localized;

            // create strings in language file
            $stringsFile = $this->target . '/' . $locale . '/' . $this->languageFilename . '.php';
            $phpFormatted = '<?php return ' . var_export($localized, true) . ';';

            file_put_contents($stringsFile, $phpFormatted);

            // save strings in json format
            $this->backup($localized, $this->backup, $locale . '.json');
        }

        return $strings;
    }

public
function
generate
(
)
{
// validate doc url and sheets
if
(
!
$
this
->
validator
->
validateDocUrl
(
$
this
->
csvUrl
)
)
{
throw
new
Exception
(
'Provided doc url is not valid.'
)
;
}
$
this
->
validator
->
validateSheets
(
$
this
->
sheets
)
;
$
strings
=
[
]
;
foreach
(
$
this
->
sheets
as
$
locale
=>
$
csvId
)
{
// create locale directories
$
this
->
createDirectory
(
$
this
->
target
.
'/'
.
$
locale
)
;
$
localized
=
$
this
->
localize
(
$
csvId
)
;
$
strings
[
$
locale
]
=
$
localized
;
// create strings in language file
$
stringsFile
=
$
this
->
target
.
'/'
.
$
locale
.
'/'
.
$
this
->
languageFilename
.
'.php'
;
$
phpFormatted
=
'<?php return '
.
var_export
(
$
localized
,
true
)
.
';'
;
file_put_contents
(
$
stringsFile
,
$
phpFormatted
)
;
// save strings in json format
$
this
->
backup
(
$
localized
,
$
this
->
backup
,
$
locale
.
'.json'
)
;
}
return
$
strings
;
}

Generates the copy from the sheets.
Language files and JSON for storage.

@return array

Generates the copy from the sheets . Language files and JSON for storage .


private function parse($csvUrl)
    {
        $csvFile = fopen($csvUrl, 'r');
        $strings = [];

        if ($csvFile !== false) {
            while (($row = fgetcsv($csvFile, 1000, ',')) !== false) {
                if ($row[0] !== '' && $row[0] !== 'id') {
                    $id = $this->str->strip($row[0]);
                    $value = $row[1];

                    if ($this->nested) {
                        if ($this->str->hasDots($id)) {
                            $strings = array_replace_recursive($strings, $this->str->convertToArray($id, $value));
                        } else {
                            $strings[$id] = $value;
                        }
                    } else {
                        $strings[$id] = $value;
                    }
                }
            }

            fclose($csvFile);
        }

        return $strings;
    }

private function parse ( $ csvUrl ) { $ csvFile = fopen ( $ csvUrl , 'r' ) ; $ strings = [ ] ; if ( $ csvFile !== false ) { while ( ( $ row = fgetcsv ( $ csvFile , 1000 , ',' ) ) !== false ) { if ( $ row [ 0 ] !== '' && $ row [ 0 ] !== 'id' ) { $ id = $ this -> str -> strip ( $ row [ 0 ] ) ; $ value = $ row [ 1 ] ; if ( $ this -> nested ) { if ( $ this -> str -> hasDots ( $ id ) ) { $ strings = array_replace_recursive ( $ strings , $ this -> str -> convertToArray ( $ id , $ value ) ) ; } else { $ strings [ $ id ] = $ value ; } } else { $ strings [ $ id ] = $ value ; } } } fclose ( $ csvFile ) ; } return $ strings ; }

Parse provided csv document.

@param string $csvUrl Url of google doc.

@return array


private function localize($csvId)
    {
        $strings = [];
        $urlPart = '&single=true&gid=';

        if (is_array($csvId)) {
            foreach ($csvId as $id) {
                $parsed = $this->parse($this->csvUrl . $urlPart . $id);
                $strings = array_merge($strings, $parsed);
            }
        } else {
            $strings = $this->parse($this->csvUrl . $urlPart . $csvId);
        }

        return $strings;
    }

private function localize ( $ csvId ) { $ strings = [ ] ; $ urlPart = '&single=true&gid=' ; if ( is_array ( $ csvId ) ) { foreach ( $ csvId as $ id ) { $ parsed = $ this -> parse ( $ this -> csvUrl . $ urlPart . $ id ) ; $ strings = array_merge ( $ strings , $ parsed ) ; } } else { $ strings = $ this -> parse ( $ this -> csvUrl . $ urlPart . $ csvId ) ; } return $ strings ; }

Append sheet array by locale.
If array is provided append the sheets to the same locale.

@param string/array $csvId Id of csv doc.

@return array

Append sheet array by locale . If array is provided append the sheets to the same locale .


private function backup(array $strings, $path, $filename)
    {
        $stringsFile = $path . '/' . $filename;
        $jsonStrings = json_encode($strings, JSON_PRETTY_PRINT);

        $this->createDirectory($path);

        file_put_contents($stringsFile, $jsonStrings);
    }

private function backup ( array $ strings , $ path , $ filename ) { $ stringsFile = $ path . '/' . $ filename ; $ jsonStrings = json_encode ( $ strings , JSON_PRETTY_PRINT ) ; $ this -> createDirectory ( $ path ) ; file_put_contents ( $ stringsFile , $ jsonStrings ) ; }

Save backup strings in JSON format

@param array $strings
@param string $path
@param string $filename

@return void


public function getAllByAssetTypeCode($assetTypeCode)
    {
        /* aliases and tables */
        $asType = 'at';
        $asAcc = 'acc';
        /* SELECT FROM prxgt_acc_type_asset */
        $query = $this->conn->select();
        $tbl = $this->resource->getTableName(TypeAsset::ENTITY_NAME);
        $cols = [];
        $query->from([$asType => $tbl], $cols);
        /* LEFT JOIN prxgt_acc_account */
        $tbl = $this->resource->getTableName(Entity::ENTITY_NAME);
        $on = $asAcc . '.' . Entity::A_ASSET_TYPE_ID . '=' . $asType . '.' . TypeAsset::A_ID;
        $cols = [
            Entity::A_ID,
            Entity::A_ASSET_TYPE_ID,
            Entity::A_BALANCE,
            Entity::A_CUST_ID
        ];
        $query->joinLeft([$asAcc => $tbl], $on, $cols);
        /* WHERE */
        $where = $asType . '.' . TypeAsset::A_CODE . '=:' . self::BIND_CODE;
        $query->where($where);
        /* bind vars and fetch results */
        $bind = [self::BIND_CODE => $assetTypeCode];
        $rs = $this->conn->fetchAll($query, $bind);
        $result = [];
        foreach ($rs as $one) {
            $item = new Entity($one);
            $result[$item->getId()] = $item;
        }
        return $result;
    }

public
function
getAllByAssetTypeCode
(
$
assetTypeCode
)
{
/* aliases and tables */
$
asType
=
'at'
;
$
asAcc
=
'acc'
;
/* SELECT FROM prxgt_acc_type_asset */
$
query
=
$
this
->
conn
->
select
(
)
;
$
tbl
=
$
this
->
resource
->
getTableName
(
TypeAsset
::
ENTITY_NAME
)
;
$
cols
=
[
]
;
$
query
->
from
(
[
$
asType
=>
$
tbl
]
,
$
cols
)
;
/* LEFT JOIN prxgt_acc_account */
$
tbl
=
$
this
->
resource
->
getTableName
(
Entity
::
ENTITY_NAME
)
;
$
on
=
$
asAcc
.
'.'
.
Entity
::
A_ASSET_TYPE_ID
.
'='
.
$
asType
.
'.'
.
TypeAsset
::
A_ID
;
$
cols
=
[
Entity
::
A_ID
,
Entity
::
A_ASSET_TYPE_ID
,
Entity
::
A_BALANCE
,
Entity
::
A_CUST_ID
]
;
$
query
->
joinLeft
(
[
$
asAcc
=>
$
tbl
]
,
$
on
,
$
cols
)
;
/* WHERE */
$
where
=
$
asType
.
'.'
.
TypeAsset
::
A_CODE
.
'=:'
.
self
::
BIND_CODE
;
$
query
->
where
(
$
where
)
;
/* bind vars and fetch results */
$
bind
=
[
self
::
BIND_CODE
=>
$
assetTypeCode
]
;
$
rs
=
$
this
->
conn
->
fetchAll
(
$
query
,
$
bind
)
;
$
result
=
[
]
;
foreach
(
$
rs
as
$
one
)
{
$
item
=
new
Entity
(
$
one
)
;
$
result
[
$
item
->
getId
(
)
]
=
$
item
;
}
return
$
result
;
}

Get all accounts by asset type code.

@param string $assetTypeCode
@return \Praxigento\Accounting\Repo\Data\Account[]|null

SELECT
paa.*
FROM prxgt_acc_type_asset pata
LEFT JOIN prxgt_acc_account paa
ON pata.id = paa.asset_type_id
WHERE pata.code = "PV";


public function getAssetTypeId($accountId)
    {
        $result = null;
        /** @var Entity $entity */
        $entity = $this->getById($accountId);
        if ($entity) {
            $result = $entity->getAssetTypeId();
        }
        return $result;
    }

public
function
getAssetTypeId
(
$
accountId
)
{
$
result
=
;
/** @var Entity $entity */
$
entity
=
$
this
->
getById
(
$
accountId
)
;
if
(
$
entity
)
{
$
result
=
$
entity
->
getAssetTypeId
(
)
;
}
return
$
result
;
}

Get asset type ID for the given account.

@param int $accountId
@return int

Get asset type ID for the given account .


public function getCustomerAccByAssetCode($customerId, $assetTypeCode)
    {
        $assetTypeId = $this->daoTypeAsset->getIdByCode($assetTypeCode);
        $result = $this->getByCustomerId($customerId, $assetTypeId);
        return $result;
    }

public function getCustomerAccByAssetCode ( $ customerId , $ assetTypeCode ) { $ assetTypeId = $ this -> daoTypeAsset -> getIdByCode ( $ assetTypeCode ) ; $ result = $ this -> getByCustomerId ( $ customerId , $ assetTypeId ) ; return $ result ; }

Get account data by customer ID & asset type code.

@param int $customerId
@param string $assetTypeCode
@return Entity account ID

Get account data by customer ID & asset type code .


public function getSystemCustomerId()
    {
        if (is_null($this->cachedSysCustId)) {
            $conn = $this->conn;
            /* there is no cached value for the customer ID, select data from DB */
            $where = Cfg::E_CUSTOMER_A_EMAIL . '=' . $conn->quote(Cfg::SYS_CUSTOMER_EMAIL);
            $data = $this->daoGeneric->getEntities(Cfg::ENTITY_MAGE_CUSTOMER, Cfg::E_CUSTOMER_A_ENTITY_ID,
                $where);
            if (count($data) == 0) {
                $bind = [
                    Cfg::E_CUSTOMER_A_WEBSITE_ID => Cfg::DEF_WEBSITE_ID_ADMIN,
                    Cfg::E_CUSTOMER_A_EMAIL => Cfg::SYS_CUSTOMER_EMAIL
                ];
                $id = $this->daoGeneric->addEntity(Cfg::ENTITY_MAGE_CUSTOMER, $bind);
                if ($id > 0) {
                    $this->cachedSysCustId = $id;
                }
            } else {
                $first = reset($data);
                $this->cachedSysCustId = $first[Cfg::E_CUSTOMER_A_ENTITY_ID];
            }
        }
        return $this->cachedSysCustId;
    }

Return MageID for customer that represents store owner in accounting. Create new system customer
if it is not exist yet.

@return int

Return MageID for customer that represents store owner in accounting . Create new system customer if it is not exist yet .


public function exec($request)
    {
        assert($request instanceof ARequest);
        $result = new AResponse();
        $debitAccId = $request->getDebitAccId();
        $creditAccId = $request->getCreditAccId();
        $operationId = $request->getOperationId();
        $dateApplied = $request->getDateApplied();
        $value = $request->getValue();
        $note = $request->getNote();

        /* limit amount by MIN & MAX */
        if (
            ($value > Cfg::LIMIT_AMOUNT_MAX) ||
            ($value < Cfg::LIMIT_AMOUNT_MIN)
        ) {
            throw new \Exception("Illegal value for amount transaction: $value.");
        }

        /* get account type for debit account */
        $debitAcc = $this->daoAcc->getById($debitAccId);
        $debitAssetTypeId = $debitAcc->getAssetTypeId();
        /* get account type for credit account */
        $creditAcc = $this->daoAcc->getById($creditAccId);
        $creditAssetTypeId = $creditAcc->getAssetTypeId();
        /* asset types should be equals */
        if (
            !is_null($debitAssetTypeId) &&
            ($debitAssetTypeId == $creditAssetTypeId)
        ) {
            /* add transaction */
            $toAdd = [
                ETransaction::A_OPERATION_ID => $operationId,
                ETransaction::A_DEBIT_ACC_ID => $debitAccId,
                ETransaction::A_CREDIT_ACC_ID => $creditAccId,
                ETransaction::A_VALUE => $value,
                ETransaction::A_DATE_APPLIED => $dateApplied
            ];
            if (!is_null($note)) {
                $toAdd[ETransaction::A_NOTE] = $note;
            }
            $idCreated = $this->daoTrans->create($toAdd);
            $result->setTransactionId($idCreated);
        } else {
            throw new \Exception("Asset type (#$debitAssetTypeId) for debit account #$debitAccId is not equal to "
                . "asset type (#$creditAssetTypeId) for credit account $creditAccId.");
        }
        $result->markSucceed();
        return $result;
    }

Add new transaction and update current balances.
@param ARequest $request
@return AResponse
@throws \Exception

Add new transaction and update current balances .


private function buildStrategiesKey($strategies)
    {
        foreach ($strategies as $name => $config) {
            switch ($config['strategy_class']) {
                case 'Basecamp':
                case 'Behance':
                case 'Bitly':
                case 'Do':
                case 'Dropbox':
                case 'Evernote':
                case 'Foursquare':
                case 'GitHub':
                case 'Google':
                case 'Harvest':
                case 'Instagram':
                case 'Live':
                case 'Mixi':
                case 'Strava':
                case 'Yahoojp':
                case 'Yammer':
                case 'ResourceGuru':
                    $config['client_id'] = $config['id'];
                    $config['client_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'Bitbucket':
                case 'Flickr':
                case 'SinaWeibo':
                case 'Twitter':
                case 'Vimeo':
                    $config['key'] = $config['id'];
                    unset($config['id']);
                    break;
                case 'Disqus':
                    $config['api_key'] = $config['id'];
                    $config['api_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'LinkedIn':
                    $config['api_key'] = $config['id'];
                    $config['secret_key'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'Facebook':
                case 'PayPal':
                case 'VKontakte':
                    $config['app_id'] = $config['id'];
                    $config['app_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
                case 'Tumblr':
                    $config['consumer_key'] = $config['id'];
                    $config['consumer_secret'] = $config['secret'];
                    unset($config['id']);
                    unset($config['secret']);
                    break;
            }
            // Set new configuration
            $strategies[$name] = $config;
        }

        return $strategies;
    }

private
function
buildStrategiesKey
(
$
strategies
)
{
foreach
(
$
strategies
as
$
name
=>
$
config
)
{
switch
(
$
config
[
'strategy_class'
]
)
{
case
'Basecamp'
:
case
'Behance'
:
case
'Bitly'
:
case
'Do'
:
case
'Dropbox'
:
case
'Evernote'
:
case
'Foursquare'
:
case
'GitHub'
:
case
'Google'
:
case
'Harvest'
:
case
'Instagram'
:
case
'Live'
:
case
'Mixi'
:
case
'Strava'
:
case
'Yahoojp'
:
case
'Yammer'
:
case
'ResourceGuru'
:
$
config
[
'client_id'
]
=
$
config
[
'id'
]
;
$
config
[
'client_secret'
]
=
$
config
[
'secret'
]
;
unset
(
$
config
[
'id'
]
)
;
unset
(
$
config
[
'secret'
]
)
;
break
;
case
'Bitbucket'
:
case
'Flickr'
:
case
'SinaWeibo'
:
case
'Twitter'
:
case
'Vimeo'
:
$
config
[
'key'
]
=
$
config
[
'id'
]
;
unset
(
$
config
[
'id'
]
)
;
break
;
case
'Disqus'
:
$
config
[
'api_key'
]
=
$
config
[
'id'
]
;
$
config
[
'api_secret'
]
=
$
config
[
'secret'
]
;
unset
(
$
config
[
'id'
]
)
;
unset
(
$
config
[
'secret'
]
)
;
break
;
case
'LinkedIn'
:
$
config
[
'api_key'
]
=
$
config
[
'id'
]
;
$
config
[
'secret_key'
]
=
$
config
[
'secret'
]
;
unset
(
$
config
[
'id'
]
)
;
unset
(
$
config
[
'secret'
]
)
;
break
;
case
'Facebook'
:
case
'PayPal'
:
case
'VKontakte'
:
$
config
[
'app_id'
]
=
$
config
[
'id'
]
;
$
config
[
'app_secret'
]
=
$
config
[
'secret'
]
;
unset
(
$
config
[
'id'
]
)
;
unset
(
$
config
[
'secret'
]
)
;
break
;
case
'Tumblr'
:
$
config
[
'consumer_key'
]
=
$
config
[
'id'
]
;
$
config
[
'consumer_secret'
]
=
$
config
[
'secret'
]
;
unset
(
$
config
[
'id'
]
)
;
unset
(
$
config
[
'secret'
]
)
;
break
;
}
// Set new configuration
$
strategies
[
$
name
]
=
$
config
;
}
return
$
strategies
;
}

Converts the key id and secret in the keys suitable for every strategy

@param $strategies
@return array


public function parse(\Opauth $opauth)
    {
        $callbackTransport = $opauth->env['callback_transport'];

        switch($callbackTransport) {
            case 'session':
                $response = $_SESSION['opauth'];
                unset($_SESSION['opauth']);
                break;
            case 'post':
                $response = unserialize(base64_decode($_POST['opauth']));
                break;
            case 'get':
                $response = unserialize(base64_decode($_GET['opauth']));
                break;
            default:
                throw new UnsupportedCallbackException(sprintf('Callback transport "%s" is not supported. Are only supported: session, post, get', $callbackTransport));
                break;
        }

        return $response;
    }

Parse response of the Opauth object

@param \Opauth $opauth
@return array
@throws \DCS\OpauthBundle\Exception\UnsupportedCallbackException


public function loginAction($strategy)
    {
        $config = $this->get('dcs_opauth.strategy_parser')->get($strategy);
        $opauth = new \Opauth($config);
    }

public function loginAction ( $ strategy ) { $ config = $ this -> get ( 'dcs_opauth.strategy_parser' ) -> get ( $ strategy ) ; $ opauth = new \ Opauth ( $ config ) ; }

Call the provider for the authentication


public function render($path, $data = [])
    {
        $this->data = array_merge($this->data, $data);
        $this->setPath($path);
        $contents = $this->renderContents();

        return $contents;
    }

public function render ( $ path , $ data = [ ] ) { $ this -> data = array_merge ( $ this -> data , $ data ) ; $ this -> setPath ( $ path ) ; $ contents = $ this -> renderContents ( ) ; return $ contents ; }

render Renders the view using the given data

@param $path
@param array $data
@return mixed


private function getAssetTypes()
    {
        $result = [];
        $types = $this->daoTypeAsset->get();
        /** @var ETypeAsset $type */
        foreach ($types as $type) {
            $typeId = $type->getId();
            $typeCode = $type->getCode();
            $result[$typeId] = $typeCode;
        }
        return $result;
    }

private
function
getAssetTypes
(
)
{
$
result
=
[
]
;
$
types
=
$
this
->
daoTypeAsset
->
get
(
)
;
/** @var ETypeAsset $type */
foreach
(
$
types
as
$
type
)
{
$
typeId
=
$
type
->
getId
(
)
;
$
typeCode
=
$
type
->
getCode
(
)
;
$
result
[
$
typeId
]
=
$
typeCode
;
}
return
$
result
;
}

Get all asset types.

@return array [id => code]


public function send()
	{
		if ($this->getProtocolVersion() && $this->getStatusCode()) {
			header(static::VERSION_DELIMITER . $this->getProtocolVersion() . ' ' . $this->getStatusCode() . ' ' . $this->getReasonPhrase());
		}

		foreach ($this->getHeaders() as $key => $value) {
			header($key . static::HEADER_DELIMITER . implode(static::HEADER_VALUE_DELIMITER, $value));
		}

		echo $this->getBody();
	}

public
function
send
(
)
{
if
(
$
this
->
getProtocolVersion
(
)
&&
$
this
->
getStatusCode
(
)
)
{
header
(
static
::
VERSION_DELIMITER
.
$
this
->
getProtocolVersion
(
)
.
' '
.
$
this
->
getStatusCode
(
)
.
' '
.
$
this
->
getReasonPhrase
(
)
)
;
}
foreach
(
$
this
->
getHeaders
(
)
as
$
key
=>
$
value
)
{
header
(
$
key
.
static
::
HEADER_DELIMITER
.
implode
(
static
::
HEADER_VALUE_DELIMITER
,
$
value
)
)
;
}
echo
$
this
->
getBody
(
)
;
}


public function authenticate($responseData)
    {
        $token = new OpauthToken($responseData, $this->roles);
        $this->securityContext->setToken($token);
    }

public function authenticate ( $ responseData ) { $ token = new OpauthToken ( $ responseData , $ this -> roles ) ; $ this -> securityContext -> setToken ( $ token ) ; }

Set token with the response data

@param $responseData


protected function verifyToken(Request $request)
    {
        $time = (int) ($request->input('_time') ?: $request->header('X-API-TIME'));
        $token = $request->input('_token') ?: $request->header('X-API-TOKEN');

        return abs(time() - $time) < (int) config('api.token_duration') &&
            $this->token->verify($token, $this->getKeyFromRequest($request), $time);
    }

protected function verifyToken ( Request $ request ) { $ time = ( int ) ( $ request -> input ( '_time' ) ? : $ request -> header ( 'X-API-TIME' ) ) ; $ token = $ request -> input ( '_token' ) ? : $ request -> header ( 'X-API-TOKEN' ) ; return abs ( time ( ) - $ time ) < ( int ) config ( 'api.token_duration' ) && $ this -> token -> verify ( $ token , $ this -> getKeyFromRequest ( $ request ) , $ time ) ; }

Verify the api token from request.

@param  \Illuminate\Http\Request  $request
@return bool


public function validateDocUrl($url)
    {
        $pattern = '/http:\/\/docs\.google\.com\/spreadsheets\/d\/.*\/export\?format=csv/';

        if (is_null($url) || $url === '' || preg_match($pattern, $url) !== 1) {
            return false;
        }

        return true;
    }

Provided url must be a valid google doc url.

@param string $url Url of google doc.

@return boolean

Provided url must be a valid google doc url .


protected function registerClient()
    {
        $this->app->singleton('api.client', function ($app) {
            $client = new Client(
                $app['encrypter'],
                $app['config']->get('api.clients', [])
            );

            $client->setDefaultAppKey($app['config']->get('api.default_client'));

            return $client;
        });

        $this->app->alias('api.client', Client::class);
    }

protected function registerClient ( ) { $ this -> app -> singleton ( 'api.client' , function ( $ app ) { $ client = new Client ( $ app [ 'encrypter' ] , $ app [ 'config' ] -> get ( 'api.clients' , [ ] ) ) ; $ client -> setDefaultAppKey ( $ app [ 'config' ] -> get ( 'api.default_client' ) ) ; return $ client ; } ) ; $ this -> app -> alias ( 'api.client' , Client :: class ) ; }

Register the Client singleton.

@return void


protected function registerToken()
    {
        $this->app->singleton('api.token', function ($app) {
            return new Token($app['api.client']);
        });

        $this->app->alias('api.token', Token::class);
    }

protected function registerToken ( ) { $ this -> app -> singleton ( 'api.token' , function ( $ app ) { return new Token ( $ app [ 'api.client' ] ) ; } ) ; $ this -> app -> alias ( 'api.token' , Token :: class ) ; }

Register the Token singleton.

@return void


protected function registerForConsole()
    {
        $this->publishes([
            __DIR__.'/../config/api.php' => base_path('config/api.php'),
        ], 'laravel-api');

        $this->commands([
            Console\GenerateClientCommand::class,
            Console\GenerateTokenCommand::class,
        ]);
    }

protected function registerForConsole ( ) { $ this -> publishes ( [ __DIR__ . '/../config/api.php' => base_path ( 'config/api.php' ) , ] , 'laravel-api' ) ; $ this -> commands ( [ Console \ GenerateClientCommand :: class , Console \ GenerateTokenCommand :: class , ] ) ; }


public static function start($name = null)
	{
		if (session_status() !== PHP_SESSION_NONE) {
			throw new \RuntimeException('Can\'t start a new session.');
		}

		if ($name !== null) {
			session_name($name);
		}

		session_start();
	}

public
static
function
start
(
$
name
=
)
{
if
(
session_status
(
)
!==
PHP_SESSION_NONE
)
{
throw
new
\
RuntimeException
(
'Can\'t start a new session.'
)
;
}
if
(
$
name
!==
)
{
session_name
(
$
name
)
;
}
session_start
(
)
;
}

Initialize the session, if none exists.

@param $name = null
@return null
@throws \RuntimeException on failure.


protected final static function retrospect(string $name){
		return call_user_func_array('array_merge', array_map(function($class) use ($name){
			return property_exists($class, $name) ? $class::${$name} : [];
		}, array_reverse(static::hierarchy())));
	}

protected final static function retrospect ( string $ name ) { return call_user_func_array ( 'array_merge' , array_map ( function ( $ class ) use ( $ name ) { return property_exists ( $ class , $ name ) ? $ class :: $ { $ name } : [ ] ; } , array_reverse ( static :: hierarchy ( ) ) ) ) ; }

Returns a static property value as an array
extended by a similar values provided by parent classes.

@param string $name
@return array

Returns a static property value as an array extended by a similar values provided by parent classes .


private function setStatus($statusCode, $reasonPhrase = '')
	{
		if ($reasonPhrase === '' && isset(self::$reasonPhrases[$statusCode])) {
			$reasonPhrase = self::$reasonPhrases[$statusCode];
		}

		$this->statusCode = $statusCode;
		$this->reasonPhrase = $reasonPhrase;

		return $this;
	}

private function setStatus ( $ statusCode , $ reasonPhrase = '' ) { if ( $ reasonPhrase === '' && isset ( self :: $ reasonPhrases [ $ statusCode ] ) ) { $ reasonPhrase = self :: $ reasonPhrases [ $ statusCode ] ; } $ this -> statusCode = $ statusCode ; $ this -> reasonPhrase = $ reasonPhrase ; return $ this ; }

Set the status.

@param int $statusCode
@param string $reasonPhrase = ''
@return $this


public function tree($css) {
        // Do stuff
        $this->_tokens = $this->tokenize($css);
        $results = $this->_parseTokens(array_shift($this->_tokens));

        // Add remaining items to root element
        while (count($this->_tokens)) {
            if (!$this->ignoreErrors) {
                $this->errors[] = new ParseError('Unmatched }', $this->_css, $this->_tokens[0]['index']);
            }
            $results = array_merge($results, $this->_parseTokens(array_shift($this->_tokens)));
        }

        return $results;
    }

public
function
tree
(
$
css
)
{
// Do stuff
$
this
->
_tokens
=
$
this
->
tokenize
(
$
css
)
;
$
results
=
$
this
->
_parseTokens
(
array_shift
(
$
this
->
_tokens
)
)
;
// Add remaining items to root element
while
(
count
(
$
this
->
_tokens
)
)
{
if
(
!
$
this
->
ignoreErrors
)
{
$
this
->
errors
[
]
=
new
ParseError
(
'Unmatched }'
,
$
this
->
_css
,
$
this
->
_tokens
[
0
]
[
'index'
]
)
;
}
$
results
=
array_merge
(
$
results
,
$
this
->
_parseTokens
(
array_shift
(
$
this
->
_tokens
)
)
)
;
}
return
$
results
;
}

Get tokens as tree

@param string $css
@return array


protected function _findTokens($tokens) {
        $list = [];

        foreach ($tokens as $token) {
            $index = 0;
            while (true) {
                $index = strpos($this->_cssLC, $token, $index);
                if ($index === false) {
                    break;
                }
                $list[] = [
                    'token' => $token,
                    'index' => $index
                ];
                $index ++;
            }
        }

        usort($list, function($a, $b) {
            return $a['index'] - $b['index'];
        });
        return $list;
    }

protected function _findTokens ( $ tokens ) { $ list = [ ] ; foreach ( $ tokens as $ token ) { $ index = 0 ; while ( true ) { $ index = strpos ( $ this -> _cssLC , $ token , $ index ) ; if ( $ index === false ) { break ; } $ list [ ] = [ 'token' => $ token , 'index' => $ index ] ; $ index ++ ; } } usort ( $ list , function ( $ a , $ b ) { return $ a [ 'index' ] - $ b [ 'index' ] ; } ) ; return $ list ; }

Find all tokens in code

@param array $tokens Array of tokens
@return array


protected function _findEndOfQuotedString($quote, $start) {
        $nextEscape = strpos($this->_css, '\\', $start + 1);
        $end = strpos($this->_css, $quote, $start + 1);

        if ($end === false) {
            // Invalid string
            return false;
        }

        while ($nextEscape !== false && $nextEscape < $end) {
            if ($end === $nextEscape + 1) {
                $end = strpos($this->_css, $quote, $end + 1);
                if ($end === false) {
                    // Invalid string
                    return false;
                }
            }
            $nextEscape = strpos($this->_css, '\\', $nextEscape + 2);
        }

        return $end + 1;
    }

protected
function
_findEndOfQuotedString
(
$
quote
,
$
start
)
{
$
nextEscape
=
strpos
(
$
this
->
_css
,
'\\'
,
$
start
+
1
)
;
$
end
=
strpos
(
$
this
->
_css
,
$
quote
,
$
start
+
1
)
;
if
(
$
end
===
false
)
{
// Invalid string
return
false
;
}
while
(
$
nextEscape
!==
false
&&
$
nextEscape
<
$
end
)
{
if
(
$
end
===
$
nextEscape
+
1
)
{
$
end
=
strpos
(
$
this
->
_css
,
$
quote
,
$
end
+
1
)
;
if
(
$
end
===
false
)
{
// Invalid string
return
false
;
}
}
$
nextEscape
=
strpos
(
$
this
->
_css
,
'\\'
,
$
nextEscape
+
2
)
;
}
return
$
end
+
1
;
}

Find end of quoted string

@param string $quote Quote character
@param int $start Position of first quote
@return int|bool Position of character after end of string, false if string is broken


protected function _findEndOfURL($start = 0) {
        $length = strlen($this->_css);
        $index = $start + 4;

        while ($index < $length) {
            $next = substr($this->_css, $index, 1);
            switch ($next) {
                case '"':
                case '\'':
                    // quoted url
                    $end = $this->_findEndOfQuotedString($next, $index);
                    if ($end === false) {
                        return new ParseError('Incomplete string', $this->_css, $index);
                    }
                    $end = strpos($this->_css, ')', $end);
                    return $end === false ? new ParseError('Cannot find end of URL', $this->_css, $start) : $end + 1;

                case ' ':
                case "\t":
                case "\r":
                case "\n":
                    // skip whitespace
                    $index ++;
                    break;

                default:
                    // unquoted url
                    while (true) {
                        switch ($next) {
                            case ')':
                                return $index + 1;

                            case '"':
                            case '\'':
                            case '(':
                            case ' ':
                            case "\t":
                            case "\r":
                            case "\n":
                                return new ParseError('Invalid URL', $this->_css, $start);

                            default:
                                if (ord(substr($this->_css, $index, 1)) < 32) {
                                    return new ParseError('Invalid URL', $this->_css, $start);
                                }
                        }
                        $index ++;
                        if ($index >= $length) {
                            return new ParseError('Cannot find end of URL', $this->_css, $start);
                        }
                        $next = substr($this->_css, $index, 1);
                    }
            }
        }
        return new ParseError('Cannot find end of URL', $this->_css, $start);
    }

protected
function
_findEndOfURL
(
$
start
=
0
)
{
$
length
=
strlen
(
$
this
->
_css
)
;
$
index
=
$
start
+
4
;
while
(
$
index
<
$
length
)
{
$
next
=
substr
(
$
this
->
_css
,
$
index
,
1
)
;
switch
(
$
next
)
{
case
'"'
:
case
'\''
:
// quoted url
$
end
=
$
this
->
_findEndOfQuotedString
(
$
next
,
$
index
)
;
if
(
$
end
===
false
)
{
return
new
ParseError
(
'Incomplete string'
,
$
this
->
_css
,
$
index
)
;
}
$
end
=
strpos
(
$
this
->
_css
,
')'
,
$
end
)
;
return
$
end
===
false
new
ParseError
(
'Cannot find end of URL'
,
$
this
->
_css
,
$
start
)
:
$
end
+
1
;
case
' '
:
case
"\t"
:
case
"\r"
:
case
"\n"
:
// skip whitespace
$
index
++
;
break
;
default
:
// unquoted url
while
(
true
)
{
switch
(
$
next
)
{
case
')'
:
return
$
index
+
1
;
case
'"'
:
case
'\''
:
case
'('
:
case
' '
:
case
"\t"
:
case
"\r"
:
case
"\n"
:
return
new
ParseError
(
'Invalid URL'
,
$
this
->
_css
,
$
start
)
;
default
:
if
(
ord
(
substr
(
$
this
->
_css
,
$
index
,
1
)
)
<
32
)
{
return
new
ParseError
(
'Invalid URL'
,
$
this
->
_css
,
$
start
)
;
}
}
$
index
++
;
if
(
$
index
>=
$
length
)
{
return
new
ParseError
(
'Cannot find end of URL'
,
$
this
->
_css
,
$
start
)
;
}
$
next
=
substr
(
$
this
->
_css
,
$
index
,
1
)
;
}
}
}
return
new
ParseError
(
'Cannot find end of URL'
,
$
this
->
_css
,
$
start
)
;
}

Find end of url

@param int $start
@return int|ParseError Position of character after end of url() or error message


protected function _checkRule($words, $extra, $ignoreErrors) {
        $pairs = $this->_findRulePairs($words);

        if (is_bool($pairs)) {
            $value = $this->_mergeWords($words) . $extra;
            if (!strlen($value)) {
                return false;
            }

            $index = $words[0]['index'];
            if ($pairs === false && !$this->ignoreErrors && !$ignoreErrors) {
                $this->errors[] = new ParseError('Invalid css rule', $this->_css, $index);
            }
            return [
                'token' => 'code',
                'code'  => $value,
                'index' => $index,
            ];
        }
        return $pairs;
    }

protected
function
_checkRule
(
$
words
,
$
extra
,
$
ignoreErrors
)
{
$
pairs
=
$
this
->
_findRulePairs
(
$
words
)
;
if
(
is_bool
(
$
pairs
)
)
{
$
value
=
$
this
->
_mergeWords
(
$
words
)
.
$
extra
;
if
(
!
strlen
(
$
value
)
)
{
return
false
;
}
$
index
=
$
words
[
0
]
[
'index'
]
;
if
(
$
pairs
===
false
&&
!
$
this
->
ignoreErrors
&&
!
$
ignoreErrors
)
{
$
this
->
errors
[
]
=
new
ParseError
(
'Invalid css rule'
,
$
this
->
_css
,
$
index
)
;
}
return
[
'token'
=>
'code'
,
'code'
=>
$
value
,
'index'
=>
$
index
,
]
;
}
return
$
pairs
;
}

Check for valid css rule, return either code or rule token

@param array $words Array of words
@param string $extra Additional text to add if returning code
@param bool $ignoreErrors True if errors should be ignored
@return array|bool

Check for valid css rule return either code or rule token


protected function _mergeWords($words) {
        $value = '';

        foreach ($words as $word) {
            $value .= $word['text'];
        }

        return trim($value);
    }

protected function _mergeWords ( $ words ) { $ value = '' ; foreach ( $ words as $ word ) { $ value .= $ word [ 'text' ] ; } return trim ( $ value ) ; }

Merge words list to string

@param array $words
@return string


protected function _checkSelectors($words) {
        $selectors = $this->_getSelectors($words);
        $result = [
            'token' => '{',
            'code'  => $this->_mergeWords($words),
            'index' => $words[0]['index'],
        ];

        if (!count($selectors)) {
            return $result;
        }

        if (substr($selectors[0], 0, 1) === '@') {
            $split = preg_split('/\s+/', $selectors[0]);
            $result['atRule'] = substr($split[0], 1);
            $selectors[0] = trim(substr($selectors[0], 1 + strlen($result['atRule'])));
            $result['atValues'] = $selectors;
        } else {
            $result['selectors'] = $selectors;
        }

        return $result;
    }

protected function _checkSelectors ( $ words ) { $ selectors = $ this -> _getSelectors ( $ words ) ; $ result = [ 'token' => '{' , 'code' => $ this -> _mergeWords ( $ words ) , 'index' => $ words [ 0 ] [ 'index' ] , ] ; if ( ! count ( $ selectors ) ) { return $ result ; } if ( substr ( $ selectors [ 0 ] , 0 , 1 ) === '@' ) { $ split = preg_split ( '/\s+/' , $ selectors [ 0 ] ) ; $ result [ 'atRule' ] = substr ( $ split [ 0 ] , 1 ) ; $ selectors [ 0 ] = trim ( substr ( $ selectors [ 0 ] , 1 + strlen ( $ result [ 'atRule' ] ) ) ) ; $ result [ 'atValues' ] = $ selectors ; } else { $ result [ 'selectors' ] = $ selectors ; } return $ result ; }

Get token with selectors list

@param array $words
@return array


protected function _getSelectors($words) {
        $selectors = [];
        $selector = '';

        foreach ($words as $word) {
            if ($word['type'] !== 'text') {
                $selector .= $word['text'];
                continue;
            }

            $list = explode(',', $word['text']);
            $selector .= array_shift($list);
            while (count($list) > 0) {
                $selectors[] = trim($selector);
                $selector = array_shift($list);
            }
        }

        $selectors[] = trim($selector);

        $results = [];
        foreach ($selectors as $row) {
            if (strlen($row) > 0) {
                $results[] = $row;
            }
        }
        return $results;
    }

protected function _getSelectors ( $ words ) { $ selectors = [ ] ; $ selector = '' ; foreach ( $ words as $ word ) { if ( $ word [ 'type' ] !== 'text' ) { $ selector .= $ word [ 'text' ] ; continue ; } $ list = explode ( ',' , $ word [ 'text' ] ) ; $ selector .= array_shift ( $ list ) ; while ( count ( $ list ) > 0 ) { $ selectors [ ] = trim ( $ selector ) ; $ selector = array_shift ( $ list ) ; } } $ selectors [ ] = trim ( $ selector ) ; $ results = [ ] ; foreach ( $ selectors as $ row ) { if ( strlen ( $ row ) > 0 ) { $ results [ ] = $ row ; } } return $ results ; }

Get list of selectors from list of words

@param array $words
@return array


protected function _parseTokens($item) {
        $results = [];
        while ($item !== null) {
            switch ($item['token']) {
                case '}':
                    return $results;

                case '{':
                    $item['children'] = $this->_parseTokens(array_shift($this->_tokens));
                    $results[] = $item;
                    break;

                default:
                    $results[] = $item;
            }

            $item = array_shift($this->_tokens);
        }
        return $results;
    }

protected function _parseTokens ( $ item ) { $ results = [ ] ; while ( $ item !== null ) { switch ( $ item [ 'token' ] ) { case '}' : return $ results ; case '{' : $ item [ 'children' ] = $ this -> _parseTokens ( array_shift ( $ this -> _tokens ) ) ; $ results [ ] = $ item ; break ; default : $ results [ ] = $ item ; } $ item = array_shift ( $ this -> _tokens ) ; } return $ results ; }

Convert to tree

@param array $item
@return array


public static function setCurrentAppKeyForRequest($key, Request $request = null)
    {
        $request = $request ?: app('request');

        $request->attributes->set(static::CURRENT_APP_KEY, $key);

        return $request;
    }

public static function setCurrentAppKeyForRequest ( $ key , Request $ request = null ) { $ request = $ request ? : app ( 'request' ) ; $ request -> attributes -> set ( static :: CURRENT_APP_KEY , $ key ) ; return $ request ; }

Set the current app key for the request.

@param  string  $key
@param  \Illuminate\Http\Request|null  $request
@return \Illuminate\Http\Request

Set the current app key for the request .