public function setAllowOrigin($origin): void
    {
        $origin = trim($origin);
        // fixme - send catchable error if origin isn't valid
        //  possibly could check with filter_var
        if (strlen($origin) > 0) {
            $this->allowOrigin = $origin;
        }
    }

//  possibly could check with filter_var

Set the access-control-allow-origin header.

@param string $origin The origin to allow.

@return void

Set the access - control - allow - origin header .


public function sendfile(): bool
    {
        if ($this->internalError) {
            $this->sendInternalError();
            return false;
        }
        if ($this->cacheok) {
            header("HTTP/1.1 304 Not Modified");
            return true;
        }
        if (is_null($this->path)) {
            header("HTTP/1.0 404 Not Found");
            return false;
        }
        if ($this->badrange) {
            header("HTTP/1.1 416 Range Not Satisfiable");
            return false;
        }
        if ($this->istext) {
            return $this->serveText();
        }
        return $this->sendContent();
    }

public
function
sendfile
(
)
:
bool
{
if
(
$
this
->
internalError
)
{
$
this
->
sendInternalError
(
)
;
return
false
;
}
if
(
$
this
->
cacheok
)
{
header
(
"HTTP/1.1 304 Not Modified"
)
;
return
true
;
}
if
(
is_null
(
$
this
->
path
)
)
{
header
(
"HTTP/1.0 404 Not Found"
)
;
return
false
;
}
if
(
$
this
->
badrange
)
{
header
(
"HTTP/1.1 416 Range Not Satisfiable"
)
;
return
false
;
}
if
(
$
this
->
istext
)
{
return
$
this
->
serveText
(
)
;
}
return
$
this
->
sendContent
(
)
;
}

Serve the file.

@return bool True on success, False on failure.


public function registerProvider(TextingProviderInterface $provider)
    {
        if (!$this->defaultProvider) {
            $this->defaultProvider = &$provider;
        }

        $this->providers[$provider->getName()] = $provider;
    }

public function registerProvider ( TextingProviderInterface $ provider ) { if ( ! $ this -> defaultProvider ) { $ this -> defaultProvider = & $ provider ; } $ this -> providers [ $ provider -> getName ( ) ] = $ provider ; }

Will register the provider to be used later on.

@param TextingProviderInterface $provider

Will register the provider to be used later on .


public function denormalize($data, $class, $format = null, array $context = [])
    {
        $reflection = new ReflectionClass($class);
        $instance = $reflection->newInstanceWithoutConstructor();

        foreach ($data as $key => $value) {
            $property = $reflection->getProperty($key);
            $property->setAccessible(true);
            $property->setValue($instance, $value);
        }

        return $instance;
    }

public function denormalize ( $ data , $ class , $ format = null , array $ context = [ ] ) { $ reflection = new ReflectionClass ( $ class ) ; $ instance = $ reflection -> newInstanceWithoutConstructor ( ) ; foreach ( $ data as $ key => $ value ) { $ property = $ reflection -> getProperty ( $ key ) ; $ property -> setAccessible ( true ) ; $ property -> setValue ( $ instance , $ value ) ; } return $ instance ; }

Denormalizes data back into an object of the given class.

@param mixed  $data    data to restore
@param string $class   the expected class to instantiate
@param string $format  format the given data was extracted from
@param array  $context options available to the denormalizer

@return object

Denormalizes data back into an object of the given class .


public function supportsDenormalization($data, $type, $format = null)
    {
        return in_array(AbstractExplicitMessage::class, class_parents($type, true), true);
    }

public function supportsDenormalization ( $ data , $ type , $ format = null ) { return in_array ( AbstractExplicitMessage :: class , class_parents ( $ type , true ) , true ) ; }

Checks whether the given class is supported for denormalization by this normalizer.

@param mixed  $data   Data to denormalize from
@param string $type   The class to which the data should be denormalized
@param string $format The format being deserialized from

@return bool

Checks whether the given class is supported for denormalization by this normalizer .


final public function validate(array $data, $rules, string $type = null)
    {
        try {
            $this->setMessages($rules);
        } catch (\TypeError $e) {
        }
        try {
            $this->setCustomAttributes($rules);
        } catch (\TypeError $e) {
        }

        try {
            $validator = app('validator')->make(
                array_filter($data),
                $rules->getRules($type),
                $this->messages,
                $this->customAttributes
            );

            $this->validating($validator, $rules, $type);
        } catch (\TypeError $e) {
        }

        if (isset($validator) && $validator->fails()) {
            throw new ValidationException($validator);
        }
    }

final public function validate ( array $ data , $ rules , string $ type = null ) { try { $ this -> setMessages ( $ rules ) ; } catch ( \ TypeError $ e ) { } try { $ this -> setCustomAttributes ( $ rules ) ; } catch ( \ TypeError $ e ) { } try { $ validator = app ( 'validator' ) -> make ( array_filter ( $ data ) , $ rules -> getRules ( $ type ) , $ this -> messages , $ this -> customAttributes ) ; $ this -> validating ( $ validator , $ rules , $ type ) ; } catch ( \ TypeError $ e ) { } if ( isset ( $ validator ) && $ validator -> fails ( ) ) { throw new ValidationException ( $ validator ) ; } }

Validates data.

@param array $data
@param Validation\CustomAttributes|Validation\Messages|Validation\Rules|Validation\Validating $rules
@param string $type
@throws ValidationException


public function validateModel(Model $model, Validation\Rules $rules, string $type = null)
    {
        try {
            $this->setModel($rules, $model);
        } catch (\TypeError $e) {
        }

        $this->validate($model->getAttributes(), $rules, $type);
    }

public function validateModel ( Model $ model , Validation \ Rules $ rules , string $ type = null ) { try { $ this -> setModel ( $ rules , $ model ) ; } catch ( \ TypeError $ e ) { } $ this -> validate ( $ model -> getAttributes ( ) , $ rules , $ type ) ; }

Validates model's data.

@param Model $model
@param Validation\Rules|Eloquent\ModelAccess $rules
@param string $type


public function getActionAttribute($value)
    {
        switch ($this->type) {
            case MenuItemContract::TYPE_ROUTE:
                return trans('menu::menu.type.route');

            case MenuItemContract::TYPE_URL:
                return trans('menu::menu.type.url');

            default:
                return trans('menu::menu.type.unknown');
        }
    }

public function getActionAttribute ( $ value ) { switch ( $ this -> type ) { case MenuItemContract :: TYPE_ROUTE : return trans ( 'menu::menu.type.route' ) ; case MenuItemContract :: TYPE_URL : return trans ( 'menu::menu.type.url' ) ; default : return trans ( 'menu::menu.type.unknown' ) ; } }

Localized string which represents the
type of the menu item.

@param $value

@return string

Localized string which represents the type of the menu item .


public function getUrlAttribute($value)
    {
        if ($this->hasChildren()) {
            return MenuItemContract::URL_EMPTY;
        }

        switch ($this->type) {
            case MenuItemContract::TYPE_ROUTE:
                return $this->routeGracefulOnError($this->target, $this->parameters);

            case MenuItemContract::TYPE_URL:
                return $this->target;

            default:
                return;
        }
    }

public function getUrlAttribute ( $ value ) { if ( $ this -> hasChildren ( ) ) { return MenuItemContract :: URL_EMPTY ; } switch ( $ this -> type ) { case MenuItemContract :: TYPE_ROUTE : return $ this -> routeGracefulOnError ( $ this -> target , $ this -> parameters ) ; case MenuItemContract :: TYPE_URL : return $ this -> target ; default : return ; } }

Builds the targeting url based upon the given
type if the current item.

@param $value

@return string

Builds the targeting url based upon the given type if the current item .


public function goNext($commit=false)
    {
        // call ValidateForm()
        $recArr = $this->readInputRecord();
        $this->setActiveRecord($recArr);

   		 try
        {
             if ($this->ValidateForm() == false)
            return;
        }catch (Openbizx\Validation\Exception $e)
        {
            $this->processFormObjError($e->errors);
            return;
        }

        $this->activeRecord = $this->readInputRecord();
		$viewObj = $this->getWebpageObject();
        // get the step
    	if($viewObj->getCurrentStep()){
        	$step = $viewObj->getCurrentStep();
        }else{
        	$step = $_GET['step'];
        }
        if (!$step || $step=="")
            $step=1;

        // redirect the prev step
        /* @var $viewObj WebPageWizard */

        $viewObj->renderStep($step+1);
    }

public
function
goNext
(
$
commit
=
false
)
{
// call ValidateForm()
$
recArr
=
$
this
->
readInputRecord
(
)
;
$
this
->
setActiveRecord
(
$
recArr
)
;
try
{
if
(
$
this
->
ValidateForm
(
)
==
false
)
return
;
}
catch
(
Openbizx
\
Validation
\
Exception
$
e
)
{
$
this
->
processFormObjError
(
$
e
->
errors
)
;
return
;
}
$
this
->
activeRecord
=
$
this
->
readInputRecord
(
)
;
$
viewObj
=
$
this
->
getWebpageObject
(
)
;
// get the step
if
(
$
viewObj
->
getCurrentStep
(
)
)
{
$
step
=
$
viewObj
->
getCurrentStep
(
)
;
}
else
{
$
step
=
$
_GET
[
'step'
]
;
}
if
(
!
$
step
||
$
step
==
""
)
$
step
=
1
;
// redirect the prev step
/* @var $viewObj WebPageWizard */
$
viewObj
->
renderStep
(
$
step
+
1
)
;
}

Go to next wizard page

@param boolean $commit true if need to commit current form data
@return void
@access remote


public function skip()
    {
		$viewObj = $this->getWebpageObject();
        // get the step
    	if($viewObj->getCurrentStep()){
        	$step = $viewObj->getCurrentStep();
        }else{
        	$step = $_GET['step'];
        }
        if (!$step || $step=="")
            $step=1;

        $viewObj->renderStep($step+2);
    }

public
function
skip
(
)
{
$
viewObj
=
$
this
->
getWebpageObject
(
)
;
// get the step
if
(
$
viewObj
->
getCurrentStep
(
)
)
{
$
step
=
$
viewObj
->
getCurrentStep
(
)
;
}
else
{
$
step
=
$
_GET
[
'step'
]
;
}
if
(
!
$
step
||
$
step
==
""
)
$
step
=
1
;
$
viewObj
->
renderStep
(
$
step
+
2
)
;
}

Skip current wizard page

@return void
@access remote


public function goBack()
    {
        $recArr = $this->readInputRecord();
        $this->setActiveRecord($recArr);
		$this->activeRecord = $this->readInputRecord();

        $viewObj = $this->getWebpageObject();

        // get the step
        if($viewObj->getCurrentStep()){
        	$step = $viewObj->getCurrentStep();
        }else{
        	$step = $_GET['step'];
        }

        // redirect the prev step
        /* @var $viewObj WebPageWizard */

        $viewObj->renderStep($step-1);
    }

public
function
goBack
(
)
{
$
recArr
=
$
this
->
readInputRecord
(
)
;
$
this
->
setActiveRecord
(
$
recArr
)
;
$
this
->
activeRecord
=
$
this
->
readInputRecord
(
)
;
$
viewObj
=
$
this
->
getWebpageObject
(
)
;
// get the step
if
(
$
viewObj
->
getCurrentStep
(
)
)
{
$
step
=
$
viewObj
->
getCurrentStep
(
)
;
}
else
{
$
step
=
$
_GET
[
'step'
]
;
}
// redirect the prev step
/* @var $viewObj WebPageWizard */
$
viewObj
->
renderStep
(
$
step
1
)
;
}

Go to previous wizard page

@return void
@access remote


public function doFinish() //- call FinishWizard() by default

    {
        // call ValidateForm()
        $recArr = $this->readInputRecord();
        $this->setActiveRecord($recArr);
    	$this->setFormInputs($this->formInputs);

   		 try
        {
             if ($this->ValidateForm() == false)
            return;
        }catch (Openbizx\Validation\Exception $e)
        {
        	$this->processFormObjError($e->errors);
            return;
        }

        $this->activeRecord = $this->readInputRecord();

        /* @var $viewObj WebPageWizard */
        $viewObj = $this->getWebpageObject();

        $r = $viewObj->commit();
        if (!$r)
            return;

        $this->processPostAction();
    }

public
function
doFinish
(
)
//- call FinishWizard() by default
{
// call ValidateForm()
$
recArr
=
$
this
->
readInputRecord
(
)
;
$
this
->
setActiveRecord
(
$
recArr
)
;
$
this
->
setFormInputs
(
$
this
->
formInputs
)
;
try
{
if
(
$
this
->
ValidateForm
(
)
==
false
)
return
;
}
catch
(
Openbizx
\
Validation
\
Exception
$
e
)
{
$
this
->
processFormObjError
(
$
e
->
errors
)
;
return
;
}
$
this
->
activeRecord
=
$
this
->
readInputRecord
(
)
;
/* @var $viewObj WebPageWizard */
$
viewObj
=
$
this
->
getWebpageObject
(
)
;
$
r
=
$
viewObj
->
commit
(
)
;
if
(
!
$
r
)
return
;
$
this
->
processPostAction
(
)
;
}

Finish the wizard process

@return void
@access remote


public function cancel()
    {
        // clean the session record
        $this->dropSession = true;
        Openbizx::$app->getSessionContext()->cleanObj($this->objectName, true);
    }

public
function
cancel
(
)
{
// clean the session record
$
this
->
dropSession
=
true
;
Openbizx
::
$
app
->
getSessionContext
(
)
->
cleanObj
(
$
this
->
objectName
,
true
)
;
}

Clean up the sessions of view and all forms

@return void


public function render()
    {
        $viewobj = $this->getWebpageObject();
        $viewobj->setFormState($this->objectName, 'visited', 1);

        return parent::render();
    }

public function render ( ) { $ viewobj = $ this -> getWebpageObject ( ) ; $ viewobj -> setFormState ( $ this -> objectName , 'visited' , 1 ) ; return parent :: render ( ) ; }

Render this form

@return @return string - HTML text of this form's read mode


public static function generate($length = null)
    {
        if ($length === null) {
            $length = self::DEFAULT_LENGTH;
        }
        $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
        $randomString = '';
        for ($i = 0; $i < $length; ++$i) {
            $randomString .= $characters[rand(0, strlen($characters) - 1)];
        }

        return $randomString;
    }

public static function generate ( $ length = null ) { if ( $ length === null ) { $ length = self :: DEFAULT_LENGTH ; } $ characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567' ; $ randomString = '' ; for ( $ i = 0 ; $ i < $ length ; ++ $ i ) { $ randomString .= $ characters [ rand ( 0 , strlen ( $ characters ) - 1 ) ] ; } return $ randomString ; }

Generates a TOTP key.

@param int|null $length Key length (default 16)

@return string TOTP key


public static function isEmpty(callable $callback, Context $context): bool
    {
        $policy = $context->setAccessPolicy(Context::ACCESS_POLICY_RETURN_NULL);

        try {
            $val = $callback($context);
        } finally {
            $context->setAccessPolicy($policy);
        }

        if ($val instanceof \Countable) {
            return $val->count() == 0;
        }

        return empty($val);
    }

public static function isEmpty ( callable $ callback , Context $ context ) : bool { $ policy = $ context -> setAccessPolicy ( Context :: ACCESS_POLICY_RETURN_NULL ) ; try { $ val = $ callback ( $ context ) ; } finally { $ context -> setAccessPolicy ( $ policy ) ; } if ( $ val instanceof \ Countable ) { return $ val -> count ( ) == 0 ; } return empty ( $ val ) ; }

Check if a return value is empty. A value is considered empty if it cannot be accessed or
if it is countable and count is 0 or if PHP's empty-operator returns true when the
vallue is passed.

@param callable $callback Callback being used to compute the value.
@param Context $context Expression context to be passed to the callback.
@return bool Returns true if the computed value is empty.

Check if a return value is empty . A value is considered empty if it cannot be accessed or if it is countable and count is 0 or if PHP s empty - operator returns true when the vallue is passed .


public static function ternaryShortcut(callable $a, callable $b, Context $context)
    {
        $policy = $context->setAccessPolicy(Context::ACCESS_POLICY_RETURN_NULL);

        try {
            $val = $a($context);
        } finally {
            $context->setAccessPolicy($policy);
        }

        if ($val instanceof \Countable) {
            if ($val->count()) {
                return $val;
            }

            return $b($context);
        }

        return empty($val) ? $b($context) : $val;
    }

public static function ternaryShortcut ( callable $ a , callable $ b , Context $ context ) { $ policy = $ context -> setAccessPolicy ( Context :: ACCESS_POLICY_RETURN_NULL ) ; try { $ val = $ a ( $ context ) ; } finally { $ context -> setAccessPolicy ( $ policy ) ; } if ( $ val instanceof \ Countable ) { if ( $ val -> count ( ) ) { return $ val ; } return $ b ( $ context ) ; } return empty ( $ val ) ? $ b ( $ context ) : $ val ; }

Evaluate the given ternary shortcut, callback a is evaluated, returns result of a if it is
not empty, otherwise returns result of b.

@param callable $a Value to be empty-checked.
@param callable $b Value to be used in case a evaluates to empty.
@param Context $context
@return mixed ternary shortcut value.

Evaluate the given ternary shortcut callback a is evaluated returns result of a if it is not empty otherwise returns result of b .


public static function contains($container, $val): bool
    {
        if (\is_array($container)) {
            return \in_array($val, $container, true);
        }

        if ($container instanceof \Traversable) {
            foreach ($container as $tmp) {
                if ($tmp === $val) {
                    return true;
                }
            }
        }

        return false;
    }

public static function contains ( $ container , $ val ) : bool { if ( \ is_array ( $ container ) ) { return \ in_array ( $ val , $ container , true ) ; } if ( $ container instanceof \ Traversable ) { foreach ( $ container as $ tmp ) { if ( $ tmp === $ val ) { return true ; } } } return false ; }

Check if the given value is contained within the given container. Supported container
types are arrays and traversable objects.

@param mixed $container The container to be checked.
@param mixed $val The value to be checked for.
@return boolean Returns true if the container contains the given value.

Check if the given value is contained within the given container . Supported container types are arrays and traversable objects .


public function merge(&$anotherMIObj)
    {
        $old_varValue = $this->varValue;
        $this->varValue = array();
        foreach ($anotherMIObj as $key => $value) {
            if (!$old_varValue[$key]) {
                $this->varValue[$key] = $value;
            } else {
                $this->varValue[$key] = $old_varValue[$key];
            }
        }
        foreach ($old_varValue as $key => $value) {
            if (!isset($this->varValue[$key])) {
                $this->varValue[$key] = $value;
            }
        }
    }

public function merge ( & $ anotherMIObj ) { $ old_varValue = $ this -> varValue ; $ this -> varValue = array ( ) ; foreach ( $ anotherMIObj as $ key => $ value ) { if ( ! $ old_varValue [ $ key ] ) { $ this -> varValue [ $ key ] = $ value ; } else { $ this -> varValue [ $ key ] = $ old_varValue [ $ key ] ; } } foreach ( $ old_varValue as $ key => $ value ) { if ( ! isset ( $ this -> varValue [ $ key ] ) ) { $ this -> varValue [ $ key ] = $ value ; } } }

Merge to another MetaIterator object

@param MetaIterator $anotherMIObj another MetaIterator object
@return void


public static function create(
        $containerConfig = null,
        ?RouterInterface $router = null,
        ?DispatcherInterface $dispatcher = null,
        ?ResponseInterface $defaultResponse = null
    ): App {
        $container = self::buildContainer($containerConfig);
        $dispatcher = $dispatcher ?: new Dispatcher();
        $defaultResponse = $defaultResponse ?: new Response();
        $router = $router ?: new Router(
            [],
            ($container->has('router.options') ? $container->get('router.options') : [])
        );

        if ($container->has('router.routes') && is_array($container->get('router.routes'))) {
            $router->addRoutes($container->get('router.routes'));
        }

        $container->set(Dispatcher::class, $dispatcher);
        $container->set(Router::class, $router);
        $container->set(Response::class, $defaultResponse);

        $app = new App($container, $router, $dispatcher, $defaultResponse);

        if ($container->has('app.env') && is_string($container->get('app.env'))) {
            $app->setEnv($container->get('app.env'));
        }

        if ($container->has('app.error.handler') && true === (bool) $container->get('app.error.handler')) {
            $app->enableErrorHandler();
        }

        return $app;
    }

public static function create ( $ containerConfig = null , ? RouterInterface $ router = null , ? DispatcherInterface $ dispatcher = null , ? ResponseInterface $ defaultResponse = null ) : App { $ container = self :: buildContainer ( $ containerConfig ) ; $ dispatcher = $ dispatcher ? : new Dispatcher ( ) ; $ defaultResponse = $ defaultResponse ? : new Response ( ) ; $ router = $ router ? : new Router ( [ ] , ( $ container -> has ( 'router.options' ) ? $ container -> get ( 'router.options' ) : [ ] ) ) ; if ( $ container -> has ( 'router.routes' ) && is_array ( $ container -> get ( 'router.routes' ) ) ) { $ router -> addRoutes ( $ container -> get ( 'router.routes' ) ) ; } $ container -> set ( Dispatcher :: class , $ dispatcher ) ; $ container -> set ( Router :: class , $ router ) ; $ container -> set ( Response :: class , $ defaultResponse ) ; $ app = new App ( $ container , $ router , $ dispatcher , $ defaultResponse ) ; if ( $ container -> has ( 'app.env' ) && is_string ( $ container -> get ( 'app.env' ) ) ) { $ app -> setEnv ( $ container -> get ( 'app.env' ) ) ; } if ( $ container -> has ( 'app.error.handler' ) && true === ( bool ) $ container -> get ( 'app.error.handler' ) ) { $ app -> enableErrorHandler ( ) ; } return $ app ; }

Build App object and load config.

@param string|ContainerInterface|null $containerConfig
@param RouterInterface|null           $router
@param DispatcherInterface|null       $dispatcher
@param null|ResponseInterface         $defaultResponse

@throws \EnderLab\MiddleEarth\Router\RouterException
@throws \Psr\Container\ContainerExceptionInterface
@throws \Psr\Container\NotFoundExceptionInterface
@throws \Exception

@return App


public function dispatch($key, $arguments)
    {
        $event = new GenericEvent(
            $key,
            $arguments
        );

        $this->eventDispatcher->dispatch($key, $event);

        return $event;
    }

public function dispatch ( $ key , $ arguments ) { $ event = new GenericEvent ( $ key , $ arguments ) ; $ this -> eventDispatcher -> dispatch ( $ key , $ event ) ; return $ event ; }

Notify Helper Create a generic event and dispatch the event

@todo move to WobbleCodeNotificationBundle

@param string $key       Event key name
@param array  $arguments Arguments with Organization included

@example of arguments

$arguments = [
'notifyLanguage' => 'es',
'notifyUserTrigger' => $user,
'notifyUsers' => [],
'notifyExternal' => 'notify@email.com',
'data' => [
'invitation' => $invitation
]
];

@return GenericEvent Dispatched event


public function countByGroup($fieldGroup, $match = [], $query = null, $sort = null, $limit = null)
    {
        $group = [
            '_id' => '$'.$fieldGroup,
            'count' => [ '$sum' => 1]
        ];

        return $this->aggregateGroup($group, $match, $query, $sort, $limit);
    }

public function countByGroup ( $ fieldGroup , $ match = [ ] , $ query = null , $ sort = null , $ limit = null ) { $ group = [ '_id' => '$' . $ fieldGroup , 'count' => [ '$sum' => 1 ] ] ; return $ this -> aggregateGroup ( $ group , $ match , $ query , $ sort , $ limit ) ; }

Count items by group

@param mixed $collection
@param mixed $fieldGroup
@param mixed $match

@return array Multidimensional array with key => count per group


public function aggregateGroup($group, $match = [], $query = null, $sort = null, $limit = null)
    {
        $query = $this->getDefault('query', $query);

        $collection = $this->dm->getDocumentCollection($this->document);

        $pipeline = [];

        if ($query) {
            $query = $this->addNativeQuery($this->queryFields, $query);
            $match = array_merge($match, $query);
        }

        if (count($match)) {
            $pipeline[] = [
                '$match' => $match
            ];
        }

        $pipeline[] = [
            '$group' => $group
        ];

        if ($sort) {
            $pipeline[] = [
                '$sort' => $sort
            ];
        }

        if ($limit) {
            $pipeline[] = [
                '$limit' => $limit
            ];
        }

        $return = $collection->aggregate($pipeline);

        return iterator_to_array($return);
    }

public function aggregateGroup ( $ group , $ match = [ ] , $ query = null , $ sort = null , $ limit = null ) { $ query = $ this -> getDefault ( 'query' , $ query ) ; $ collection = $ this -> dm -> getDocumentCollection ( $ this -> document ) ; $ pipeline = [ ] ; if ( $ query ) { $ query = $ this -> addNativeQuery ( $ this -> queryFields , $ query ) ; $ match = array_merge ( $ match , $ query ) ; } if ( count ( $ match ) ) { $ pipeline [ ] = [ '$match' => $ match ] ; } $ pipeline [ ] = [ '$group' => $ group ] ; if ( $ sort ) { $ pipeline [ ] = [ '$sort' => $ sort ] ; } if ( $ limit ) { $ pipeline [ ] = [ '$limit' => $ limit ] ; } $ return = $ collection -> aggregate ( $ pipeline ) ; return iterator_to_array ( $ return ) ; }

Aggregate with custom group

@param mixed $collection
@param mixed $fieldGroup
@param mixed $match

@return array Multidimensional array with key => sum per item


public function find($id, array $filters = [])
    {
        $qb = $this->dm->createQueryBuilder($this->document);

        if (count($filters)) {
            $qb = $this->addFilters($qb, $filters);
        }

        $qb->field('_id')->equals(new \MongoId($id));

        return $qb->getQuery()->getSingleResult();
    }

public function find ( $ id , array $ filters = [ ] ) { $ qb = $ this -> dm -> createQueryBuilder ( $ this -> document ) ; if ( count ( $ filters ) ) { $ qb = $ this -> addFilters ( $ qb , $ filters ) ; } $ qb -> field ( '_id' ) -> equals ( new \ MongoId ( $ id ) ) ; return $ qb -> getQuery ( ) -> getSingleResult ( ) ; }

Find a document with support for conditions

@param array $filters List or conditional selectors http://bit.ly/1efirww

@example filters

[
[
'field' => 'id',
'selector' => 'equals',
'value' => 12
],
…
]

@return MongoCursor


public function getMongoIds($objects)
    {
        $ids = [];

        foreach ($objects as $object) {
            $ids[] = new \MongoId($object->getId());
        }

        return $ids;
    }

public function getMongoIds ( $ objects ) { $ ids = [ ] ; foreach ( $ objects as $ object ) { $ ids [ ] = new \ MongoId ( $ object -> getId ( ) ) ; } return $ ids ; }

Get array of MongoIds of this objects

@param array $objects

@return array MongoIds array


public function normalizeDate($date)
    {
        if ($date instanceof \DateTime) {
            return $date;
        }

        $date = preg_replace('/\.[0-9]+/', '', $date);
        return \DateTime::createFromFormat(\DateTime::ISO8601, $date);
    }

public function normalizeDate ( $ date ) { if ( $ date instanceof \ DateTime ) { return $ date ; } $ date = preg_replace ( '/\.[0-9]+/' , '' , $ date ) ; return \ DateTime :: createFromFormat ( \ DateTime :: ISO8601 , $ date ) ; }

Normalize date from ISO8601, if is string it returns a DateTime object

@param {DateTime|string|bool} $date

@return {DateTime|bool} Return DateTime or false for Invalid Dates

Normalize date from ISO8601 if is string it returns a DateTime object


public function isInFormRefLibs($formName)
    {
        if ($this->formRefLibs) {
            $this->formRefLibs->rewind();
            while ($this->formRefLibs->valid()) {
                $reference = $this->formRefLibs->current();
                if ($reference->objectName == $formName) {
                    return true;
                }
                $this->formRefLibs->next();
            }
            return false;
        } else {
            return true;
        }
    }

public function isInFormRefLibs ( $ formName ) { if ( $ this -> formRefLibs ) { $ this -> formRefLibs -> rewind ( ) ; while ( $ this -> formRefLibs -> valid ( ) ) { $ reference = $ this -> formRefLibs -> current ( ) ; if ( $ reference -> objectName == $ formName ) { return true ; } $ this -> formRefLibs -> next ( ) ; } return false ; } else { return true ; } }

Check the Form is in the lib

@param string $formName form name
@return bool inside or not


public function render()
    {
        if (!$this->allowAccess()) {
            $accessDenyWebpage = Openbizx::getObject(OPENBIZ_ACCESS_DENIED_WEBPAGE);
            return $accessDenyWebpage->render();
        }
        $this->initAllForms();
        // check the "fld_..." arg in url and put it in the search rule
        $this->processRequest();
        return $this->_render();
    }

Render this WebPage.

@return mixed either print html content, or return html content
@example ../../../example/ViewObject.php


public function getCurrentPageUrl()
    {
        $pageURL = 'http';
        if ($_SERVER["HTTPS"] == "on") {
            $pageURL .= "s";
        }
        $pageURL .= "://";
        if ($_SERVER["SERVER_PORT"] != "80") {
            $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        } else {
            $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
        }
        return $pageURL;
    }

public function getCurrentPageUrl ( ) { $ pageURL = 'http' ; if ( $ _SERVER [ "HTTPS" ] == "on" ) { $ pageURL .= "s" ; } $ pageURL .= "://" ; if ( $ _SERVER [ "SERVER_PORT" ] != "80" ) { $ pageURL .= $ _SERVER [ "SERVER_NAME" ] . ":" . $ _SERVER [ "SERVER_PORT" ] . $ _SERVER [ "REQUEST_URI" ] ; } else { $ pageURL .= $ _SERVER [ "SERVER_NAME" ] . $ _SERVER [ "REQUEST_URI" ] ; } return $ pageURL ; }

Get current page URL

@return string page URL


protected function initAllForms()
    {
        foreach ($this->formRefs as $formRef) {
            $formRef->setViewName($this->objectName);
            $formName = $formRef->objectName;
            $formObj = Openbizx::getObject($formName);
            if ($formRef->subForms && method_exists($formObj, "SetSubForms")) {
                $formObj->setSubForms($formRef->subForms);
            }
        }
    }

protected function initAllForms ( ) { foreach ( $ this -> formRefs as $ formRef ) { $ formRef -> setViewName ( $ this -> objectName ) ; $ formName = $ formRef -> objectName ; $ formObj = Openbizx :: getObject ( $ formName ) ; if ( $ formRef -> subForms && method_exists ( $ formObj , "SetSubForms" ) ) { $ formObj -> setSubForms ( $ formRef -> subForms ) ; } } }

Initialize all form objects.

@return void


public static function compareIntegers($value, $setting_value)
    {
        $okay = false;

        $actual = self::getIntegerValue($value);
        $operator = self::getOperator($setting_value);
        $expected = self::getIntegerValue($setting_value);
        switch ($operator) {
            case '>':
                $okay = $actual > $expected;
                break;
            case '>=':
                $okay = $actual >= $expected;
                break;
            case '<':
                $okay = $actual < $expected;
                break;
            case '<=':
                $okay = $actual <= $expected;
                break;
            case '!=':
                $okay = $actual != $expected;
                break;
            case '=':
            default:
                $okay = $actual == $expected;
                break;
        }

        return $okay;
    }

public static function compareIntegers ( $ value , $ setting_value ) { $ okay = false ; $ actual = self :: getIntegerValue ( $ value ) ; $ operator = self :: getOperator ( $ setting_value ) ; $ expected = self :: getIntegerValue ( $ setting_value ) ; switch ( $ operator ) { case '>' : $ okay = $ actual > $ expected ; break ; case '>=' : $ okay = $ actual >= $ expected ; break ; case '<' : $ okay = $ actual < $ expected ; break ; case '<=' : $ okay = $ actual <= $ expected ; break ; case '!=' : $ okay = $ actual != $ expected ; break ; case '=' : default : $ okay = $ actual == $ expected ; break ; } return $ okay ; }

Compares the given values according to the comparison operator the second
value might have and returns whether the evaluation is true.

@param string $value integer value that is set in php.ini (e.g. "8M")
@param string $setting_value comparison value as string (e.g. ">=8M")

@return bool true if comparison is okay; false otherwise.

Compares the given values according to the comparison operator the second value might have and returns whether the evaluation is true .


public static function getIntegerValue($value)
    {
        if (!is_numeric($value)) {
            // strip excessive whitespace
            $value = trim($value);
            // strip comparison operator
            $value = ltrim($value, '<>!=');
            // remove the K|M|G suffix if necessary
            $len = strlen($value);
            if (!is_numeric($value)) {
                $quantity = substr($value, 0, $len - 1);
                // we need this, as PHP sets a memory_limit of 0 if the ini value is 0.25M
                // another example: 2.75M will be 2M for PHP (e.g. on post_max_size)
                $quantity = intval($quantity);
            } else {
                $quantity = $value;
            }
            // get unit if this string represents a byte value
            $unit = strtolower(substr($value, $len - 1));
            switch ($unit) {
                case 'k':
                    $quantity *= 1024;
                    break;
                case 'm':
                    $quantity *= 1048576;
                    break;
                case 'g':
                    $quantity *= 1073741824;
                    break;
            }

            return $quantity;
        }

        return intval($value);
    }

Returns the integer value of the given value.

@param mixed $value string to interpret (e.g. ">=2.75M")

@return int integer value as PHP interprets it on ini settings

Returns the integer value of the given value .


public static function findSourceFiles(string $path)
    {
        $result = array();
        $reader = dir($path);

        while ($file = $reader->read())
        {
            if ($file === '.' || $file === '..')
                continue;

            $file = $path . '/' . $file;
            if (substr($file, -4) === ".php")
            {
                $result[] = $file;
            }
            elseif (is_dir($file))
            {
                $sub = self::findSourceFiles($file);
                foreach ($sub as $f)
                    $result[] = $f;
            }
        }

        return $result;
    }

public static function findSourceFiles ( string $ path ) { $ result = array ( ) ; $ reader = dir ( $ path ) ; while ( $ file = $ reader -> read ( ) ) { if ( $ file === '.' || $ file === '..' ) continue ; $ file = $ path . '/' . $ file ; if ( substr ( $ file , - 4 ) === ".php" ) { $ result [ ] = $ file ; } elseif ( is_dir ( $ file ) ) { $ sub = self :: findSourceFiles ( $ file ) ; foreach ( $ sub as $ f ) $ result [ ] = $ f ; } } return $ result ; }

Find all .php source files in the specified path or any subdirectory,
and return them in an array.

@return array The list of .php files.

Find all . php source files in the specified path or any subdirectory and return them in an array .


public function registerNS(string $ns, string $path, $standard = Autoloader::PSR4)
    {
        if (!file_exists($path) || !is_dir($path) || !is_readable($path))
            throw new \InvalidArgumentException("Path $path is not readable");

        if ($standard !== Autoloader::PSR0 && $standard !== Autoloader::PSR4 && !is_callable($standard))
            throw new \InvalidArgumentException("Invalid standard: $standard");

        // Strip a leading namespace separator
        $ns = trim($ns, '\\');

        // Get the namespace parts
        $parts = explode('\\', $ns);

        $this->registered_namespaces[$ns] = true;

        // Make sure there is a trailing namespace separator
        if ($ns !== "" && substr($ns, -1, 1) !== '\\')
            $ns .= '\\';

        $ref = &$this->root_namespace;
        foreach ($parts as $part)
        {
            // Registering empty namespace
            if ($part === "")
                break;

            if (!isset($ref['sub_ns'][$part]))
                $ref['sub_ns'][$part] = ['loaders' => [], 'sub_ns' => []];

            $ref = &$ref['sub_ns'][$part];
        }

        $ref['loaders'][] = [
            'ns' => $ns,
            'path' => $path,
            'std' => $standard
        ];
    }

Register a namespace with the autoloader.

@param $ns string The namespace to register
@param $path string The path where to find classes in this namespace
@param $standard mixed Autoloader::PSR4 or Autoloader::PSR0. PSR4 is
used by default. You may also provide a callback
function here that will be used as the loader for
this namespace, rather than the provided PSR-0
and PSR-4 loaders.

Register a namespace with the autoloader .


public function buildCache()
    {
        if ($this->cache === null)
            throw new \LogicException("Cannot build cache without a cache instance");

        $this->cache->set('cache_built', false);
        $this->cache->set('classpaths', array());

        $stack = array($this->root_namespace);

        while (!empty($stack))
        {
            $ref = array_pop($stack);
            foreach ($ref['loaders'] as $loader)
            {
                if ($loader['std'] !== Autoloader::PSR4)
                    throw new \LogicException("Cache builder only works with pure PSR4-based namespaces");

                $class_count = 0;
                $root = $loader['path'] . DIRECTORY_SEPARATOR;
                $ns = $loader['ns'];
                $php_files = self::findSourceFiles($loader['path']);
                foreach ($php_files as $file)
                {
                    $rel_file = substr($file, strlen($root));

                    // Store absolute resolved paths when not using stream wrappers
                    if (strpos($file, '://') === false) $file = realpath($file);
                    $parts = explode(DIRECTORY_SEPARATOR, $rel_file);
                    $class_name = substr($ns . implode('\\', $parts), 0, -4);
                    if ($this->cache->has('classpaths', $class_name))
                    {
                        $conflict = $this->cache->get('classpaths', $class_name);
                        throw new \LogicException(sprintf(
                            "Duplicate class definition in file %s and %s (conflicting namespace: %s)",
                            $file,
                            $conflict,
                            $ns
                        ));
                    }

                    $this->cache->set('classpaths', $class_name, $file);
                    ++$class_count;
                }
                self::getLogger()->info('Found {0} classes in namespace {1}', [$class_count, $ns]);
            }

            foreach ($ref['sub_ns'] as $sub_ns)
                array_push($stack, $sub_ns);
        }

        $this->cache->set('cache_built', true);
        self::getLogger()->info('Class cache built');
    }

Build or rebuild the class cache. This will scan all defined PSR4 paths for .php files,
deduce the resulting classname from the path and add the path to the cache.

This works only when solely PSR4 namespaces are defined. There is
ambiguity in the file path -> class name for PSR0-based namespaces as
directory separators can be converted to either namespace separators or
underscores. To avoid this ambiguity, a exception is thrown when PSR0 namespaces
have been registered.

If any of the paths contain files that are not PSR4 compatible, errors may occur,
because the files are not actually loaded to check if they contain the correct class.
When two or more files map to the same class name, a LogicException is thrown.

When authorative mode is enabled, after running buildCache the class loader will only
load classes that were found by buildCache.

Build or rebuild the class cache . This will scan all defined PSR4 paths for . php files deduce the resulting classname from the path and add the path to the cache .


public static function findComposerAutoloader()
    {
        // Find the Composer Autoloader class using its (generated) name
        $list = get_declared_classes();
        foreach ($list as $cl)
            if (substr($cl, 0, 18) === "ComposerAutoloader")
                return $cl;

        // @codeCoverageIgnoreStart
        // Tests run using composer autoloader
        return null;
        // @codeCoverageIgnoreEnd
    }

Find the class name of the Composer autoloader. The name starts
with ComposerAutoloader and has a random suffix. Therefore, the list
of class names is obtained and all class names are compared with this pattern.

Find the class name of the Composer autoloader . The name starts with ComposerAutoloader and has a random suffix . Therefore the list of class names is obtained and all class names are compared with this pattern .


public static function findComposerAutoloaderVendorDir(string $composer_loader_class)
    {
        $ref = new \ReflectionClass($composer_loader_class);

        // Composer is located at MyProject/vendor/composer
        $path = dirname($ref->getFileName());
        return dirname($path);
    }

Get the Composer vendor directory, using the Composer autoloader class
name provided.

@param string $composer_loader_class The fully qualified class name of the Composer autoloader
@return string The vendor dir used by composer

Get the Composer vendor directory using the Composer autoloader class name provided .


public function getClassLoaders(string $class)
    {
        $parts = explode("\\", $class);
        $result = array();
        $ref = &$this->root_namespace;
        $sub_ns = "";
        foreach ($parts as $part)
        {
            foreach ($ref['loaders'] as $loader)
                $result[] = $loader;

            if (!isset($ref['sub_ns'][$part]))
                break;

            $ref = &$ref['sub_ns'][$part];
        }

        // Reverse the result, because the last one is the most specific
        // namespace, which would be the one to try first.
        return array_reverse($result);
    }

Get a list of class loaders that may be able to load the specified
class or namespace. The resulting list is ordered so that the most
specific class loader comes first and the most generic comes last.

@param string $class The fully qualified class (or namespace) to be loaded
@return array A list of loaders, each containing keys:
- 'path' where the classes are stored
- 'std' either Autoloader::PSR0, Autoloader::PSR4 or a callable to be used
delegate the autoload task to
- 'ns' the namespace this loader provides

Get a list of class loaders that may be able to load the specified class or namespace . The resulting list is ordered so that the most specific class loader comes first and the most generic comes last .


public function getMiddlewareOrFallback(string $name, $middleMan, $result = null)
    {
        // asserts instead of type-hints because this is a trait and another trait uses it.
        assert($middleMan instanceof MiddlewareDispatcher);

        if (! $middleMan->groupIsEmpty('getters')) {
            $result = $middleMan->callGetters($name, $result);
        } elseif (is_object($result)) {
            $result = $result->$name;
        } else {
            $result = $this->getVisibleAttribute($name);
        }
        return $result;
    }

Gets the value of the given attribute through middleware or locally as a fallback.

@param string $name
@param $middleMan
@param mixed $result
@return mixed|null

Gets the value of the given attribute through middleware or locally as a fallback .


public function setMiddlewareOrFallback(string $name, $value, $middleMan, $result = null)
    {
        // asserts instead of type-hints because this is a trait and another trait uses it.
        assert($middleMan instanceof MiddlewareDispatcher);

        if (! $middleMan->groupIsEmpty('setters')) {
            $result = $middleMan->callSetters($name, $value, $result);
        } elseif (is_object($result)) {
            $result = $result->$name = $value;
        } else {
            $result = $this->setVisibleAttribute($name, $value);
        }
        return $result;
    }

Sets the value of the given attribute through middleware or locally as a fallback.

@param string $name
@param mixed $value
@param $middleMan
@param mixed $result
@return mixed

Sets the value of the given attribute through middleware or locally as a fallback .


public function withStringLimit(int $strlim): Printable
    {
        return new Printable($this->value, $this->callable, $strlim, $this->arrlim);
    }

public function withStringLimit ( int $ strlim ) : Printable { return new Printable ( $ this -> value , $ this -> callable , $ strlim , $ this -> arrlim ) ; }

Return a new Printable with the given string limit.

@param int $strlim
@return \Quanta\Printable

Return a new Printable with the given string limit .


public function withArrayLimit(int $arrlim): Printable
    {
        return new Printable($this->value, $this->callable, $this->strlim, $arrlim);
    }

public function withArrayLimit ( int $ arrlim ) : Printable { return new Printable ( $ this -> value , $ this -> callable , $ this -> strlim , $ arrlim ) ; }

Return a new Printable with the given array limit.

@param int $arrlim
@return \Quanta\Printable

Return a new Printable with the given array limit .


private function string(string $value): string
    {
        if ($this->callable && is_callable($value)) {
            return sprintf('function %s()', $value);
        }

        return strlen($value) > $this->strlim
            ? $this->quoted(substr($value, 0, $this->strlim) . '...')
            : $this->quoted($value);
    }

private
function
string
(
string
$
value
)
:
string
{
if
(
$
this
->
callable
&&
is_callable
(
$
value
)
)
{
return
sprintf
(
'function %s()'
,
$
value
)
;
}
return
strlen
(
$
value
)
>
$
this
->
strlim
$
this
->
quoted
(
substr
(
$
value
,
0
,
$
this
->
strlim
)
.
'...'
)
:
$
this
->
quoted
(
$
value
)
;
}

Return a formatted string from the given string.

Prepend the string with an ellipsis when it is longer than the limit.

@param string $value
@return string

Return a formatted string from the given string .


private function array(array $value): string
    {
        if ($this->callable && is_callable($value)) {
            $class = ! is_string($value[0])
                ? $this->classname($value[0])
                : $value[0];

            $method = $value[1];

            return sprintf('function %s::%s()', $class, $method);
        }

        $slice = array_slice($value, 0, $this->arrlim, true);

        $elems = $this->isAssociative($slice)
            ? array_map([$this, 'arrayPair'], array_keys($slice), $slice)
            : array_map([$this, 'arrayValue'], $slice);

        return vsprintf('[%s%s]', [
            implode(', ', $elems),
            count($value) > $this->arrlim ? ', ...' : '',
        ]);
    }

private
function
array
(
array
$
value
)
:
string
{
if
(
$
this
->
callable
&&
is_callable
(
$
value
)
)
{
$
class
=
!
is_string
(
$
value
[
0
]
)
$
this
->
classname
(
$
value
[
0
]
)
:
$
value
[
0
]
;
$
method
=
$
value
[
1
]
;
return
sprintf
(
'function %s::%s()'
,
$
class
,
$
method
)
;
}
$
slice
=
array_slice
(
$
value
,
0
,
$
this
->
arrlim
,
true
)
;
$
elems
=
$
this
->
isAssociative
(
$
slice
)
array_map
(
[
$
this
,
'arrayPair'
]
,
array_keys
(
$
slice
)
,
$
slice
)
:
array_map
(
[
$
this
,
'arrayValue'
]
,
$
slice
)
;
return
vsprintf
(
'[%s%s]'
,
[
implode
(
', '
,
$
elems
)
,
count
(
$
value
)
>
$
this
->
arrlim
', ...'
:
''
,
]
)
;
}

Return a formatted string from the given array.

@param array $value
@return string

Return a formatted string from the given array .


private function arrayPair($key, $val): string
    {
        $key_str = is_int($key) ? $key : $this->quoted($key);

        $val_str = $this->arrayValue($val);

        return sprintf('%s => %s', $key_str, $val_str);
    }

private
function
arrayPair
(
$
key
,
$
val
)
:
string
{
$
key_str
=
is_int
(
$
key
)
$
key
:
$
this
->
quoted
(
$
key
)
;
$
val_str
=
$
this
->
arrayValue
(
$
val
)
;
return
sprintf
(
'%s => %s'
,
$
key_str
,
$
val_str
)
;
}

Return a formatted string for the given key => value pair.

@param int|string    $key
@param mixed         $val
@return string

Return a formatted string for the given key = > value pair .


private function arrayValue($val): string
    {
        return ! is_array($val)
            ? (string) new Printable($val, $this->callable, $this->strlim)
            : '[...]';
    }

private function arrayValue ( $ val ) : string { return ! is_array ( $ val ) ? ( string ) new Printable ( $ val , $ this -> callable , $ this -> strlim ) : '[...]' ; }

Return a formatted strinf for the given array value.

@param mixed $val
@return string

Return a formatted strinf for the given array value .


private function object($value): string
    {
        $class = $this->classname($value);

        if ($class == \Closure::class) {
            return 'function {closure}()';
        }

        return ($this->callable && is_callable($value))
            ? sprintf('function %s::__invoke()', $class)
            : sprintf('Object(%s)', $class);
    }

private
function
object
(
$
value
)
:
string
{
$
class
=
$
this
->
classname
(
$
value
)
;
if
(
$
class
==
\
Closure
::
class
)
{
return
'function {closure}()'
;
}
return
(
$
this
->
callable
&&
is_callable
(
$
value
)
)
sprintf
(
'function %s::__invoke()'
,
$
class
)
:
sprintf
(
'Object(%s)'
,
$
class
)
;
}

Return a formatted string from the given object.

@param object $value
@return string

Return a formatted string from the given object .


public function reject(RejectEnvelopeEvent $event)
    {
        if (!function_exists('newrelic_end_transaction')) {
            return;
        }

        newrelic_notice_error($event->getEnvelope()->getName(), $event->getException());
        newrelic_end_transaction();
    }

public function reject ( RejectEnvelopeEvent $ event ) { if ( ! function_exists ( 'newrelic_end_transaction' ) ) { return ; } newrelic_notice_error ( $ event -> getEnvelope ( ) -> getName ( ) , $ event -> getException ( ) ) ; newrelic_end_transaction ( ) ; }

Reject is called when a task throws an exception

@param RejectEnvelopeEvent $event


public function boot(\Illuminate\Routing\Router $router)
  {

    Config::set('auth.model', 'Askedio\Laravelcp\Models\User');
    Config::set('auth.password.email', 'lcp::emails.password');

    $router->middleware('auth', 'Askedio\Laravelcp\Http\Middleware\Authenticate');
    $router->middleware('auth.basic', 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth');
    $router->middleware('guest', 'Askedio\Laravelcp\Http\Middleware\RedirectIfAuthenticated');
    $router->middleware('role', 'Askedio\Laravelcp\Http\Middleware\VerifyRole');
    $router->middleware('permission', 'Askedio\Laravelcp\Http\Middleware\VerifyPermission');

    $loader = \Illuminate\Foundation\AliasLoader::getInstance();
    $loader->alias('Nav', 'Askedio\Laravelcp\Helpers\NavigationHelper');
    $loader->alias('Hook', 'Askedio\Laravelcp\Helpers\HookHelper');
    $loader->alias('Search', 'Askedio\Laravelcp\Helpers\SearchHelper');

    NavigationHelper::Initialize();
    HookHelper::Initialize();
    SearchHelper::Initialize();

    if (! $this->app->routesAreCached()) {
      require realpath(__DIR__.'/../Http/routes.php');
    }

    $this->loadTranslationsFrom(realpath(__DIR__.'/../Resources/Lang'), 'lcp');

    $this->loadViewsFrom(realpath(__DIR__.'/../Resources/Views'), 'lcp');

    NavigationHelper::Add(['nav' => 'main', 'sort' => '0',  'link' => url('/dashboard'), 'title' => trans('lcp::nav.dashboard'), 'icon' => 'fa-dashboard']);

    $this->publishes([
      realpath(__DIR__.'/../Resources/Views') => base_path('resources/views/vendor/askedio/laravelcp'),
    ], 'views');

    $this->publishes([
      realpath(__DIR__.'/../Resources/Assets') => public_path('assets'),
    ], 'public');

    $this->publishes([
      realpath(__DIR__.'/../Resources/Config') => config_path('')
    ], 'config');

    $this->publishes([
      realpath(__DIR__.'/../Database/Migrations') => database_path('migrations')
    ], 'migrations');

    $this->publishes([
      realpath(__DIR__.'/../Database/Seeds') => database_path('seeds')
    ], 'seeds');

  }

Register routes, translations, views and publishers.

@return void

Register routes translations views and publishers .


static public function render($webpage)
    {
        $tplEngine = $webpage->templateEngine;
        $tplAttributes = ViewRenderer::buildTemplateAttributes($webpage);

        ob_start();

        if ($tplEngine == "Smarty" || $tplEngine == null) {
            ViewRenderer::renderSmarty($webpage, $tplAttributes);
        } else {
            ViewRenderer::renderPHP($webpage, $tplAttributes);
        }

        $html = ob_get_contents();
        ob_end_clean();

        if (defined("OPENBIZ_PAGE_MINIFY") && OPENBIZ_PAGE_MINIFY == 1) {
            $html = self::MinifyOutput($html);
        }
        return $html;
    }

static public function render ( $ webpage ) { $ tplEngine = $ webpage -> templateEngine ; $ tplAttributes = ViewRenderer :: buildTemplateAttributes ( $ webpage ) ; ob_start ( ) ; if ( $ tplEngine == "Smarty" || $ tplEngine == null ) { ViewRenderer :: renderSmarty ( $ webpage , $ tplAttributes ) ; } else { ViewRenderer :: renderPHP ( $ webpage , $ tplAttributes ) ; } $ html = ob_get_contents ( ) ; ob_end_clean ( ) ; if ( defined ( "OPENBIZ_PAGE_MINIFY" ) && OPENBIZ_PAGE_MINIFY == 1 ) { $ html = self :: MinifyOutput ( $ html ) ; } return $ html ; }

Render view object

@param WebPage $webpage
@return string result of rendering process


static protected function renderSmarty($webpage, $tplAttributes = Array())
    {
        $smarty = TemplateHelper::getSmartyTemplate();

        $viewOutput = $webpage->outputAttrs();
        foreach ($viewOutput as $k => $v) {
            $smarty->assign($k, $v);
        }
        // render the formobj attributes
        $smarty->assign("view", $viewOutput);

        //Translate Array of template variables to \Zend template object
        foreach ($tplAttributes as $key => $value) {
            $smarty->assign($key, $value);
        }

        self::registerSmartyPlugin($smarty);

        //if ($webpage->consoleOutput) {
            $smarty->display(TemplateHelper::getTplFileWithPath($webpage->templateFile, $webpage->package));
        //} else {
        //    return $smarty->fetch(TemplateHelper::getTplFileWithPath($webpage->templateFile, $webpage->package));
        //}
    }

Render smarty template for view object

@param WebPage $webpage
@param string $tplFile
@return string result of rendering process


static protected function renderPHP($viewObj, $tplAttributes = Array())
    {
        $view = TemplateHelper::getZendTemplate();
        $tplFile = TemplateHelper::getTplFileWithPath($viewObj->templateFile, $viewObj->package);
        $view->addScriptPath(dirname($tplFile));

        //Translate Array of template variables to \Zend template object
        foreach ($tplAttributes as $key => $value) {
            if ($value == NULL) {
                $view->$key = '';
            } else {
                $view->$key = $value;
            }
        }
        if ($viewObj->consoleOutput) {
            echo $view->render($viewObj->templateFile);
        } else {
            return $view->render($viewObj->templateFile);
        }
    }

Render PHP template for view object

@param EasyForm $formObj
@param string $tplFile
@return string result of rendering process


static protected function setHeaders($viewObj)
    {
        // get the cache attribute
        // if cache = browser, set the cache control in headers
        header('Pragma:', true);
        header('Cache-Control: max-age=3600', true);
        $offset = 60 * 60 * 24 * - 1;
        $ExpStr = "Expires: " . gmdate("D, d M Y H:i:s", time() + $offset) . " GMT";
        header($ExpStr, true);
    }

Set headers of view

@param WebPage $viewObj
@return void


public function create(IssueInterface $issue, UserInterface $user)
    {
        $comment = new $this->className();

        return $comment
            ->setIssue($issue)
            ->setWrittenBy($user);
    }

public function create ( IssueInterface $ issue , UserInterface $ user ) { $ comment = new $ this -> className ( ) ; return $ comment -> setIssue ( $ issue ) -> setWrittenBy ( $ user ) ; }

Creates an instance of comment.

@param \Kreta\Component\Issue\Model\Interfaces\IssueInterface $issue The issue
@param \Kreta\Component\User\Model\Interfaces\UserInterface   $user  The user

@return \Kreta\Component\Comment\Model\Interfaces\CommentInterface


public static function listDir(string $dir, bool $recursive = true)
    {
        $contents = array();
        $subdirs = array();
        $reader = dir($dir);
        while ($entry = $reader->read())
        {
            if ($entry === "." || $entry === "..")
                continue;

            $entry = $dir . DIRECTORY_SEPARATOR . $entry;
            if (substr($entry, -4) === ".php")
            {
                $contents[] = $entry;
            }
            elseif (is_dir($entry) && $recursive)
            {
                $subdirs = array_merge($subdirs, self::listDir($entry));
            }
        }

        // Sort the direct contents of the directory so that index.php comes first
        usort($contents, function ($a, $b) {
            $sla = strlen($a);
            $slb = strlen($b);

            // index files come first
            $a_idx = substr($a, -10) === "/index.php";
            $b_idx = substr($b, -10) === "/index.php";
            if ($a_idx !== $b_idx)
                return $a_idx ? -1 : 1;

            // sort the rest alphabetically
            return strcasecmp($a, $b);
        });

        // Add the contents of subdirectories to the direct contents
        return array_merge($contents, $subdirs);
    }

Find files and directories in a directory. The contents are filtered on
.php files and files.

@param $dir string The directory to list
@param $recursive boolean Whether to also scan subdirectories
@return array The contents of the directory.

Find files and directories in a directory . The contents are filtered on . php files and files .


protected function sortModules()
    {
        parent::sortModules();

        if ($this->root !== null && $this->root_search_path !== $this->search_path)
        {
            $this->root = null;
            $this->root_search_path = null;
        }
    }

protected function sortModules ( ) { parent :: sortModules ( ) ; if ( $ this -> root !== null && $ this -> root_search_path !== $ this -> search_path ) { $ this -> root = null ; $ this -> root_search_path = null ; } }

Sort the modules, check if anything has changed

Sort the modules check if anything has changed


public function getRoutes()
    {
        if (!$this->sorted)
            $this->sortModules();

        $cache = $this->getCachedData();

        if ($cache !== null && $this->root === null)
        {
            $root = $cache->get('data');
            if ($root instanceof Route)
            {
                $this->root = $root;
                $this->root_search_path = $cache->get('search_path');
            }
        }

        if ($this->root !== null)
            return $this->root;

        $this->root = new Route('/', 0);
        $this->root_search_path = $this->search_path;
        foreach ($this->search_path as $module => $info)
        {
            $app_path = $info['path'];
            $files = self::listDir($app_path);
            foreach ($files as $path)
            {
                $file = str_replace($app_path, "", $path);
                $parts = array_filter(explode("/", $file));
                $ptr = $this->root;

                $cnt = 0;
                $l = count($parts);
                foreach ($parts as $part)
                {
                    $last = $cnt === $l - 1;
                    if ($last)
                    {
                        if ($part === "index.php")
                        {
                            // Only store if empty -
                            $ptr->addApp($path, '', $module);
                        }
                        else
                        {
                            $app_name = substr($part, 0, -4);

                            // Strip file extension
                            $ext = "";
                            $ext_pos = strrpos($app_name, '.');
                            if (!empty($ext_pos))
                            {
                                $ext = substr($app_name, $ext_pos);
                                $app_name = substr($app_name, 0, $ext_pos);
                            }

                            $app = $ptr->getSubRoute($app_name);
                            $app->addApp($path, $ext, $module);
                        }
                        break;
                    }

                    // Move the pointer deeper
                    $ptr = $ptr->getSubRoute($part);
                    ++$cnt;
                }
            }
        }

        if ($cache !== null)
            $cache->set('data', $this->root);

        return $this->root;
    }

public
function
getRoutes
(
)
{
if
(
!
$
this
->
sorted
)
$
this
->
sortModules
(
)
;
$
cache
=
$
this
->
getCachedData
(
)
;
if
(
$
cache
!==
&&
$
this
->
root
===
)
{
$
root
=
$
cache
->
get
(
'data'
)
;
if
(
$
root
instanceof
Route
)
{
$
this
->
root
=
$
root
;
$
this
->
root_search_path
=
$
cache
->
get
(
'search_path'
)
;
}
}
if
(
$
this
->
root
!==
)
return
$
this
->
root
;
$
this
->
root
=
new
Route
(
'/'
,
0
)
;
$
this
->
root_search_path
=
$
this
->
search_path
;
foreach
(
$
this
->
search_path
as
$
module
=>
$
info
)
{
$
app_path
=
$
info
[
'path'
]
;
$
files
=
self
::
listDir
(
$
app_path
)
;
foreach
(
$
files
as
$
path
)
{
$
file
=
str_replace
(
$
app_path
,
""
,
$
path
)
;
$
parts
=
array_filter
(
explode
(
"/"
,
$
file
)
)
;
$
ptr
=
$
this
->
root
;
$
cnt
=
0
;
$
l
=
count
(
$
parts
)
;
foreach
(
$
parts
as
$
part
)
{
$
last
=
$
cnt
===
$
l
1
;
if
(
$
last
)
{
if
(
$
part
===
"index.php"
)
{
// Only store if empty -
$
ptr
->
addApp
(
$
path
,
''
,
$
module
)
;
}
else
{
$
app_name
=
substr
(
$
part
,
0
,
4
)
;
// Strip file extension
$
ext
=
""
;
$
ext_pos
=
strrpos
(
$
app_name
,
'.'
)
;
if
(
!
empty
(
$
ext_pos
)
)
{
$
ext
=
substr
(
$
app_name
,
$
ext_pos
)
;
$
app_name
=
substr
(
$
app_name
,
0
,
$
ext_pos
)
;
}
$
app
=
$
ptr
->
getSubRoute
(
$
app_name
)
;
$
app
->
addApp
(
$
path
,
$
ext
,
$
module
)
;
}
break
;
}
// Move the pointer deeper
$
ptr
=
$
ptr
->
getSubRoute
(
$
part
)
;
++
$
cnt
;
}
}
}
if
(
$
cache
!==
)
$
cache
->
set
(
'data'
,
$
this
->
root
)
;
return
$
this
->
root
;
}

Get all routes available from all modules. If the routes have already been
determined, they will be used. Clear the cache to redo this.

@return array The available routes and the associated controller

Get all routes available from all modules . If the routes have already been determined they will be used . Clear the cache to redo this .


protected function renderMenuItems(&$menuItemArray)
    {
        $sHTML = "";
        if (isset($menuItemArray["ATTRIBUTES"])) {
            $sHTML .= $this->renderSingleMenuItem($menuItemArray);
        } else {
            foreach ($menuItemArray as $menuItem) {
                $sHTML .= $this->renderSingleMenuItem($menuItem);
            }
        }
        return $sHTML;
    }

protected function renderMenuItems ( & $ menuItemArray ) { $ sHTML = "" ; if ( isset ( $ menuItemArray [ "ATTRIBUTES" ] ) ) { $ sHTML .= $ this -> renderSingleMenuItem ( $ menuItemArray ) ; } else { foreach ( $ menuItemArray as $ menuItem ) { $ sHTML .= $ this -> renderSingleMenuItem ( $ menuItem ) ; } } return $ sHTML ; }

Render menu items

@param array $menuItemArray menu item array
@return string html content of the menu items


protected function renderSingleMenuItem(&$menuItem)
    {
        $profile = Openbizx::$app->getUserProfile();
        $svcobj = Openbizx::getService(ACCESS_SERVICE);
        $role = isset($profile["ROLE"]) ? $profile["ROLE"] : null;

        if ( isset($menuItem["ATTRIBUTES"]['URL']) ) {
            $url = $menuItem["ATTRIBUTES"]["URL"];
        } elseif ( isset($menuItem["ATTRIBUTES"]['VIEW']) ) {
            $view = $menuItem["ATTRIBUTES"]["VIEW"];
            // menuitem's containing VIEW attribute is renderd if access is granted in accessservice.xml
            // menuitem's are rendered if no definition is found in accessservice.xml (default)
            if ($svcobj->allowViewAccess($view, $role)) {
                $url = "javascript:GoToView('" . $view . "')";
            } else {
                return '';
            }
        }

        $caption = $this->translate($menuItem["ATTRIBUTES"]["CAPTION"]);
        $target = $menuItem["ATTRIBUTES"]["TARGET"];
        $icon = $menuItem["ATTRIBUTES"]["ICON"];
        $img = $icon ? "getImageUrl() . "/$icon' class=menu_img> " : "";

        if ($view)
            $url = "javascript:GoToView('" . $view . "')";

        if ($target)
            $sHTML .= "
$img" . $caption . "";
        else
            $sHTML .= "
$img" . $caption . "";
        if ($menuItem["MENUITEM"]) {
            $sHTML .= "\n
\n";
            $sHTML .= $this->renderMenuItems($menuItem["MENUITEM"]);
            $sHTML .= "
";
        }
        $sHTML .= "
\n";

        return $sHTML;
    }

Render single menu item

@param array $menuItem menu item metadata xml array
@return string html content of each menu item


public function writeCsv(array $data): self
	{
		fputcsv($this->handler, $data, $this->delimiter, $this->enclosure, $this->escapeChar);
		return $this;
	}

public function writeCsv ( array $ data ) : self { fputcsv ( $ this -> handler , $ data , $ this -> delimiter , $ this -> enclosure , $ this -> escapeChar ) ; return $ this ; }

Zapise jako csv radek
@param array $data
@return self


protected function configure()
    {
        parent::configure();

        $this->setName('check');

        $this->addOption(
            'config',
            'c',
            InputOption::VALUE_OPTIONAL,
            'Path to config file that defines the checks to process.'
        );

        $this->addOption(
            'config-handler',
            null,
            InputOption::VALUE_OPTIONAL,
            'Classname of a custom config handler implementing Environaut\Config\IConfigHandler.'
        );

        $this->addOption(
            'cache-location',
            null,
            InputOption::VALUE_OPTIONAL,
            'File path and name for the cache location to read from. Overrides defaults and config file value.'
        );

        $this->addOption(
            'no-cache',
            null,
            InputOption::VALUE_NONE,
            'Disables the use of caching (reading/writing). Remember, that the old cache file still survives!'
        );

        $this->setDescription('Check environment according to a set of checks.');

        $this->setHelp(
<<<EOT

<info>This command checks the environment according to the checks from the configuration file.</info>

By default the <comment>current working directory</comment> will be used to find the configuration file and
all defined classes (checks and validators etc.).

Use
<comment>--autoload-dir [path/to/src]</comment> to change the autoload directory or
<comment>--config [path/to/environaut.(json|xml|php)]</comment> to set the configuration file lookup path or
<comment>--no-cache</comment> to disable to usage of a cache file.
EOT
        );
    }

Define options supported by this command and set name, description and help texts.

Define options supported by this command and set name description and help texts .


protected function readConfig()
    {
        $this->config = $this->getConfigHandler()->getConfig();

        if ($this->config->has('introduction')) {
            $this->output->writeln($this->config->get('introduction'));
            $this->output->writeln('');
        }
    }

protected function readConfig ( ) { $ this -> config = $ this -> getConfigHandler ( ) -> getConfig ( ) ; if ( $ this -> config -> has ( 'introduction' ) ) { $ this -> output -> writeln ( $ this -> config -> get ( 'introduction' ) ) ; $ this -> output -> writeln ( '' ) ; } }

Reads configuration via default or given config file handler


protected function runChecks()
    {
        $runner_impl = $this->config->getRunnerImplementor();

        $runner = new $runner_impl();

        if (!$runner instanceof IRunner) {
            throw new \InvalidArgumentException('The given runner "' . $runner_impl . '" must implement IRunner.');
        }

        $runner->setConfig($this->config);
        $runner->setCommand($this);
        $runner->setParameters(new Parameters($this->config->get('runner', array())));
        $runner->setCache($this->getLoadedCache());

        $run_was_successful = $runner->run();

        $this->report = $runner->getReport();

        $this->writeCache($run_was_successful);
    }

protected
function
runChecks
(
)
{
$
runner_impl
=
$
this
->
config
->
getRunnerImplementor
(
)
;
$
runner
=
new
$
runner_impl
(
)
;
if
(
!
$
runner
instanceof
IRunner
)
{
throw
new
\
InvalidArgumentException
(
'The given runner "'
.
$
runner_impl
.
'" must implement IRunner.'
)
;
}
$
runner
->
setConfig
(
$
this
->
config
)
;
$
runner
->
setCommand
(
$
this
)
;
$
runner
->
setParameters
(
new
Parameters
(
$
this
->
config
->
get
(
'runner'
,
array
(
)
)
)
)
;
$
runner
->
setCache
(
$
this
->
getLoadedCache
(
)
)
;
$
run_was_successful
=
$
runner
->
run
(
)
;
$
this
->
report
=
$
runner
->
getReport
(
)
;
$
this
->
writeCache
(
$
run_was_successful
)
;
}

Runs all checks and collects results in a report.

Runs all checks and collects results in a report .


protected function runExport()
    {
        $export_impl = $this->config->getExportImplementor();

        $exporter = new $export_impl();

        if (!$exporter instanceof IExport) {
            throw new \InvalidArgumentException('The given exporter "' . $export_impl . '" must implement IExport.');
        }

        $exporter->setCommand($this);
        $exporter->setReport($this->report);
        $exporter->setParameters(new Parameters($this->config->get('export', array())));

        $exporter->run();
    }

protected
function
runExport
(
)
{
$
export_impl
=
$
this
->
config
->
getExportImplementor
(
)
;
$
exporter
=
new
$
export_impl
(
)
;
if
(
!
$
exporter
instanceof
IExport
)
{
throw
new
\
InvalidArgumentException
(
'The given exporter "'
.
$
export_impl
.
'" must implement IExport.'
)
;
}
$
exporter
->
setCommand
(
$
this
)
;
$
exporter
->
setReport
(
$
this
->
report
)
;
$
exporter
->
setParameters
(
new
Parameters
(
$
this
->
config
->
get
(
'export'
,
array
(
)
)
)
)
;
$
exporter
->
run
(
)
;
}

Runs the export with the collected report from the checks.

Runs the export with the collected report from the checks .


protected function writeCache($run_was_successful)
    {
        $disable_caching = $this->input->getOption('no-cache');
        if (!empty($disable_caching)) {
            return;
        }

        $cache_implementor = $this->config->getCacheImplementor();
        $cache = new $cache_implementor();

        if (!$cache instanceof ICache) {
            throw new \InvalidArgumentException(
                'The given cache class "' . $cache_implementor . '" does not implement ICache.'
            );
        }

        $cache_params = new Parameters($this->config->get('cache', array()));
        $cache->setParameters($cache_params);

        // TODO use something like getenv('ENVIRONAUT_CACHE_DIR')?
        $cache_location = $this->input->getOption('cache-location');
        if (!empty($cache_location)) {
            $cache->setLocation($cache_location);
        }

        $cache->addAll(
            $this->report->getCachableSettings() // gets only cachable settings from successful checks
        );

        if ($cache->save()) {
            $this->output->writeln(
                PHP_EOL . 'Writing cachable settings to "<comment>' . $cache->getLocation() .
                '</comment>" for subsequent runs...<info>ok</info>.' . PHP_EOL
            );
        } else {
            $this->output->writeln(
                PHP_EOL . 'Writing cachable settings to "<comment>' . $cache->getLocation() .
                '</comment>" for subsequent runs...<error>FAILED</error>.' . PHP_EOL
            );
        }
    }

Write the cachable settings from the run checks to a cache file for later reuse.

@todo should cache only be written if all checks succeeded?

@param boolean $run_was_successful whether or not the checks ran successfully

Write the cachable settings from the run checks to a cache file for later reuse .


protected function getLoadedCache()
    {
        if ($this->input->getOption('no-cache')) {
            $this->readonly_cache = new ReadOnlyCache();
            return $this->readonly_cache;
        }

        $cache_implementor = $this->config->getReadOnlyCacheImplementor();
        $cache = new $cache_implementor();

        if (!$cache instanceof IReadOnlyCache) {
            throw new \InvalidArgumentException(
                'The given cache class "' . $cache_implementor . '" does not implement IReadOnlyCache.'
            );
        }

        $cache_params = new Parameters($this->config->get('cache', array()));
        $cache_location = $this->input->getOption('cache-location');

        $this->readonly_cache = $cache;
        $this->readonly_cache->setParameters($cache_params);
        if (!empty($cache_location)) {
            if (is_readable($cache_location)) {
                $this->readonly_cache->setLocation($cache_location);
            } else {
                $this->output->writeln(
                    '<comment>Given cache location could not be read. ' .
                    'Using fallback from config or default location.</comment>'
                );
            }
        }

        $this->readonly_cache->load();

        $this->output->writeln(
            '<info>Loaded <comment>' . count($cache->getAll()) . '</comment> cached settings from:</info> ' .
            $cache->getLocation()
        );
        $this->output->writeln('');

        return $this->readonly_cache;
    }

Creates a cache instance and tries to load it according to command line argument or config.

The cache is used in the runner to allow checks to access old values that may already have
been configured and thus improve their flow and e.g. not ask values again or just confirm them.

@return IReadOnlyCache cache instance

Creates a cache instance and tries to load it according to command line argument or config .


protected function initialize(InputInterface $input, OutputInterface $output)
    {
        parent::initialize($input, $output); // necessary to register autoloader

        $config = $input->getOption('config');
        if (!empty($config)) {
            if (!is_readable($config)) {
                throw new \InvalidArgumentException('Config file path "' . $config . '" is not readable.');
            }

            $this->config_path = $config;

            if ($input->getOption('verbose')) {
                $output->writeln('<comment>Config file path specified: ' . $this->config_path . '</comment>');
            }
        } else {
            $this->config_path = $this->getCurrentWorkingDirectory();

            if ($input->getOption('verbose')) {
                $output->writeln(
                    '<comment>Config file path not specified, using "' . $this->config_path .
                    '" as default lookup location.</comment>'
                );
            }
        }

        $config_handler_implementor = $input->getOption('config-handler');
        if (empty($config_handler_implementor)) {
            $config_handler_implementor = 'Environaut\Config\ConfigHandler';
        }

        $this->config_handler = new $config_handler_implementor();
        $this->config_handler->addLocation($this->config_path);

        // TODO allow multiple locations for config option?
        // $config_reader->setLocations(array($this->config_path));
    }

Initializes the command just after the input has been validated.

@param InputInterface $input An InputInterface instance
@param OutputInterface $output An OutputInterface instance

Initializes the command just after the input has been validated .


public function read($command, $eol = PHP_EOL)
    {
        exec($command, $output);
        return implode($eol, $output);
    }

public function read ( $ command , $ eol = PHP_EOL ) { exec ( $ command , $ output ) ; return implode ( $ eol , $ output ) ; }

reads the result of a command.

@param string $command
@param string $eol
@return string


public function flush(
        $command,
        array $streams,
        array &$pipes = [],
        $cwd = null,
        array $env = null,
        array $options = []
    ) {
        $process = proc_open($command, $streams, $pipes, $cwd, $env, $options);
        if (!is_resource($process)) {
            throw new \RuntimeException('Error to open the process');
        }
        return proc_close($process);
    }

public
function
flush
(
$
command
,
array
$
streams
,
array
&
$
pipes
=
[
]
,
$
cwd
=
,
array
$
env
=
,
array
$
options
=
[
]
)
{
$
process
=
proc_open
(
$
command
,
$
streams
,
$
pipes
,
$
cwd
,
$
env
,
$
options
)
;
if
(
!
is_resource
(
$
process
)
)
{
throw
new
\
RuntimeException
(
'Error to open the process'
)
;
}
return
proc_close
(
$
process
)
;
}

Links the command with the current STD streams.

@param string $command
@param array $streams
@param array $pipes
@param string $cwd
@param array $env
@param array $options
@return int

Links the command with the current STD streams .


protected function valueIsChainable($value): bool
    {
        $chainableObjects = $this->getChainableObjects();
        if (! is_object($value)) {
            return false;
        } elseif (in_array('object', $chainableObjects)) {
            return true;
        } else {
            $isInstanceOf = function (string $chainable) use ($value) {
                return $value instanceof $chainable;
            };
            return count(array_filter($chainableObjects, $isInstanceOf)) !== 0;
        }
    }

protected function valueIsChainable ( $ value ) : bool { $ chainableObjects = $ this -> getChainableObjects ( ) ; if ( ! is_object ( $ value ) ) { return false ; } elseif ( in_array ( 'object' , $ chainableObjects ) ) { return true ; } else { $ isInstanceOf = function ( string $ chainable ) use ( $ value ) { return $ value instanceof $ chainable ; } ; return count ( array_filter ( $ chainableObjects , $ isInstanceOf ) ) !== 0 ; } }

Whether or not the given value is a chainable object.

@param mixed $value
@return bool

Whether or not the given value is a chainable object .


protected function validateForm($cleanError = true)
    {
        if($cleanError == true)
        {
            $this->validateErrors = array();
        }
        $this->dataPanel->rewind();
        while($this->dataPanel->valid())
        {
            /* @var $element Element */
            $element = $this->dataPanel->current();
            if($element->label)
            {
                $elementName = $element->label;
            }
            else
            {
                $elementName = $element->text;
            }
            if ($element->checkRequired() === true &&
                    ($element->value==null || $element->value == ""))
            {
                $errorMessage = $this->getMessage("FORM_ELEMENT_REQUIRED",array($elementName));
                $this->validateErrors[$element->objectName] = $errorMessage;
                //return false;
            }
            elseif ($element->value!==null && $element->Validate() == false)
            {
                $validateService = Openbizx::getService(VALIDATE_SERVICE);
                $errorMessage = $this->getMessage("FORM_ELEMENT_INVALID_INPUT",array($elementName,$value,$element->validator));
                if ($errorMessage == false)
                { //Couldn't get a clear error message so let's try this
                    $errorMessage = $validateService->getErrorMessage($element->validator, $elementName);
                }
                $this->validateErrors[$element->objectName] = $errorMessage;
                //return false;
            }
            $this->dataPanel->next() ;
        }
        if (count($this->validateErrors) > 0)
        {
            throw new Openbizx\Validation\Exception($this->validateErrors);
            return false;
        }
        return true;
    }

Validate input on EasyForm level
default form validation do nothing.
developers need to override this method to implement their logic

@return boolean

Validate input on EasyForm level default form validation do nothing . developers need to override this method to implement their logic


public function isSatisfiedBy(GroupItem $item)
    {
        $field_name = $this->field_name;

        if(in_array($item->$field_name, $this->val)){
            return ($item->$field_name == $this->val);
        }else{
            return ($item->$field_name == $this->val);
        }
    }

public function isSatisfiedBy ( GroupItem $ item ) { $ field_name = $ this -> field_name ; if ( in_array ( $ item -> $ field_name , $ this -> val ) ) { return ( $ item -> $ field_name == $ this -> val ) ; } else { return ( $ item -> $ field_name == $ this -> val ) ; } }

Checks if given item meets all criteria

@param GroupItem $item

@return bool


public function completeFlow(ClientEntity $client)
    {
        // Validate any scopes that are in the request
        $scopeParam = $this->server->getRequestHandler()->getParam('scope');
        $scopes = $this->validateScopes($scopeParam, $client);

        // Create a new session
        $session = new SessionEntity($this->server);
        $session->setOwner('client', $client->getId());
        $session->associateClient($client);

        // Generate an access token
        $accessToken = new AccessTokenEntity($this->server);
        $accessToken->setId();
        $accessToken->setExpireTime($this->getAccessTokenTTL() + time());

        // Associate scopes with the session and access token
        foreach ($scopes as $scope) {
            $session->associateScope($scope);
        }

        foreach ($session->getScopes() as $scope) {
            $accessToken->associateScope($scope);
        }

        // Save everything
        $session->save();
        $accessToken->setSession($session);
        $accessToken->save();

        $this->server->getTokenType()->setSession($session);
        $this->server->getTokenType()->setParam('access_token', $accessToken->getId());
        $this->server->getTokenType()->setParam('expires_in', $this->getAccessTokenTTL());

        return $this->server->getTokenType()->generateResponse();
    }

Complete the client credentials grant

@return array

@throws


public function getSqlValue($input = null)
    {
        $value = ($input !== null) ? $input : $this->value;
        if ($value === null) {
            return "";
        }
        /*
          if ($this->type != 'Number')
          {
          if (get_magic_quotes_gpc() == 0) {
          $val = addcslashes($value, "\000\n\r\\'\"\032");
          }
          return "'$value'";
          }
         */

        return $value;
    }

Get string used in sql - with single quote, or without single quote in case of number

@param mixed $input the value to add quote. If null, use the current field value
@return string string used in sql

Get string used in sql - with single quote or without single quote in case of number


public function getValue($formatted = true)
    {
        // need to ensure that value are retrieved from source/cache
        //if ($this->getDataObj()->CheckDataRetrieved() == false)
        //$this->getDataObj()->getActiveRecord();

        if ($this->_prevValue == $this->value) {
            return $this->_getValueCache;
        }
        //$value = stripcslashes($this->value);
        $value = $this->value;
        if ($this->valueExpression && trim($this->column) == "") {
            $value = Expression::evaluateExpression($this->valueExpression, $this->getDataObj());
        }
        if ($this->format && $formatted) {
            $value = Openbizx::$app->getTypeManager()->valueToFormattedString($this->type, $this->format, $value);
        }
        $this->_prevValue = $this->value;
        $this->_getValueCache = $value;
        return $value;
    }

Get the value of the field.

@param boolean $formatted true if want to get the formatted value
@return mixed string or number depending on the field type


public function saveOldValue($value = null)
    {
        if ($value) {
            $this->oldValue = $value;
        } else {
            $this->oldValue = $this->value;
        }
    }

public function saveOldValue ( $ value = null ) { if ( $ value ) { $ this -> oldValue = $ value ; } else { $ this -> oldValue = $ this -> value ; } }

Save the old value to an internal variable

@param mixed $value
@return void


public function getDefaultValue()
    {
        if ($this->defaultValue !== null) {
            return Expression::evaluateExpression($this->defaultValue, $this->getDataObj());
        }
        return "";
    }

public function getDefaultValue ( ) { if ( $ this -> defaultValue !== null ) { return Expression :: evaluateExpression ( $ this -> defaultValue , $ this -> getDataObj ( ) ) ; } return "" ; }

Get default value of the field

@return string the default value of the field


public function getValueOnCreate()
    {
        if ($this->valueOnCreate !== null) {
            return $this->getSqlValue(Expression::evaluateExpression($this->valueOnCreate, $this->getDataObj()));
        }
        return "";
    }

public function getValueOnCreate ( ) { if ( $ this -> valueOnCreate !== null ) { return $ this -> getSqlValue ( Expression :: evaluateExpression ( $ this -> valueOnCreate , $ this -> getDataObj ( ) ) ) ; } return "" ; }

Get the value when a new record is created

@return mixed the value of the field


public function getValueOnUpdate()
    {
        if ($this->valueOnUpdate !== null)
            return $this->getSqlValue(Expression::evaluateExpression($this->valueOnUpdate, $this->getDataObj()));
        return "";
    }

public function getValueOnUpdate ( ) { if ( $ this -> valueOnUpdate !== null ) return $ this -> getSqlValue ( Expression :: evaluateExpression ( $ this -> valueOnUpdate , $ this -> getDataObj ( ) ) ) ; return "" ; }

Get the value when a record is updated

@return mixed the value of the field


public function checkRequired()
    {
        if (!$this->required || $this->required == "") {
            return false;
        } elseif ($this->required == "Y") {
            $required = true;
        } elseif ($required != "N") {
            $required = false;
        } else {
            $required = Expression::evaluateExpression($this->required, $this->getDataObj());
        }
        return $required;
    }

public function checkRequired ( ) { if ( ! $ this -> required || $ this -> required == "" ) { return false ; } elseif ( $ this -> required == "Y" ) { $ required = true ; } elseif ( $ required != "N" ) { $ required = false ; } else { $ required = Expression :: evaluateExpression ( $ this -> required , $ this -> getDataObj ( ) ) ; } return $ required ; }

Check if the field is a required field

@return boolean true if the field is a required field


public function checkValueType($value = null)
    {
        if (!$value) {
            $value = $this->value;
        }
        $validator = Openbizx::getService(VALIDATE_SERVICE);
        switch ($this->type) {
            case "Number":
                $result = is_numeric($value);
                break;

            case "Text":
                $result = is_string($value);
                break;

            case "Date":
                $result = $validator->date($value);
                break;
            /*
              case "Datetime":    // zend doesn't support date time
              $result = $validator->date($value);
              break;

              case "Currency":
              $result = $validator->date($value);
              break;
             */
            case "Phone":
                $result = $validator->phone($value);
                break;

            default:
                $result = true;
                break;
        }

        return $result;
    }

Check value type

@param mixed $value
@return mixed|boolean


public function validate()
    {
        $ret = true;
        if ($this->validator)
            $ret = Expression::evaluateExpression($this->validator, $this->getDataObj());
        return $ret;
    }

public function validate ( ) { $ ret = true ; if ( $ this -> validator ) $ ret = Expression :: evaluateExpression ( $ this -> validator , $ this -> getDataObj ( ) ) ; return $ ret ; }

Check if the field has valid value

@return boolean true if validation is good


public function findFile($name, $relative = true)
    {
        if ($this->refFindTemplate === null) {
            $this->refFindTemplate = new ReflectionMethod('Twig_Loader_Filesystem', 'findTemplate');
            $this->refFindTemplate->setAccessible(true);
        }

        $name = $this->prepareName($name);
        $path = $this->refFindTemplate->invoke($this->fsloader, $name);
        return $relative ? ltrim(str_replace($this->basePath, '', $path), DIRECTORY_SEPARATOR) : $path;
    }

public function findFile ( $ name , $ relative = true ) { if ( $ this -> refFindTemplate === null ) { $ this -> refFindTemplate = new ReflectionMethod ( 'Twig_Loader_Filesystem' , 'findTemplate' ) ; $ this -> refFindTemplate -> setAccessible ( true ) ; } $ name = $ this -> prepareName ( $ name ) ; $ path = $ this -> refFindTemplate -> invoke ( $ this -> fsloader , $ name ) ; return $ relative ? ltrim ( str_replace ( $ this -> basePath , '' , $ path ) , DIRECTORY_SEPARATOR ) : $ path ; }

Find resource file path.

@param string $name
@param bool   $relative

@return string


protected function prepareName($name)
    {
        $name = preg_replace('#/{2,}#', '/', strtr($name, '\\', '/'));
        if (isset($name[0]) && static::NP_PREFIX != $name[0]) {
            $name = static::NP_PREFIX.$this->theme.'/'.$name;
        }

        return $name;
    }

protected function prepareName ( $ name ) { $ name = preg_replace ( '#/{2,}#' , '/' , strtr ( $ name , '\\' , '/' ) ) ; if ( isset ( $ name [ 0 ] ) && static :: NP_PREFIX != $ name [ 0 ] ) { $ name = static :: NP_PREFIX . $ this -> theme . '/' . $ name ; } return $ name ; }

Prepend theme namespace if namespace not set.

@param string $name
@return string

Prepend theme namespace if namespace not set .


public function useTheme($theme)
    {
        if (!in_array($theme, $this->fsloader->getNamespaces())) {
            throw new Twig_Error_Loader(sprintf('Theme "%s" not registered.', $theme));
        }

        $this->theme = $theme;
    }

public
function
useTheme
(
$
theme
)
{
if
(
!
in_array
(
$
theme
,
$
this
->
fsloader
->
getNamespaces
(
)
)
)
{
throw
new
Twig_Error_Loader
(
sprintf
(
'Theme "%s" not registered.'
,
$
theme
)
)
;
}
$
this
->
theme
=
$
theme
;
}

Set loader theme.

@param $theme
@throws Twig_Error_Loader


public function registerTheme($themeNamespace, $autoUse = true)
    {
        $basePath = $this->basePath;
        $parentNamespace = null;

        $themesInheritanceList = explode(static::NP_DELIMITER, ltrim($themeNamespace, static::NP_DELIMITER));
        while ($themeName = array_shift($themesInheritanceList)) {
            $leaf = count($themesInheritanceList);
            list($basePath, $parentNamespace) = $this->addTheme($basePath, $themeName, $parentNamespace, $leaf);
        }

        if ($autoUse) {
            $this->useTheme($parentNamespace);
        }

        return $this;
    }

public function registerTheme ( $ themeNamespace , $ autoUse = true ) { $ basePath = $ this -> basePath ; $ parentNamespace = null ; $ themesInheritanceList = explode ( static :: NP_DELIMITER , ltrim ( $ themeNamespace , static :: NP_DELIMITER ) ) ; while ( $ themeName = array_shift ( $ themesInheritanceList ) ) { $ leaf = count ( $ themesInheritanceList ) ; list ( $ basePath , $ parentNamespace ) = $ this -> addTheme ( $ basePath , $ themeName , $ parentNamespace , $ leaf ) ; } if ( $ autoUse ) { $ this -> useTheme ( $ parentNamespace ) ; } return $ this ; }

Register theme for future using.

@param string $themeNamespace Full theme namespace
@param bool $autoUse          Use this theme by default

@return $this


protected function addTheme($basePath, $themeName, $parentNamespace = null, $isContainer = false)
    {
        $themePaths = array();
        $themeNamespace = $themeName;

        /**
         * If parent namespace provided, inherit paths from parent and append parent namespace to the theme namespace.
         */
        if ($parentNamespace) {
            if (!in_array($parentNamespace, $this->fsloader->getNamespaces())) {
                throw new Twig_Error_Loader(sprintf('Parent theme "%s" not registered.', $parentNamespace));
            }

            $themePaths = $this->fsloader->getPaths($parentNamespace);
            $themeNamespace = $parentNamespace.static::NP_DELIMITER.$themeName;
        }

        /**
         * Default directory optional.
         * Default directory should be on same level with the new theme.
         */
        $themeDefaultPath = $basePath.DIRECTORY_SEPARATOR.static::DEFAULT_THEME_NAME;
        $themeDefaultPath .= $this->filesDir ? DIRECTORY_SEPARATOR . $this->filesDir : '';
        if (is_dir($themeDefaultPath)) {

            $themeDefaultNamespace = ($parentNamespace ? $parentNamespace.static::NP_DELIMITER : '');
            $themeDefaultNamespace .= static::DEFAULT_THEME_NAME;

            // Strict base name @[@parent]@base
            $this->fsloader->setPaths($themeDefaultPath, static::NP_PREFIX.$themeDefaultNamespace);

            // Add default to theme paths
            if (!in_array($themeDefaultNamespace, $themePaths)) {
                array_unshift($themePaths, $themeDefaultPath);
            }

            // Regular default name with full parent inheritance [@parent]@base
            $this->fsloader->setPaths($themePaths, $themeDefaultNamespace);

        }

        /**
         * Check if theme path directory exists.
         * In case theme is not leaf it is can be only container and it is can do not have files directory,
         * so only default path will be added to namespace paths.
         */
        $themePath = $basePath.DIRECTORY_SEPARATOR.$themeName;
        if (!is_dir($themePath)) {
            throw new Twig_Error_Loader(
                sprintf('Container directory "%s" for theme "%s" not found.', $themePath, $themeNamespace)
            );
        }

        if (!$isContainer) {

            $themeFilesPath = $this->filesDir ? $themePath.DIRECTORY_SEPARATOR.$this->filesDir : $themePath;
            if (!is_dir($themeFilesPath)) {
                throw new Twig_Error_Loader(
                    sprintf('Files directory "%s" for theme "%s" not found.', $themeFilesPath, $themeNamespace)
                );
            }

            // Add theme path to the top of paths
            if (!in_array($themeFilesPath, $themePaths)) {
                array_unshift($themePaths, $themeFilesPath);
            }

            // Strict theme namespace @[@parent]@theme
            $this->fsloader->setPaths($themeFilesPath, static::NP_PREFIX.$themeNamespace);

        }

        // Regular theme namespace [@parent]@theme
        $this->fsloader->setPaths($themePaths, $themeNamespace);

        return array($themePath, $themeNamespace);
    }

Add theme paths to loader.

@param string $basePath        Base theme path
@param string $themeName       Theme name
@param string $parentNamespace Paths would be inherited from this theme
@param bool   $isContainer     Is theme only container

@return array (new theme base path, new theme namespace)
@throws Twig_Error_Loader


public static function key2offset(array &$arr, $key)
    {
        return isset($arr[$key]) ? array_flip(array_keys($arr))[$key] : false;
    }

public static function key2offset ( array & $ arr , $ key ) { return isset ( $ arr [ $ key ] ) ? array_flip ( array_keys ( $ arr ) ) [ $ key ] : false ; }

Return the array offset corresponding to an array key.
@param  Array  &$arr
@param  strin|int $key
@return int

Return the array offset corresponding to an array key .


public static function offset2key(array &$arr, $offset)
    {
        $keys = array_keys($arr);
        return isset($keys[$offset]) ? $keys[$offset] : false;
    }

public static function offset2key ( array & $ arr , $ offset ) { $ keys = array_keys ( $ arr ) ; return isset ( $ keys [ $ offset ] ) ? $ keys [ $ offset ] : false ; }

Returns the array key corresponding to a given array offset.
@param  Array  &$arr
@param  int $offset
@return string|int

Returns the array key corresponding to a given array offset .


public static function stDeviation(array $arr)
    {
        if (!is_array($arr) || sizeof($arr) < 2) {
            return null;
        }
        $mean = self::mean($arr);
        array_walk($arr, function (&$x) use ($mean) {
            $x = ($x - $mean)*($x -$mean);

        });
        return sqrt(array_sum($arr)/(sizeof($arr)-1));
    }

public static function stDeviation ( array $ arr ) { if ( ! is_array ( $ arr ) || sizeof ( $ arr ) < 2 ) { return null ; } $ mean = self :: mean ( $ arr ) ; array_walk ( $ arr , function ( & $ x ) use ( $ mean ) { $ x = ( $ x - $ mean ) * ( $ x - $ mean ) ; } ) ; return sqrt ( array_sum ( $ arr ) / ( sizeof ( $ arr ) - 1 ) ) ; }

Returns the standard deviation of numeric array values.
@param  array  $arr
@return float|null

Returns the standard deviation of numeric array values .


public function setMiddleware($middleware): Route
    {
        if( !is_array($middleware) ){
            $middleware = [$middleware];
        }

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

        return $this;
    }

public function setMiddleware ( $ middleware ) : Route { if ( ! is_array ( $ middleware ) ) { $ middleware = [ $ middleware ] ; } $ this -> middleware = array_merge ( $ this -> middleware , $ middleware ) ; return $ this ; }

Apply middleware to this route

@param string|array $middleware
@return Route