public function newCFDIReader(
        string $content,
        array &$errors = [],
        array &$warnings = [],
        bool $requireTimbre = true
    ): CFDIReader {
        // before creation
        $schemaValidator = $this->newSchemasValidator();
        $schemaValidator->validate($content);

        // creation
        $cfdireader = new CFDIReader($content, $requireTimbre);

        // after creation
        $postValidator = $this->newPostValidator();
        $postValidator->validate($cfdireader);
        $errors = $postValidator->issues->messages(PostValidations\IssuesTypes::ERROR)->all();
        $warnings = $postValidator->issues->messages(PostValidations\IssuesTypes::WARNING)->all();
        return $cfdireader;
    }

public
function
newCFDIReader
(
string
$
content
,
array
&
$
errors
=
[
]
,
array
&
$
warnings
=
[
]
,
bool
$
requireTimbre
=
true
)
:
CFDIReader
{
// before creation
$
schemaValidator
=
$
this
->
newSchemasValidator
(
)
;
$
schemaValidator
->
validate
(
$
content
)
;
// creation
$
cfdireader
=
new
CFDIReader
(
$
content
,
$
requireTimbre
)
;
// after creation
$
postValidator
=
$
this
->
newPostValidator
(
)
;
$
postValidator
->
validate
(
$
cfdireader
)
;
$
errors
=
$
postValidator
->
issues
->
messages
(
PostValidations
\
IssuesTypes
::
ERROR
)
->
all
(
)
;
$
warnings
=
$
postValidator
->
issues
->
messages
(
PostValidations
\
IssuesTypes
::
WARNING
)
->
all
(
)
;
return
$
cfdireader
;
}

Create a CFDI Reader, it has to be valid otherwise a exception will be thrown
@param string $content
@param array $errors
@param array $warnings
@param bool $requireTimbre
@return CFDIReader

Create a CFDI Reader it has to be valid otherwise a exception will be thrown


public function handle(CommandInterface $command)
    {
        if (!$commandHandler = $this->handlerResolver->resolve($command)) {
            throw new HandlerNotFoundException();
        }

        $commandHandler->handle($command);
    }

public function handle ( CommandInterface $ command ) { if ( ! $ commandHandler = $ this -> handlerResolver -> resolve ( $ command ) ) { throw new HandlerNotFoundException ( ) ; } $ commandHandler -> handle ( $ command ) ; }

Handle the command

@param CommandInterface $command
@throws HandlerNotFoundException


public function set($name, $value, $minutes = 0, $path = '/', $domain = null, $secure = false, $httpOnly = true)
    {
        $expire = ($minutes == 0) ? 0 : time() + ($minutes * 60);

        $cookie = new Cookie($name, $value, $expire, $path, $domain, $secure, $httpOnly);

        $this->cookies[$name] = $cookie;

        return $this;
    }

public function set ( $ name , $ value , $ minutes = 0 , $ path = '/' , $ domain = null , $ secure = false , $ httpOnly = true ) { $ expire = ( $ minutes == 0 ) ? 0 : time ( ) + ( $ minutes * 60 ) ; $ cookie = new Cookie ( $ name , $ value , $ expire , $ path , $ domain , $ secure , $ httpOnly ) ; $ this -> cookies [ $ name ] = $ cookie ; return $ this ; }

Set a new cookies into the collection

@param $name
@param $value
@param int $minutes
@param string $path
@param null $domain
@param bool|false $secure
@param bool|true $httpOnly
@return $this


public function get($name, $default = null)
    {
        if (null !== ($value = $this->request->cookies->get($name))) {
            return $value ?: $default;
        }

        return $default;
    }

public function get ( $ name , $ default = null ) { if ( null !== ( $ value = $ this -> request -> cookies -> get ( $ name ) ) ) { return $ value ? : $ default ; } return $ default ; }

Get cookie value

@param $name
@param null $default
@return mixed|null


public static function firstBy(array $array, Closure $closure)
    {
        foreach ($array as $key => $value) {
            if (true === call_user_func_array($closure, array($key, $value))) {
                return $value;
            }
        }
        return null;
    }

public static function firstBy ( array $ array , Closure $ closure ) { foreach ( $ array as $ key => $ value ) { if ( true === call_user_func_array ( $ closure , array ( $ key , $ value ) ) ) { return $ value ; } } return null ; }

Get first value in array from closure

@param array $array
@param callable $closure
@return mixed


public function isPasswordValid($encodedPassword, $rawPassword, $salt)
    {
        return ! $this->isPasswordTooLong($rawPassword) && password_verify($rawPassword, $encodedPassword);
    }

public function isPasswordValid ( $ encodedPassword , $ rawPassword , $ salt ) { return ! $ this -> isPasswordTooLong ( $ rawPassword ) && password_verify ( $ rawPassword , $ encodedPassword ) ; }

Check if password is valid

@param $encodedPassword
@param $rawPassword
@param $salt
@return bool


public function node(...$nodePath)
    {
        $node = $this->retrieveNode(...$nodePath);
        return (null === $node) ? null : clone $node;
    }

public function node ( ... $ nodePath ) { $ node = $ this -> retrieveNode ( ... $ nodePath ) ; return ( null === $ node ) ? null : clone $ node ; }

Return the node in the path inside the Comprobante
Returns null if the node does not exists
The node retrieved is always a copy

@param string[] ...$nodePath
@return SimpleXMLElement|null


public function attribute(string ...$nodePath): string
    {
        // cast to string since array_pop can return NULL
        $attribute = (string) array_pop($nodePath);
        $node = $this->retrieveNode(...$nodePath);
        return (null !== $node) ? (string) $node[$attribute] : '';
    }

Get the attribute content of a comprobante or child node
Return an empty string if the node or the attribute does not exists

The last argument is always the attribute name

@param string[] ...$nodePath
@return string


private function appendChild(SimpleXMLElement $source, SimpleXMLElement $parent, array $nss): SimpleXMLElement
    {
        $new = $parent->addChild($this->normalizeName($source->getName()), (string) $source);
        $this->populateNode($source, $new, $nss);
        return $new;
    }

private function appendChild ( SimpleXMLElement $ source , SimpleXMLElement $ parent , array $ nss ) : SimpleXMLElement { $ new = $ parent -> addChild ( $ this -> normalizeName ( $ source -> getName ( ) ) , ( string ) $ source ) ; $ this -> populateNode ( $ source , $ new , $ nss ) ; return $ new ; }

Utility function to create a child

@param SimpleXMLElement $source
@param SimpleXMLElement $parent
@param array $nss
@return SimpleXMLElement


private function populateNode(SimpleXMLElement $source, SimpleXMLElement $destination, array $nss)
    {
        // populate attributes
        foreach ($nss as $ns) {
            foreach ($source->attributes($ns) as $attribute) {
                /* @var $attribute SimpleXMLElement */
                $destination->addAttribute($this->normalizeName($attribute->getName()), (string) $attribute);
            }
        }
        // populate children
        foreach ($nss as $ns) {
            foreach ($source->children($ns) as $child) {
                $this->appendChild($child, $destination, $nss);
            }
        }
    }

private
function
populateNode
(
SimpleXMLElement
$
source
,
SimpleXMLElement
$
destination
,
array
$
nss
)
{
// populate attributes
foreach
(
$
nss
as
$
ns
)
{
foreach
(
$
source
->
attributes
(
$
ns
)
as
$
attribute
)
{
/* @var $attribute SimpleXMLElement */
$
destination
->
addAttribute
(
$
this
->
normalizeName
(
$
attribute
->
getName
(
)
)
,
(
string
)
$
attribute
)
;
}
}
// populate children
foreach
(
$
nss
as
$
ns
)
{
foreach
(
$
source
->
children
(
$
ns
)
as
$
child
)
{
$
this
->
appendChild
(
$
child
,
$
destination
,
$
nss
)
;
}
}
}

Utility function to copy contents from one element to other without namespaces

@param SimpleXMLElement $source
@param SimpleXMLElement $destination
@param array $nss
@return void


private function retrieveNode(string ...$nodePath)
    {
        $node = $this->comprobante;
        foreach ($nodePath as $level) {
            if (! isset($node->{$level})) {
                return null;
            }
            $node = $node->{$level};
        }
        return $node;
    }

private function retrieveNode ( string ... $ nodePath ) { $ node = $ this -> comprobante ; foreach ( $ nodePath as $ level ) { if ( ! isset ( $ node -> { $ level } ) ) { return null ; } $ node = $ node -> { $ level } ; } return $ node ; }

Private helper to locate a node
@see node(), attribute()
@param string[] ...$nodePath
@return null|SimpleXMLElement


protected function hasRequiredValue($value)
    {
        $valid = true;

        // $_FILES
        if ($value instanceof UploadedFile && !$value->isValid()) {
            $valid = false;
        }
        // Null
        else if (is_null($value)) {
            $valid = false;
        }
        // String
        else if ((is_string($value) && trim($value) === '')) {
            $valid = false;
        }
        // Array
        else if((is_array($value) && !$value)) {
            $valid = false;
        }

        return $valid;
    }

protected
function
hasRequiredValue
(
$
value
)
{
$
valid
=
true
;
// $_FILES
if
(
$
value
instanceof
UploadedFile
&&
!
$
value
->
isValid
(
)
)
{
$
valid
=
false
;
}
// Null
else
if
(
is_null
(
$
value
)
)
{
$
valid
=
false
;
}
// String
else
if
(
(
is_string
(
$
value
)
&&
trim
(
$
value
)
===
''
)
)
{
$
valid
=
false
;
}
// Array
else
if
(
(
is_array
(
$
value
)
&&
!
$
value
)
)
{
$
valid
=
false
;
}
return
$
valid
;
}

Check if posted value is valid

@param $value
@return bool


public function addDoctrineQueries(DebugStack $debugStack)
    {
        foreach ($debugStack->queries as $query) {

            if (!$query['params']) {
                $query['params'] = array();
            }

            if (!$query['types']) {
                $query['types'] = array();
            }

            // Because doctrine columns can be more advanced we need to convert them to string
            // This is a quick a dirty way of doing it so could do with going elsewhere
            $query['params'] = $this->convertDoctrineParameters($query['params'], $query['types']);

            $queries = array(
                array(
                    'query'    => $query['sql'],
                    'bindings' => $query['params'],
                    'time'     => $query['executionMS'],
                )
            );

            $this->addQueries($queries);
        }

        return $this;
    }

Add queries for doctrine off the DebugStack logger

@param DebugStack $debugStack
@return $this


public function addTimers($timers = array())
    {
        foreach ($timers as $name => $timer) {
            $this->timers[$name] = $timer;
        }

        return $this;
    }

public function addTimers ( $ timers = array ( ) ) { foreach ( $ timers as $ name => $ timer ) { $ this -> timers [ $ name ] = $ timer ; } return $ this ; }

Add timers to profiler

->addTimers(array(
'Test' => array(
'start' => time(),
'time' => time() + 1000,
),
));

@param array $timers
@return $this


protected function getFileSize($size)
    {
        $units = array('Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB');
        return round($size / pow(1024, ($i = floor(log($size, 1024)))), 2).' '.$units[$i];
    }

protected
function
getFileSize
(
$
size
)
{
$
units
=
array
(
'Bytes'
,
'KB'
,
'MB'
,
'GB'
,
'TB'
,
'PB'
,
'EB'
)
;
return
round
(
$
size
/
pow
(
1024
,
(
$
i
=
floor
(
log
(
$
size
,
1024
)
)
)
)
,
2
)
.
' '
.
$
units
[
$
i
]
;
}

Calculate the human-readable file size with units.

@param  int     $size
@return string

Calculate the human - readable file size with units .


public function append(ValidatorInterface $validator)
    {
        if (false === $this->getIndex($validator)) {
            $this->validators[] = $validator;
        }
    }

public function append ( ValidatorInterface $ validator ) { if ( false === $ this -> getIndex ( $ validator ) ) { $ this -> validators [ ] = $ validator ; } }

Append a validator into the list of validators,
this will search if the validator object does not exists
@param ValidatorInterface $validator

Append a validator into the list of validators this will search if the validator object does not exists


public function remove(ValidatorInterface $validator)
    {
        $index = $this->getIndex($validator);
        if (false !== $index) {
            unset($this->validators[$index]);
            $this->validators = array_values($this->validators);
        }
    }

public function remove ( ValidatorInterface $ validator ) { $ index = $ this -> getIndex ( $ validator ) ; if ( false !== $ index ) { unset ( $ this -> validators [ $ index ] ) ; $ this -> validators = array_values ( $ this -> validators ) ; } }

Remove a validator from the list of validators
@param ValidatorInterface $validator


public function get($index)
    {
        if (! array_key_exists($index, $this->validators)) {
            throw new \OutOfBoundsException('Validator does not exists');
        }
        return $this->validators[$index];
    }

public
function
get
(
$
index
)
{
if
(
!
array_key_exists
(
$
index
,
$
this
->
validators
)
)
{
throw
new
\
OutOfBoundsException
(
'Validator does not exists'
)
;
}
return
$
this
->
validators
[
$
index
]
;
}

Return a registered instance of a validator identified by index
@param int $index
@return ValidatorInterface


public static function make(array $arguments): self
    {
        if (! count($arguments)) {
            throw new \InvalidArgumentException('Cannot construct without arguments');
        }
        $script = array_shift($arguments);

        $filenames = [];
        $localPath = null;
        while (null !== $argument = array_shift($arguments)) {
            if (in_array($argument, ['--local-path', '-l'])) {
                $localPath = (count($arguments)) ? array_shift($arguments) : '';
                continue;
            }
            if (false === strpos($argument, '-')) {
                $filenames[] = $argument;
                continue;
            }
            throw new \InvalidArgumentException("Invalid argument '$argument'");
        }

        $command = new self($script, $filenames);
        $command->localPath = (null !== $localPath && 'disable' === $localPath) ? '' : $localPath;
        return $command;
    }

public
static
function
make
(
array
$
arguments
)
:
self
{
if
(
!
count
(
$
arguments
)
)
{
throw
new
\
InvalidArgumentException
(
'Cannot construct without arguments'
)
;
}
$
script
=
array_shift
(
$
arguments
)
;
$
filenames
=
[
]
;
$
localPath
=
;
while
(
!==
$
argument
=
array_shift
(
$
arguments
)
)
{
if
(
in_array
(
$
argument
,
[
'--local-path'
,
'-l'
]
)
)
{
$
localPath
=
(
count
(
$
arguments
)
)
array_shift
(
$
arguments
)
:
''
;
continue
;
}
if
(
false
===
strpos
(
$
argument
,
'-'
)
)
{
$
filenames
[
]
=
$
argument
;
continue
;
}
throw
new
\
InvalidArgumentException
(
"Invalid argument '$argument'"
)
;
}
$
command
=
new
self
(
$
script
,
$
filenames
)
;
$
command
->
localPath
=
(
!==
$
localPath
&&
'disable'
===
$
localPath
)
''
:
$
localPath
;
return
$
command
;
}

Use this function to build the validate object from arguments values
@param string[] $arguments
@return Validate


public function run()
    {
        $factory = new CFDIFactory($this->localPath);
        foreach ($this->filenames as $filename) {
            $this->runFilename($factory, $filename);
        }
    }

public function run ( ) { $ factory = new CFDIFactory ( $ this -> localPath ) ; foreach ( $ this -> filenames as $ filename ) { $ this -> runFilename ( $ factory , $ filename ) ; } }


protected function runFilename(CFDIFactory $factory, string $argument)
    {
        if ('' === $argument) {
            $this->error('FATAL: Empty filename');
            return;
        }
        $filename = realpath($argument);
        if ('' === $filename || ! is_file($filename) || ! is_readable($filename)) {
            $this->error("File $argument FATAL: not found or is not readable");
            return;
        }
        // do the object creation
        try {
            $errors = [];
            $warnings = [];
            $reader = $factory->newCFDIReader(file_get_contents($filename), $errors, $warnings);
            foreach ($errors as $message) {
                $this->error("File $argument ERROR: $message");
            }
            foreach ($warnings as $message) {
                $this->error("File $argument WARNING: $message");
            }
            $this->write("File $argument UUID: " . $reader->getUUID());
        } catch (\Exception $ex) {
            $this->error("File $argument FATAL: " . $ex->getMessage());
        }
    }

Run only a filename, used in the run loop
@param CFDIFactory $factory
@param string $argument
@return void

Run only a filename used in the run loop


public function authorize(CredentialsInterface $credentials)
    {
        // Check if user can be found
        if ( ! $user = $this->userProvider->findUserByUsername($credentials->getUsername())) {
            throw new UserNotFoundException(sprintf('User "%s" not found', $credentials->getUsername()));
        }

        // Check if password is valid
        if ( ! $this->passwordEncoder->isPasswordValid($user->getPassword(), $credentials->getPassword(), $user->getSalt())) {
            throw new BadCredentialsException(sprintf('Password for user "%s" was incorrect', $credentials->getUsername()));
        }

        // Put user in the auth storage
        $this->storage->setIdentifier($this->storageKey, $user->getUsername());

        $this->user = $user;

        $this->loggedIn = true;

        return $user;
    }

public
function
authorize
(
CredentialsInterface
$
credentials
)
{
// Check if user can be found
if
(
!
$
user
=
$
this
->
userProvider
->
findUserByUsername
(
$
credentials
->
getUsername
(
)
)
)
{
throw
new
UserNotFoundException
(
sprintf
(
'User "%s" not found'
,
$
credentials
->
getUsername
(
)
)
)
;
}
// Check if password is valid
if
(
!
$
this
->
passwordEncoder
->
isPasswordValid
(
$
user
->
getPassword
(
)
,
$
credentials
->
getPassword
(
)
,
$
user
->
getSalt
(
)
)
)
{
throw
new
BadCredentialsException
(
sprintf
(
'Password for user "%s" was incorrect'
,
$
credentials
->
getUsername
(
)
)
)
;
}
// Put user in the auth storage
$
this
->
storage
->
setIdentifier
(
$
this
->
storageKey
,
$
user
->
getUsername
(
)
)
;
$
this
->
user
=
$
user
;
$
this
->
loggedIn
=
true
;
return
$
user
;
}

Try and authorize a user based on credentials

@param CredentialsInterface $credentials
@return UserInterface
@throws UserNotFoundException
@throws BadCredentialsException


public function isLoggedIn()
    {
        if (null === $this->loggedIn) {
            $this->user = $this->loadUser();
            $this->loggedIn = $this->user instanceof UserInterface;
        }

        return $this->loggedIn;
    }

public function isLoggedIn ( ) { if ( null === $ this -> loggedIn ) { $ this -> user = $ this -> loadUser ( ) ; $ this -> loggedIn = $ this -> user instanceof UserInterface ; } return $ this -> loggedIn ; }

Check if user is logged in

@return bool


public function login(UserInterface $user)
    {
        // Check if user can be found.
        // Stops trying to login a user that hasn't been added to database yet
        if ( ! $this->userProvider->findUserByUsername($user->getUsername())) {
            throw new UserNotFoundException(sprintf('User "%s" not found', $user->getUsername()));
        }

        // Put user in the auth storage
        $this->storage->setIdentifier($this->storageKey, $user->getUsername());

        $this->user = $user;

        $this->loggedIn = true;
    }

Login a given user

@param UserInterface $user
@throws UserNotFoundException


public function logout()
    {
        $this->storage->removeIdentifier($this->storageKey);
        $this->user = null;
        $this->loggedIn = false;
    }

public function logout ( ) { $ this -> storage -> removeIdentifier ( $ this -> storageKey ) ; $ this -> user = null ; $ this -> loggedIn = false ; }


public function add($name, $constraints)
    {
        if ( ! isset($this->constraints[$name])) {
            $this->constraints[$name] = [];
        }

        if (!is_array($constraints)) {
            $constraints = array($constraints);
        }

        foreach ($constraints as $constraint) {
            $this->constraints[$name][] = $constraint;
        }

        return $this;
    }

public function add ( $ name , $ constraints ) { if ( ! isset ( $ this -> constraints [ $ name ] ) ) { $ this -> constraints [ $ name ] = [ ] ; } if ( ! is_array ( $ constraints ) ) { $ constraints = array ( $ constraints ) ; } foreach ( $ constraints as $ constraint ) { $ this -> constraints [ $ name ] [ ] = $ constraint ; } return $ this ; }

Add a constraint to the validator

@param $name
@param ConstraintInterface|ConstraintInterface[] $constraints
@return $this


public function validate($input)
    {
        $this->messages = [];
        $this->input = $input;

        /**
         * @var ConstraintInterface $constraint
         */
        foreach ($this->constraints as $field => $constraints) {
            foreach ($constraints as $constraint) {

                // If value is empty and rule needs a value we can skip
                // checking the field
                if ($constraint->shouldSkipOnNoValue() && $this->isValueEmpty($this->getInput($field))) {
                    continue;
                }

                $constraint->validate($this, $field, $this->getInput($field));
            }

        }

        return count($this->messages) === 0;
    }

Validate given input

@param $input
@return bool


public function urlRedirectAction(Request $request, $path, $permanent = false, $scheme = null, $httpPort = null, $httpsPort = null)
    {
        /** @var ConfigInterface $config */
        $config = $this->container->get('config');

        if ('' == $path) {
            throw new HttpException($permanent ? 410 : 404);
        }

        $statusCode = $permanent ? 301 : 302;
        // redirect if the path is a full URL

        if (parse_url($path, PHP_URL_SCHEME)) {
            return new RedirectResponse($path, $statusCode);
        }

        if (null === $scheme) {
            $scheme = $request->getScheme();
        }

        $qs = $request->getQueryString();

        if ($qs) {

            if (strpos($path, '?') === false) {
                $qs = '?'.$qs;
            }
            else {
                $qs = '&'.$qs;
            }
        }
        $port = '';

        if ('http' === $scheme) {

            if (null === $httpPort) {

                if ('http' === $request->getScheme()) {
                    $httpPort = $request->getPort();
                }
                elseif ($config->has('request.http_port')) {
                    $httpPort = $config->get('request.http_port');
                }
            }

            if (null !== $httpPort && 80 != $httpPort) {
                $port = ":$httpPort";
            }
        }
        elseif ('https' === $scheme) {

            if (null === $httpsPort) {

                if ('https' === $request->getScheme()) {
                    $httpsPort = $request->getPort();
                }
                elseif ($config->has('request.https_port')) {
                    $httpsPort = $config->get('request.https_port');
                }
            }

            if (null !== $httpsPort && 443 != $httpsPort) {
                $port = ":$httpsPort";
            }
        }

        $url = $scheme.'://'.$request->getHost().$port.$request->getBaseUrl().$path.$qs;

        return new RedirectResponse($url, $statusCode);
    }

public
function
urlRedirectAction
(
Request
$
request
,
$
path
,
$
permanent
=
false
,
$
scheme
=
,
$
httpPort
=
,
$
httpsPort
=
)
{
/** @var ConfigInterface $config */
$
config
=
$
this
->
container
->
get
(
'config'
)
;
if
(
''
==
$
path
)
{
throw
new
HttpException
(
$
permanent
410
:
404
)
;
}
$
statusCode
=
$
permanent
301
:
302
;
// redirect if the path is a full URL
if
(
parse_url
(
$
path
,
PHP_URL_SCHEME
)
)
{
return
new
RedirectResponse
(
$
path
,
$
statusCode
)
;
}
if
(
===
$
scheme
)
{
$
scheme
=
$
request
->
getScheme
(
)
;
}
$
qs
=
$
request
->
getQueryString
(
)
;
if
(
$
qs
)
{
if
(
strpos
(
$
path
,
'?'
)
===
false
)
{
$
qs
=
'?'
.
$
qs
;
}
else
{
$
qs
=
'&'
.
$
qs
;
}
}
$
port
=
''
;
if
(
'http'
===
$
scheme
)
{
if
(
===
$
httpPort
)
{
if
(
'http'
===
$
request
->
getScheme
(
)
)
{
$
httpPort
=
$
request
->
getPort
(
)
;
}
elseif
(
$
config
->
has
(
'request.http_port'
)
)
{
$
httpPort
=
$
config
->
get
(
'request.http_port'
)
;
}
}
if
(
!==
$
httpPort
&&
80
!=
$
httpPort
)
{
$
port
=
":$httpPort"
;
}
}
elseif
(
'https'
===
$
scheme
)
{
if
(
===
$
httpsPort
)
{
if
(
'https'
===
$
request
->
getScheme
(
)
)
{
$
httpsPort
=
$
request
->
getPort
(
)
;
}
elseif
(
$
config
->
has
(
'request.https_port'
)
)
{
$
httpsPort
=
$
config
->
get
(
'request.https_port'
)
;
}
}
if
(
!==
$
httpsPort
&&
443
!=
$
httpsPort
)
{
$
port
=
":$httpsPort"
;
}
}
$
url
=
$
scheme
.
'://'
.
$
request
->
getHost
(
)
.
$
port
.
$
request
->
getBaseUrl
(
)
.
$
path
.
$
qs
;
return
new
RedirectResponse
(
$
url
,
$
statusCode
)
;
}

Redirects to a URL.

The response status code is 302 if the permanent parameter is false (default),
and 301 if the redirection is permanent.

In case the path is empty, the status code will be 404 when permanent is false
and 410 otherwise.

@param Request $request
@param $path
@param bool|false $permanent
@param null $scheme
@param null $httpPort
@param null $httpsPort
@return RedirectResponse
@throws HttpException


public function getPath()
    {
        if (null === $this->path) {
            $reflected = new \ReflectionObject($this);
            $this->path = dirname($reflected->getFileName());
        }

        return $this->path;
    }

public function getPath ( ) { if ( null === $ this -> path ) { $ reflected = new \ ReflectionObject ( $ this ) ; $ this -> path = dirname ( $ reflected -> getFileName ( ) ) ; } return $ this -> path ; }

Gets the Bundle directory path.

@return string The Bundle absolute path

@api


public function get(int $index): string
    {
        if (! array_key_exists($index, $this->messages)) {
            throw new \OutOfBoundsException('Message does not exists');
        }
        return $this->messages[$index];
    }

public
function
get
(
int
$
index
)
:
string
{
if
(
!
array_key_exists
(
$
index
,
$
this
->
messages
)
)
{
throw
new
\
OutOfBoundsException
(
'Message does not exists'
)
;
}
return
$
this
->
messages
[
$
index
]
;
}

Get a message by index

@param int $index
@return string
@throws \OutOfBoundsException if the message does not exists


protected function generateCustomPostTypeName()
    {
        $matches = [];
        preg_match('@(\\\\)?([\w]+)$@', get_called_class(), $matches);
        $cptName = strtolower(
            preg_replace('/(?<=\\w)(?=[A-Z])/', "-$1", $matches[2])
        );
        return $cptName;
    }

protected function generateCustomPostTypeName ( ) { $ matches = [ ] ; preg_match ( '@(\\\\)?([\w]+)$@' , get_called_class ( ) , $ matches ) ; $ cptName = strtolower ( preg_replace ( '/(?<=\\w)(?=[A-Z])/' , "-$1" , $ matches [ 2 ] ) ) ; return $ cptName ; }

Overwrite to change the way the custom post type name is determined.
This value is fed into the PostTypeBuilder. If an existing post type of
the same name exist, it will load the existing configuration to allow
modification.

@return string

Overwrite to change the way the custom post type name is determined . This value is fed into the PostTypeBuilder . If an existing post type of the same name exist it will load the existing configuration to allow modification .


public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('base_url', array($this, 'getBaseUrl')),
            new \Twig_SimpleFunction('current_url', array($this, 'getCurrentUrl')),
            new \Twig_SimpleFunction('asset_url', array($this, 'asset')),
            new \Twig_SimpleFunction('url_to', array($this, 'to')),
            new \Twig_SimpleFunction('secure_url_to', array($this, 'secureTo')),
            new \Twig_SimpleFunction('route', array($this, 'route')),
        );
    }

public function getFunctions ( ) { return array ( new \ Twig_SimpleFunction ( 'base_url' , array ( $ this , 'getBaseUrl' ) ) , new \ Twig_SimpleFunction ( 'current_url' , array ( $ this , 'getCurrentUrl' ) ) , new \ Twig_SimpleFunction ( 'asset_url' , array ( $ this , 'asset' ) ) , new \ Twig_SimpleFunction ( 'url_to' , array ( $ this , 'to' ) ) , new \ Twig_SimpleFunction ( 'secure_url_to' , array ( $ this , 'secureTo' ) ) , new \ Twig_SimpleFunction ( 'route' , array ( $ this , 'route' ) ) , ) ; }

Returns a list of functions to add to the existing list.

@return array An array of functions

Returns a list of functions to add to the existing list .


public function resolve(CommandInterface $command)
    {
        $handlerClass = $this->getHandlerClass($command);

        try {
            $handler = $this->container->get($handlerClass);
            return $handler;
        }
        catch(\Exception $e) {
            return null;
        }
    }

public function resolve ( CommandInterface $ command ) { $ handlerClass = $ this -> getHandlerClass ( $ command ) ; try { $ handler = $ this -> container -> get ( $ handlerClass ) ; return $ handler ; } catch ( \ Exception $ e ) { return null ; } }

Resolve handler for command

@param CommandInterface $command
@return CommandHandlerInterface


protected function setup(CFDIReader $cfdi, Issues $issues)
    {
        $this->errors = $issues->messages(IssuesTypes::ERROR);
        $this->warnings = $issues->messages(IssuesTypes::WARNING);
        $this->comprobante = $cfdi->comprobante();
    }

protected function setup ( CFDIReader $ cfdi , Issues $ issues ) { $ this -> errors = $ issues -> messages ( IssuesTypes :: ERROR ) ; $ this -> warnings = $ issues -> messages ( IssuesTypes :: WARNING ) ; $ this -> comprobante = $ cfdi -> comprobante ( ) ; }

Configure this helper class
@param CFDIReader $cfdi
@param Issues $issues


protected function sumNodes(SimpleXMLElement $collection = null, $attribute = '')
    {
        if (null === $collection) {
            return 0;
        }
        $sum = 0;
        if ('' === $attribute) {
            foreach ($collection as $node) {
                $sum = $sum + $this->value($node);
            }
        } else {
            foreach ($collection as $node) {
                $sum = $sum + $this->value($node[$attribute]);
            }
        }
        return $sum;
    }

protected function sumNodes ( SimpleXMLElement $ collection = null , $ attribute = '' ) { if ( null === $ collection ) { return 0 ; } $ sum = 0 ; if ( '' === $ attribute ) { foreach ( $ collection as $ node ) { $ sum = $ sum + $ this -> value ( $ node ) ; } } else { foreach ( $ collection as $ node ) { $ sum = $ sum + $ this -> value ( $ node [ $ attribute ] ) ; } } return $ sum ; }

Compute the sum of a collection of nodes considering an attribute
@param SimpleXMLElement $collection
@param string $attribute
@return float


public function get($name, $default = null)
    {
        if ( ! $this->has($name)) {
            return $default;
        }

        $return = $this->oldInput[$name];

        unset($this->oldInput[$name]);

        return $return;
    }

public function get ( $ name , $ default = null ) { if ( ! $ this -> has ( $ name ) ) { return $ default ; } $ return = $ this -> oldInput [ $ name ] ; unset ( $ this -> oldInput [ $ name ] ) ; return $ return ; }

Gets and clears input from the stack.

@param string $name
@param null $default Default value if $name does not exist.

@return array


public function setSequentialPosition($position, MetaDataBinding $context)
    {
        add_action('do_meta_boxes', function ($post_type) use ($position, $context) {
            global $wp_meta_boxes;

            if ($context->getBindingName() !== $post_type) {
                return;
            }

            foreach ($wp_meta_boxes[$post_type]['side']['core'] as $key => $metaBox) {
                // Don't replace our recently positioned taxonomy
                if (preg_match('/^understory-taxonomy.+/', $key)) {
                    continue;
                }

                if (
                    is_array($metaBox)
                    && isset($metaBox['args'])
                    && is_array($metaBox['args'])
                    && isset($metaBox['args']['taxonomy'])
                    && $metaBox['args']['taxonomy'] === $this->getBindingName()
                ) {
                    $wp_meta_boxes[$post_type]['side']['core']['understory-taxonomy' . $position] = $metaBox;
                    unset($wp_meta_boxes[$post_type]['side']['core'][$key]);

                }

            }
        }, 10000, 1);
    }

Sets the Taxonomy Meta Box Order.
@param $position
@param MetaDataBinding $context


protected function generateTaxonomyName()
    {
        $matches = [];
        preg_match('@\\\\([\w]+)$@', get_called_class(), $matches);
        $taxonomyName = strtolower(
            preg_replace('/(?<=\\w)(?=[A-Z])/', "-$1", $matches[1])
        );

        // Use the existing WordPress taxonomy post_tag with an underscore
        if ($taxonomyName === 'post-tag') {
            $taxonomyName = 'post_tag';
        }

        return $taxonomyName;
    }

Overwrite to change the way the taxonomy name is determined.
This value is fed into the TaxonomyBuilder. If an existing taxonomy of
the same name exist, it will load the existing configuration to allow
modification.

@return string

Overwrite to change the way the taxonomy name is determined . This value is fed into the TaxonomyBuilder . If an existing taxonomy of the same name exist it will load the existing configuration to allow modification .


public function redirect($path, $route, $scheme = null)
    {
        return [
            '_controller' => 'Tomahawk\\Routing\\Controller\\RedirectController::urlRedirectAction',
            'path' => $path,
            'permanent' => true,
            'scheme' => $scheme,
            'httpPort' => $this->context->getHttpPort(),
            'httpsPort' => $this->context->getHttpsPort(),
            '_route' => $route,
        ];
    }

Redirects the user to another URL.

@param string $path The path info to redirect to
@param string $route The route name that matched
@param string|null $scheme The URL scheme (null to keep the current one)

@return array An array of parameters


protected function registerCommands()
    {
        if ($this->commandsRegistered) {
            return;
        }

        $this->commandsRegistered = true;

        $this->kernel->boot();

        foreach ($this->kernel->getBundles() as $bundle) {
            if ($bundle instanceof Bundle) {
                $bundle->registerCommands($this);
            }
        }
    }

protected function registerCommands ( ) { if ( $ this -> commandsRegistered ) { return ; } $ this -> commandsRegistered = true ; $ this -> kernel -> boot ( ) ; foreach ( $ this -> kernel -> getBundles ( ) as $ bundle ) { if ( $ bundle instanceof Bundle ) { $ bundle -> registerCommands ( $ this ) ; } } }


public function getBundleMetadata(BundleInterface $bundle)
    {
        $namespace = $bundle->getNamespace();
        $metadata = $this->getMetadataForNamespace($namespace);
        if (!$metadata->getMetadata()) {
            throw new \RuntimeException(sprintf('Bundle "%s" does not contain any mapped entities.', $bundle->getName()));
        }

        $path = $this->getBasePathForClass($bundle->getName(), $bundle->getNamespace(), $bundle->getPath());

        $metadata->setPath($path);
        $metadata->setNamespace($bundle->getNamespace());

        return $metadata;
    }

Gets the metadata of all classes of a bundle.

@param BundleInterface $bundle A BundleInterface instance

@return ClassMetadataCollection A ClassMetadataCollection instance

@throws \RuntimeException When bundle does not contain mapped entities

Gets the metadata of all classes of a bundle .


public function getNamespaceMetadata($namespace, $path = null)
    {
        $metadata = $this->getMetadataForNamespace($namespace);
        if (!$metadata->getMetadata()) {
            throw new \RuntimeException(sprintf('Namespace "%s" does not contain any mapped entities.', $namespace));
        }

        $this->findNamespaceAndPathForMetadata($metadata, $path);

        return $metadata;
    }

Gets the metadata of all classes of a namespace.

@param string $namespace A namespace name
@param string $path      The path where the class is stored (if known)

@return ClassMetadataCollection A ClassMetadataCollection instance

@throws \RuntimeException When namespace not contain mapped entities

Gets the metadata of all classes of a namespace .


public function findNamespaceAndPathForMetadata(ClassMetadataCollection $metadata, $path = null)
    {
        $all = $metadata->getMetadata();
        if (class_exists($all[0]->name)) {
            $r = new \ReflectionClass($all[0]->name);
            $path = $this->getBasePathForClass($r->getName(), $r->getNamespaceName(), dirname($r->getFilename()));
            $ns = $r->getNamespaceName();

        } elseif ($path) {
            // Get namespace by removing the last component of the FQCN
            $nsParts = explode('\\', $all[0]->name);
            array_pop($nsParts);
            $ns = implode('\\', $nsParts);

        } else {
            throw new \RuntimeException(sprintf('Unable to determine where to save the "%s" class (use the --path option).', $all[0]->name));
        }

        $metadata->setPath($path);
        $metadata->setNamespace($ns);
    }

Find and configure path and namespace for the metadata collection.

@param ClassMetadataCollection $metadata
@param string|null             $path

@throws \RuntimeException When unable to determine the path

Find and configure path and namespace for the metadata collection .


protected function add($type, $name, $source, $dependencies, $attributes)
    {
        $dependencies = (array) $dependencies;

        $attributes = (array) $attributes;

        $this->assets[$type][$name] = compact('source', 'dependencies', 'attributes');

        return $this;
    }

protected function add ( $ type , $ name , $ source , $ dependencies , $ attributes ) { $ dependencies = ( array ) $ dependencies ; $ attributes = ( array ) $ attributes ; $ this -> assets [ $ type ] [ $ name ] = compact ( 'source' , 'dependencies' , 'attributes' ) ; return $ this ; }

Add an asset to the array of registered assets.

@param  string  $type
@param  string  $name
@param  string  $source
@param  array   $dependencies
@param  array   $attributes
@return $this

Add an asset to the array of registered assets .


public function render($view, array $parameters = [], Response $response = null)
    {
        $content = $this->renderView($view, $parameters);

        if (null === $response) {
            $response = new Response();
        }

        $response->setContent($content);

        return $response;
    }

public function render ( $ view , array $ parameters = [ ] , Response $ response = null ) { $ content = $ this -> renderView ( $ view , $ parameters ) ; if ( null === $ response ) { $ response = new Response ( ) ; } $ response -> setContent ( $ content ) ; return $ response ; }

Returns a response

@param $view
@param array $parameters
@param Response|null $response
@return Response


public function save($id, $value, $lifetime = false)
    {
        $this->cacheProvider->save($id, $value, $lifetime);
    }

public function save ( $ id , $ value , $ lifetime = false ) { $ this -> cacheProvider -> save ( $ id , $ value , $ lifetime ) ; }

Save an item into the cache

@param $id
@param $value
@param bool $lifetime
@return bool


public function loadContent(string $content)
    {
        // run this method with libxml internal errors enabled
        if (true !== libxml_use_internal_errors(true)) {
            try {
                $this->loadContent($content);
            } finally {
                libxml_use_internal_errors(false);
            }
        }

        libxml_clear_errors(); // clear previous libxml errors
        $dom = new DOMDocument();
        @$dom->loadXML($content, LIBXML_NOWARNING | LIBXML_NONET);
        if (false !== $loaderror = libxml_get_last_error()) {
            libxml_clear_errors();  // clear recently libxml errors
            throw new CFDICleanerException('XML Error: ' . $loaderror->message);
        }
        $prefix = $dom->lookupPrefix('http://www.sat.gob.mx/cfd/3');
        if (! $prefix) {
            throw new CFDICleanerException('The XML document is not a CFDI');
        }
        $version = $this->xpathQuery('/' . $prefix . ':Comprobante/@version', $dom->documentElement);
        if ($version->length != 1) {
            $version = $this->xpathQuery('/' . $prefix . ':Comprobante/@Version', $dom->documentElement);
        }
        if ($version->length != 1) {
            throw new CFDICleanerException('The XML document does not contains a version');
        }
        if (! $this->isVersionAllowed($version->item(0)->nodeValue)) {
            throw new CFDICleanerException(
                'The XML document version "' . $version->item(0)->nodeValue . '" is not compatible'
            );
        }
        $this->dom = $dom;
    }

Load the string content as a CFDI
This is exposed to reuse the current object instead of create a new instance

@param string $content

@throws CFDICleanerException when the content is not valid xml
@throws CFDICleanerException when the document does not use the namespace http://www.sat.gob.mx/cfd/3
@throws CFDICleanerException when cannot find a Comprobante version (or Version) attribute
@throws CFDICleanerException when the version is not compatible

@return void


public function removeNonSatNSschemaLocations()
    {
        $xsi = $this->dom->lookupPrefix('http://www.w3.org/2001/XMLSchema-instance');
        if (! $xsi) {
            return;
        }
        $schemaLocations = $this->xpathQuery("//@$xsi:schemaLocation");
        if ($schemaLocations->length === 0) {
            return;
        }
        for ($s = 0; $s < $schemaLocations->length; $s++) {
            $this->removeNonSatNSschemaLocation($schemaLocations->item($s));
        }
    }

Procedure to drop schemaLocations that are not allowed
If the schemaLocation is empty then remove the attribute

@return void


public function removeNonSatNSNodes()
    {
        $nss = [];
        foreach ($this->xpathQuery('//namespace::*') as $node) {
            $namespace = $node->nodeValue;
            if ($this->isNameSpaceAllowed($namespace)) {
                continue;
            }
            $nss[] = $namespace;
        }
        if (! count($nss)) {
            return;
        }
        foreach ($nss as $namespace) {
            $this->removeNonSatNSNode($namespace);
        }
    }

public function removeNonSatNSNodes ( ) { $ nss = [ ] ; foreach ( $ this -> xpathQuery ( '//namespace::*' ) as $ node ) { $ namespace = $ node -> nodeValue ; if ( $ this -> isNameSpaceAllowed ( $ namespace ) ) { continue ; } $ nss [ ] = $ namespace ; } if ( ! count ( $ nss ) ) { return ; } foreach ( $ nss as $ namespace ) { $ this -> removeNonSatNSNode ( $ namespace ) ; } }

Procedure to remove all nodes that are not from an allowed namespace
@return void


public function removeUnusedNamespaces()
    {
        $nss = [];
        foreach ($this->xpathQuery('//namespace::*') as $node) {
            $namespace = $node->nodeValue;
            if (! $namespace || $this->isNameSpaceAllowed($namespace)) {
                continue;
            }
            $prefix = $this->dom->lookupPrefix($namespace);
            $nss[$prefix] = $namespace;
        }
        $nss = array_unique($nss);
        foreach ($nss as $prefix => $namespace) {
            $this->dom->documentElement->removeAttributeNS($namespace, $prefix);
        }
    }

public function removeUnusedNamespaces ( ) { $ nss = [ ] ; foreach ( $ this -> xpathQuery ( '//namespace::*' ) as $ node ) { $ namespace = $ node -> nodeValue ; if ( ! $ namespace || $ this -> isNameSpaceAllowed ( $ namespace ) ) { continue ; } $ prefix = $ this -> dom -> lookupPrefix ( $ namespace ) ; $ nss [ $ prefix ] = $ namespace ; } $ nss = array_unique ( $ nss ) ; foreach ( $ nss as $ prefix => $ namespace ) { $ this -> dom -> documentElement -> removeAttributeNS ( $ namespace , $ prefix ) ; } }

Procedure to remove not allowed xmlns definitions
@return void


protected function initializeBindings()
    {
        if (!$this->getMetaDataBinding()) {
            $siteClass = get_class($this->site);
            if ($binding = $siteClass::getPost()) {
                $this->setMetaDataBinding($binding);
            }

        }
        $this->bindRegistryItems();
    }

protected function initializeBindings ( ) { if ( ! $ this -> getMetaDataBinding ( ) ) { $ siteClass = get_class ( $ this -> site ) ; if ( $ binding = $ siteClass :: getPost ( ) ) { $ this -> setMetaDataBinding ( $ binding ) ; } } $ this -> bindRegistryItems ( ) ; }

If the delegated MetaDataBinding hasn't been set yet,
assume the current post, as a PostType object.
Use to bind Registery items.

If the delegated MetaDataBinding hasn t been set yet assume the current post as a PostType object . Use to bind Registery items .


protected function bindRegistryItems()
    {
        foreach ($this->registry as $registerable) {
            if ($registerable instanceof DelegatesMetaDataBinding) {
                $registerable->setMetaDataBinding($this->getMetaDataBinding());
            }
        }
    }

protected function bindRegistryItems ( ) { foreach ( $ this -> registry as $ registerable ) { if ( $ registerable instanceof DelegatesMetaDataBinding ) { $ registerable -> setMetaDataBinding ( $ this -> getMetaDataBinding ( ) ) ; } } }

Set binding on any Registry items that delegate to a MetaDataBinding.

Set binding on any Registry items that delegate to a MetaDataBinding .


public function getFileNameDashedCase()
    {
        $calledClass = preg_replace('/.*Views/i', '', get_called_class());

        $calledClass = strtolower(
            preg_replace('/(?<=\\w)(?=[A-Z])/', '-$1', $calledClass)
        );

        return str_replace('\\', DIRECTORY_SEPARATOR, $calledClass);
    }

public function getFileNameDashedCase ( ) { $ calledClass = preg_replace ( '/.*Views/i' , '' , get_called_class ( ) ) ; $ calledClass = strtolower ( preg_replace ( '/(?<=\\w)(?=[A-Z])/' , '-$1' , $ calledClass ) ) ; return str_replace ( '\\' , DIRECTORY_SEPARATOR , $ calledClass ) ; }

Return the file name based on the class name that is dashed lower case.
This file name format is used by WordPress.

@return string

Return the file name based on the class name that is dashed lower case . This file name format is used by WordPress .


private function initializeContext()
    {
        $this->context = Timber\Timber::get_context();

        $this->context['page'] = $this;
        $this->context['post'] = $this->getMetaDataBinding();

        $this->context = $this->configureContext($this->context);

        foreach ($this->contextRegistry as $key => $value) {

            if (is_callable($value)) {
                $value = call_user_func($value);
            }
            $this->context[$key] = $value;
        }

        return $this->context;
    }

private function initializeContext ( ) { $ this -> context = Timber \ Timber :: get_context ( ) ; $ this -> context [ 'page' ] = $ this ; $ this -> context [ 'post' ] = $ this -> getMetaDataBinding ( ) ; $ this -> context = $ this -> configureContext ( $ this -> context ) ; foreach ( $ this -> contextRegistry as $ key => $ value ) { if ( is_callable ( $ value ) ) { $ value = call_user_func ( $ value ) ; } $ this -> context [ $ key ] = $ value ; } return $ this -> context ; }

Return the Timber context with the View's context values added.

@return array

Return the Timber context with the View s context values added .


public function render()
    {
        $this->initializeBindings();
        return Timber\Timber::compile($this->getTemplate(), $this->initializeContext());
    }

public function render ( ) { $ this -> initializeBindings ( ) ; return Timber \ Timber :: compile ( $ this -> getTemplate ( ) , $ this -> initializeContext ( ) ) ; }

Render the View after initialzing the bindings and context


public function load($force = false)
    {
        $this->config = array();

        // Check if we have a compiled cached file
        if ( ! $force && $this->cacheFile && file_exists($this->cacheFile)) {
            $this->config = include($this->cacheFile);
            return;
        }

        foreach ($this->configDirectories as $configDirectory) {

            $finder = new Finder();
            $finder->in($configDirectory)->depth('== 0')->files()->name('*.php');

            foreach ($finder as $file) {
                /**
                 * @var \Symfony\Component\Finder\SplFileInfo $file
                 */

                // If file starts with config_ its a compiled one so ignore
                if (Str::is($file->getFilename(), '*config_*')) {
                    continue;
                }

                $configName = substr($file->getFilename(), 0, -4);

                $values = $this->loader->load($file->getRealPath());

                foreach ($values as $config => $value) {

                    $key = sprintf('%s.%s', $configName, $config);

                    $this->set($key, $value);
                }
            }
        }

    }

Load config files

@param bool|false $force


public function match($path, $name, $callback = null, array $schemes = [])
    {
        return $this->any($path, $name, $callback, $schemes);
    }

public function match ( $ path , $ name , $ callback = null , array $ schemes = [ ] ) { return $ this -> any ( $ path , $ name , $ callback , $ schemes ) ; }

Match a given path

You would proceed this method call by setting allowed methods

@param $path
@param $name
@param null $callback
@param array $schemes
@return Route


public function section($name, $options = [], \Closure $callback)
    {
        $sub_collection = new RouteCollection();

        $sub_router = new self();
        $sub_router->setInSection(true);
        $sub_router->setRoutes($sub_collection);

        $callback($sub_router, $sub_collection);

        $sub_collection->addPrefix($name);
        $sub_collection->addDefaults($options);

        $this->getRoutes()->addCollection($sub_collection);

        return $this;
    }

public function section ( $ name , $ options = [ ] , \ Closure $ callback ) { $ sub_collection = new RouteCollection ( ) ; $ sub_router = new self ( ) ; $ sub_router -> setInSection ( true ) ; $ sub_router -> setRoutes ( $ sub_collection ) ; $ callback ( $ sub_router , $ sub_collection ) ; $ sub_collection -> addPrefix ( $ name ) ; $ sub_collection -> addDefaults ( $ options ) ; $ this -> getRoutes ( ) -> addCollection ( $ sub_collection ) ; return $ this ; }

Create a route section

@param $name
@param array $options
@param \Closure $callback

@deprecated This method is deprecated as of 2.1 and will be removed in 3.0 use Router::group instead

@return $this


public function group($options, \Closure $callback)
    {
        $prefix = null;

        if ( ! (is_string($options) || is_array($options))) {
            throw new \RuntimeException('Options must either be a string or array');
        }

        if (is_string($options)) {
            $prefix = $options;
            $options = [];
        }
        else if (is_array($options) && isset($options['prefix'])) {
            $prefix = $options['prefix'];
        }

        $subCollection = new RouteCollection();

        $subRouter = new self();
        $subRouter
            ->setInGroup(true)
            ->setRoutes($subCollection);

        $callback($subRouter, $subCollection);

        if ($prefix) {
            $subCollection->addPrefix($prefix);
        }

        if ($options) {
            if (isset($options['domain'])) {
                $subCollection->setHost($options['domain']);
            }

            if (isset($options['schemes'])) {
                $subCollection->setSchemes($options['schemes']);
            }

            if (isset($options['methods'])) {
                $subCollection->setMethods($options['methods']);
            }

            if (isset($options['defaults'])) {
                $subCollection->addDefaults($options['defaults']);
            }

            if (isset($options['options'])) {
                $subCollection->addOptions($options['options']);
            }

            if (isset($options['requirements'])) {
                $subCollection->addRequirements($options['requirements']);
            }
        }

        $this->getRoutes()->addCollection($subCollection);

        return $this;
    }

Create a route group

@param string|array $options
@param \Closure $callback
@return $this


public function start($name)
    {
        if (in_array($name, $this->openBlocks)) {
            throw new \InvalidArgumentException(sprintf('A block named "%s" is already started.', $name));
        }

        $this->openBlocks[] = $name;
        $this->blocks[$name] = '';

        ob_start();
        ob_implicit_flush(0);
    }

Starts a new block.

This method starts an output buffer that will be
closed when the stop() method is called.

@param string $name The block name

@throws \InvalidArgumentException if a block with the same name is already started

@api


public function stop()
    {
        if (!$this->openBlocks) {
            throw new \LogicException('No block started.');
        }

        $name = array_pop($this->openBlocks);

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

public
function
stop
(
)
{
if
(
!
$
this
->
openBlocks
)
{
throw
new
\
LogicException
(
'No block started.'
)
;
}
$
name
=
array_pop
(
$
this
->
openBlocks
)
;
$
this
->
blocks
[
$
name
]
=
ob_get_clean
(
)
;
}

Stops a block.

@throws \LogicException if no block has been started

@api


public function output($name, $default = false)
    {
        if (isset($this->blocks[$name])) {

            echo $this->blocks[$name];

            return true;
        }

        if (isset($this->blockDefaults[$name])) {

            echo $this->blockDefaults[$name];

            return true;
        }

        if (false !== $default) {
            echo $default;

            return true;
        }

        return false;
    }

public function output ( $ name , $ default = false ) { if ( isset ( $ this -> blocks [ $ name ] ) ) { echo $ this -> blocks [ $ name ] ; return true ; } if ( isset ( $ this -> blockDefaults [ $ name ] ) ) { echo $ this -> blockDefaults [ $ name ] ; return true ; } if ( false !== $ default ) { echo $ default ; return true ; } return false ; }

Outputs a block.

@param string $name The block name

@param bool $default
@return Boolean true if the block is defined or if a default content has been provided, false otherwise

@api


protected function createController($controller)
    {
        if (false === strpos($controller, '::')) {
            $count = substr_count($controller, ':');
            if (2 == $count && $this->parser) {
                // controller in the a:b:c notation then
                $controller = $this->parser->parse($controller);
            }
            else if (1 == $count) {
                // controller in the service:method notation
                list($service, $method) = explode(':', $controller, 2);
                return array($this->container->get($service), $method);
            }
            else if ($this->container->has($controller) && method_exists($service = $this->container->get($controller), '__invoke')) {
                return $service;
            }
            else {
                throw new \InvalidArgumentException(sprintf('Unable to find controller "%s".', $controller));
            }
        }

        list($class, $method) = explode('::', $controller, 2);

        if (!class_exists($class)) {
            throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $class));
        }

        $controller = $this->instantiateController($class);

        return array($controller, $method);
    }

Returns a callable for the given controller.

@param string $controller A Controller string

@return mixed A PHP callable

@throws \InvalidArgumentException

Returns a callable for the given controller .


protected function instantiateController($class)
    {
        $reflector = new ReflectionClass($class);

        $constructor = $reflector->getConstructor();

        if ($constructor && $constructor->getParameters()) {
            $controller = $this->container->get($class);
        }
        else {
            $controller = new $class();
        }

        if ($controller instanceof ContainerAwareInterface) {
            $controller->setContainer($this->container);
        }

        return $controller;
    }

protected function instantiateController ( $ class ) { $ reflector = new ReflectionClass ( $ class ) ; $ constructor = $ reflector -> getConstructor ( ) ; if ( $ constructor && $ constructor -> getParameters ( ) ) { $ controller = $ this -> container -> get ( $ class ) ; } else { $ controller = new $ class ( ) ; } if ( $ controller instanceof ContainerAwareInterface ) { $ controller -> setContainer ( $ this -> container ) ; } return $ controller ; }

Returns an instantiated controller

@param string $class A class name

@return object


public function validateUrl($url)
    {
        foreach ($this->validUrlStartChars as $char) {
            if (0 === strpos($url, $char)) {
                return true;
            }
        }

        return false !== filter_var($url, FILTER_VALIDATE_URL);
    }

public function validateUrl ( $ url ) { foreach ( $ this -> validUrlStartChars as $ char ) { if ( 0 === strpos ( $ url , $ char ) ) { return true ; } } return false !== filter_var ( $ url , FILTER_VALIDATE_URL ) ; }

Determine if the given path is a valid URL.

@param $url
@return bool

Determine if the given path is a valid URL .


protected function findTemplate($template, $throw = true)
    {
        $logicalName = (string) $template;

        if (isset($this->cache[$logicalName])) {
            return $this->cache[$logicalName];
        }

        $file = null;
        try {
            $file = parent::findTemplate($logicalName);
        } catch (\Twig_Error_Loader $e) {
            $twigLoaderException = $e;

            // for BC
            try {
                $template = $this->parser->parse($template);
                $file = $this->locator->locate($template);
            } catch (\Exception $e) {
            }
        }

        if (false === $file || null === $file) {
            if ($throw) {
                throw $twigLoaderException;
            }

            return false;
        }

        return $this->cache[$logicalName] = $file;
    }

protected
function
findTemplate
(
$
template
,
$
throw
=
true
)
{
$
logicalName
=
(
string
)
$
template
;
if
(
isset
(
$
this
->
cache
[
$
logicalName
]
)
)
{
return
$
this
->
cache
[
$
logicalName
]
;
}
$
file
=
;
try
{
$
file
=
parent
::
findTemplate
(
$
logicalName
)
;
}
catch
(
\
Twig_Error_Loader
$
e
)
{
$
twigLoaderException
=
$
e
;
// for BC
try
{
$
template
=
$
this
->
parser
->
parse
(
$
template
)
;
$
file
=
$
this
->
locator
->
locate
(
$
template
)
;
}
catch
(
\
Exception
$
e
)
{
}
}
if
(
false
===
$
file
||
===
$
file
)
{
if
(
$
throw
)
{
throw
$
twigLoaderException
;
}
return
false
;
}
return
$
this
->
cache
[
$
logicalName
]
=
$
file
;
}

Returns the path to the template file.

The file locator is used to locate the template when the naming convention
is the symfony one (i.e. the name can be parsed).
Otherwise the template is located using the locator from the twig library.

@param string|TemplateReferenceInterface $template The template
@param bool                              $throw    When true, a \Twig_Error_Loader exception will be thrown if a template could not be found

@return string The path to the template file

@throws \Twig_Error_Loader if the template could not be found


static public function setApplicationEntityManager(Application $application, $emName)
    {
        /** @var $em \Doctrine\ORM\EntityManager */
        $em = $application->getKernel()->getContainer()->get('doctrine')->getManager($emName);

        $helperSet = $application->getHelperSet();
        $helperSet->set(new ConnectionHelper($em->getConnection()), 'db');
        $helperSet->set(new EntityManagerHelper($em), 'em');
    }

Convenience method to push the helper sets of a given entity manager into the application.

@param Application $application
@param string      $emName

Convenience method to push the helper sets of a given entity manager into the application .


static public function setApplicationConnection(Application $application, $connName)
    {
        $connection = $application->getKernel()->getContainer()->get('doctrine')->getConnection($connName);
        $helperSet = $application->getHelperSet();
        $helperSet->set(new ConnectionHelper($connection), 'db');
    }

static public function setApplicationConnection ( Application $ application , $ connName ) { $ connection = $ application -> getKernel ( ) -> getContainer ( ) -> get ( 'doctrine' ) -> getConnection ( $ connName ) ; $ helperSet = $ application -> getHelperSet ( ) ; $ helperSet -> set ( new ConnectionHelper ( $ connection ) , 'db' ) ; }

Convenience method to push the helper sets of a given connection into the application.

@param Application $application
@param string      $connName

Convenience method to push the helper sets of a given connection into the application .


public function renderView($template)
    {
        if (array_key_exists($template, $this->views)) {
            echo $this->views[$template]->render();
            return false;
        }

        return $template;
    }

public function renderView ( $ template ) { if ( array_key_exists ( $ template , $ this -> views ) ) { echo $ this -> views [ $ template ] -> render ( ) ; return false ; } return $ template ; }

Called by the WordPress include_template filter, so we can
intercept it and render our registered View object instead.

This is not a great solution because WordPress filters should not
cause side effects, but in this case, on render is the only time
this filter should be called. Still, we will acknowledge that
it is a hack

@param  string $template template file
@return string           template file, return false if rendering

Called by the WordPress include_template filter so we can intercept it and render our registered View object instead .


public function open()
    {
        $attributes = [
            'method' => $this->method,
            'action' => $this->url
        ];

        $attributes = array_merge($attributes, $this->attributes);

        return sprintf('<form%s>', $this->attributes($attributes));
    }

public function open ( ) { $ attributes = [ 'method' => $ this -> method , 'action' => $ this -> url ] ; $ attributes = array_merge ( $ attributes , $ this -> attributes ) ; return sprintf ( '<form%s>' , $ this -> attributes ( $ attributes ) ) ; }


public function addTransformers(array $dataTransformers)
    {
        foreach ($dataTransformers as $type => $dataTransformer) {

            if ( ! $dataTransformer instanceof DataTransformerInterface) {
                throw new InvalidDataTransformerException();
            }

            $this->addTransformer($type, $dataTransformer);
        }

        return $this;
    }

public function addTransformers ( array $ dataTransformers ) { foreach ( $ dataTransformers as $ type => $ dataTransformer ) { if ( ! $ dataTransformer instanceof DataTransformerInterface ) { throw new InvalidDataTransformerException ( ) ; } $ this -> addTransformer ( $ type , $ dataTransformer ) ; } return $ this ; }

Add a group of data transformers

array (
'date' => DataTransformerInterface
)

@param array $dataTransformers
@return $this


function public ($segment, array $parameters=[], $version='v1.1') {
        $options = [
            'http' => [
                'method'  => 'GET',
                'timeout' => 10,
            ],
        ];

        $publicUrl = $this->getPublicUrl($version);
        $url = $publicUrl . $segment . '?' . http_build_query(array_filter($parameters));
        $feed = file_get_contents($url, false, stream_context_create($options));
        return json_decode($feed, true);
    }

function public ( $ segment , array $ parameters = [ ] , $ version = 'v1.1' ) { $ options = [ 'http' => [ 'method' => 'GET' , 'timeout' => 10 , ] , ] ; $ publicUrl = $ this -> getPublicUrl ( $ version ) ; $ url = $ publicUrl . $ segment . '?' . http_build_query ( array_filter ( $ parameters ) ) ; $ feed = file_get_contents ( $ url , false , stream_context_create ( $ options ) ) ; return json_decode ( $ feed , true ) ; }

Execute a public API request

@param $segment
@param array $parameters
@return array


public function market($segment, array $parameters=[]) {
        $baseUrl = $this->marketUrl;
        return $this->nonPublicRequest($baseUrl, $segment, $parameters);
    }

public function market ( $ segment , array $ parameters = [ ] ) { $ baseUrl = $ this -> marketUrl ; return $ this -> nonPublicRequest ( $ baseUrl , $ segment , $ parameters ) ; }

Execute a market API request

@param $segment
@param array $parameters
@return array


public function account($segment, array $parameters=[]) {
        $baseUrl = $this->accountUrl;
        return $this->nonPublicRequest($baseUrl, $segment, $parameters);
    }

public function account ( $ segment , array $ parameters = [ ] ) { $ baseUrl = $ this -> accountUrl ; return $ this -> nonPublicRequest ( $ baseUrl , $ segment , $ parameters ) ; }

Execute an account API request

@param $segment
@param array $parameters
@return array


public static function prepareAttributes(array $attributes)
    {
        return [
            'title'       => Arr::get($attributes, 'title'),
            'description' => Arr::get($attributes, 'description'),
            'keywords'    => Arr::get($attributes, 'keywords', []),
            'extras'      => Arr::get($attributes, 'extras', []),
            'noindex'     => Arr::get($attributes, 'noindex', false),
        ];
    }

public static function prepareAttributes ( array $ attributes ) { return [ 'title' => Arr :: get ( $ attributes , 'title' ) , 'description' => Arr :: get ( $ attributes , 'description' ) , 'keywords' => Arr :: get ( $ attributes , 'keywords' , [ ] ) , 'extras' => Arr :: get ( $ attributes , 'extras' , [ ] ) , 'noindex' => Arr :: get ( $ attributes , 'noindex' , false ) , ] ; }

Prepare the attributes.

@param  array  $attributes

@return array


public function addExtra($key, $value)
    {
        return $this->setExtras(
            $this->extras->put($key, $value)->all()
        );
    }

public function addExtra ( $ key , $ value ) { return $ this -> setExtras ( $ this -> extras -> put ( $ key , $ value ) -> all ( ) ) ; }

Add an extra meta.

@param  string  $key
@param  mixed   $value

@return $this


function fetchObject($className = '\\stdClass', $params = array())
    {
        if ($className) {
            if ($params) {
                return mysqli_fetch_object($this->result, $className, $params);
            } else {
                return mysqli_fetch_object($this->result, $className);
            }
        } else {
            return mysqli_fetch_object($this->result);
        }
    }

function fetchObject ( $ className = '\\stdClass' , $ params = array ( ) ) { if ( $ className ) { if ( $ params ) { return mysqli_fetch_object ( $ this -> result , $ className , $ params ) ; } else { return mysqli_fetch_object ( $ this -> result , $ className ) ; } } else { return mysqli_fetch_object ( $ this -> result ) ; } }

Returns the current row of a result set as an object
@param string The name of the class to instantiate, set the properties of and return. If not specified, a \stdClass object is returned.
@param array An optional array of parameters to pass to the constructor for class_name objects.
@return object


static function dialog($openControlId, $message, array $action = array())
    {
        Manialink::appendScript(static::getDialog($openControlId, $message, $action));
    }

static function dialog ( $ openControlId , $ message , array $ action = array ( ) ) { Manialink :: appendScript ( static :: getDialog ( $ openControlId , $ message , $ action ) ) ; }

Teh infamous dialog box

@param string $openControlId Id of the element that will open the dialog when clicked
@param string $message Message to show in the dialog
@param array $action A ManiaScript Framework Action


static function getInstance()
    {
        if (\array_key_exists('default', static::$connections)) {
            return static::$connections['default'];
        }

        $config = Config::getInstance();

        $params = new ConnectionParams();
        $params->id = 'default';
        $params->host = $config->host;
        $params->user = $config->user;
        $params->password = $config->password;
        $params->database = $config->database;
        $params->charset = $config->charset;
        $params->persistent = $config->persistent;

        return static::factory($params);
    }

static function getInstance ( ) { if ( \ array_key_exists ( 'default' , static :: $ connections ) ) { return static :: $ connections [ 'default' ] ; } $ config = Config :: getInstance ( ) ; $ params = new ConnectionParams ( ) ; $ params -> id = 'default' ; $ params -> host = $ config -> host ; $ params -> user = $ config -> user ; $ params -> password = $ config -> password ; $ params -> database = $ config -> database ; $ params -> charset = $ config -> charset ; $ params -> persistent = $ config -> persistent ; return static :: factory ( $ params ) ; }

The easiest way to retrieve a database connection. Works as a singleton,
and returns a connection with the default parameters
@return \ManiaLib\Database\Connection

The easiest way to retrieve a database connection . Works as a singleton and returns a connection with the default parameters


function beginTransaction()
    {
        if ($this->transactionRollback) {
            throw new Exception('Transaction must be rollback\'ed!');
        }
        if ($this->transactionRefCount === null) {
            $this->execute('BEGIN');
            $this->transactionRefCount = 1;
        } else {
            $this->transactionRefCount++;
        }
    }

function
beginTransaction
(
)
{
if
(
$
this
->
transactionRollback
)
{
throw
new
Exception
(
'Transaction must be rollback\'ed!'
)
;
}
if
(
$
this
->
transactionRefCount
===
)
{
$
this
->
execute
(
'BEGIN'
)
;
$
this
->
transactionRefCount
=
1
;
}
else
{
$
this
->
transactionRefCount
++
;
}
}

ACID Transactions
ONLY WORKS WITH INNODB TABLES !

----

It handles EXPERIMENTAL (== never tested!!!) nested transactions
one "BEGIN" on the first call of beginTransaction
one "COMMIT" on the last call of commitTransaction (when the ref count is 1)
one "ROLLBACK" on the first call of rollbackTransaction


final public static function load($noconfirmation = false,
                                      $createManialinkElement = true)
    {
        self::$domDocument = new \DOMDocument('1.0', 'utf8');
        self::$parentNodes = array();

        if ($createManialinkElement) {
            $maniacode = self::$domDocument->createElement('maniacode');
            if ($noconfirmation)
                $maniacode->setAttribute('noconfirmation', $noconfirmation);
            self::$domDocument->appendChild($maniacode);
            self::$parentNodes[] = $maniacode;
        }
    }

final public static function load ( $ noconfirmation = false , $ createManialinkElement = true ) { self :: $ domDocument = new \ DOMDocument ( '1.0' , 'utf8' ) ; self :: $ parentNodes = array ( ) ; if ( $ createManialinkElement ) { $ maniacode = self :: $ domDocument -> createElement ( 'maniacode' ) ; if ( $ noconfirmation ) $ maniacode -> setAttribute ( 'noconfirmation' , $ noconfirmation ) ; self :: $ domDocument -> appendChild ( $ maniacode ) ; self :: $ parentNodes [ ] = $ maniacode ; } }

Loads the Maniacode GUI Toolkit. This should be called before doing anything with the toolkit

@param bool True if you don't want to see a message at the end of the execution of the maniacode
@param bool Wheter you want to create the root "<maniacode>" element in the XML

Loads the Maniacode GUI Toolkit . This should be called before doing anything with the toolkit


final public static function render($return = false)
    {
        if ($return) {
            return self::$domDocument->saveXML();
        } else {
            header('Content-Type: text/xml; charset=utf-8');
            echo self::$domDocument->saveXML();
            exit();
        }
    }

final
public
static
function
render
(
$
return
=
false
)
{
if
(
$
return
)
{
return
self
::
$
domDocument
->
saveXML
(
)
;
}
else
{
header
(
'Content-Type: text/xml; charset=utf-8'
)
;
echo
self
::
$
domDocument
->
saveXML
(
)
;
exit
(
)
;
}
}

Renders the Maniacode if no return the script will be stopped
@param bool Whether you want to return the XML instead of printing it
@return mixed The XML string if param true, in other case it returns void


public function connect(){
        $this->stream = stream_socket_client('tcp://'.$this->host.':'.$this->port, $errno, $errstr, 10);
        if(!$this->stream){
            throw new Exception("Error $errno : $errstr");
        }

        return fgets($this->stream);
    }

public
function
connect
(
)
{
$
this
->
stream
=
stream_socket_client
(
'tcp://'
.
$
this
->
host
.
':'
.
$
this
->
port
,
$
errno
,
$
errstr
,
10
)
;
if
(
!
$
this
->
stream
)
{
throw
new
Exception
(
"Error $errno : $errstr"
)
;
}
return
fgets
(
$
this
->
stream
)
;
}

Connect to the service
@return string service informations json_decoded
@throws Exception


public function watch($enable = true, $format = 'json'){
        if($enable){
            fwrite($this->stream, '?WATCH={"enable":true,"'.$format.'":true}');
        }else{
            fwrite($this->stream, '?WATCH={"enable":false}');
        }
    }

public function watch ( $ enable = true , $ format = 'json' ) { if ( $ enable ) { fwrite ( $ this -> stream , '?WATCH={"enable":true,"' . $ format . '":true}' ) ; } else { fwrite ( $ this -> stream , '?WATCH={"enable":false}' ) ; } }

Set service watch settings

@param bool $enable tell the service to watch or not the devices (default: true)
@param string $format the desired format of the returned datas (default: json)


function setBgcolor($bgcolor)
    {
        $this->bgcolor = $bgcolor;
        $this->setStyle(null);
        $this->setSubStyle(null);
    }

function setBgcolor ( $ bgcolor ) { $ this -> bgcolor = $ bgcolor ; $ this -> setStyle ( null ) ; $ this -> setSubStyle ( null ) ; }

Sets the background color of the element using a 3-digit RGB hexadecimal
value. For example, "fff" is white and "000" is black
@param string 3-digit RGB hexadecimal value

Sets the background color of the element using a 3 - digit RGB hexadecimal value . For example fff is white and 000 is black


function setImage($image, $absoluteUrl = false)
    {
        $this->setStyle(null);
        $this->setSubStyle(null);
        if (!$absoluteUrl) {
            $this->image = Manialink::$imagesURL . $image;
        } else {
            $this->image = $image;
        }
    }

function setImage ( $ image , $ absoluteUrl = false ) { $ this -> setStyle ( null ) ; $ this -> setSubStyle ( null ) ; if ( ! $ absoluteUrl ) { $ this -> image = Manialink :: $ imagesURL . $ image ; } else { $ this -> image = $ image ; } }

Applies an image to the element
@param string The image filename (or URL)
@param bool Whether to prefix the filename with the default images dir URL


function setImageid($imageid)
    {
        $this->setStyle(null);
        $this->setSubStyle(null);
        $this->imageid = $imageid;
    }

function setImageid ( $ imageid ) { $ this -> setStyle ( null ) ; $ this -> setSubStyle ( null ) ; $ this -> imageid = $ imageid ; }

Set the image id of the element, used for internationalization

Set the image id of the element used for internationalization


function setImageFocus($imageFocus, $absoluteUrl = false)
    {
        $this->setStyle(null);
        $this->setSubStyle(null);
        if (!$absoluteUrl) {
            $this->imageFocus = Manialink::$imagesURL . $imageFocus;
        } else {
            $this->imageFocus = $imageFocus;
        }
    }

function setImageFocus ( $ imageFocus , $ absoluteUrl = false ) { $ this -> setStyle ( null ) ; $ this -> setSubStyle ( null ) ; if ( ! $ absoluteUrl ) { $ this -> imageFocus = Manialink :: $ imagesURL . $ imageFocus ; } else { $ this -> imageFocus = $ imageFocus ; } }

Applies an image to the highlighter state of the element
@param string The image filename (or URL)
@param bool Whether to prefix the filename with the default images dir URL


function setImageFocusid($imageFocusid)
    {
        $this->setStyle(null);
        $this->setSubStyle(null);
        $this->imageFocusid = $imageFocusid;
    }

function setImageFocusid ( $ imageFocusid ) { $ this -> setStyle ( null ) ; $ this -> setSubStyle ( null ) ; $ this -> imageFocusid = $ imageFocusid ; }

Set the image focus id of the element, used for internationalization

Set the image focus id of the element used for internationalization


function addLink(\ManiaLib\Gui\Element $object)
    {
        $this->manialink = $object->getManialink();
        $this->url = $object->getUrl();
        $this->maniazone = $object->getManiazone();
        $this->goto = $object->getGoto();
        $this->action = $object->getAction();
        $this->actionKey = $object->getActionKey();
        if ($object->getAddPlayerId()) {
            $this->addPlayerId = 1;
        }
    }

function addLink ( \ ManiaLib \ Gui \ Element $ object ) { $ this -> manialink = $ object -> getManialink ( ) ; $ this -> url = $ object -> getUrl ( ) ; $ this -> maniazone = $ object -> getManiazone ( ) ; $ this -> goto = $ object -> getGoto ( ) ; $ this -> action = $ object -> getAction ( ) ; $ this -> actionKey = $ object -> getActionKey ( ) ; if ( $ object -> getAddPlayerId ( ) ) { $ this -> addPlayerId = 1 ; } }

Imports links and actions from another Manialink element
@param \ManiaLib\Gui\Element The source object


public static function getConfig($key = null, $default = null)
    {
        $key = self::KEY.(is_null($key) ? '' : '.'.$key);

        return config()->get($key, $default);
    }

public static function getConfig ( $ key = null , $ default = null ) { $ key = self :: KEY . ( is_null ( $ key ) ? '' : '.' . $ key ) ; return config ( ) -> get ( $ key , $ default ) ; }

Get the seo config.

@param  string|null  $key
@param  mixed|null   $default

@return mixed


public static function setConfig($key, $value = null)
    {
        config()->set(self::KEY.'.'.$key, $value);
    }

public static function setConfig ( $ key , $ value = null ) { config ( ) -> set ( self :: KEY . '.' . $ key , $ value ) ; }

Set the seo config.

@param  string      $key
@param  mixed|null  $value


public static function getTrans($key = null, $replace = [], $locale = null)
    {
        return trans(self::KEY.'::'.$key, $replace, $locale);
    }

public static function getTrans ( $ key = null , $ replace = [ ] , $ locale = null ) { return trans ( self :: KEY . '::' . $ key , $ replace , $ locale ) ; }

Get the seo translation.

@param  string  $key
@param  array   $replace
@param  string  $locale

@return string


public function getArray($key, callable $callback = null)
    {
        $list = $this->get($key);
        if (!is_array($list)) {
            return [];
        }
        if (is_callable($callback)) {
            return array_map($callback, $list);
        }
        return $list;
    }

public function getArray ( $ key , callable $ callback = null ) { $ list = $ this -> get ( $ key ) ; if ( ! is_array ( $ list ) ) { return [ ] ; } if ( is_callable ( $ callback ) ) { return array_map ( $ callback , $ list ) ; } return $ list ; }

Get a list item from collection with given key.
If item does not exist an empty array is returned.

@param string        $key
@param callable|null $callback Optional callable to map items in list

@return array

Get a list item from collection with given key . If item does not exist an empty array is returned .


static function stripStyles($string)
    {
        $string = preg_replace('/(?<!\$)((?:\$\$)*)\$[^$0-9a-hlp]/iu', '$1', $string);
        $string = self::stripLinks($string);
        $string = self::stripColors($string);
        return $string;
    }

static function stripStyles ( $ string ) { $ string = preg_replace ( '/(?<!\$)((?:\$\$)*)\$[^$0-9a-hlp]/iu' , '$1' , $ string ) ; $ string = self :: stripLinks ( $ string ) ; $ string = self :: stripColors ( $ string ) ; return $ string ; }


public static function createOne($oldUrl, $newUrl, $status = Response::HTTP_MOVED_PERMANENTLY)
    {
        $redirect = new self([
            'old_url' => $oldUrl,
            'new_url' => $newUrl,
            'status'  => $status,
        ]);

        $redirect->save();

        return $redirect;
    }

public static function createOne ( $ oldUrl , $ newUrl , $ status = Response :: HTTP_MOVED_PERMANENTLY ) { $ redirect = new self ( [ 'old_url' => $ oldUrl , 'new_url' => $ newUrl , 'status' => $ status , ] ) ; $ redirect -> save ( ) ; return $ redirect ; }

Create a redirect url.

@param  string  $oldUrl
@param  string  $newUrl
@param  int     $status

@return \Arcanedev\LaravelSeo\Models\Redirect


public function numbers($index = 1, $size = 10, $pattern = null, $searchPattern = MatchingStrategy::STARTS_WITH)
    {
        return $this->numbers->invoke($index, $size, $pattern, $searchPattern);
    }

public function numbers ( $ index = 1 , $ size = 10 , $ pattern = null , $ searchPattern = MatchingStrategy :: STARTS_WITH ) { return $ this -> numbers -> invoke ( $ index , $ size , $ pattern , $ searchPattern ) ; }

Get all inbound numbers associated with your Nexmo account

@param int $index                Page index
@param int $size                 Page size (max 100)
@param int $pattern              A matching pattern
@param int $searchPattern        Strategy for matching pattern.
0 = starts with
1 = anywhere
2 = ends with

@return Entity\NumberCollection|Entity\Number[]
@throws Exception


static function factory($driver = null)
    {
        try {
            switch ($driver) {
                case APC:
                    return static::getDriver('APC');
                case MEMCACHED:
                    try {
                        return static::getDriver('Memcached');
                    } catch (Exception $e) {
                        return static::getDriver('Memcache');
                    }
                case MEMCACHE:
                    return static::getDriver('Memcache');
                case MYSQL:
                    return static::getDriver('MySQL');
                default:
                    throw new Exception();
            }
        } catch (Exception $e) {
            $config = Config::getInstance();
            $driver = $config->fallbackDriver ?: 'NoCache';
            return static::getDriver($driver);
        }
    }

static function factory ( $ driver = null ) { try { switch ( $ driver ) { case APC : return static :: getDriver ( 'APC' ) ; case MEMCACHED : try { return static :: getDriver ( 'Memcached' ) ; } catch ( Exception $ e ) { return static :: getDriver ( 'Memcache' ) ; } case MEMCACHE : return static :: getDriver ( 'Memcache' ) ; case MYSQL : return static :: getDriver ( 'MySQL' ) ; default : throw new Exception ( ) ; } } catch ( Exception $ e ) { $ config = Config :: getInstance ( ) ; $ driver = $ config -> fallbackDriver ? : 'NoCache' ; return static :: getDriver ( $ driver ) ; } }

Factory for getting instances on cache objects.
You specify the driver to use as a parameter, and
it automatically falls back to the "NoCache" driver
if not found
@return \ManiaLib\Cache\CacheInterface

Factory for getting instances on cache objects . You specify the driver to use as a parameter and it automatically falls back to the NoCache driver if not found


final public static function load($root = true, $timeout = 0, $version = 1, $background = self::DEFAULT_BACKGROUND, $navigable3d = false)
    {
        if (class_exists('\ManiaLib\Application\Config')) {
            $config = \ManiaLib\Application\Config::getInstance();
            self::$langsURL = $config->getLangsURL();
            self::$imagesURL = $config->getImagesURL();
            self::$mediaURL = $config->getMediaURL();
        }

        // Load the XML object
        self::$domDocument = new \DOMDocument('1.0', 'utf-8');
        self::$parentNodes = array();
        self::$parentLayouts = array();
        self::$parentFrames = array();

        if ($root) {
            $nodeManialink = self::$domDocument->createElement('manialink');
            $nodeManialink->setAttribute('version', $version);
            $nodeManialink->setAttribute('background', $background);
            $nodeManialink->setAttribute('navigable3d', (int)$navigable3d);
            self::$domDocument->appendChild($nodeManialink);
            self::$parentNodes[] = $nodeManialink;

            $nodeTimeout = self::$domDocument->createElement('timeout');
            $nodeManialink->appendChild($nodeTimeout);
            $nodeTimeout->nodeValue = $timeout;
        } else {
            $frame = self::$domDocument->createElement('frame');
            self::$domDocument->appendChild($frame);
            self::$parentNodes[] = $frame;
        }
    }

final
public
static
function
load
(
$
root
=
true
,
$
timeout
=
0
,
$
version
=
1
,
$
background
=
self
::
DEFAULT_BACKGROUND
,
$
navigable3d
=
false
)
{
if
(
class_exists
(
'\ManiaLib\Application\Config'
)
)
{
$
config
=
\
ManiaLib
\
Application
\
Config
::
getInstance
(
)
;
self
::
$
langsURL
=
$
config
->
getLangsURL
(
)
;
self
::
$
imagesURL
=
$
config
->
getImagesURL
(
)
;
self
::
$
mediaURL
=
$
config
->
getMediaURL
(
)
;
}
// Load the XML object
self
::
$
domDocument
=
new
\
DOMDocument
(
'1.0'
,
'utf-8'
)
;
self
::
$
parentNodes
=
array
(
)
;
self
::
$
parentLayouts
=
array
(
)
;
self
::
$
parentFrames
=
array
(
)
;
if
(
$
root
)
{
$
nodeManialink
=
self
::
$
domDocument
->
createElement
(
'manialink'
)
;
$
nodeManialink
->
setAttribute
(
'version'
,
$
version
)
;
$
nodeManialink
->
setAttribute
(
'background'
,
$
background
)
;
$
nodeManialink
->
setAttribute
(
'navigable3d'
,
(
int
)
$
navigable3d
)
;
self
::
$
domDocument
->
appendChild
(
$
nodeManialink
)
;
self
::
$
parentNodes
[
]
=
$
nodeManialink
;
$
nodeTimeout
=
self
::
$
domDocument
->
createElement
(
'timeout'
)
;
$
nodeManialink
->
appendChild
(
$
nodeTimeout
)
;
$
nodeTimeout
->
nodeValue
=
$
timeout
;
}
else
{
$
frame
=
self
::
$
domDocument
->
createElement
(
'frame'
)
;
self
::
$
domDocument
->
appendChild
(
$
frame
)
;
self
::
$
parentNodes
[
]
=
$
frame
;
}
}

Loads the Manialink GUI toolkit. This should be called before doing
anything with the toolkit.
@param bool Whether you want to create the root "<manialink>" element in the XML

Loads the Manialink GUI toolkit . This should be called before doing anything with the toolkit .


final public static function beginFrame($x = 0, $y = 0, $z = 0, $scale = null,
                                            \ManiaLib\Gui\Layouts\AbstractLayout $layout = null)
    {
        $frame = new Elements\Frame();
        $frame->setPosition($x, $y, $z);
        $frame->setScale($scale);
        if ($layout instanceof Layouts\AbstractLayout) {
            $frame->setLayout($layout);
        }
        $frame->buildXML();

        self::$parentFrames[] = $frame;
        self::$parentNodes[] = $frame->getDOMElement();
        self::$parentLayouts[] = $frame->getLayout();
    }

final public static function beginFrame ( $ x = 0 , $ y = 0 , $ z = 0 , $ scale = null , \ ManiaLib \ Gui \ Layouts \ AbstractLayout $ layout = null ) { $ frame = new Elements \ Frame ( ) ; $ frame -> setPosition ( $ x , $ y , $ z ) ; $ frame -> setScale ( $ scale ) ; if ( $ layout instanceof Layouts \ AbstractLayout ) { $ frame -> setLayout ( $ layout ) ; } $ frame -> buildXML ( ) ; self :: $ parentFrames [ ] = $ frame ; self :: $ parentNodes [ ] = $ frame -> getDOMElement ( ) ; self :: $ parentLayouts [ ] = $ frame -> getLayout ( ) ; }

Creates a new Manialink frame, with an optionnal associated layout

@param float X position
@param float Y position
@param float Z position
@param float Scale (default is null or 1)
@param \ManiaLib\Gui\Layouts\AbstractLayout The optionnal layout associated with the frame. If
you pass a layout object, all the items inside the frame will be
positionned using constraints defined by the layout

Creates a new Manialink frame with an optionnal associated layout


final public static function endFrame()
    {
        if (!end(self::$parentNodes)->hasChildNodes()) {
            end(self::$parentNodes)->nodeValue = ' ';
        }
        array_pop(self::$parentNodes);
        array_pop(self::$parentLayouts);
        $frame = array_pop(self::$parentFrames);
        $frame->save();
    }

final
public
static
function
endFrame
(
)
{
if
(
!
end
(
self
::
$
parentNodes
)
->
hasChildNodes
(
)
)
{
end
(
self
::
$
parentNodes
)
->
nodeValue
=
' '
;
}
array_pop
(
self
::
$
parentNodes
)
;
array_pop
(
self
::
$
parentLayouts
)
;
$
frame
=
array_pop
(
self
::
$
parentFrames
)
;
$
frame
->
save
(
)
;
}


final public static function redirect($link, $render = true)
    {
        self::$domDocument = new \DOMDocument('1.0', 'utf-8');
        self::$parentNodes = array();
        self::$parentLayouts = array();

        $redirect = self::$domDocument->createElement('redirect');
        $redirect->appendChild(self::$domDocument->createTextNode($link));
        self::$domDocument->appendChild($redirect);
        self::$parentNodes[] = $redirect;

        if ($render) {
            if (ob_get_contents()) {
                ob_clean();
            }
            header('Content-Type: text/xml; charset=utf-8');
            echo self::$domDocument->saveXML();
        } else {
            return self::$domDocument->saveXML();
        }
    }

final
public
static
function
redirect
(
$
link
,
$
render
=
true
)
{
self
::
$
domDocument
=
new
\
DOMDocument
(
'1.0'
,
'utf-8'
)
;
self
::
$
parentNodes
=
array
(
)
;
self
::
$
parentLayouts
=
array
(
)
;
$
redirect
=
self
::
$
domDocument
->
createElement
(
'redirect'
)
;
$
redirect
->
appendChild
(
self
::
$
domDocument
->
createTextNode
(
$
link
)
)
;
self
::
$
domDocument
->
appendChild
(
$
redirect
)
;
self
::
$
parentNodes
[
]
=
$
redirect
;
if
(
$
render
)
{
if
(
ob_get_contents
(
)
)
{
ob_clean
(
)
;
}
header
(
'Content-Type: text/xml; charset=utf-8'
)
;
echo
self
::
$
domDocument
->
saveXML
(
)
;
}
else
{
return
self
::
$
domDocument
->
saveXML
(
)
;
}
}

Redirects the user to the specified Manialink


static function appendXML($XML)
    {
        $doc = new \DOMDocument('1.0', 'utf-8');
        $doc->loadXML($XML);
        $node = self::$domDocument->importNode($doc->firstChild, true);
        end(self::$parentNodes)->appendChild($node);
    }

static function appendXML ( $ XML ) { $ doc = new \ DOMDocument ( '1.0' , 'utf-8' ) ; $ doc -> loadXML ( $ XML ) ; $ node = self :: $ domDocument -> importNode ( $ doc -> firstChild , true ) ; end ( self :: $ parentNodes ) -> appendChild ( $ node ) ; }

Append some XML code to the document
@param string Some XML code


private function buildDriver($driver, array $extra = [])
    {
        $router  = $this->app->make(\Illuminate\Contracts\Routing\Registrar::class);
        $class   = Seo::getConfig("redirector.drivers.$driver.class");
        $options = Seo::getConfig("redirector.drivers.$driver.options", []);

        return new $class($router, array_merge($extra, $options));
    }

private function buildDriver ( $ driver , array $ extra = [ ] ) { $ router = $ this -> app -> make ( \ Illuminate \ Contracts \ Routing \ Registrar :: class ) ; $ class = Seo :: getConfig ( "redirector.drivers.$driver.class" ) ; $ options = Seo :: getConfig ( "redirector.drivers.$driver.options" , [ ] ) ; return new $ class ( $ router , array_merge ( $ extra , $ options ) ) ; }

Build the redirector.

@param  string  $driver
@param  array   $extra

@return mixed


function setBorder($borderWidth = 0, $borderHeight = 0)
    {
        $this->borderWidth = $borderWidth;
        $this->xIndex = $borderWidth;
        $this->borderHeight = $borderHeight;
        $this->yIndex = -$borderHeight;
    }

function setBorder ( $ borderWidth = 0 , $ borderHeight = 0 ) { $ this -> borderWidth = $ borderWidth ; $ this -> xIndex = $ borderWidth ; $ this -> borderHeight = $ borderHeight ; $ this -> yIndex = - $ borderHeight ; }

Sets the gap between the layout outer border and its content
@param Border width
@param Border height


static function declareFont($name, $normal, $bold = null, $italic = null, $boldItalic = null)
    {
        self::$fonts[$name] = array(
            0 => $normal,
            StyleParser::BOLD => $bold ?: $normal,
            StyleParser::ITALIC => $italic ?: $normal,
            StyleParser::BOLD | StyleParser::ITALIC => $boldItalic ?: ($bold ?: ($italic ?: $normal))
        );
    }

static function declareFont ( $ name , $ normal , $ bold = null , $ italic = null , $ boldItalic = null ) { self :: $ fonts [ $ name ] = array ( 0 => $ normal , StyleParser :: BOLD => $ bold ? : $ normal , StyleParser :: ITALIC => $ italic ? : $ normal , StyleParser :: BOLD | StyleParser :: ITALIC => $ boldItalic ? : ( $ bold ? : ( $ italic ? : $ normal ) ) ) ; }

Declare a font to use with onImage function


static function onImage($string, $image, $fontName, $x = 0, $y = 0, $size = 10, $defaultColor = '000')
    {
        if ($size <= 5)
            self::onImageQuality($string, $image, $fontName, $x, $y, $size, $defaultColor, 3);
        else if ($size <= 10)
            self::onImageQuality($string, $image, $fontName, $x, $y, $size, $defaultColor, 2);
        else if ($size <= 20)
            self::onImageQuality($string, $image, $fontName, $x, $y, $size, $defaultColor, 1);
        else
            self::onImageFast($string, $image, $fontName, $x, $y, $size, $defaultColor);
    }

static function onImage ( $ string , $ image , $ fontName , $ x = 0 , $ y = 0 , $ size = 10 , $ defaultColor = '000' ) { if ( $ size <= 5 ) self :: onImageQuality ( $ string , $ image , $ fontName , $ x , $ y , $ size , $ defaultColor , 3 ) ; else if ( $ size <= 10 ) self :: onImageQuality ( $ string , $ image , $ fontName , $ x , $ y , $ size , $ defaultColor , 2 ) ; else if ( $ size <= 20 ) self :: onImageQuality ( $ string , $ image , $ fontName , $ x , $ y , $ size , $ defaultColor , 1 ) ; else self :: onImageFast ( $ string , $ image , $ fontName , $ x , $ y , $ size , $ defaultColor ) ; }

Draw a string with on an image, method will be choose depending on the size wanted
@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

Draw a string with on an image method will be choose depending on the size wanted


static function onImageFast($string, $image, $fontName, $x = 0, $y = 0, $size = 10, $defaultColor = '000')
    {
        $defaultColor = Color::StringToRgb24($defaultColor);

        $xOffset = 0;
        foreach (self::parseString($string) as $token)
            $xOffset += $token->onImage($image, $fontName, $x + $xOffset, $y, $size, $defaultColor, 1);
    }

static function onImageFast ( $ string , $ image , $ fontName , $ x = 0 , $ y = 0 , $ size = 10 , $ defaultColor = '000' ) { $ defaultColor = Color :: StringToRgb24 ( $ defaultColor ) ; $ xOffset = 0 ; foreach ( self :: parseString ( $ string ) as $ token ) $ xOffset += $ token -> onImage ( $ image , $ fontName , $ x + $ xOffset , $ y , $ size , $ defaultColor , 1 ) ; }

Draw a string with on an image using fast method. There can be glitches when using small sizes
@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

Draw a string with on an image using fast method . There can be glitches when using small sizes