private function setType(?string $t) : void
    {
        if ($t === null || $t === "") {
            $msg = "Invalid configuration. The attribute \"type\" is required.";
            throw new \InvalidArgumentException($msg);
        } else {
            if (class_exists($t) === false || $t === "DateTime") {
                $t = "AeonDigital\\SimpleTypes\\d" . $t;
            }

            if (class_exists($t) === false) {
                $msg = "The given \"type\" class does not exists.";
                throw new \InvalidArgumentException($msg);
            } else {
                $this->typeReflection = new \ReflectionClass($t);

                if ($this->isValidSimpleType() === false) {
                    $msg = "The given \"type\" class does not implements the interface \"AeonDigital\\SimpleTypes\\Interfaces\\iSimpleType\".";
                    throw new \InvalidArgumentException($msg);
                }
                $this->type = $t;
            }
        }
    }

Define o nome completo da classe que determina o
tipo deste campo.

A classe informada deve implementar a interface
"AeonDigital\SimpleTypes\Interfaces\iSimpleType".

@param       ?string $t
Nome completo da classe a ser usada.

@return      void

@throws      \InvalidArgumentException
Caso a classe indicada não seja válida.

Define o nome completo da classe que determina o tipo deste campo .


private function setInputFormat($if) : void
    {
        if ($if !== null) {
            if (is_array($if) === true) {
                $requiredKeys = ["name", "length", "check", "removeFormat", "format", "storageFormat"];

                foreach ($requiredKeys as $key) {
                    if (array_key_exists($key, $if) === false) {
                        $msg = "Lost required key in the given input format rule.";
                        throw new \InvalidArgumentException($msg);
                    } else {
                        $msg = null;
                        $kVal = $if[$key];
                        switch ($key) {
                            case "name":
                                if (is_string($kVal) === false || strlen($kVal) === 0) {
                                    $msg = "Invalid given \"$key\" of input format. Expected a not empty string.";
                                }
                                break;

                            case "length":
                                if (is_int($kVal) === false && $kVal !== null) {
                                    $msg = "Invalid given \"$key\" of input format. Expected integer or null.";
                                }
                                break;

                            case "check":
                            case "removeFormat":
                            case "format":
                            case "storageFormat":
                                if (is_callable($kVal) === false) {
                                    $msg = "Invalid given \"$key\" of input format. Expected callable.";
                                }
                                break;
                        }

                        if ($msg !== null) {
                            throw new \InvalidArgumentException($msg);
                        }
                    }
                }

                $this->inputFormat = [
                    "name"          => strtoupper($if["name"]),
                    "length"        => (($if["length"] === null) ? null : (int)$if["length"]),
                    "check"         => $if["check"],
                    "removeFormat"  => $if["removeFormat"],
                    "format"        => $if["format"],
                    "storageFormat" => $if["storageFormat"]
                ];
            } else {
                if (class_exists($if) === false) {
                    $if = "AeonDigital\\DataFormat\\Patterns\\" . str_replace(".", "\\", $if);
                }

                if (class_exists($if) === false) {
                    $msg = "The given \"inputFormat\" class does not exists.";
                    throw new \InvalidArgumentException($msg);
                } else {
                    $this->inputFormatReflection = new \ReflectionClass($if);

                    if ($this->isValidInputFormat($if) === false) {
                        $msg = "The given \"inputFormat\" class does not implements the interface \"AeonDigital\\DataFormat\\Interfaces\\iFormat\".";
                        throw new \InvalidArgumentException($msg);
                    }

                    $this->inputFormat = [
                        "name"          => $if,
                        "length"        => $if::MaxLength,
                        "check"         => $if . "::check",
                        "removeFormat"  => $if . "::removeFormat",
                        "format"        => $if . "::format",
                        "storageFormat" => $if . "::storageFormat"
                    ];
                }
            }
        }
    }

A classe informada deve implementar a interface
"AeonDigital\DataFormat\Interfaces\iFormat".

Também deve ser aceito passar um array com as configurações de
formatação. Neste caso as seguintes posições devem ser usadas:

$arr = [
string "name"
Nome deste tipo de transformação.

int "length"
Tamanho máximo que uma string pode ter para ser aceita por este formato.

callable "check"
Função que valida a string para o tipo de formatação a ser definida.

callable "removeFormat"
Função que remove a formatação padrão.

callable "format"
Função que efetivamente formata a string para seu formato final.

callable "storageFormat"
Função que converte o valor para seu formato de armazenamento.
];

@param       ?array|?string $if
Nome completo da classe a ser usada.

@return      void

@throws      \InvalidArgumentException
Caso a classe indicada não seja válida.

A classe informada deve implementar a interface AeonDigital \ DataFormat \ Interfaces \ iFormat .


public function setValue($v) : bool
    {
        $iPS = $this->internal_ProccessSet($v);

        if ($iPS["canSet"] === true) {
            $this->value                        = $iPS["value"];
            $this->rawValue                     = $iPS["rawValue"];
            $this->fieldState_IsValid           = $iPS["valid"];
            $this->fieldState_CurrentState      = $iPS["state"];
            $this->fieldState_CollectionState   = $iPS["cState"];
        }
        $this->fieldState_ValidateState             = $iPS["state"];
        $this->fieldState_ValidateStateCanSet       = $iPS["canSet"];
        $this->fieldState_CollectionValidateState   = $iPS["cState"];

        return ($iPS["canSet"] === true && $iPS["valid"] === true);
    }

public function setValue ( $ v ) : bool { $ iPS = $ this -> internal_ProccessSet ( $ v ) ; if ( $ iPS [ "canSet" ] === true ) { $ this -> value = $ iPS [ "value" ] ; $ this -> rawValue = $ iPS [ "rawValue" ] ; $ this -> fieldState_IsValid = $ iPS [ "valid" ] ; $ this -> fieldState_CurrentState = $ iPS [ "state" ] ; $ this -> fieldState_CollectionState = $ iPS [ "cState" ] ; } $ this -> fieldState_ValidateState = $ iPS [ "state" ] ; $ this -> fieldState_ValidateStateCanSet = $ iPS [ "canSet" ] ; $ this -> fieldState_CollectionValidateState = $ iPS [ "cState" ] ; return ( $ iPS [ "canSet" ] === true && $ iPS [ "valid" ] === true ) ; }

Define um novo valor para este campo.

- Campos Simples
Para que o campo assuma o novo valor ele precisa ser
compatível com o "type" definido. Caso contrário o campo
ficará com o valor "null".

-- Valores esperados
null, Bool, Int, Float, RealNumber, DateTime, String

- Campos "reference"
Campos deste tipo apenas aceitarão valores capazes de preencher os
campos do modelo de dados ao qual eles se referenciam.
Independente de tornar o modelo de dados válido ou não, os valores
serão definidos exceto se o valor passado for incompatível com o
modelo de dados configurado.

-- Valores esperados
null, iterable, Array, iModel,

- Campos "collection"
Uma coleção de dados sempre será definida como o valor de
um campo que aceite este tipo de valor.
Os membros da coleção serão convertidos para o tipo "type"
definido. Membros que não possam ser convertidos serão substituidos
por "null" e a coleção será inválida até que estes membros sejam
removidos ou substituídos.

Coleções do tipo "reference" apenas serão redefinidos se TODOS seus
itens forem capazes de tornarem-se objetos "iModel" do tipo definido
para este campo.

-- Valores esperados
null, Array

- Estado e validação
-- Independente de o valor vir a ser efetivamente definido para o campo
o estado da validação pode ser verificado usando "getLastValidateState".

-- Uma vez que o valor seja definido o campo passa a assumir o estado herdado
da validação e poderá ser verificado em "getState".

- undefined
Este valor NUNCA será aceito por nenhum tipo de campo e em
qualquer circunstância.

@param       mixed $v
Valor a ser definido para o campo.

@return      bool
Retornará "true" se o valor tornou o campo válido
ou "false" caso agora ele esteja inválido.
Também retornará "false" caso o valor seja totalmente
incompatível com o campo.


public function getStorageValue()
    {
        if ($this->isValid() === true && ($this->value !== undefined || $this->default !== undefined)) {
            return $this->internal_ProccessGet($this->value, false);
        } else {
            if ($this->isCollection() === true) {
                return [];
            } else {
                return null;
            }
        }
    }

public function getStorageValue ( ) { if ( $ this -> isValid ( ) === true && ( $ this -> value !== undefined || $ this -> default !== undefined ) ) { return $ this -> internal_ProccessGet ( $ this -> value , false ) ; } else { if ( $ this -> isCollection ( ) === true ) { return [ ] ; } else { return null ; } } }

Retorna o valor atual deste campo em seu formato de armazenamento.

- Campos Simples
O valor retornado estará sempre no mesmo "type" que aquele que o
campo está configurado para assumir. Qualquer regra para REMOÇÃO de formatação
será aplicada caso exista.

- Campos "reference"
Estes campos apenas são capazes de retornar valores "undefined", "null" ou
arrays associativos representando o respectivo modelo de dados que ele
está configurado para receber.

- Campos "collection"
O valor retornado será SEMPRE um array contendo os itens atualmente
definidos. Estes itens serão retornados conforme as regras definidas
acima para "campos simples".

Coleções do tipo "reference" apenas retornarão um array de arrays associativos
representando a coleção de modelos de dados que o campo está apto a utilizar.

-- undefined
O valor "null" deve ser retornado no lugar de "undefined" para campos simples
e "reference".

-- []
Campos do tipo "collection" em seu estado inicial retornarsão sempre um
array vazio.
Coleções que possuam valores inválidos entre seus membros também retornarão
um array vazio.

@return      mixed

Retorna o valor atual deste campo em seu formato de armazenamento .


protected function saveTheChildren()
    {
        $toReload = [];

        if (isset($this->addedChildren)) {
            foreach ($this->addedChildren as $relation => $children) {
                $relationship = call_user_func([ $this, $relation ]);
                if ($relationship instanceof HasMany) {
                    $relationship->saveMany($children);
                } else {
                    throw new PropertySetterException(
                        "Relationship " . get_class($relationship) . " is not implemented yet."
                    );
                }

                // Also save the children
                foreach ($children as $child) {
                    if ($child instanceof Model) {
                        $child->saveTheChildren();
                    }
                }

                $toReload[$relation] = true;
            }
        }

        if (isset($this->removedChildren)) {
            foreach ($this->removedChildren as $relation => $children) {
                $relationship = call_user_func([ $this, $relation ]);

                if ($relationship instanceof HasMany) {

                    foreach ($children as $child) {
                        $child->delete();
                    }

                } else {
                    throw new PropertySetterException(
                        "Relationship " . get_class($relationship) . " is not implemented yet."
                    );
                }

                $toReload[$relation] = true;
            }
        }

        if (isset($this->editedChildren)) {
            foreach ($this->editedChildren as $relation => $children) {
                $relationship = call_user_func([ $this, $relation ]);

                foreach ($children as $child) {
                    if ($child instanceof Model) {
                        $child->saveRecursively();
                    } else {
                        $child->save();
                    }
                }

                $toReload[$relation] = true;
            }
        }

        $toReload = array_keys($toReload);
        foreach ($toReload as $reload) {
            unset($this->relations[$reload]);
        }
    }

protected
function
saveTheChildren
(
)
{
$
toReload
=
[
]
;
if
(
isset
(
$
this
->
addedChildren
)
)
{
foreach
(
$
this
->
addedChildren
as
$
relation
=>
$
children
)
{
$
relationship
=
call_user_func
(
[
$
this
,
$
relation
]
)
;
if
(
$
relationship
instanceof
HasMany
)
{
$
relationship
->
saveMany
(
$
children
)
;
}
else
{
throw
new
PropertySetterException
(
"Relationship "
.
get_class
(
$
relationship
)
.
" is not implemented yet."
)
;
}
// Also save the children
foreach
(
$
children
as
$
child
)
{
if
(
$
child
instanceof
Model
)
{
$
child
->
saveTheChildren
(
)
;
}
}
$
toReload
[
$
relation
]
=
true
;
}
}
if
(
isset
(
$
this
->
removedChildren
)
)
{
foreach
(
$
this
->
removedChildren
as
$
relation
=>
$
children
)
{
$
relationship
=
call_user_func
(
[
$
this
,
$
relation
]
)
;
if
(
$
relationship
instanceof
HasMany
)
{
foreach
(
$
children
as
$
child
)
{
$
child
->
delete
(
)
;
}
}
else
{
throw
new
PropertySetterException
(
"Relationship "
.
get_class
(
$
relationship
)
.
" is not implemented yet."
)
;
}
$
toReload
[
$
relation
]
=
true
;
}
}
if
(
isset
(
$
this
->
editedChildren
)
)
{
foreach
(
$
this
->
editedChildren
as
$
relation
=>
$
children
)
{
$
relationship
=
call_user_func
(
[
$
this
,
$
relation
]
)
;
foreach
(
$
children
as
$
child
)
{
if
(
$
child
instanceof
Model
)
{
$
child
->
saveRecursively
(
)
;
}
else
{
$
child
->
save
(
)
;
}
}
$
toReload
[
$
relation
]
=
true
;
}
}
$
toReload
=
array_keys
(
$
toReload
)
;
foreach
(
$
toReload
as
$
reload
)
{
unset
(
$
this
->
relations
[
$
reload
]
)
;
}
}

Save all related entities.
@throws PropertySetterException


public function addChildrenToEntity($name, array $childEntities, $setterParameters = [])
    {
        // For each relationship, keep a list of all children that were added.
        if (!isset($this->addedChildren[$name])) {
            $this->addedChildren[$name] = [];
        }

        foreach ($childEntities as $child) {
            $this->$name->add($child);
            $this->addedChildren[$name][] = $child;
        }
    }

Add children to a related entity.
@param $name
@param array $childEntities
@param array $setterParameters


public function getModels($queryBuilder, Context $context, $resourceDefinition = null, $records = null)
    {
        $resourceDefinition = $resourceDefinition ?? $this->resourceDefinition;
        $records = $records ?? $this->getRecordLimit();

        return $this->filterAndGet($queryBuilder, $resourceDefinition, $context, $records);
    }

public function getModels ( $ queryBuilder , Context $ context , $ resourceDefinition = null , $ records = null ) { $ resourceDefinition = $ resourceDefinition ?? $ this -> resourceDefinition ; $ records = $ records ?? $ this -> getRecordLimit ( ) ; return $ this -> filterAndGet ( $ queryBuilder , $ resourceDefinition , $ context , $ records ) ; }

From a query builder, filter models based on input and processor and return the resulting
models.
Since order is important, the returned Collection will be a plain laravel collection!
@param $queryBuilder
@param Context $context
@param ResourceDefinition|string|null $resourceDefinition
@param int|null $records
@return Model[]

From a query builder filter models based on input and processor and return the resulting models . Since order is important the returned Collection will be a plain laravel collection!


protected function outputList($models, array $parameters = [], $resourceDefinition = null)
    {
        $resources = $this->filteredModelsToResources($models, $parameters, $resourceDefinition);
        return $this->toResponse($resources);
    }

protected function outputList ( $ models , array $ parameters = [ ] , $ resourceDefinition = null ) { $ resources = $ this -> filteredModelsToResources ( $ models , $ parameters , $ resourceDefinition ) ; return $ this -> toResponse ( $ resources ) ; }

Output a resource or a collection of resources

@param $models
@param array $parameters
@param null $resourceDefinition
@return \Illuminate\Http\JsonResponse


protected function resourceToArray($data)
    {
        if ($data instanceof ResourceCollection) {
            return $data->toArray();
        } else if ($data instanceof RESTResource) {
            return $data->toArray();
        } else if (ArrayHelper::isIterable($data)) {
            foreach ($data as $k => $v) {
                $data[$k] = $this->resourceToArray($v);
            }
            return $data;
        }

        return $data;
    }

protected function resourceToArray ( $ data ) { if ( $ data instanceof ResourceCollection ) { return $ data -> toArray ( ) ; } else if ( $ data instanceof RESTResource ) { return $ data -> toArray ( ) ; } else if ( ArrayHelper :: isIterable ( $ data ) ) { foreach ( $ data as $ k => $ v ) { $ data [ $ k ] = $ this -> resourceToArray ( $ v ) ; } return $ data ; } return $ data ; }

Convert collections or resources to arrays.
@param $data
@return array|mixed

Convert collections or resources to arrays .


public function generate()
    {
        $sClientKey = appSetting('site_key_client', 'nails/driver-captcha-recaptcha');

        if (empty($sClientKey)) {
            throw new CaptchaDriverException('ReCaptcha not configured.');
        }

        $oAsset = Factory::service('Asset');
        $oAsset->load('https://www.google.com/recaptcha/api.js');

        $oResponse = Factory::factory('CaptchaForm', 'nails/module-captcha');
        $oResponse->setHtml('

');

        return $oResponse;
    }

Returns the form markup for the captcha
@return string


public function verify()
    {
        $sServerKey = appSetting('site_key_server', 'nails/driver-captcha-recaptcha');

        if ($sServerKey) {

            $oHttpClient = Factory::factory('HttpClient');
            $oInput      = Factory::service('Input');

            try {

                $oResponse = $oHttpClient->post(
                    'https://www.google.com/recaptcha/api/siteverify',
                    [
                        'form_params' => [
                            'secret'   => $sServerKey,
                            'response' => $oInput->post('g-recaptcha-response'),
                            'remoteip' => $oInput->ipAddress(),
                        ],
                    ]
                );

                if ($oResponse->getStatusCode() !== 200) {
                    throw new CaptchaDriverException('Google returned a non 200 response.');
                }

                $oResponse = json_decode((string) $oResponse->getBody());

                if (empty($oResponse->success)) {
                    throw new CaptchaDriverException('Google returned an unsuccessful response.');
                }

                return true;

            } catch (\Exception $e) {
                return false;
            }

        } else {
            return false;
        }
    }

Verifies a user's captcha entry from POST Data
@return boolean

Verifies a user s captcha entry from POST Data


public static function getService($service, $new = 0)
    {
        $defaultPackage = "service";
        $serviceName = $service;
        if (strpos($service, ".") === false) {
            $serviceName = $defaultPackage . "." . $service;
        }
        return Openbizx::getObject($serviceName, $new);
    }

public static function getService ( $ service , $ new = 0 ) { $ defaultPackage = "service" ; $ serviceName = $ service ; if ( strpos ( $ service , "." ) === false ) { $ serviceName = $ defaultPackage . "." . $ service ; } return Openbizx :: getObject ( $ serviceName , $ new ) ; }

Get the service object

@param string $service service name
@return object the service object


public function render() {
		if ($this->error instanceof ValidationBaseSerializerException) {
			return $this->renderValidationSerializerException($this->error);
		} elseif ($this->error instanceof BaseSerializerException) {
			return $this->renderSerializerException($this->error);
		} elseif ($this->error instanceof CakeException) {
			return $this->renderCakeException($this->error);
		} elseif ($this->error instanceof HttpException) {
			return $this->renderHttpException($this->error);
		} else {
			// This isn't a standard CakeException, render it using the default error500 method
			return $this->error500($this->error);
		}
	}

render the Exception to the end user, if the Exception is an instance of
BaseSerializerException call our custom renderer else, call the parent
render method

@return void

render the Exception to the end user if the Exception is an instance of BaseSerializerException call our custom renderer else call the parent render method


protected function renderHttpException(HttpException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderHttpAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderHttpAsJson($error);
		}

		return $this->defaultHttpRender($error);
	}

protected function renderHttpException ( HttpException $ error ) { if ( $ this -> isJsonApiRequest ( ) ) { return $ this -> renderHttpAsJsonApi ( $ error ) ; } if ( $ this -> isJsonRequest ( ) ) { return $ this -> renderHttpAsJson ( $ error ) ; } return $ this -> defaultHttpRender ( $ error ) ; }

render exceptions of type HttpException

@param HttpException $error the HttpException error to render
@return void


protected function renderCakeException(CakeException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderCakeAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderCakeAsJson($error);
		}

		return $this->defaultCakeRender($error);
	}

protected function renderCakeException ( CakeException $ error ) { if ( $ this -> isJsonApiRequest ( ) ) { return $ this -> renderCakeAsJsonApi ( $ error ) ; } if ( $ this -> isJsonRequest ( ) ) { return $ this -> renderCakeAsJson ( $ error ) ; } return $ this -> defaultCakeRender ( $ error ) ; }

render exceptions of type CakeException

@param CakeException $error the CakeException error to render
@return void


protected function renderSerializerException(BaseSerializerException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderSerializerAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderSerializerAsJson($error);
		}

		return $this->defaultSerializerRender($error);
	}

protected function renderSerializerException ( BaseSerializerException $ error ) { if ( $ this -> isJsonApiRequest ( ) ) { return $ this -> renderSerializerAsJsonApi ( $ error ) ; } if ( $ this -> isJsonRequest ( ) ) { return $ this -> renderSerializerAsJson ( $ error ) ; } return $ this -> defaultSerializerRender ( $ error ) ; }

render exceptions of type BaseSerializerException

@param BaseSerializerException $error the BaseSerializerException error to render
@return void


protected function renderValidationSerializerException(ValidationBaseSerializerException $error) {
		if ($this->isJsonApiRequest()) {
			return $this->renderValidationSerializerAsJsonApi($error);
		}

		if ($this->isJsonRequest()) {
			return $this->renderValidationSerializerAsJson($error);
		}

		return $this->defaultValidationSerializerRender($error);
	}

protected function renderValidationSerializerException ( ValidationBaseSerializerException $ error ) { if ( $ this -> isJsonApiRequest ( ) ) { return $ this -> renderValidationSerializerAsJsonApi ( $ error ) ; } if ( $ this -> isJsonRequest ( ) ) { return $ this -> renderValidationSerializerAsJson ( $ error ) ; } return $ this -> defaultValidationSerializerRender ( $ error ) ; }

render exceptions of type ValidationBaseSerializerException

@param ValidationBaseSerializerException $error the ValidationBaseSerializerException error to render
@return void


protected function renderHttpAsJson(HttpException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');

		$url = $this->controller->request->here();
		$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
		$this->controller->response->statusCode($code);
		$this->controller->set(array(
			'code' => $code,
			'name' => h(get_class($error)),
			'message' => h($error->getMessage()),
			'url' => h($url),
			'error' => $error,
			'_serialize' => array('code', 'name', 'message', 'url')
		));
		$this->_outputMessage($this->template);
	}

render the HttpException for a JSON request

@param HttpException $error an instance of HttpException
@return void


protected function renderHttpAsJsonApi(HttpException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		// Set the correct Status Code
		$this->controller->response->statusCode($error->getCode());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				'id' => null,
				'href' => null,
				'status' => h($error->getCode()),
				'code' => h(get_class($error)),
				'title' => h($error->getMessage()),
				'detail' => h($error->getMessage()),
				'links' => array(),
				'paths' => array(),
			),
		);
		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

render the HttpException for a JSON API request

@param HttpException $error an instance of HttpException
@return void


protected function renderCakeAsJson(CakeException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');

		$url = $this->controller->request->here();
		$code = ($error->getCode() >= 400 && $error->getCode() < 506) ? $error->getCode() : 500;
		$this->controller->response->statusCode($code);
		$this->controller->set(array(
			'code' => $code,
			'name' => h(get_class($error)),
			'message' => h($error->getMessage()),
			'url' => h($url),
			'error' => $error,
			'_serialize' => array('code', 'name', 'message', 'url')
		));
		$this->controller->set($error->getAttributes());
		$this->_outputMessage($this->template);
	}

render the CakeException for a JSON request

@param CakeException $error an instance of CakeException
@return void


protected function renderCakeAsJsonApi(CakeException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		// Set the correct Status Code
		$this->controller->response->statusCode($error->getCode());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				'id' => null,
				'href' => null,
				'status' => h($error->getCode()),
				'code' => h(get_class($error)),
				'title' => h($error->getMessage()),
				'detail' => h($error->getAttributes()),
				'links' => array(),
				'paths' => array(),
			),
		);
		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

render the CakeException for a JSON API request

@param CakeException $error an instance of CakeException
@return void


protected function defaultSerializerRender(BaseSerializerException $error) {
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's expectations
		$this->controller->set('id', $error->id());
		$this->controller->set('href', $error->href());
		$this->controller->set('status', $error->status());
		$this->controller->set('code', $error->code());
		$this->controller->set('title', $error->title());
		$this->controller->set('detail', $error->detail());
		$this->controller->set('links', $error->links());
		$this->controller->set('paths', $error->paths());
		$this->controller->set('error', $error);

		$this->controller->set('url', $this->controller->request->here());

		if (empty($template)) {
			$template = "SerializersErrors./Errors/serializer_exception";
		}

		$this->controller->render($template);
		$this->controller->afterFilter();
		return $this->controller->response->send();
	}

render the BaseSerializerException in the general case

@param BaseSerializerException $error an instance of BaseSerializerException
@return void


protected function renderSerializerAsJson(BaseSerializerException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');
		$this->controller->response->statusCode($error->status());

		// set all the values we have from our exception to populate the json object
		$this->controller->set('id', h($error->id()));
		$this->controller->set('href', h($error->href()));
		$this->controller->set('status', h($error->status()));
		$this->controller->set('code', h($error->code()));
		$this->controller->set('title', h($error->title()));
		$this->controller->set('detail', h($error->detail()));
		$this->controller->set('links', h($error->links()));
		$this->controller->set('paths', h($error->paths()));

		$this->controller->set('_serialize', array(
			'id', 'href', 'status', 'code', 'title ', 'detail', 'links', 'paths'
		));

		if (empty($template)) {
			$template = "SerializersErrors./Errors/serializer_exception";
		}

		$this->controller->render($template);
		$this->controller->afterFilter();
		return $this->controller->response->send();
	}

render the BaseSerializerException for a JSON request

@param BaseSerializerException $error an instance of BaseSerializerException
@return void


protected function renderSerializerAsJsonApi(BaseSerializerException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		// Set the correct Status Code
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				array(
					'id' => h($error->id()),
					'href' => h($error->href()),
					'status' => h($error->status()),
					'code' => h($error->code()),
					'title' => h($error->title()),
					'detail' => h($error->detail()),
					'links' => $error->links(),
					'paths' => $error->paths(),
				),
			),
		);
		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

render the BaseSerializerException for a JSON API request

@param BaseSerializerException $error an instance of BaseSerializerException
@return void


protected function defaultValidationSerializerRender(ValidationBaseSerializerException $error) {
		$this->addHttpCodes();
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's expectations
		$this->controller->set('title', $error->title());
		$this->controller->set('validationErrors', $error->validationErrors());
		$this->controller->set('status', $error->status());
		$this->controller->set('error', $error);

		$this->controller->set('url', $this->controller->request->here());

		if (empty($template)) {
			$template = "SerializersErrors./Errors/validation_serializer_exception";
		}

		$this->controller->render($template);
		$this->controller->afterFilter();
		return $this->controller->response->send();
	}

render the ValidationBaseSerializerException in the general case

@param ValidationBaseSerializerException $error an instance of ValidationBaseSerializerException
@return void


protected function renderValidationSerializerAsJson(ValidationBaseSerializerException $error) {
		// Set the view class as json and render as json
		$this->controller->viewClass = 'Json';
		$this->controller->response->type('json');
		$this->addHttpCodes();
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => $error->validationErrors(),
		);

		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

render the ValidationBaseSerializerException for a JSON request

@param ValidationBaseSerializerException $error an instance of ValidationBaseSerializerException
@return void


protected function renderValidationSerializerAsJsonApi(ValidationBaseSerializerException $error) {
		// Add a response type for JSON API
		$this->controller->response->type(array('jsonapi' => 'application/vnd.api+json'));
		// Set the controller to response as JSON API
		$this->controller->response->type('jsonapi');
		$this->addHttpCodes();
		$this->controller->response->statusCode($error->status());

		// set the errors object to match JsonApi's standard
		$errors = array(
			'errors' => array(
				array(
					'id' => h($error->id()),
					'href' => h($error->href()),
					'status' => h($error->status()),
					'code' => h($error->code()),
					'title' => h($error->title()),
					'detail' => h($error->validationErrors()),
					'links' => h($error->links()),
					'paths' => h($error->paths()),
				),
			),
		);

		// json encode the errors
		$jsonEncodedErrors = json_encode($errors);

		// set the body to the json encoded errors
		$this->controller->response->body($jsonEncodedErrors);
		return $this->controller->response->send();
	}

render the ValidationBaseSerializerException for a JSON API request

@param ValidationBaseSerializerException $error an instance of ValidationBaseSerializerException
@return void


public function openSessionByID($sessionID, $userProfile = null)
    {
        $session = $this->driver->openSessionByID(
            $sessionID,
            $this,
            $userProfile
        );

        if ($session == null) {
            $this->invalidSessionAccessed();
        }

        return $session;
    }

public function openSessionByID ( $ sessionID , $ userProfile = null ) { $ session = $ this -> driver -> openSessionByID ( $ sessionID , $ this , $ userProfile ) ; if ( $ session == null ) { $ this -> invalidSessionAccessed ( ) ; } return $ session ; }

Opens an existing session.

Opens and returns the data for an existing session, if and only if the
client sent a valid existing session ID. Otherwise returns null.

@param array $cookieData
@param null $userProfile
@return Session|null


function createSession(array $cookieData, $userProfile = null)
    {
        if (!array_key_exists($this->sessionConfig->getSessionName(), $cookieData)) {
            return $this->driver->createSession($this, $userProfile);
        }

        $sessionID = $cookieData[$this->sessionConfig->getSessionName()];
        $existingSession = $this->openSessionByID($sessionID, $userProfile);

        if ($existingSession !== null) {
            return $existingSession;
        }

        $this->invalidSessionAccessed();
        return $this->driver->createSession($this, $userProfile);
    }

function createSession ( array $ cookieData , $ userProfile = null ) { if ( ! array_key_exists ( $ this -> sessionConfig -> getSessionName ( ) , $ cookieData ) ) { return $ this -> driver -> createSession ( $ this , $ userProfile ) ; } $ sessionID = $ cookieData [ $ this -> sessionConfig -> getSessionName ( ) ] ; $ existingSession = $ this -> openSessionByID ( $ sessionID , $ userProfile ) ; if ( $ existingSession !== null ) { return $ existingSession ; } $ this -> invalidSessionAccessed ( ) ; return $ this -> driver -> createSession ( $ this , $ userProfile ) ; }

Create a new session or open existing session.

Opens and returns the data for an existing session, if and only if the
client sent a valid existing session ID. Otherwise creates a new session.

@param array $cookieData
@param $userProfile
@return Session

Create a new session or open existing session .


protected function prepareText(&$text) {

        // check if it is a string
        if (!is_string($text)) {

            // it is not, raise a flag
            return false;
        }

        // trim any front or ending spaces
        $text = trim($text);

        // if there is no text, no need to continue
        if (strlen($text) == 0) {

            // there is not text, raise a flag
            return false;
        }

        return true;
    }

Prepare the text, if the text has no length, return false to indicate something went wrong
@param $text
@return bool

Prepare the text if the text has no length return false to indicate something went wrong


public function display($text) {

        // prepare the text for the particular style of text
        // if it returns false, the text is bad
        if (!$this->prepareText($text)) {

            // chaining
            return $this;
        }

        // justify the text
        $text = $this->clio->justify($text, $this->justification);

        // create the specified number of lines before
        if ($this->spaceBefore > 0) {

            //  move down the space before number of lines
            $this->clio->newLine($this->spaceBefore);
        }

        // calculate any empty lines needed to create the height
        $top = $bottom = 0;

        // if there was anything higher than one requiring empty styled lines
        if ($this->height > 1) {

            // take off the actual title line
            $spaces = $this->height - 1;

            // the top will be the base value of dividing by two
            $top = intdiv($spaces,2);

            // the bottom will be that base value + the remainder
            $bottom = intdiv($spaces,2) + ($spaces % 2);
        }

        // set up the styling
        $this->clio->style($this->style);

        // display any empty lines needed above the title for the height
        $this->displayEmptyLines($top);

        // display the title text
        $this->clio->line($text);

        // display any empty lines needed below the title for the height
        $this->displayEmptyLines($bottom);

        // clear the formatting
        $this->clio->clear();

        // if there is space after
        if ($this->spaceAfter > 0) {

            // display the space after
            $this->clio->newLine($this->spaceAfter);
        }

        // chaining
        return $this;
    }

Display one Title

@param string $text - the text of the title
@return $this


private function displayEmptyLines($lines)
    {
        // create an empty line
        $emptyLine = str_pad(" ", $this->clio->getWidth());

        // if there is more than one line
        for ($i = 0; $i < $lines; ++$i) {

            // generate an empty line
            $this->clio->line($emptyLine);
        }

    }

private
function
displayEmptyLines
(
$
lines
)
{
// create an empty line
$
emptyLine
=
str_pad
(
" "
,
$
this
->
clio
->
getWidth
(
)
)
;
// if there is more than one line
for
(
$
i
=
0
;
$
i
<
$
lines
;
++
$
i
)
{
// generate an empty line
$
this
->
clio
->
line
(
$
emptyLine
)
;
}
}

Helper function to output a number of lines that have the full width
@param $lines


public function init(Application $cli, $commands = [])
    {
        $this->cli = $cli;
        $this->commands = $commands;
    }

public function init ( Application $ cli , $ commands = [ ] ) { $ this -> cli = $ cli ; $ this -> commands = $ commands ; }

ConsoleProvider constructor.
@param Application $cli
@param array $commands


public function onKernelResponse(FilterResponseEvent $event)
    {
        if ($event->isMasterRequest()) {
            $request = $event->getRequest();
            $response = $event->getResponse();

            if ($request->isXmlHttpRequest() && !$response->isRedirection()) {
                // flash messages
                if ($request->hasSession() && !$response->headers->has('X-Flash-Messages')) {
                    $this->setFlashMessageHeader($response, $request->getSession());
                }

                // title, fullTitle
                $this->setTitleHeaders($response);

                // exception info (debug only)
                if ($this->debug && $this->lastException) {
                    $this->setExceptionHeader($response, $this->lastException);
                    $this->lastException = null;
                }
            }
        }
    }

public
function
onKernelResponse
(
FilterResponseEvent
$
event
)
{
if
(
$
event
->
isMasterRequest
(
)
)
{
$
request
=
$
event
->
getRequest
(
)
;
$
response
=
$
event
->
getResponse
(
)
;
if
(
$
request
->
isXmlHttpRequest
(
)
&&
!
$
response
->
isRedirection
(
)
)
{
// flash messages
if
(
$
request
->
hasSession
(
)
&&
!
$
response
->
headers
->
has
(
'X-Flash-Messages'
)
)
{
$
this
->
setFlashMessageHeader
(
$
response
,
$
request
->
getSession
(
)
)
;
}
// title, fullTitle
$
this
->
setTitleHeaders
(
$
response
)
;
// exception info (debug only)
if
(
$
this
->
debug
&&
$
this
->
lastException
)
{
$
this
->
setExceptionHeader
(
$
response
,
$
this
->
lastException
)
;
$
this
->
lastException
=
;
}
}
}
}

On kernel response.

@param FilterResponseEvent $event


public function init(StandardDebugBar $debugBar){
        $this->debugBar = $debugBar;
        $this->debugBarRenderer = $debugBar->getJavascriptRenderer();
    }

public function init ( StandardDebugBar $ debugBar ) { $ this -> debugBar = $ debugBar ; $ this -> debugBarRenderer = $ debugBar -> getJavascriptRenderer ( ) ; }

DebugBarProvider constructor.
@param StandardDebugBar $debugBar


public static function sessionStart($name, $lifetime = 0, $path = '/', $domain = null, $secure = null)
    {
        // Set the cookie name before we start.
        session_name($name . '_Session');

        // Set the domain to default to the current domain.
        $domain = isset($domain) ? $domain : $_SERVER['SERVER_NAME'];

        // Set the default secure value to whether the site is being accessed with SSL
        $secure = isset($secure) ? $secure : isset($_SERVER['HTTPS']);

        // Set the cookie settings and start the session
        session_set_cookie_params($lifetime, $path, $domain, $secure, true);

        $id = session_id();
        if(empty($id)) {
            session_start();
        }

        // Make sure the session hasn't expired, and destroy it if it has
        if (self::validateSession()) {

            // Check to see if the session is new or a hijacking attempt
            if (!self::preventHijacking()) {

                // Reset session data and regenerate id
                $_SESSION = array();
                $_SESSION['ipAddress'] = $_SERVER['REMOTE_ADDR'];
                $_SESSION['userAgent'] = $_SERVER['HTTP_USER_AGENT'];
                self::regenerateSession();

                // Give a 5% chance of the session id changing on any request
            } elseif (self::shouldRandomlyRegenerate()) {
                self::regenerateSession();
            }
        } else {
            self::destroySession();
        }
    }

Creates a secure session
@param $name
@param int $lifetime
@param string $path
@param null $domain
@param null $secure


private static function preventHijacking()
    {
        if (!isset($_SESSION['ipAddress']) || !isset($_SESSION['userAgent'])) {
            return false;
        }
        if ($_SESSION['ipAddress'] != $_SERVER['REMOTE_ADDR']) {
            return false;
        }
        if ($_SESSION['userAgent'] != $_SERVER['HTTP_USER_AGENT']) {
            return false;
        }
        return true;
    }

private static function preventHijacking ( ) { if ( ! isset ( $ _SESSION [ 'ipAddress' ] ) || ! isset ( $ _SESSION [ 'userAgent' ] ) ) { return false ; } if ( $ _SESSION [ 'ipAddress' ] != $ _SERVER [ 'REMOTE_ADDR' ] ) { return false ; } if ( $ _SESSION [ 'userAgent' ] != $ _SERVER [ 'HTTP_USER_AGENT' ] ) { return false ; } return true ; }

Checks session IP and user agent are still the same
@return bool


private static function  regenerateSession()
    {
        // If this session is obsolete it means there already is a new id
        if (isset($_SESSION['OBSOLETE']) && $_SESSION['OBSOLETE'] == true) {
            return;
        }

        // Set current session to expire in 10 seconds
        $_SESSION['OBSOLETE'] = true;
        $_SESSION['EXPIRES'] = time() + 10;

        // Create new session without destroying the old one
        session_regenerate_id(false);

        // Grab current session ID and close both sessions to allow other scripts to use them
        $newSession = session_id();
        session_write_close();

        // Set session ID to the new one, and start it back up again
        session_id($newSession);
        session_start();

        // Now we unset the obsolete and expiration values for the session we want to keep
        unset($_SESSION['OBSOLETE']);
        unset($_SESSION['EXPIRES']);
    }

Creates a fresh session Id to make it harder to hack
If the site is very slow in parts increase the expiry time
10 seconds is a good default which allows ajax calls to work
without losing the session


private static function validateSession()
    {
        if (isset($_SESSION['OBSOLETE']) && !isset($_SESSION['EXPIRES'])) {
            return false;
        }

        if (isset($_SESSION['EXPIRES']) && $_SESSION['EXPIRES'] < time()) {
            return false;
        }

        return true;
    }

private static function validateSession ( ) { if ( isset ( $ _SESSION [ 'OBSOLETE' ] ) && ! isset ( $ _SESSION [ 'EXPIRES' ] ) ) { return false ; } if ( isset ( $ _SESSION [ 'EXPIRES' ] ) && $ _SESSION [ 'EXPIRES' ] < time ( ) ) { return false ; } return true ; }

Checks whether the session has expired or not
@return bool


public function linkLayers()
    {
        for ($i = 1; $i < count($this->structure); $i++) {
            $this->layers[$i]->bind($this->layers[$i - 1]);
        }
    }

public function linkLayers ( ) { for ( $ i = 1 ; $ i < count ( $ this -> structure ) ; $ i ++ ) { $ this -> layers [ $ i ] -> bind ( $ this -> layers [ $ i - 1 ] ) ; } }


protected function _paramBackbone($key)
    {
        if (isset($this->_request['model'])) {
            $model = json_decode($this->_request['model'], true);

            return $model[$key];
        }

        return null;
    }

protected function _paramBackbone ( $ key ) { if ( isset ( $ this -> _request [ 'model' ] ) ) { $ model = json_decode ( $ this -> _request [ 'model' ] , true ) ; return $ model [ $ key ] ; } return null ; }

Extract request param from backbone model request

@param string $key
@return string|null


public static function register( $px, $json ){

		// プラグイン設定の初期化
		if( !is_object(@$json) ){
			$json = json_decode('{}');
		}
		if( !is_array(@$json->paths_ignore) ){
			$json->paths_ignore = array();
		}
		// var_dump($json);

		$self = new self( $px, $json );

		$px->pxcmd()->register('publish', array($self, 'exec_home'));
	}

public
static
function
register
(
$
px
,
$
json
)
{
// プラグイン設定の初期化
if
(
!
is_object
(
@
$
json
)
)
{
$
json
=
json_decode
(
'{}'
)
;
}
if
(
!
is_array
(
@
$
json
->
paths_ignore
)
)
{
$
json
->
paths_ignore
=
array
(
)
;
}
// var_dump($json);
$
self
=
new
self
(
$
px
,
$
json
)
;
$
px
->
pxcmd
(
)
->
register
(
'publish'
,
array
(
$
self
,
'exec_home'
)
)
;
}

Before content function
@param object $px Picklesオブジェクト
@param object $json プラグイン設定
```
{
"paths_ignore": [
// パブリッシュ対象から常に除外するパスを設定する。
// (ここに設定されたパスは、動的なプレビューは可能)
"/sample_pages/no_publish/*"
]
}
```


private function cli_header(){
		ob_start();
		print $this->px->pxcmd()->get_cli_header();
		print 'publish directory(tmp): '.$this->path_tmp_publish."\n";
		print 'lockfile: '.$this->path_lockfile."\n";
		print 'publish directory: '.$this->path_publish_dir."\n";
		print 'domain: '.$this->domain."\n";
		print 'docroot directory: '.$this->path_docroot."\n";
		print 'ignore: '.join(', ', $this->plugin_conf->paths_ignore)."\n";
		print 'region: '.join(', ', $this->paths_region)."\n";
		print 'ignore (tmp): '.join(', ', $this->paths_ignore)."\n";
		print 'keep cache: '.($this->flg_keep_cache ? 'true' : 'false')."\n";
		print '------------'."\n";
		flush();
		return ob_get_clean();
	}

private
function
cli_header
(
)
{
ob_start
(
)
;
print
$
this
->
px
->
pxcmd
(
)
->
get_cli_header
(
)
;
print
'publish directory(tmp): '
.
$
this
->
path_tmp_publish
.
"\n"
;
print
'lockfile: '
.
$
this
->
path_lockfile
.
"\n"
;
print
'publish directory: '
.
$
this
->
path_publish_dir
.
"\n"
;
print
'domain: '
.
$
this
->
domain
.
"\n"
;
print
'docroot directory: '
.
$
this
->
path_docroot
.
"\n"
;
print
'ignore: '
.
join
(
', '
,
$
this
->
plugin_conf
->
paths_ignore
)
.
"\n"
;
print
'region: '
.
join
(
', '
,
$
this
->
paths_region
)
.
"\n"
;
print
'ignore (tmp): '
.
join
(
', '
,
$
this
->
paths_ignore
)
.
"\n"
;
print
'keep cache: '
.
(
$
this
->
flg_keep_cache
'true'
:
'false'
)
.
"\n"
;
print
'------------'
.
"\n"
;
flush
(
)
;
return
ob_get_clean
(
)
;
}


private function parseRawBody($startLine)
    {
        $templateSource = \file_get_contents($this->parser->getStream()->getSourceContext()->getPath());

        // parse tag contents
        \preg_match(
            '/\\s*\\{%\s*example\\s*%\\}(.*?)\\s*\\{%\\s*endexample\\s*%\\}/s',
            \implode(
                "\n",
                \array_slice(
                    \preg_split('/\\n|\\r\\n?/', $templateSource),
                    $startLine - 1,
                    $this->parser->getCurrentToken()->getLine() - $startLine + 1
                )
            ),
            $match
        );

        if (isset($match[1])) {
            return $this->removeExtraIndentation($match[1]);
        }

        return '';
    }

Parse raw template body.

@param int $startLine

@return string


private function removeExtraIndentation($string)
    {
        $lines = \preg_split('/\\n|\\r\\n?/', $string);

        // determine indentation length
        $indentLen = null;
        for ($i = 0; isset($lines[$i]); ++$i) {
            if ('' !== \trim($lines[$i])) {
                \preg_match('/^\\s*/', $lines[$i], $match);
                $indentLen = \strlen($match[0]);
                break;
            }
        }

        if (null !== $indentLen) {
            // cut each line
            $out = '';
            for (; isset($lines[$i]); ++$i) {
                if (\substr($lines[$i], 0, $indentLen) === $match[0]) {
                    $out .= \substr($lines[$i], $indentLen);
                } else {
                    $out .= $lines[$i];
                }
                $out .= "\n";
            }

            return $out;
        }

        return $string;
    }

private
function
removeExtraIndentation
(
$
string
)
{
$
lines
=
\
preg_split
(
'/\\n|\\r\\n?/'
,
$
string
)
;
// determine indentation length
$
indentLen
=
;
for
(
$
i
=
0
;
isset
(
$
lines
[
$
i
]
)
;
++
$
i
)
{
if
(
''
!==
\
trim
(
$
lines
[
$
i
]
)
)
{
\
preg_match
(
'/^\\s*/'
,
$
lines
[
$
i
]
,
$
match
)
;
$
indentLen
=
\
strlen
(
$
match
[
0
]
)
;
break
;
}
}
if
(
!==
$
indentLen
)
{
// cut each line
$
out
=
''
;
for
(
;
isset
(
$
lines
[
$
i
]
)
;
++
$
i
)
{
if
(
\
substr
(
$
lines
[
$
i
]
,
0
,
$
indentLen
)
===
$
match
[
0
]
)
{
$
out
.=
\
substr
(
$
lines
[
$
i
]
,
$
indentLen
)
;
}
else
{
$
out
.=
$
lines
[
$
i
]
;
}
$
out
.=
"\n"
;
}
return
$
out
;
}
return
$
string
;
}

Remove extra indentation from a string.

@param string $string

@return string

Remove extra indentation from a string .


public function handleRequest(RequestInterface $request, callable $next, callable $first)
    {
        $headers = [
            $this->correlationEntryName->parent() => $this->requestIdentifier->current(),
            $this->correlationEntryName->root() => $this->selectBestRootHeaderValue(),
        ];

        foreach ($headers as $headerName => $headerValue) {
            $request = $request->withHeader($headerName, $headerValue);
        }

        return $next($request);
    }

public function handleRequest ( RequestInterface $ request , callable $ next , callable $ first ) { $ headers = [ $ this -> correlationEntryName -> parent ( ) => $ this -> requestIdentifier -> current ( ) , $ this -> correlationEntryName -> root ( ) => $ this -> selectBestRootHeaderValue ( ) , ] ; foreach ( $ headers as $ headerName => $ headerValue ) { $ request = $ request -> withHeader ( $ headerName , $ headerValue ) ; } return $ next ( $ request ) ; }

Handle the request and return the response coming from the next callable.

@see http://docs.php-http.org/en/latest/plugins/build-your-own.html

@param callable $next  Next middleware in the chain, the request is passed as the first argument
@param callable $first First middleware in the chain, used to to restart a request

@return Promise resolves a PSR-7 Response or fails with an Http\Client\Exception (The same as HttpAsyncClient)

Handle the request and return the response coming from the next callable .


public static function parseQueryStringFromUrl($url)
    {
        $query = (string) parse_url($url, \PHP_URL_QUERY);
        parse_str($query, $result);
        return $result;
    }

public static function parseQueryStringFromUrl ( $ url ) { $ query = ( string ) parse_url ( $ url , \ PHP_URL_QUERY ) ; parse_str ( $ query , $ result ) ; return $ result ; }

Parse URL and return query string as assoc array

@param string $url
@return array


private function bind( $px ){
		$theme = $this;
		ob_start();
		include( $this->path_tpl.$this->page['layout'].'.html' );
		$src = ob_get_clean();
		return $src;
	}

private function bind ( $ px ) { $ theme = $ this ; ob_start ( ) ; include ( $ this -> path_tpl . $ this -> page [ 'layout' ] . '.html' ) ; $ src = ob_get_clean ( ) ; return $ src ; }

bind content to theme
@param object $px $px object
@return string HTML Source code


public function getMatch($uri)
    {
        $expression = $this->pattern->getExpression();
        $matches = [];

        if (preg_match($expression, $uri, $matches) === 0) {
            return false;
        }

        $matches = $this->cleanMatches($matches);
        $matches = $this->removeNoise($matches);
        return $matches + $this->defaults;
    }

public function getMatch ( $ uri ) { $ expression = $ this -> pattern -> getExpression ( ) ; $ matches = [ ] ; if ( preg_match ( $ expression , $ uri , $ matches ) === 0 ) { return false ; } $ matches = $ this -> cleanMatches ( $ matches ) ; $ matches = $ this -> removeNoise ( $ matches ) ; return $ matches + $ this -> defaults ; }

Method attempts to apply the generated regexp to the URI
and, if successful, returns a list of parsed parameters.

@param string $uri

@return array|false

Method attempts to apply the generated regexp to the URI and if successful returns a list of parsed parameters .


public static function getJustificationConstant($value) {

        // if the value coming in, is a integer, ensure it is one of the constants
        if (is_int($value)) {

            // get the justification integer values
            $values = array_values(self::$justificationConstants);

            // if the integer submitted is one of those values, return it
            if (in_array($value, $values)) {

                // return the valid value
                return $value;
            }

        }
        // if the value coming in is a string
        else if (is_string($value)) {

            // trim the string
            $value = trim($value);

            // transform to uppercase
            $value = strtoupper($value);

            // if it is in the array of string values
            if (isset(self::$justificationConstants[$value])) {

                // return the matching integer value
                return self::$justificationConstants[$value];

            } else {

                // not a valid string
                return self::LEFT;
            }

        } else {

            // something went wrong, return left
            return self::LEFT;
        }

        return self::LEFT;
    }

Function to take a value and turn it into a justification constant

@param string | int $value - if a string, it can be "left", "RIGHT", etc..., if an int, just needs to be a constant
@return int - the constant it represents or LEFT if it is garbage


public function listLocalFiles(){
        $files = array();
        $dir = dir($this->docsHome);
        while (false !== ($file = $dir->read())) {
            if(substr($file, -4)==".pdf"){
                $files[] = array('path'=>$this->docsHome, 'fileName'=>$file);
            }
        }
        return $files;
    }

public function listLocalFiles ( ) { $ files = array ( ) ; $ dir = dir ( $ this -> docsHome ) ; while ( false !== ( $ file = $ dir -> read ( ) ) ) { if ( substr ( $ file , - 4 ) == ".pdf" ) { $ files [ ] = array ( 'path' => $ this -> docsHome , 'fileName' => $ file ) ; } } return $ files ; }

List the local pdf files stored in Docs Home
@return array Array containing the pdf files entries. Each entry is an associative array
of type ('path'=>docs home folder, 'fileName'=>nameOfFile.pdf)


private function extractDocumentsLink($html){
        $links = array();
        //preg_match_all("#<a\ href=\"(.*)\.pdf\"#", $html, $matches);
        preg_match_all("#<a\ href=\"(.*)\"#", $html, $matches);
        foreach($matches[1] as $f) {
            $pospdf = strpos($f,".pdf");
            if($pospdf !== false) {
                $f = substr($f, 0, $pospdf + 4);
                if (!$this->excludeLink($f)) {
                    $links[] = $f;
                }
            }
        }
        return $links;
    }

Parses the main page html to extract the links to pdf documents
@param $html   html content of the main page
@return array  Array containing all the pdf documents links


private function excludeLink($href)
    {
        //If href string contains any of the 'words' in $excludes array, return true
        $excluded = false;
        foreach ($this->excludes as $word) {
            if (strpos($href, $word) !== false) {
                $excluded = true;
                break;
            }
        }
        return $excluded;
    }

Evaluates if a link to a pdf document is not a valid domains document pdf and should be excluded
@param $href   Link to the pdf document
@return bool   Evaluation result


private function saveFile($filename, $content, $hash){
        $ruta = realpath($this->docsHome).'/'.$hash."-".$filename;
        file_put_contents($ruta, $content);
    }

private function saveFile ( $ filename , $ content , $ hash ) { $ ruta = realpath ( $ this -> docsHome ) . '/' . $ hash . "-" . $ filename ; file_put_contents ( $ ruta , $ content ) ; }

Calculates a hash for the file and stores the content in docs home folder
@param $filename
@param $content
@param $hash


private function existePdf($filename, $hash){
        $ruta = realpath($this->docsHome).'/'.$hash."-".$filename;
        return file_exists($ruta);
    }

private function existePdf ( $ filename , $ hash ) { $ ruta = realpath ( $ this -> docsHome ) . '/' . $ hash . "-" . $ filename ; return file_exists ( $ ruta ) ; }

Checks if a file exists in docs home folder
@param $filename
@param $hash
@return bool


protected function getNextOrderedNumber() {

        // see if the current nesting has an entry in the orderedNumbers array
        if (array_key_exists($this->nesting, $this->orderedNumbers)) {

            // it does, so increase the number by 1
            $this->orderedNumbers[$this->nesting] = $this->orderedNumbers[$this->nesting] + 1;

        } else {

            // it doesn't, so start a new index and initialize the number at 1
            $this->orderedNumbers[$this->nesting] = 1;
        }

        // if this is the second level nesting...
        if ($this->nesting === 2) {

            // return a character starting with a
            return chr(96 + $this->orderedNumbers[$this->nesting]);

            // if this is the fourth level nesting
        } else if ($this->nesting === 4) {

            // return a character starting with A
            return chr(64 + $this->orderedNumbers[$this->nesting]);

            // otherwise use numbers for nesting level 1,3,5 and greater
        } else {

            // return the current number for this nesting
            return $this->orderedNumbers[$this->nesting];
        }

    }

This returns the correct number for a list item depending on the current nesting level
@return string


public function end() {

        // remove this ordered number tracking for this nesting
        if (array_key_exists($this->nesting, $this->orderedNumbers)) {

            // remove the item off the array
            unset ($this->orderedNumbers[$this->nesting]);
        }

        // close the start
        parent::end();

        // chaining
        return $this;
    }

End the current ordered or unordered list


public function display($text) {

        // if trimming was desired
        if ($this->trim) {

            // trim any front or ending spaces
            $text = trim($text);
        }

        // if there is no text, no need to continue
        if (strlen($text) == 0) {

            // no need to continue
            return $this;
        }

        // wordwrap to the width of the html screen
        $text = $this->clio->wordwrap($text, $this->clio->getWidth(), false);

        // now get the lines that have been wordwrapped
        $lines = explode("\n",$text);

        // shortcut to the width
        $width = $this->clio->getWidth();

        // start the justified version of the wrapped text
        $justifiedText = "";

        // create an empty line for space after
        $emptyLine = str_pad(" ",$this->clio->getWidth());

        // shortcut
        $numLines = count($lines);

        // go through each line
        for ($i=0; $i<$numLines; ++$i) {

            // get the next line
            $next = $lines[$i];

            // ask Clio to justify the text and pad to the edge
            $justifiedText .= $this->clio->justify($next,"left",$width) . "\n";

            // if this is not the last line
//            if ($i < ($numLines-1)) {
//
//                // add a new line (the last one is left for space after
//                $justifiedText .= "\n";
//            }n

        }

        // now display the text
        $this->displayWithStyling($justifiedText);

        $this->nl($this->spaceAfter);

        // chaining
        return $this;
    }

//                $justifiedText .= "\n";

Display one paragraph, which will be word-wrapped according
to the left margin and width specified in the HTML object.

Additionally, any markup will trigger styles. If the markup
isn't closed, it will continue across multiple paragraphs.
@param $text
@return $this

Display one paragraph which will be word - wrapped according to the left margin and width specified in the HTML object .


public function nl($count = 1) {

        // create an empty line for space after
        $emptyLine = str_pad(" ",$this->clio->getWidth()) . "\n";

        // go through each line
        for ($i=0; $i<$count; ++$i) {

            // display an empty line, so the styling carries through to the right edge
            $this->displayWithStyling($emptyLine);

        }
    }

Create a new line with the styling of the paragraph
@param int $count


public function fit(DataSet $dataSet, float $learningRate = 0.0): AlgorithmsInterface
    {
        $outputSize = count($dataSet->getMapper()->getOutputKeys());
        if ($outputSize !== 1) {
            throw new WrongUsageException('Linear regression assumes only one output, ' . $outputSize . ' given');
        }

        if (count($dataSet->getMapper()->getDimensionKeys()) === 1) {
            $this
                ->calculator
                ->using($dataSet)
                ->calculate(new Mean())
                ->then(new SimpleLinearCoefficients());
            ;
        } else {
            $this->coefficients = $this
                ->calculator
                ->using($dataSet)
                ->calculate(new MultipleLinearCoefficients())
                ->getResult()
                ->last()
            ;
        }

        $this->coefficients = $this->calculator->getResult()->last();

        return $this;
    }

Trains the dataSet following the Linear Regression Algorithm
@param DataSet $dataSet
@param float $learningRate
@return AlgorithmsInterface
@throws WrongUsageException


public function predict(DataSet $dataSet)
    {
        foreach ($dataSet as $instance) {
            $prediction = $this
                ->calculator
                ->calculate(new LinearPrediction($instance->getDimensions(), $this->coefficients))
                ->getResult()
                ->last()
            ;
            $instance->addResult(
                static::class,
                [
                    'type'   => self::PREDICTION,
                    'result' => $prediction
                ]
            );
        }

        $this->calculator->using($dataSet)->calculate(new Benchmark(LinearRegression::class));
        $results = $this->calculator->getResult()->of(Benchmark::class);

        $this->accuracy = $results[Benchmark::ACCURACY] ?? 0;
        $this->rmse = $results[Benchmark::RMSE] ?? 0;
    }

public function predict ( DataSet $ dataSet ) { foreach ( $ dataSet as $ instance ) { $ prediction = $ this -> calculator -> calculate ( new LinearPrediction ( $ instance -> getDimensions ( ) , $ this -> coefficients ) ) -> getResult ( ) -> last ( ) ; $ instance -> addResult ( static :: class , [ 'type' => self :: PREDICTION , 'result' => $ prediction ] ) ; } $ this -> calculator -> using ( $ dataSet ) -> calculate ( new Benchmark ( LinearRegression :: class ) ) ; $ results = $ this -> calculator -> getResult ( ) -> of ( Benchmark :: class ) ; $ this -> accuracy = $ results [ Benchmark :: ACCURACY ] ?? 0 ; $ this -> rmse = $ results [ Benchmark :: RMSE ] ?? 0 ; }

Makes a linear prediction of input based on coefficients
@param DataSet $dataSet
@throws WrongUsageException


private function initialize()
    {
        $this->pdo->exec(
            'CREATE TABLE IF NOT EXISTS `'.$this->table.'` '
            .'(id INTEGER PRIMARY KEY AUTO_INCREMENT, channel VARCHAR(255),level_name VARCHAR(255), level INTEGER, message LONGTEXT, date DATETIME)'
        );
        //Read out actual columns
        $actualFields = array();
        $rs = $this->pdo->query('SELECT * FROM `'.$this->table.'` LIMIT 0');
        for ($i = 0; $i < $rs->columnCount(); $i++) {
            $col = $rs->getColumnMeta($i);
            $actualFields[] = $col['name'];
        }
        //Calculate changed entries
        $removedColumns = array_diff(
            $actualFields,
            $this->additionalFields,
            array('id', 'channel', 'level','level_name', 'message', 'date')
        );
        $addedColumns = array_diff($this->additionalFields, $actualFields);
        //Remove columns
        if (!empty($removedColumns)) {
            foreach ($removedColumns as $c) {
                $this->pdo->exec('ALTER TABLE `'.$this->table.'` DROP `'.$c.'`;');
            }
        }
        //Add columns
        if (!empty($addedColumns)) {
            foreach ($addedColumns as $c) {
                $this->pdo->exec('ALTER TABLE `'.$this->table.'` add `'.$c.'` TEXT NULL DEFAULT NULL;');
            }
        }
        //Prepare statement
        $columns = "";
        $fields = "";
        foreach ($this->additionalFields as $f) {
            $columns.= ", $f";
            $fields.= ", :$f";
        }
        $this->statement = $this->pdo->prepare(
            'INSERT INTO `'.$this->table.'` (channel, level, level_name, message, date'.$columns.')
            VALUES (:channel, :level, :level_name, :message, :date'.$fields.')'
        );
        $this->initialized = true;
    }

Initializes this handler by creating the table if it not exists


protected function write(array $record)
    {
        if (!$this->initialized) {
            $this->initialize();
        }
        //'context' contains the array
        $contentArray = array_merge(array(
            'channel' => $record['channel'],
            'level' => $record['level'],
            'level_name' => $record['level_name'],
            'message' => $record['message'],
            'date' => $record['datetime']->format('Y-m-d H:i:s')
        ), $record['context']);
        //Fill content array with "null" values if not provided
        $contentArray = $contentArray + array_combine(
                $this->additionalFields,
                array_fill(0, count($this->additionalFields), null)
            );
        $this->statement->execute($contentArray);
    }

Writes the record down to the log of the implementing handler

@param  $record[]
@return void


protected function drawListItem($bullet, $text) {

        // determine the blank space indentation
        $indentation = $this->createIndentation();

        // In unordered list, the bullet can be specified
        $left = $indentation . $bullet;

        // determine the width of the bullet text
        $bulletTextArea = $this->clio->getWidth() - strlen($left);

        // word wrap the rest of the bullet
        $text = $this->clio->wordwrap($text,$bulletTextArea, false);

        // create an empty string that is the same with of the bullet
        $emptyBullet = str_pad("",strlen($bullet));

        // replace all newlines with a newline then indentation, then an empty bullet
        $text = str_replace("\n", "\n" . $indentation . $emptyBullet, $text);

        // show the bullet and text on multiple lines (if needed)
        $this->clio->display($left . $text)->newLine();

    }

Helper function to draw one list item

@param string $bullet - the bullet plus any white space to the right
@param string $text


public function start($text = null) {

        // if text was defined and it the first level of nesting
        if ($text && ($this->nesting === 0)) {

            // display the text with any markup
            $this->clio->display($text)->newLine();

        }

        // add one to the nesting
        ++$this->nesting;

        // chaining
        return $this;
    }

Start an ordered list
@param $text String | null - text to show on the very first line, will not work for anything nested
@return $this


public function init($config = [], $use)
    {
        $this->config = $config;
        $this->cache = $this->getCache($use);
        $this->app->addAlias($use, $config['drivers'][$use]['class']);
    }

public function init ( $ config = [ ] , $ use ) { $ this -> config = $ config ; $ this -> cache = $ this -> getCache ( $ use ) ; $ this -> app -> addAlias ( $ use , $ config [ 'drivers' ] [ $ use ] [ 'class' ] ) ; }

CacheProvider constructor.
@param array $config
@param $use
@throws \Exception


public static function get($name)
    {
        $name = (strtolower($name) === self::SIZE_ORIG) ? self::SIZE_ORIG : strtoupper($name);

        return isset(self::$allowedSize[$name]) ? self::$allowedSize[$name] : null;
    }

public static function get ( $ name ) { $ name = ( strtolower ( $ name ) === self :: SIZE_ORIG ) ? self :: SIZE_ORIG : strtoupper ( $ name ) ; return isset ( self :: $ allowedSize [ $ name ] ) ? self :: $ allowedSize [ $ name ] : null ; }

get name allowed return

@param  string      $name
@return string|null


public function buildFormForSection(
        string $forHandle,
        RequestStack $requestStack,
        SectionFormOptions $sectionFormOptions = null,
        bool $csrfProtection = true
    ): FormInterface {

        $sectionConfig = $this->getSectionConfig($forHandle);
        $section = $this->getSection($sectionConfig->getFullyQualifiedClassName());

        // If we have a slug, it means we are updating something.
        // Prep so we can get the correct $sectionEntity
        $slug = null;
        if ($sectionFormOptions !== null) {
            try {
                $slug = $sectionFormOptions->getSlug();
            } catch (\Exception $exception) {
                $slug = null;
            }
        }

        // If we hava an id, it means we are updating something.
        // Prep so we can get the correct $sectionEntity
        $id = null;
        if ($sectionFormOptions !== null) {
            try {
                $id = $sectionFormOptions->getId();
            } catch (\Exception $exception) {
                $id = null;
            }
        }

        $sectionEntity = $this->getSectionEntity(
            $sectionConfig->getFullyQualifiedClassName(),
            $section,
            $slug,
            $id
        );

        $factory = $this->getFormFactory($requestStack);

        $form = $factory
            ->createBuilder(
                FormType::class,
                $sectionEntity,
                [
                    'method' => 'POST',
                    'attr' => [
                        'novalidate' => 'novalidate'
                    ],
                    'csrf_protection' => $csrfProtection,
                    'csrf_field_name' => 'token',
                    'csrf_token_id'   => 'tardigrades',
                    'allow_extra_fields' => true // We need to allow extra fields for extra section fields (ignored in the generators)
                ]
            );

        /** @var FieldInterface $field */
        foreach ($section->getFields() as $field) {
            $fieldTypeFullyQualifiedClassName = (string) $field
                ->getFieldType()
                ->getFullyQualifiedClassName();

            /** @var FieldTypeInterface $fieldType */
            $fieldType = new $fieldTypeFullyQualifiedClassName;
            $fieldType->setConfig($field->getConfig());
            $fieldType->addToForm(
                $form,
                $section,
                $sectionEntity,
                $this->sectionManager,
                $this->readSection,
                $requestStack->getCurrentRequest()
            );
        }

        $form->add('save', SubmitType::class);
        return $form->getForm();
    }

This method generates a form based on the section config.
The for handle contains the section handle, or the FQCN of the section entity.
By pasing along SectionFormOptions this method can determine of the form
is meanth to update or create new data.

@param string $forHandle
@param RequestStack $requestStack
@param SectionFormOptions|null $sectionFormOptions
@param bool $csrfProtection
@return FormInterface

This method generates a form based on the section config . The for handle contains the section handle or the FQCN of the section entity . By pasing along SectionFormOptions this method can determine of the form is meanth to update or create new data .


private function getFormFactory(RequestStack $requestStack): FormFactory
    {
        $factory = $this->formFactory;
        if (empty($this->formFactory)) {
            $validatorBuilder = Validation::createValidatorBuilder();
            // Loads validator metadata from entity static method
            $validatorBuilder->addMethodMapping('loadValidatorMetadata');
            $validator = $validatorBuilder->getValidator();
            if (!$session = $requestStack->getCurrentRequest()->getSession()) {
                $session = new Session();
            }
            $csrfGenerator = new UriSafeTokenGenerator();
            $csrfStorage = new SessionTokenStorage($session);
            $csrfManager = new CsrfTokenManager($csrfGenerator, $csrfStorage);
            $factory = Forms::createFormFactoryBuilder()
                ->addExtension(new CsrfExtension($csrfManager))
                ->addExtension(new ValidatorExtension($validator))
                ->getFormFactory();
        }
        return $factory;
    }

If you use SexyField with symfony you might want to inject the formFactory from the framework
If you use it stand-alone this will build a form factory right here.
@return FormFactory

If you use SexyField with symfony you might want to inject the formFactory from the framework If you use it stand - alone this will build a form factory right here .


private function loadFromIterator(\Iterator $iterator)
    {
        /* @var \SplFileInfo[] $iterator */
        foreach ($iterator as $file) {
            if ($file->getFilename() === 'fixtures.yml') {
                $this->addFixture($file->getPathname());
            }
        }
    }

private
function
loadFromIterator
(
\
Iterator
$
iterator
)
{
/* @var \SplFileInfo[] $iterator */
foreach
(
$
iterator
as
$
file
)
{
if
(
$
file
->
getFilename
(
)
===
'fixtures.yml'
)
{
$
this
->
addFixture
(
$
file
->
getPathname
(
)
)
;
}
}
}

Load fixtures from YML files contained in iterator.

@param \Iterator $iterator Iterator over files from which fixtures should be loaded.

Load fixtures from YML files contained in iterator .


public function resolveRelativeUrl($url) {

        try {

            // return absolute url
            return new static($url);
        }
        catch(UrlException $exception) {}

        // anchor
        if($url[0] === '#') {

            return new static($this->getUrl(self::ALL - self::FRAGMENT) . $url);
        }

        // query
        if($url[0] === '?') {

            return new static($this->getUrl(self::ALL - self::FRAGMENT - self::QUERY) . $url);
        }

        // relative path from domain root
        if($url[0] === '/') {

            return new static($this->getUrl(self::ALL - self::FRAGMENT - self::QUERY - self::PATH) . substr($url, 1));
        }

        // relative path from current path
        else {

            $currentPath = $this->path ?: '/';

            // cut last path fragment
            if(substr($currentPath, -1) !== '/') {

                $currentPath = substr($currentPath, 0, strrpos($currentPath, '/') + 1);
            }

            return new static($this->getUrl(self::ALL - self::FRAGMENT - self::QUERY - self::PATH) . $this->getCanonicalizedPath($currentPath . $url));
        }
    }

public
function
resolveRelativeUrl
(
$
url
)
{
try
{
// return absolute url
return
new
static
(
$
url
)
;
}
catch
(
UrlException
$
exception
)
{
}
// anchor
if
(
$
url
[
0
]
===
'#'
)
{
return
new
static
(
$
this
->
getUrl
(
self
::
ALL
self
::
FRAGMENT
)
.
$
url
)
;
}
// query
if
(
$
url
[
0
]
===
'?'
)
{
return
new
static
(
$
this
->
getUrl
(
self
::
ALL
self
::
FRAGMENT
self
::
QUERY
)
.
$
url
)
;
}
// relative path from domain root
if
(
$
url
[
0
]
===
'/'
)
{
return
new
static
(
$
this
->
getUrl
(
self
::
ALL
self
::
FRAGMENT
self
::
QUERY
self
::
PATH
)
.
substr
(
$
url
,
1
)
)
;
}
// relative path from current path
else
{
$
currentPath
=
$
this
->
path
:
'/'
;
// cut last path fragment
if
(
substr
(
$
currentPath
,
1
)
!==
'/'
)
{
$
currentPath
=
substr
(
$
currentPath
,
0
,
strrpos
(
$
currentPath
,
'/'
)
+
1
)
;
}
return
new
static
(
$
this
->
getUrl
(
self
::
ALL
self
::
FRAGMENT
self
::
QUERY
self
::
PATH
)
.
$
this
->
getCanonicalizedPath
(
$
currentPath
.
$
url
)
)
;
}
}

Build absolute url of given path in given context

@param string $url

@return Url


public function install(InstalledRepositoryInterface $repo, PackageInterface $package) {
		parent::install($repo, $package);

		$strPackageName = $package->getName();

		if (self::startsWith($strPackageName, 'qcubed/plugin')) {
			$this->composerPluginInstall($package);
		}
		elseif (self::startsWith($strPackageName, 'qcubed/qcubed')) {
			// updating the framework
			$this->composerFrameworkInstall($package);
		}

	}

public
function
install
(
InstalledRepositoryInterface
$
repo
,
PackageInterface
$
package
)
{
parent
::
install
(
$
repo
,
$
package
)
;
$
strPackageName
=
$
package
->
getName
(
)
;
if
(
self
::
startsWith
(
$
strPackageName
,
'qcubed/plugin'
)
)
{
$
this
->
composerPluginInstall
(
$
package
)
;
}
elseif
(
self
::
startsWith
(
$
strPackageName
,
'qcubed/qcubed'
)
)
{
// updating the framework
$
this
->
composerFrameworkInstall
(
$
package
)
;
}
}

Respond to the install command.

@param InstalledRepositoryInterface $repo
@param PackageInterface $package


protected function composerPluginInstall ($package) {
		require_once(($this->vendorDir ? $this->vendorDir . '/' : '') . 'qcubed/qcubed/qcubed.inc.php');	// get the configuration options so we can know where to put the plugin files

		// recursively copy the contents of the install subdirectory in the plugin.
		$strPluginDir = $this->getPackageBasePath($package);
		$strInstallDir = $strPluginDir . '/install';
		$strDestDir = __INCLUDES__ . '/plugins';

		$this->filesystem->ensureDirectoryExists($strDestDir);
		$this->io->write('Copying files from ' . $strInstallDir . ' to ' . $strDestDir);
		self::copy_dir($strInstallDir, $strDestDir);
	}

Move files out of the vendor directory and into the project directory that are in the plugin's install directory.
@param $strPackageName

Move files out of the vendor directory and into the project directory that are in the plugin s install directory .


protected function composerFrameworkInstall ($package) {
		$extra = $package->getExtra();

		// recursively copy the contents of the install directory, providing each file is not there.
		$strInstallDir = self::NormalizeNonPosixPath($this->getPackageBasePath($package)) . '/install/project';
		$strDestDir = ($this->vendorDir ? $this->vendorDir . '/' : '') . '../project'; // try to find the default project location
		$strDestDir = self::NormalizeNonPosixPath($strDestDir);

		$this->io->write('Copying files from ' . $strInstallDir . ' to ' . $strDestDir);
		self::copy_dir($strInstallDir, $strDestDir);

		// Make sure particular directories are writable by the web server. These are listed in the extra section of the composer.json file.
		// We are assuming that the first time installation is installed in a subdirectory of docroot.
		$strInstallDir = self::NormalizeNonPosixPath(realpath(dirname($strDestDir)));
		$strSubDirectory = '/' . basename($strInstallDir);
		$strDocRoot = self::NormalizeNonPosixPath(realpath($strInstallDir . '/../'));
		$strConfigDirectory = $strDestDir . '/includes/configuration';

		$this->io->write('Updating permissions');
		foreach ($extra['writePermission'] as $strDir) {
			$strTargetDir = $strInstallDir . '/' . $strDir;
			if(!file_exists($strTargetDir)){
				mkdir($strTargetDir, 0777, true);
			}
			chmod ($strTargetDir, 0777);
		}

		// write configuration.inc.php only if it does not exists
		if (!file_exists($strConfigDirectory . '/configuration.inc.php')) {
			// fix up the configuration file
			$strFile = file_get_contents($strConfigDirectory . '/configuration.inc.sample.php');
			if ($strFile) {
				$strFile = str_replace (['{docroot}', '{vd}', '{subdir}'], [$strDocRoot, '', $strSubDirectory], $strFile);
				file_put_contents($strConfigDirectory . '/configuration.inc.php', $strFile);
			}
		}
	}

First time installation of framework. For first-time installation, we create the project directory and modify
the configuration file.

@param $strPackageName

First time installation of framework . For first - time installation we create the project directory and modify the configuration file .


public function update(InstalledRepositoryInterface $repo, PackageInterface $initial, PackageInterface $target) {
		parent::install($repo, $initial, $target);

		$strPackageName = $target->getName();
		if (self::startsWith($strPackageName, 'qcubed/plugin')) {
			$this->composerPluginInstall($target);
		}
		elseif (self::startsWith($strPackageName, 'qcubed/qcubed')) {
			// updating the framework
			$this->composerFrameworkUpdate($target);
		}

	}

public
function
update
(
InstalledRepositoryInterface
$
repo
,
PackageInterface
$
initial
,
PackageInterface
$
target
)
{
parent
::
install
(
$
repo
,
$
initial
,
$
target
)
;
$
strPackageName
=
$
target
->
getName
(
)
;
if
(
self
::
startsWith
(
$
strPackageName
,
'qcubed/plugin'
)
)
{
$
this
->
composerPluginInstall
(
$
target
)
;
}
elseif
(
self
::
startsWith
(
$
strPackageName
,
'qcubed/qcubed'
)
)
{
// updating the framework
$
this
->
composerFrameworkUpdate
(
$
target
)
;
}
}

Respond to an update command.

@param InstalledRepositoryInterface $repo
@param PackageInterface $initial
@param PackageInterface $target


protected function composerFrameworkUpdate ($package) {
		require_once(($this->vendorDir ? $this->vendorDir . '/' : '') . 'qcubed/qcubed/qcubed.inc.php');	// get the configuration options so we can know where to put the plugin files

		// recursively copy the contents of the install directory, providing each file is not there.
		$strInstallDir = $this->getPackageBasePath($package) . '/install/project';
		$strDestDir = __PROJECT__;

		// copy_dir will not overwrite files, but will add any new stub files
		$this->io->write('Copying files from ' . $strInstallDir . ' to ' . $strDestDir);
		self::copy_dir($strInstallDir, $strDestDir);
	}

Update a package. In particular, new install files will be moved to the correct location.

@param $package

Update a package . In particular new install files will be moved to the correct location .


public function uninstall(InstalledRepositoryInterface $repo, PackageInterface $package)
	{
		$strPackageName = $package->getName();
		if (self::startsWith($strPackageName, 'qcubed/plugin')) {
			$this->composerPluginUninstall($package);
		}
		parent::uninstall ($repo, $package);
	}

public function uninstall ( InstalledRepositoryInterface $ repo , PackageInterface $ package ) { $ strPackageName = $ package -> getName ( ) ; if ( self :: startsWith ( $ strPackageName , 'qcubed/plugin' ) ) { $ this -> composerPluginUninstall ( $ package ) ; } parent :: uninstall ( $ repo , $ package ) ; }

Uninstalls a plugin if requested.

@param InstalledRepositoryInterface $repo
@param PackageInterface $package


public function composerPluginUninstall (PackageInterface $package) {
		require_once(($this->vendorDir ? $this->vendorDir . '/' : '') . 'qcubed/qcubed/qcubed.inc.php');	// get the configuration options so we can know where the plugin files are

		// recursively delete the contents of the install directory, providing each file is there.
		$strPluginDir = $this->getPackageBasePath($package) . '/install';
		$strDestDir = __INCLUDES__ . '/plugins';

		$this->io->write('Removing files from ' . $strPluginDir);
		self::remove_matching_dir($strPluginDir, $strDestDir);
	}

Delete the given plugin.

@param PackageInterface $package


protected static function remove_matching_dir($src,$dst) {
		if (!$dst || !$src || !is_dir($src) || !is_dir($dst)) return;	// prevent deleting an entire disk by accidentally calling this with an empty string!
		$dir = opendir($src);

		while(false !== ( $file = readdir($dir)) ) {
			if (( $file != '.' ) && ( $file != '..' )) {
				if ( is_dir($src . '/' . $file) ) {
					self::remove_dir($dst . '/' . $file);
				}
				else {
					if (file_exists($dst . '/' . $file)) {
						unlink($dst . '/' . $file);
					}
				}
			}
		}
		closedir($dir);
	}

Remove the files in the destination directory whose names match the files in the source directory.

@param string $src	Source directory
@param string $dst	Destination directory

Remove the files in the destination directory whose names match the files in the source directory .


protected static function remove_dir($dst) {
		if (!$dst || !is_dir($dst)) return;	// prevent deleting an entire disk by accidentally calling this with an empty string!
		$dir = opendir($dst);

		while(false !== ( $file = readdir($dir)) ) {
			if (( $file != '.' ) && ( $file != '..' )) {
				if ( is_dir($dst . '/' . $file) ) {
					self::remove_dir($dst . '/' . $file);
				}
				else {
					unlink($dst . '/' . $file);
				}
			}
		}
		closedir($dir);
		rmdir($dst);
	}

Delete a directory and all of its contents.

@param string $dst Directory to delete

Delete a directory and all of its contents .


public function setColors($textColor = null, $fillColor = null) {

        // if the text color was specified
        if ($textColor) {

            // store it
            $this->textColor = new Color($textColor);

        // not set
        } else {

            // clear out the text color
            $this->textColor = null;
        }

        // if the fill color was specified
        if ($fillColor) {

            // store it
            $this->fillColor = new Color($fillColor);

        // not set
        } else {

            // clear out the text color
            $this->fillColor = null;
        }

        // chaining
        return $this;

    }

public
function
setColors
(
$
textColor
=
,
$
fillColor
=
)
{
// if the text color was specified
if
(
$
textColor
)
{
// store it
$
this
->
textColor
=
new
Color
(
$
textColor
)
;
// not set
}
else
{
// clear out the text color
$
this
->
textColor
=
;
}
// if the fill color was specified
if
(
$
fillColor
)
{
// store it
$
this
->
fillColor
=
new
Color
(
$
fillColor
)
;
// not set
}
else
{
// clear out the text color
$
this
->
fillColor
=
;
}
// chaining
return
$
this
;
}

Set the colors of a column

@param null | int | string | ColorInterface $textColor - any valid setting for the Color constructor
@param null | int | string | ColorInterface $fillColor
@return $this


protected function getTextArea() {

        // initialize the return value
        $textArea = 0;

        // if the width has a value (if it is calculated, it may not)
        if ($this->width) {
            // subtract the padding from the width
            $textArea = $this->width - $this->rightPadding - $this->leftPadding;
        }

        // if it goes below zero
        if ($textArea < 0) {

            // make it zero
            $textArea = 0;
        }

        return $textArea;
    }

Calculate the text area by taking the width and subtracting any padding
@return int


public function calculateWidth($data, $markupDefinition = null) {

        // if the width is not calculated, or the data is invalid
        if (($this->calculateWidth === false) || !is_array($data) || (count($data) === 0)) {

            // nothing to do, it is not a calculated width
            return;
        }

        // initialize the array of sizes of each string
        $sizes = [];

        // reset the width
        $this->width = null;

        // if the header text was specified
        if ($this->headerText) {

            // add the length to the array of string lengths
            $sizes[] = strlen($this->headerText);
        }

        // go through and create an array sizes
        for ($i=0; $i<count($data); ++$i) {

            // get the text (make it into a string)
            $text = strval($data[$i]);

            // if the markup definition was sent in
            if ($markupDefinition) {

                // strip out any markup symbols
                $text = $markupDefinition->stripMarkupSymbols($text);
            }

            // add the size of this text to the array of sizes
            $sizes[] = strlen($text);
        }

        // now get the highest value in the array of sizes and add the padding
        $widestText = max($sizes) + $this->rightPadding + $this->leftPadding;

        // if the maximum width is defined and the width hasn't already maxed out
        if ($this->maximumWidth) {

            // check to ensure the text length is less than or equal to the maximum width
            if ($widestText <= $this->maximumWidth) {

                // the width is now the newest text length
                $this->width = $widestText;

            } else {
                // set the width to the maximum width (text will be truncated)
                $this->width = $this->maximumWidth;
            }

        // there is no maximum width
        } else {

            // just set the width to that widest text
            $this->width = $widestText;
        }

    }

Run the data through and make the width as wide as the widest text

@param array $data
@param Definition $markupDefinition


public function scopeGetByDateValue($obQuery, $sField, $sDate, $sCondition = '=')
    {

        if(empty($sDate) || empty($sCondition) || empty($sField)) {
            return $obQuery;
        }

        return $obQuery->where($sField, $sCondition, $sDate);
    }

public function scopeGetByDateValue ( $ obQuery , $ sField , $ sDate , $ sCondition = '=' ) { if ( empty ( $ sDate ) || empty ( $ sCondition ) || empty ( $ sField ) ) { return $ obQuery ; } return $ obQuery -> where ( $ sField , $ sCondition , $ sDate ) ; }

Get by date
@param \Illuminate\Database\Eloquent\Builder|\October\Rain\Database\Builder $obQuery
@param string $sDate
@param string $sField
@param string $sCondition
@return \Illuminate\Database\Eloquent\Builder|\October\Rain\Database\Builder;


public function getDateValue($sFieldName, $sFormat = 'd.m.Y')
    {
        if(empty($sFieldName) || empty($sFormat)) {
            return null;
        }

        /** @var Carbon $obDate */
        $obDate = $this->$sFieldName;
        if(empty($obDate) || !$obDate instanceof Carbon) {
            return $obDate;
        }

        return $obDate->format($sFormat);
    }

public
function
getDateValue
(
$
sFieldName
,
$
sFormat
=
'd.m.Y'
)
{
if
(
empty
(
$
sFieldName
)
||
empty
(
$
sFormat
)
)
{
return
;
}
/** @var Carbon $obDate */
$
obDate
=
$
this
->
$
sFieldName
;
if
(
empty
(
$
obDate
)
||
!
$
obDate
instanceof
Carbon
)
{
return
$
obDate
;
}
return
$
obDate
->
format
(
$
sFormat
)
;
}

Get date value
@param string $sFieldName
@param string $sFormat
@return null|string


protected function castAttribute($key, $value)
	{
		$type = $this->getCastType($key);
		if (!empty($type) && !in_array($type, $this->originalCastTypes))
		{
			$method = 'as'.Str::studly($type);
			if (method_exists($this, $method))
				return call_user_func([$this, $method], $value, $key, $type);
		}
		return parent::castAttribute($key, $value);
	}

protected function castAttribute ( $ key , $ value ) { $ type = $ this -> getCastType ( $ key ) ; if ( ! empty ( $ type ) && ! in_array ( $ type , $ this -> originalCastTypes ) ) { $ method = 'as' . Str :: studly ( $ type ) ; if ( method_exists ( $ this , $ method ) ) return call_user_func ( [ $ this , $ method ] , $ value , $ key , $ type ) ; } return parent :: castAttribute ( $ key , $ value ) ; }

Cast an attribute to a native PHP type.

@param  string  $key
@param  mixed  $value
@return mixed

Cast an attribute to a native PHP type .


public function attributesToArray()
	{
		$data = parent::attributesToArray();
		foreach ($this->getCasts() as $key => $type)
		{
			if (!empty($type) && !in_array($type, $this->originalCastTypes) && isset($data[$key]))
			{
				$method = Str::camel($type).'ToArray';
				if (method_exists($this, $method))
					$data[$key] = call_user_func([$this, $method], $data[$key], $key, $type);
			}
		}
		return $data;
	}

public function attributesToArray ( ) { $ data = parent :: attributesToArray ( ) ; foreach ( $ this -> getCasts ( ) as $ key => $ type ) { if ( ! empty ( $ type ) && ! in_array ( $ type , $ this -> originalCastTypes ) && isset ( $ data [ $ key ] ) ) { $ method = Str :: camel ( $ type ) . 'ToArray' ; if ( method_exists ( $ this , $ method ) ) $ data [ $ key ] = call_user_func ( [ $ this , $ method ] , $ data [ $ key ] , $ key , $ type ) ; } } return $ data ; }

Convert the model's attributes to an array.

@return array

Convert the model s attributes to an array .


public function offsetSet($key, $value)
	{
		$value = $value instanceof TreeNode ? $value : new TreeNode($value);

		if (is_null($key)) {
			$this->items[] = $value;
		} else {
			$this->items[$key] = $value;
		}
	}

public function offsetSet ( $ key , $ value ) { $ value = $ value instanceof TreeNode ? $ value : new TreeNode ( $ value ) ; if ( is_null ( $ key ) ) { $ this -> items [ ] = $ value ; } else { $ this -> items [ $ key ] = $ value ; } }

Set the item at a given offset.

@param  mixed  $key
@param  mixed  $value
@return void


public function get($name, array $options = [])
    {
        if (!isset($this->menuCollection[$name])) {
            if (!isset($this->menuInfoCollection[$name])) {
                throw new \InvalidArgumentException(\sprintf('The menu "%s" is not defined.', $name));
            }

            $menuInfo = $this->menuInfoCollection[$name];
            $service = $menuInfo['id'];
            $method = isset($menuInfo['method']) ? $menuInfo['method'] : 'getMenu';
            $menu = $this->container->get($service)->$method($this->factory, $this->helper);

            $event = new ConfigureMenuEvent($menu, $this->factory, $this->helper, $name);
            $this->container->get('event_dispatcher')->dispatch('imatic_view.configure_menu.' . $name, $event);

            $this->menuCollection[$name] = $menu;
        }

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

public
function
get
(
$
name
,
array
$
options
=
[
]
)
{
if
(
!
isset
(
$
this
->
menuCollection
[
$
name
]
)
)
{
if
(
!
isset
(
$
this
->
menuInfoCollection
[
$
name
]
)
)
{
throw
new
\
InvalidArgumentException
(
\
sprintf
(
'The menu "%s" is not defined.'
,
$
name
)
)
;
}
$
menuInfo
=
$
this
->
menuInfoCollection
[
$
name
]
;
$
service
=
$
menuInfo
[
'id'
]
;
$
method
=
isset
(
$
menuInfo
[
'method'
]
)
$
menuInfo
[
'method'
]
:
'getMenu'
;
$
menu
=
$
this
->
container
->
get
(
$
service
)
->
$
method
(
$
this
->
factory
,
$
this
->
helper
)
;
$
event
=
new
ConfigureMenuEvent
(
$
menu
,
$
this
->
factory
,
$
this
->
helper
,
$
name
)
;
$
this
->
container
->
get
(
'event_dispatcher'
)
->
dispatch
(
'imatic_view.configure_menu.'
.
$
name
,
$
event
)
;
$
this
->
menuCollection
[
$
name
]
=
$
menu
;
}
return
$
this
->
menuCollection
[
$
name
]
;
}

Retrieves a menu by its name.

@param string $name
@param array  $options

@return ItemInterface

@throws \InvalidArgumentException if the menu does not exists