public function toArray($entity)
    {
        $entityManager = $this->getEntityManager();
        $unitOfWork    = $entityManager->getUnitOfWork();
        $classMetadata = $this->getClassMetadata();
        $result        = [];

        foreach ($unitOfWork->getOriginalEntityData($entity) as $field => $value) {
            if ($classMetadata->hasAssociation($field)) {
                $associationMapping = $classMetadata->getAssociationMapping($field);

                // Only owning side of x-1 associations can have a FK column.
                if (!$associationMapping['isOwningSide'] || !($associationMapping['type'] & ClassMetadata::TO_ONE)) {
                    continue;
                }

                if ($value !== null) {
                    $newValId    = $unitOfWork->getEntityIdentifier($value);
                    $targetClass = $entityManager->getClassMetadata($associationMapping['targetEntity']);

                    /** @noinspection ForeachSourceInspection */
                    foreach ($associationMapping['joinColumns'] as $joinColumn) {
                        $sourceColumn = $joinColumn['name'];
                        $targetColumn = $joinColumn['referencedColumnName'];

                        if ($value === null) {
                            $result[$sourceColumn] = null;
                        } elseif ($targetClass->containsForeignIdentifier) {
                            $result[$sourceColumn] = $newValId[$targetClass->getFieldForColumn($targetColumn)];
                        } else {
                            $result[$sourceColumn] = $newValId[$targetClass->fieldNames[$targetColumn]];
                        }
                    }
                }
            } elseif ($classMetadata->hasField($field)) {
                $columnName          = $classMetadata->getFieldName($field);
                $result[$columnName] = $value;
            }
        }

        return $result;
    }

Returns the object and its properties as an array.

@param mixed $entity

@return array
@throws \Doctrine\ORM\Mapping\MappingException

Returns the object and its properties as an array .


private function filterFiles(array $files)
    {
        $result = [];
        //\React\Http\Io\UploadedFile::class;
        foreach ($files as $fileName => $file) {
            if ($file instanceof UploadedFile && $file->error !== UPLOAD_ERR_NO_FILE) {
                $result[$fileName] = $file;
            }
        }

        return $result;
    }

private function filterFiles ( array $ files ) { $ result = [ ] ; //\React\Http\Io\UploadedFile::class; foreach ( $ files as $ fileName => $ file ) { if ( $ file instanceof UploadedFile && $ file -> error !== UPLOAD_ERR_NO_FILE ) { $ result [ $ fileName ] = $ file ; } } return $ result ; }

Files filter.
@param array $files
@return UploadedFile[]


public function getSizeLimit()
    {
        // Get the lowest between post_max_size and upload_max_filesize, log a warning if the first is < than the latter
        $limit = $this->sizeToBytes(ini_get('upload_max_filesize'));
        $postLimit = $this->sizeToBytes(ini_get('post_max_size'));
        if ($postLimit > 0 && $postLimit < $limit) {
            Reaction::$app->logger->warning('PHP.ini\'s \'post_max_size\' is less than \'upload_max_filesize\'.', __METHOD__);
            $limit = $postLimit;
        }
        if ($this->maxSize !== null && $limit > 0 && $this->maxSize < $limit) {
            $limit = $this->maxSize;
        }
        if (isset($_POST['MAX_FILE_SIZE']) && $_POST['MAX_FILE_SIZE'] > 0 && $_POST['MAX_FILE_SIZE'] < $limit) {
            $limit = (int)$_POST['MAX_FILE_SIZE'];
        }

        return $limit;
    }

Returns the maximum size allowed for uploaded files.

This is determined based on four factors:

- 'upload_max_filesize' in php.ini
- 'post_max_size' in php.ini
- 'MAX_FILE_SIZE' hidden field
- [[maxSize]]

@return int the size limit for uploaded files.

Returns the maximum size allowed for uploaded files .


public function has($key)
    {
        return (isset($this->bag[$key]) || array_key_exists($key, $this->bag));
    }

public function has ( $ key ) { return ( isset ( $ this -> bag [ $ key ] ) || array_key_exists ( $ key , $ this -> bag ) ) ; }

If bag container have given key.

@param  string|int
@return bool


public function handle(Input $input, Output $output): int
    {
        $exitCode = 1;

        try {
            $exitCode = $this->console->dispatch($input, $output);
        } catch (Throwable $exception) {
            // Show the exception
            // TODO: Implement
            dd($exception);
        }

        $this->app->events()->trigger(
            ConsoleKernelHandled::class,
            [new ConsoleKernelHandled($input, $exitCode)]
        );

        return $exitCode;
    }

public
function
handle
(
Input
$
input
,
Output
$
output
)
:
int
{
$
exitCode
=
1
;
try
{
$
exitCode
=
$
this
->
console
->
dispatch
(
$
input
,
$
output
)
;
}
catch
(
Throwable
$
exception
)
{
// Show the exception
// TODO: Implement
dd
(
$
exception
)
;
}
$
this
->
app
->
events
(
)
->
trigger
(
ConsoleKernelHandled
::
class
,
[
new
ConsoleKernelHandled
(
$
input
,
$
exitCode
)
]
)
;
return
$
exitCode
;
}

Handle a console input.

@param Input  $input  The input
@param Output $output The output

@throws \Valkyrja\Http\Exceptions\HttpException

@return int


public function terminate(Input $input, int $exitCode): void
    {
        $this->app->events()->trigger(
            ConsoleKernelTerminate::class,
            [new ConsoleKernelTerminate($input, $exitCode)]
        );
    }

public function terminate ( Input $ input , int $ exitCode ) : void { $ this -> app -> events ( ) -> trigger ( ConsoleKernelTerminate :: class , [ new ConsoleKernelTerminate ( $ input , $ exitCode ) ] ) ; }

Terminate the kernel request.

@param Input $input    The input
@param int   $exitCode The response

@return void


public function accountCategories(Account $account)
    {
        $this->dataCollection->add('account', $account);

        $categoryMapper = new CategoryMapper(Database::get('money'));
        $categories     = $categoryMapper->findAllByAccountId($account->getId());

        $this->dataCollection->add('categories', $categories);

        return $this->render('Categories');
    }

public function accountCategories ( Account $ account ) { $ this -> dataCollection -> add ( 'account' , $ account ) ; $ categoryMapper = new CategoryMapper ( Database :: get ( 'money' ) ) ; $ categories = $ categoryMapper -> findAllByAccountId ( $ account -> getId ( ) ) ; $ this -> dataCollection -> add ( 'categories' , $ categories ) ; return $ this -> render ( 'Categories' ) ; }

Category component for account categories list.

@param  Account $account
@return string

Category component for account categories list .


public function run()
    {
        try {
            $this->init();
            $this->executeController();
        } catch (\Exception $e) {
            $this->logger->addCritical('Exception caught', array('exception' => $e));
            $this->response->setHttpResponseCode(500);
        }
    }

public
function
run
(
)
{
try
{
$
this
->
init
(
)
;
$
this
->
executeController
(
)
;
}
catch
(
\
Exception
$
e
)
{
$
this
->
logger
->
addCritical
(
'Exception caught'
,
array
(
'exception'
=>
$
e
)
)
;
$
this
->
response
->
setHttpResponseCode
(
500
)
;
}
}

Process the request, and generate output.

@return void

Process the request and generate output .


private function init()
    {
        $timeZone = $this->appConfig->getTimeZone();
        if (!empty($timeZone)) {
            $this->timeZone->setDefaultTimeZone($timeZone);
        }
    }

private function init ( ) { $ timeZone = $ this -> appConfig -> getTimeZone ( ) ; if ( ! empty ( $ timeZone ) ) { $ this -> timeZone -> setDefaultTimeZone ( $ timeZone ) ; } }

Initialize application using config data.

@return void

Initialize application using config data .


public function execute(array $args, FunctionProphecy $function)
    {
        if (is_string($this->exception)) {
            $classname = $this->exception;
            $reflection = new ReflectionClass($classname);
            $constructor = $reflection->getConstructor();

            if ($constructor->isPublic() && 0 == $constructor->getNumberOfRequiredParameters()) {
                throw $reflection->newInstance();
            }

            if (!$this->instantiator) {
                $this->instantiator = new Instantiator();
            }

            throw $this->instantiator->instantiate($classname);
        }

        throw $this->exception;
    }

public function execute ( array $ args , FunctionProphecy $ function ) { if ( is_string ( $ this -> exception ) ) { $ classname = $ this -> exception ; $ reflection = new ReflectionClass ( $ classname ) ; $ constructor = $ reflection -> getConstructor ( ) ; if ( $ constructor -> isPublic ( ) && 0 == $ constructor -> getNumberOfRequiredParameters ( ) ) { throw $ reflection -> newInstance ( ) ; } if ( ! $ this -> instantiator ) { $ this -> instantiator = new Instantiator ( ) ; } throw $ this -> instantiator -> instantiate ( $ classname ) ; } throw $ this -> exception ; }

Throws predefined exception.

@param array          $args
@param FunctionProphecy $function

@throws object


public function toArray()
    {
        return [
            'name' => $this->name,
            'title' => $this->title,
            'type' => $this->type,
            'value' => $this->value,
            'attributes' => $this->getAttributesData(),
        ];
    }

public function toArray ( ) { return [ 'name' => $ this -> name , 'title' => $ this -> title , 'type' => $ this -> type , 'value' => $ this -> value , 'attributes' => $ this -> getAttributesData ( ) , ] ; }

Gets all field data in an array.

@return array


public function init()
    {
        parent::init();
        $this->db = Instance::ensure($this->db, DatabaseInterface::class);
        if ($this->cache !== null) {
            $this->cache = Instance::ensure($this->cache, CacheInterface::class);
        }
    }

public function init ( ) { parent :: init ( ) ; $ this -> db = Instance :: ensure ( $ this -> db , DatabaseInterface :: class ) ; if ( $ this -> cache !== null ) { $ this -> cache = Instance :: ensure ( $ this -> cache , CacheInterface :: class ) ; } }

Initializes the application component.
This method overrides the parent implementation by establishing the database connection.

Initializes the application component . This method overrides the parent implementation by establishing the database connection .


protected function getChildrenList()
    {
        return (new Query())->from($this->itemChildTable)
            ->all($this->db)
            ->then(
                function($rows) {
                    $parents = [];
                    foreach ($rows as $row) {
                        $parents[$row['parent']][] = $row['child'];
                    }

                    return $parents;
                }
            );
    }

protected function getChildrenList ( ) { return ( new Query ( ) ) -> from ( $ this -> itemChildTable ) -> all ( $ this -> db ) -> then ( function ( $ rows ) { $ parents = [ ] ; foreach ( $ rows as $ row ) { $ parents [ $ row [ 'parent' ] ] [ ] = $ row [ 'child' ] ; } return $ parents ; } ) ; }

Returns the children for every parent.
@return ExtendedPromiseInterface with array the children list. Each array key is a parent item name,
and the corresponding array value is a list of child item names.


protected function detectLoop($parent, $child)
    {
        if ($child->name === $parent->name) {
            return reject(true);
        }

        return $this->getChildren($child->name)
            ->then(function($children) use ($parent) {
                $promises = [];
                foreach ($children as $grandchild) {
                    $promises[] = $this->detectLoop($parent, $grandchild);
                }
                return !empty($promises)
                    ? all($promises)->then(function() { return false; })
                    : false;
            }, function() {
                return false;
            });
    }

protected function detectLoop ( $ parent , $ child ) { if ( $ child -> name === $ parent -> name ) { return reject ( true ) ; } return $ this -> getChildren ( $ child -> name ) -> then ( function ( $ children ) use ( $ parent ) { $ promises = [ ] ; foreach ( $ children as $ grandchild ) { $ promises [ ] = $ this -> detectLoop ( $ parent , $ grandchild ) ; } return ! empty ( $ promises ) ? all ( $ promises ) -> then ( function ( ) { return false ; } ) : false ; } , function ( ) { return false ; } ) ; }

Checks whether there is a loop in the authorization item hierarchy.
@param Item $parent the parent item
@param Item $child the child item to be added to the hierarchy
@return ExtendedPromiseInterface with bool whether a loop exists

Checks whether there is a loop in the authorization item hierarchy .


public function invalidateCache()
    {
        $this->_checkAccessAssignments = [];
        if ($this->cache !== null) {
            $this->items = null;
            $this->rules = null;
            $this->parents = null;
            return $this->cache->delete($this->cacheKey)
                ->then(function() {
                    return true;
                }, function() {
                    return true;
                });
        }
        return resolve(true);
    }

public function invalidateCache ( ) { $ this -> _checkAccessAssignments = [ ] ; if ( $ this -> cache !== null ) { $ this -> items = null ; $ this -> rules = null ; $ this -> parents = null ; return $ this -> cache -> delete ( $ this -> cacheKey ) -> then ( function ( ) { return true ; } , function ( ) { return true ; } ) ; } return resolve ( true ) ; }

Invalidate all cache
@return ExtendedPromiseInterface


public function getLastBatchNumber() {
        $result = $this->getEntities()->createQueryBuilder()
            ->select('o, MAX(o.batch) as max_batch')
            ->from('Mitch\LaravelDoctrine\Migrations\Migration', 'o')
            ->getQuery()->getResult()[0]['max_batch'];

        return $result ?: 0;
    }

Get the last migration batch number.

@return int


public static function html($content = null, $code = 200, array $headers = [])
    {
        return new Response\Html($content, $code , $headers);
    }

public static function html ( $ content = null , $ code = 200 , array $ headers = [ ] ) { return new Response \ Html ( $ content , $ code , $ headers ) ; }

Create HTML response

@param string $content
@param int $code
@param array $headers
@return Response\Html


public static function json($content = null, $code = 200, array $headers = [])
    {
        return new Response\Json($content, $code , $headers);
    }

public static function json ( $ content = null , $ code = 200 , array $ headers = [ ] ) { return new Response \ Json ( $ content , $ code , $ headers ) ; }

Create JSON response

@param string $content
@param int $code
@param array $headers
@return Response\Json


public static function template($template, array $vars = [], $code = 200, array $headers = [])
    {
        return new Response\Template($template, $vars, $code , $headers);
    }

public static function template ( $ template , array $ vars = [ ] , $ code = 200 , array $ headers = [ ] ) { return new Response \ Template ( $ template , $ vars , $ code , $ headers ) ; }

Create template response

@param string $template
@param array $vars
@param int $code
@param array $headers
@return Response\Template


protected static function others(FileManager $fileManager, array &$parameters)
    {
        if (in_array(
            static::explain($parameters, 'Do you want to create Model layer?', '[y/n]'),
            static::POSITIVES)
        ) {
            $fileManager->execute('model');
        }
        if (in_array(
            static::explain($parameters, 'Do you want to create Repository layer?', '[y/n]'),
            self::POSITIVES
        )) {
            $fileManager->execute('repository');
        }
    }

Ask for others layers
@param FileManager $fileManager
@param array $parameters


public function getAdapter()
    {
        if ($this->_adapter instanceof Zend_Filter_Compress_CompressInterface) {
            return $this->_adapter;
        }

        $adapter = $this->_adapter;
        $options = $this->getAdapterOptions();
        if (!class_exists($adapter)) {

            if (Zend_Loader::isReadable('Zend/Filter/Compress/' . ucfirst($adapter) . '.php')) {
                $adapter = 'Zend_Filter_Compress_' . ucfirst($adapter);
            }
            Zend_Loader::loadClass($adapter);
        }

        $this->_adapter = new $adapter($options);
        if (!$this->_adapter instanceof Zend_Filter_Compress_CompressInterface) {

            throw new Zend_Filter_Exception("Compression adapter '" . $adapter . "' does not implement Zend_Filter_Compress_CompressInterface");
        }
        return $this->_adapter;
    }

Returns the current adapter, instantiating it if necessary

@return string

Returns the current adapter instantiating it if necessary


public function setAdapter($adapter)
    {
        if ($adapter instanceof Zend_Filter_Compress_CompressInterface) {
            $this->_adapter = $adapter;
            return $this;
        }
        if (!is_string($adapter)) {

            throw new Zend_Filter_Exception('Invalid adapter provided; must be string or instance of Zend_Filter_Compress_CompressInterface');
        }
        $this->_adapter = $adapter;

        return $this;
    }

Sets compression adapter

@param  string|Zend_Filter_Compress_CompressInterface $adapter Adapter to use
@return Zend_Filter_Compress


private static function setPrefix(array $config)
	{
		if(array_key_exists('prefix', $config))
		{
			static::$prefix = $config['prefix'];
		}

		// Route group prefix must be set or defined.
		if(is_null(static::$prefix))
		{
			throw new Exception(__CLASS__ . ': $prefix can not be null.');
		}
	}

Set static prefix value.

@param  array $config
@return void


private function getValue($name)
    {
        if (!$this->serverAccessor->contains($name)) {
            return null;
        }

        return $this->serverAccessor->getValue($name);
    }

private function getValue ( $ name ) { if ( ! $ this -> serverAccessor -> contains ( $ name ) ) { return null ; } return $ this -> serverAccessor -> getValue ( $ name ) ; }

Gets named http request value.

@param string $name Name of property.

@return mixed Value of property or null if not exists.


public function indexAction($offset = 0, $limit = 5, $table = null, $show = null)
    {
        return array(self::$views_dir.'hello', array(
            'altdb'=>$this->getContainer()->get('request')->getUrlArg('altdb'),
            'title' => $this->trans("Hello"),
        ));
    }

public function indexAction ( $ offset = 0 , $ limit = 5 , $ table = null , $ show = null ) { return array ( self :: $ views_dir . 'hello' , array ( 'altdb' => $ this -> getContainer ( ) -> get ( 'request' ) -> getUrlArg ( 'altdb' ) , 'title' => $ this -> trans ( "Hello" ) , ) ) ; }

The home page of the controller

@param   int     $offset   The offset used for the tables dump
@param   int     $limit    The limit used for the tables dump
@param   string  $table    The name of a table to isolate it
@param   mixed   $show     ??
@return  string            The home page view content


public function installAction()
    {
        $_altdb = $this->getContainer()->get('request')->getUrlArg('altdb');
        $SQLITE = $this->getContainer()->get('database');
        $tables = \CarteBlanche\Library\AutoObject\AutoObjectMapper::getObjectsStructure( $_altdb );
        if (!empty($tables)) {
            $installed = array();
            foreach ($tables as $table) {
                $err = $SQLITE->add_table( $table['table'], $table['structure'] );
                if (!$err) {
                    trigger_error( "An error occurred while creating table '{$table['table']}'!", E_USER_ERROR);
                }
                $installed[] = $table['table'];
            }
        }
        $this->getContainer()->get('session')
            ->setFlash("ok:".$this->trans('OK - Tables "%list%" created', array('list'=>join("', '", $installed))));
        $this->getContainer()->get('session')->commit();
        $this->getContainer()->get('router')->redirect(
            $this->getContainer()->get('router')->buildUrl('altdb',$_altdb)
        );
    }

Page of system installation

@return string The view content


public function bootErrorAction(array $errors = null)
    {
        $session = $this->getContainer()->get('session');
        $original_errors = $session->has('boot_errors') ? $session->get('boot_errors') : $errors;
        $running_user = $this->getKernel()->whoAmI();

        return array(self::$views_dir.'errors', array(
            'title'=>$this->trans('System errors'),
            'original_errors'=>$original_errors,
            'running_user' => $running_user,
            'errors'=>$errors
        ));
    }

public
function
bootErrorAction
(
array
$
errors
=
)
{
$
session
=
$
this
->
getContainer
(
)
->
get
(
'session'
)
;
$
original_errors
=
$
session
->
has
(
'boot_errors'
)
$
session
->
get
(
'boot_errors'
)
:
$
errors
;
$
running_user
=
$
this
->
getKernel
(
)
->
whoAmI
(
)
;
return
array
(
self
::
$
views_dir
.
'errors'
,
array
(
'title'
=>
$
this
->
trans
(
'System errors'
)
,
'original_errors'
=>
$
original_errors
,
'running_user'
=>
$
running_user
,
'errors'
=>
$
errors
)
)
;
}

Page of system errors

@param   null|array  $errors
@return  array


private static function getSerializer()
    {
        if (!isset(static::$_serializer)) {
            $superClosure = new \SuperClosure\Serializer();
            static::$_serializer = new \Zumba\JsonSerializer\JsonSerializer($superClosure);
        }
        return static::$_serializer;
    }

private static function getSerializer ( ) { if ( ! isset ( static :: $ _serializer ) ) { $ superClosure = new \ SuperClosure \ Serializer ( ) ; static :: $ _serializer = new \ Zumba \ JsonSerializer \ JsonSerializer ( $ superClosure ) ; } return static :: $ _serializer ; }

Get serializer instance
@return \Zumba\JsonSerializer\JsonSerializer
@see VarDumper::serialize()
@see VarDumper::unserialize()


public function incrVersion($filename)
    {
        $pat = "|^\d+$|";

        $parts = explode(".", $filename);
        $partsCount = count($parts);

        if ($partsCount == 1) {
            return $filename . ".1";
        }

        if ($partsCount == 2) {
            if (preg_match($pat, $parts[1])) {
                return $parts[0] . "." . ++$parts[1];
            }

            return $parts[0] . ".1." . $parts[1];
        }

        if (preg_match($pat, $parts[$partsCount - 1])) {
            return implode(".", array_slice($parts, 0, -1)) . "." . ++$parts[$partsCount - 1];
        }

        if (preg_match($pat, $parts[$partsCount - 2])) {
            return implode(
                ".",
                array_slice($parts, 0, -2)
            )
            . "." . ++$parts[$partsCount - 2]
            . "." . $parts[$partsCount - 1];
        }

        return implode(".", array_slice($parts, 0, -1)) . ".1." . $parts[$partsCount - 1];
    }

public function incrVersion ( $ filename ) { $ pat = "|^\d+$|" ; $ parts = explode ( "." , $ filename ) ; $ partsCount = count ( $ parts ) ; if ( $ partsCount == 1 ) { return $ filename . ".1" ; } if ( $ partsCount == 2 ) { if ( preg_match ( $ pat , $ parts [ 1 ] ) ) { return $ parts [ 0 ] . "." . ++ $ parts [ 1 ] ; } return $ parts [ 0 ] . ".1." . $ parts [ 1 ] ; } if ( preg_match ( $ pat , $ parts [ $ partsCount - 1 ] ) ) { return implode ( "." , array_slice ( $ parts , 0 , - 1 ) ) . "." . ++ $ parts [ $ partsCount - 1 ] ; } if ( preg_match ( $ pat , $ parts [ $ partsCount - 2 ] ) ) { return implode ( "." , array_slice ( $ parts , 0 , - 2 ) ) . "." . ++ $ parts [ $ partsCount - 2 ] . "." . $ parts [ $ partsCount - 1 ] ; } return implode ( "." , array_slice ( $ parts , 0 , - 1 ) ) . ".1." . $ parts [ $ partsCount - 1 ] ; }

Returns new version of filename. abc.2.ext -> abc.3.ext; abc.4 -> abc.5
abc -> abc.1
@param  string $filename Old version of filename
@return New    version of filename

Returns new version of filename . abc . 2 . ext - > abc . 3 . ext ; abc . 4 - > abc . 5 abc - > abc . 1


public function getBody($format = 'object')
    {
        if (! $this->isValidBodyFormat($format)) {
            return;
        }

        $method = 'body' . ucfirst($format);

        return call_user_func_array([$this, $method], [null]);

    }

public function getBody ( $ format = 'object' ) { if ( ! $ this -> isValidBodyFormat ( $ format ) ) { return ; } $ method = 'body' . ucfirst ( $ format ) ; return call_user_func_array ( [ $ this , $ method ] , [ null ] ) ; }

Returns the xml|json as string, array or object.

@return string|array|object

Returns the xml|json as string array or object .


protected function bodyArray()
    {
        if (is_xml($this->body)) {
            return xml_decode($this->body, true);
        }

        if (is_json($this->body)) {
            return json_decode($this->body, true);
        }

    }

protected function bodyArray ( ) { if ( is_xml ( $ this -> body ) ) { return xml_decode ( $ this -> body , true ) ; } if ( is_json ( $ this -> body ) ) { return json_decode ( $ this -> body , true ) ; } }

It return the xml|json as an array.

@return array


protected function bodyObject()
    {
        if (is_xml($this->body)) {
            return xml_decode($this->body);
        }

        if (is_json($this->body)) {
            return json_decode($this->body);
        }

    }

protected function bodyObject ( ) { if ( is_xml ( $ this -> body ) ) { return xml_decode ( $ this -> body ) ; } if ( is_json ( $ this -> body ) ) { return json_decode ( $ this -> body ) ; } }

It return the xml|json as an object.

@return array


public function getResultsFromQuery($query, $limit = 0, $connection='default')
    {
        try
        {
            $this->queryValidator->isValidQuery($query, $connection);

            $query = $this->queryValidator->getLimitedQuery($query, $limit);

            $this->dynamicRepo->setUp($connection);
            $res = $this->dynamicRepo->execute($query);

            $duration = $this->dynamicRepo->getExecutionDuration();
            $duration = number_format($duration, 7, '.', ',');

            return [
                "results" => $res,
                "duration" => $duration
            ];
        }
        catch (ParameterNotPassedException $e)
        {
            throw $e;
        }
        catch (ValidationFailedException $e)
        {
            throw $e;
        }
        catch (TypeNotValidException $e)
        {
            throw $e;
        }
        catch (DBALException $e)
        {
            $exceptionText = "There was an error when executing the query, your database's message:\n\n{$e->getPrevious()->getMessage()}";
            throw new DatabaseException($exceptionText, 500, $e);
        }
    }

Calls the dynamic repository and calls the results from the query

@param $query
@param int $limit
@param string $connection
@return array
@throws DatabaseException
@throws ParameterNotPassedException
@throws ValidationFailedException
@throws \Exception


public function setDefaults()
    {
        if ( !$this->getResponseCode() ) $this->setResponseCode(200);
        if ( !$this->getContentType() ) $this->setContentType('text/html');
        if ( !$this->getServer() ) $this->setServer('Skeetr 0.0.1');
    }

public
function
setDefaults
(
)
{
if
(
!
$
this
->
getResponseCode
(
)
)
$
this
->
setResponseCode
(
200
)
;
if
(
!
$
this
->
getContentType
(
)
)
$
this
->
setContentType
(
'text/html'
)
;
if
(
!
$
this
->
getServer
(
)
)
$
this
->
setServer
(
'Skeetr 0.0.1'
)
;
}

Sets the default server and content type headers and response code if
not is setted allready.

Sets the default server and content type headers and response code if not is setted allready .


public function setBody(Body $body)
    {
        parent::setBody($body);

        return $this->addHeaders(array(
            'Content-Length' => (string) strlen($this->body)
        ), true);
    }

public function setBody ( Body $ body ) { parent :: setBody ( $ body ) ; return $ this -> addHeaders ( array ( 'Content-Length' => ( string ) strlen ( $ this -> body ) ) , true ) ; }

Set message body

@param  string  $body the new body of the message
@return boolean Returns TRUE on success or FALSE on failure.


public function toArray($default = true)
    {
        if ( $default ) $this->setDefaults();
        return array(
            'responseCode' => $this->getResponseCode(),
            'body' => $this->getBody()->toString(),
            'headers' => $this->getHeaders()
        );
    }

public function toArray ( $ default = true ) { if ( $ default ) $ this -> setDefaults ( ) ; return array ( 'responseCode' => $ this -> getResponseCode ( ) , 'body' => $ this -> getBody ( ) -> toString ( ) , 'headers' => $ this -> getHeaders ( ) ) ; }

Returns a array with the values of this Response

@param  boolean $default if TRUE setDefaults() is called
@return array


protected function getUniqueValidationRule($field) {
        $rule = 'unique:' . get_class($this) . ',' . $field . ',' . $this->getHeadId() . ',id';

        // ignore other versions of this entity
        if($this->getHeadId()) {
            $rule .= ',headVersion,!=,' . $this->getHeadId();
        }

        return $rule;
    }

protected
function
getUniqueValidationRule
(
$
field
)
{
$
rule
=
'unique:'
.
get_class
(
$
this
)
.
','
.
$
field
.
','
.
$
this
->
getHeadId
(
)
.
',id'
;
// ignore other versions of this entity
if
(
$
this
->
getHeadId
(
)
)
{
$
rule
.=
',headVersion,!=,'
.
$
this
->
getHeadId
(
)
;
}
return
$
rule
;
}

Returns a validation rule that validates this entity for uniqueness, ignoring other versions.

@param $field
@return string

Returns a validation rule that validates this entity for uniqueness ignoring other versions .


public function fromS3($key, $expiration = null, $downloadAs = null)
    {
        $args = array();
        if (!empty($downloadAs)) {
            if (empty($expiration)) {
                throw new \RuntimeException("Unable to set download name on URL without expiration.");
            }
            $args['ResponseContentDisposition'] = 'attachment;filename='.$downloadAs;
        }

        return $this->getServiceLocator()->get('FzyCommon\Service\Aws\S3')->getObjectUrl($this->getServiceLocator()->get('FzyCommon\Service\Aws\S3\Config')->get('bucket'), $key, $expiration, $args);
    }

Returns the S3 URL for the file at the specified key.
expiration determines how long the URL will work
downlaodAs specifies what the file name should start as when downloading
@param $key
@param  null   $expiration
@param  null   $downloadAs
@return string

Returns the S3 URL for the file at the specified key . expiration determines how long the URL will work downlaodAs specifies what the file name should start as when downloading


public static function getAdapter(\ADOConnection $adoConnection)
    {
        $adoConnectionDriver = strtolower(get_class($adoConnection));
        switch ($adoConnectionDriver) {
            //case 'adodb_mysqlt':
            case 'adodb_mysqli':
                $connectionId = self::getADOConnectionId($adoConnection);
                $adapter = Mysqli::getAdapter($connectionId);
                break;
            case 'adodb_pdo':
            case 'adodb_pdo_mysql':
                $connectionId = self::getADOConnectionId($adoConnection);
                $adapter = PDO::getAdapter($connectionId);
                break;
            default:
                throw new Exception\UnsupportedDriverException(__METHOD__ . ". Driver '$adoConnectionDriver' not supported");
        }
        return $adapter;
    }

Return a Zend\Db\Adapter\Adapter connection from an existing ADODb connection

@throws Exception\UnsupportedDriverException
@throws Exception\AdoNotConnectedException when connection is not initialized

@param \ADOConnection $adoConnection
@return Adapter

Return a Zend \ Db \ Adapter \ Adapter connection from an existing ADODb connection


protected static function getADOConnectionId(\ADOConnection $adoConnection)
    {
        $connectionId = $adoConnection->_connectionID;
        if (!$connectionId) {
            throw new Exception\AdoNotConnectedException(__METHOD__ . ". Error: Invalid usage, adodb connection must be connected before use (see connect(), pconnect()");
        }
        return $connectionId;
    }

Return internal adodb internal connection id
@throws Exception\AdoNotConnectedException when connection is not initialized
@param \ADOConnection $adoConnection
@return \MySQLI|\PDO


public function actionError(RequestApplicationInterface $app, \Throwable $exception) {
        $logMessage = get_class($exception);
        if ($exception->getMessage()) {
            $logMessage .= "\n" . $exception->getMessage();
        }
        if ($exception->getFile() || $exception->getLine()) {
            $logMessage .= "\n" . $exception->getFile() . ":" . $exception->getLine();
        }
        \Reaction::$app->logger->logRaw($logMessage);
    }

public function actionError ( RequestApplicationInterface $ app , \ Throwable $ exception ) { $ logMessage = get_class ( $ exception ) ; if ( $ exception -> getMessage ( ) ) { $ logMessage .= "\n" . $ exception -> getMessage ( ) ; } if ( $ exception -> getFile ( ) || $ exception -> getLine ( ) ) { $ logMessage .= "\n" . $ exception -> getFile ( ) . ":" . $ exception -> getLine ( ) ; } \ Reaction :: $ app -> logger -> logRaw ( $ logMessage ) ; }

Show error to user
@param RequestApplicationInterface $app
@param \Throwable                  $exception


protected static function wrapCurlError($ch)
    {
        $nativeCode = curl_errno($ch);
        $message    = 'Curl error: ' . curl_error($ch);
        if (!isset(self::$errorMap[$nativeCode])) {
            return new HTTP_Request2_Exception($message, 0, $nativeCode);
        } else {
            $class = self::$errorMap[$nativeCode][0];
            $code  = empty(self::$errorMap[$nativeCode][1])
                     ? 0 : self::$errorMap[$nativeCode][1];
            return new $class($message, $code, $nativeCode);
        }
    }

protected
static
function
wrapCurlError
(
$
ch
)
{
$
nativeCode
=
curl_errno
(
$
ch
)
;
$
message
=
'Curl error: '
.
curl_error
(
$
ch
)
;
if
(
!
isset
(
self
::
$
errorMap
[
$
nativeCode
]
)
)
{
return
new
HTTP_Request2_Exception
(
$
message
,
0
,
$
nativeCode
)
;
}
else
{
$
class
=
self
::
$
errorMap
[
$
nativeCode
]
[
0
]
;
$
code
=
empty
(
self
::
$
errorMap
[
$
nativeCode
]
[
1
]
)
0
:
self
::
$
errorMap
[
$
nativeCode
]
[
1
]
;
return
new
$
class
(
$
message
,
$
code
,
$
nativeCode
)
;
}
}

Creates a subclass of HTTP_Request2_Exception from curl error data

@param resource $ch curl handle

@return HTTP_Request2_Exception


protected function callbackReadBody($ch, $fd, $length)
    {
        if (!$this->eventSentHeaders) {
            $this->request->setLastEvent(
                'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
            );
            $this->eventSentHeaders = true;
        }
        if (in_array($this->request->getMethod(), self::$bodyDisallowed)
            || 0 == $this->contentLength || $this->position >= $this->contentLength
        ) {
            return '';
        }
        if (is_string($this->requestBody)) {
            $string = substr($this->requestBody, $this->position, $length);
        } elseif (is_resource($this->requestBody)) {
            $string = fread($this->requestBody, $length);
        } else {
            $string = $this->requestBody->read($length);
        }
        $this->request->setLastEvent('sentBodyPart', strlen($string));
        $this->position += strlen($string);
        return $string;
    }

protected function callbackReadBody ( $ ch , $ fd , $ length ) { if ( ! $ this -> eventSentHeaders ) { $ this -> request -> setLastEvent ( 'sentHeaders' , curl_getinfo ( $ ch , CURLINFO_HEADER_OUT ) ) ; $ this -> eventSentHeaders = true ; } if ( in_array ( $ this -> request -> getMethod ( ) , self :: $ bodyDisallowed ) || 0 == $ this -> contentLength || $ this -> position >= $ this -> contentLength ) { return '' ; } if ( is_string ( $ this -> requestBody ) ) { $ string = substr ( $ this -> requestBody , $ this -> position , $ length ) ; } elseif ( is_resource ( $ this -> requestBody ) ) { $ string = fread ( $ this -> requestBody , $ length ) ; } else { $ string = $ this -> requestBody -> read ( $ length ) ; } $ this -> request -> setLastEvent ( 'sentBodyPart' , strlen ( $ string ) ) ; $ this -> position += strlen ( $ string ) ; return $ string ; }

Callback function called by cURL for reading the request body

@param resource $ch     cURL handle
@param resource $fd     file descriptor (not used)
@param integer  $length maximum length of data to return

@return   string      part of the request body, up to $length bytes


protected function callbackWriteHeader($ch, $string)
    {
        // we may receive a second set of headers if doing e.g. digest auth
        if ($this->eventReceivedHeaders || !$this->eventSentHeaders) {
            // don't bother with 100-Continue responses (bug #15785)
            if (!$this->eventSentHeaders
                || $this->response->getStatus() >= 200
            ) {
                $this->request->setLastEvent(
                    'sentHeaders', curl_getinfo($ch, CURLINFO_HEADER_OUT)
                );
            }
            $upload = curl_getinfo($ch, CURLINFO_SIZE_UPLOAD);
            // if body wasn't read by a callback, send event with total body size
            if ($upload > $this->position) {
                $this->request->setLastEvent(
                    'sentBodyPart', $upload - $this->position
                );
                $this->position = $upload;
            }
            if ($upload && (!$this->eventSentHeaders
                            || $this->response->getStatus() >= 200)
            ) {
                $this->request->setLastEvent('sentBody', $upload);
            }
            $this->eventSentHeaders = true;
            // we'll need a new response object
            if ($this->eventReceivedHeaders) {
                $this->eventReceivedHeaders = false;
                $this->response             = null;
            }
        }
        if (empty($this->response)) {
            $this->response = new HTTP_Request2_Response(
                $string, false, curl_getinfo($ch, CURLINFO_EFFECTIVE_URL)
            );
        } else {
            $this->response->parseHeaderLine($string);
            if ('' == trim($string)) {
                // don't bother with 100-Continue responses (bug #15785)
                if (200 <= $this->response->getStatus()) {
                    $this->request->setLastEvent('receivedHeaders', $this->response);
                }

                if ($this->request->getConfig('follow_redirects') && $this->response->isRedirect()) {
                    $redirectUrl = new Net_URL2($this->response->getHeader('location'));

                    // for versions lower than 5.2.10, check the redirection URL protocol
                    if (!defined('CURLOPT_REDIR_PROTOCOLS') && $redirectUrl->isAbsolute()
                        && !in_array($redirectUrl->getScheme(), array('http', 'https'))
                    ) {
                        return -1;
                    }

                    if ($jar = $this->request->getCookieJar()) {
                        $jar->addCookiesFromResponse($this->response, $this->request->getUrl());
                        if (!$redirectUrl->isAbsolute()) {
                            $redirectUrl = $this->request->getUrl()->resolve($redirectUrl);
                        }
                        if ($cookies = $jar->getMatching($redirectUrl, true)) {
                            curl_setopt($ch, CURLOPT_COOKIE, $cookies);
                        }
                    }
                }
                $this->eventReceivedHeaders = true;
            }
        }
        return strlen($string);
    }

Callback function called by cURL for saving the response headers

@param resource $ch     cURL handle
@param string   $string response header (with trailing CRLF)

@return   integer     number of bytes saved
@see      HTTP_Request2_Response::parseHeaderLine()


protected function callbackWriteBody($ch, $string)
    {
        // cURL calls WRITEFUNCTION callback without calling HEADERFUNCTION if
        // response doesn't start with proper HTTP status line (see bug #15716)
        if (empty($this->response)) {
            throw new HTTP_Request2_MessageException(
                "Malformed response: {$string}",
                HTTP_Request2_Exception::MALFORMED_RESPONSE
            );
        }
        if ($this->request->getConfig('store_body')) {
            $this->response->appendBody($string);
        }
        $this->request->setLastEvent('receivedBodyPart', $string);
        return strlen($string);
    }

Callback function called by cURL for saving the response body

@param resource $ch     cURL handle (not used)
@param string   $string part of the response body

@return   integer     number of bytes saved
@throws   HTTP_Request2_MessageException
@see      HTTP_Request2_Response::appendBody()


public function addCommandCollection(CommandCollection $collection)
	{
		$collection->setConsole($this);
		$class = new ClassType($collection);
		$this->collections[Strings::lower($class->getShortName())] = $collection;
	}

public function addCommandCollection ( CommandCollection $ collection ) { $ collection -> setConsole ( $ this ) ; $ class = new ClassType ( $ collection ) ; $ this -> collections [ Strings :: lower ( $ class -> getShortName ( ) ) ] = $ collection ; }

Prida kolekci prikazu
@param CommandCollection $collection


private function printTime(string $text): void
	{
		$line = '[' . date('d.m.Y H:i:s', time()) . '] ' . $text;
		$this->printLine($line);
	}

private
function
printTime
(
string
$
text
)
:
void
{
$
line
=
'['
.
date
(
'd.m.Y H:i:s'
,
time
(
)
)
.
'] '
.
$
text
;
$
this
->
printLine
(
$
line
)
;
}


private function printConsoleHelp(ClassType $class): void
	{
		$this->printLine($class->getDescription());
		$this->printLine();

		foreach ($this->getMethod($class) as $method) {
			$line = $class->getShortName() . ':' . $method->name;

			foreach ($method->getParameters() as $param) {
				$line .= ' /' . $param->getName();
				if ($param->isDefaultValueAvailable()) {
					$line .= '=' . $this->getValue($param->getDefaultValue());
				}
			}
			$description = $method->getDescription();
			if (!empty($description)) {
				$line .= "\t\t(" . Strings::replace($description, '/\ +/', ' ') . ')';
			}
			$this->printLine($line);
		}
		$this->printLine();
	}

private
function
printConsoleHelp
(
ClassType
$
class
)
:
void
{
$
this
->
printLine
(
$
class
->
getDescription
(
)
)
;
$
this
->
printLine
(
)
;
foreach
(
$
this
->
getMethod
(
$
class
)
as
$
method
)
{
$
line
=
$
class
->
getShortName
(
)
.
':'
.
$
method
->
name
;
foreach
(
$
method
->
getParameters
(
)
as
$
param
)
{
$
line
.=
' /'
.
$
param
->
getName
(
)
;
if
(
$
param
->
isDefaultValueAvailable
(
)
)
{
$
line
.=
'='
.
$
this
->
getValue
(
$
param
->
getDefaultValue
(
)
)
;
}
}
$
description
=
$
method
->
getDescription
(
)
;
if
(
!
empty
(
$
description
)
)
{
$
line
.=
"\t\t("
.
Strings
::
replace
(
$
description
,
'/\ +/'
,
' '
)
.
')'
;
}
$
this
->
printLine
(
$
line
)
;
}
$
this
->
printLine
(
)
;
}

Vypise napovedu pro danou tridu v konzoli
@param ClassType $class


private function printHtmlHelp(ClassType $class): void
	{
		$desc = Html::el('h1');
		$desc->setText($class->getDescription());
		$this->printLine((string) $desc);

		foreach ($this->getMethod($class) as $method) {
			$desc = Html::el('pre');
			$desc->setStyle('margin-bottom: 0px');
			$desc->setText(Strings::replace($method->getDocComment(), '/(\ |\t)+/', ' '));

			$el = Html::el('a');
			$el->setHtml($method->name);

			$args = '';
			$params = [];
			foreach ($method->getParameters() as $param) {
				$p = $param->getName();
				if ($param->isDefaultValueAvailable()) {
					$value = $param->getDefaultValue();
					$p .= '=' . $this->getValue($value);
				} else {
					$args .= (empty($args) ? '?' : '&') . $param->getName() . '=';
				}
				$params[] = $p;
			}

			$link = Strings::lower(str_replace(':', '/', $this->prefix . '/' . $class->getShortName()) . '/' . $method->name);
			$el->href('/' . $link . $args);

			$line = $desc . $el;
			if (!empty($params)) {
				$line .= ' (' . implode(', ', $params) . ')';
			}
			$this->printLine($line);
		}
	}

private
function
printHtmlHelp
(
ClassType
$
class
)
:
void
{
$
desc
=
Html
::
el
(
'h1'
)
;
$
desc
->
setText
(
$
class
->
getDescription
(
)
)
;
$
this
->
printLine
(
(
string
)
$
desc
)
;
foreach
(
$
this
->
getMethod
(
$
class
)
as
$
method
)
{
$
desc
=
Html
::
el
(
'pre'
)
;
$
desc
->
setStyle
(
'margin-bottom: 0px'
)
;
$
desc
->
setText
(
Strings
::
replace
(
$
method
->
getDocComment
(
)
,
'/(\ |\t)+/'
,
' '
)
)
;
$
el
=
Html
::
el
(
'a'
)
;
$
el
->
setHtml
(
$
method
->
name
)
;
$
args
=
''
;
$
params
=
[
]
;
foreach
(
$
method
->
getParameters
(
)
as
$
param
)
{
$
p
=
$
param
->
getName
(
)
;
if
(
$
param
->
isDefaultValueAvailable
(
)
)
{
$
value
=
$
param
->
getDefaultValue
(
)
;
$
p
.=
'='
.
$
this
->
getValue
(
$
value
)
;
}
else
{
$
args
.=
(
empty
(
$
args
)
'?'
:
'&'
)
.
$
param
->
getName
(
)
.
'='
;
}
$
params
[
]
=
$
p
;
}
$
link
=
Strings
::
lower
(
str_replace
(
':'
,
'/'
,
$
this
->
prefix
.
'/'
.
$
class
->
getShortName
(
)
)
.
'/'
.
$
method
->
name
)
;
$
el
->
href
(
'/'
.
$
link
.
$
args
)
;
$
line
=
$
desc
.
$
el
;
if
(
!
empty
(
$
params
)
)
{
$
line
.=
' ('
.
implode
(
', '
,
$
params
)
.
')'
;
}
$
this
->
printLine
(
$
line
)
;
}
}

Vypise napovedu pro danou tridu v HTML
@param ClassType $class


public function printLine(string $string = null): void
	{
		if ($string !== null) {
			echo $string;
		}
		if ($this->isConsole) {
			echo "\n";
		} else {
			echo '<br/>';
		}
	}

public function printLine ( string $ string = null ) : void { if ( $ string !== null ) { echo $ string ; } if ( $ this -> isConsole ) { echo "\n" ; } else { echo '<br/>' ; } }

Vypise retezec na jeden radek
@param string $string


public function __async_upload()
    {
        /** @var array $result Asynchronous result array */
        $result = array('status' => false);
        /** @var \samsonphp\upload\Upload $upload  Pointer to uploader object */
        $upload = null;
        // If file was uploaded
        if (uploadFile($upload)) {
            $result['status'] = true;
            $result['tag'] = '<img src="' . $upload->fullPath() . '">';
        }
        // Return result
        return $result;
    }

Function to upload images into WYSIWYG

@return array Asynchronous result


public function __async_clearHtml()
    {
        // Tags that do not change
        $allowed_tags = '

';
        // Getting html value
        $html = json_decode(file_get_contents('php://input'), true);
        // Replace tags class
        $html = strip_tags($html['html'], $allowed_tags);
        // Replace tags class
        $html = preg_replace("/<([^>]*)(class)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace tags lang
        $html = preg_replace("/<([^>]*)(lang)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace tags style
        $html = preg_replace("/<([^>]*)(style)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace tags size
        $html = preg_replace("/<([^>]*)(size)=(\"[^\"]*\"|'[^']*'|[^>]+)([^>]*)>/","<\$1>", $html);
        // Replace all transfers and
        $html = str_replace(array("\r\n", "\r", "\n", ' '), ' ', $html);
        // Replace empty tags p and b
        $html = str_replace(array("

", "

", " ", ""), '', $html);
        // Added border to table
        $html = str_replace(array(" $html);
    }

The function is intended for cleaning html code
@return array


public function beforeSave($event)
    {
        foreach ($this->attributes as $name) {
            if (!empty($this->owner->$name)) {
                $this->owner->$name = $this->jsonEncodeAttribute($name);
            } else {
                $this->owner->$name = null;
            }
        }
    }

public function beforeSave ( $ event ) { foreach ( $ this -> attributes as $ name ) { if ( ! empty ( $ this -> owner -> $ name ) ) { $ this -> owner -> $ name = $ this -> jsonEncodeAttribute ( $ name ) ; } else { $ this -> owner -> $ name = null ; } } }

Actions to take before saving the owner of this behavior.
@param CModelEvent $event event parameter.

Actions to take before saving the owner of this behavior .


public function afterFind($event)
    {
        foreach ($this->attributes as $name) {
            $this->owner->$name = $this->jsonDecodeAttribute($name);
        }
    }

public function afterFind ( $ event ) { foreach ( $ this -> attributes as $ name ) { $ this -> owner -> $ name = $ this -> jsonDecodeAttribute ( $ name ) ; } }

Actions to take after loading the owner of this behavior.
@param CEvent $event event parameter.

Actions to take after loading the owner of this behavior .


public function jsonDecodeAttribute($name, $assoc = true, $depth = 512)
    {
        $string = json_decode($this->owner->$name, $assoc, $depth);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new CException(sprintf('Failed to decode JSON attribute "%s".', $name));
        }
        return $string;
    }

public
function
jsonDecodeAttribute
(
$
name
,
$
assoc
=
true
,
$
depth
=
512
)
{
$
string
=
json_decode
(
$
this
->
owner
->
$
name
,
$
assoc
,
$
depth
)
;
if
(
json_last_error
(
)
!==
JSON_ERROR_NONE
)
{
throw
new
CException
(
sprintf
(
'Failed to decode JSON attribute "%s".'
,
$
name
)
)
;
}
return
$
string
;
}

JSON decodes the given attribute on the owner of this behavior.
@param string $name name of the attribute.
@param bool $assoc whether the result should be an associated array (default to true).
@param int $depth recursion depth.
@return string the decoded value.
@throws CException if the value cannot be decoded.

JSON decodes the given attribute on the owner of this behavior .


public static function create(Bank $bank, $type)
    {
        if (!isset(self::$allowedTypes[$type])) {
            throw new \Exception('Type is not allowed!');
        }

        $class = __NAMESPACE__ . '\\' . $bank->getParser();

        if (!class_exists($class)) {
            throw new \Exception();
        }

        return new $class();
    }

public
static
function
create
(
Bank
$
bank
,
$
type
)
{
if
(
!
isset
(
self
::
$
allowedTypes
[
$
type
]
)
)
{
throw
new
\
Exception
(
'Type is not allowed!'
)
;
}
$
class
=
__NAMESPACE__
.
'\\'
.
$
bank
->
getParser
(
)
;
if
(
!
class_exists
(
$
class
)
)
{
throw
new
\
Exception
(
)
;
}
return
new
$
class
(
)
;
}

Create new parser.

@param  Bank $bank
@param  string $type
@return ParserInterface
@throws \Exception


public function setLocale($locale = null)
    {
        if (is_string($locale)) {
            $locale = array($locale);
        } elseif ($locale instanceof Zend_Locale) {
            $locale = array($locale->toString());
        } elseif (!is_array($locale)) {

            throw new Zend_Filter_Exception('Locale has to be string, array or an instance of Zend_Locale');
        }

        foreach ($locale as $single) {
            if (!Zend_Locale::isLocale($single)) {

                throw new Zend_Filter_Exception("Unknown locale '$single'");
            }
        }

        $this->_locale = $locale;
        return $this;
    }

Set the locales which are accepted

@param  string|array|Zend_Locale $locale
@throws Zend_Filter_Exception
@return Zend_Filter_Boolean


protected function _getLocalizedQuestion($value, $yes, $locale)
    {
        if ($yes == true) {
            $question = 'yes';
            $return   = true;
        } else {
            $question = 'no';
            $return   = false;
        }
        $str = Zend_Locale::getTranslation($question, 'question', $locale);
        $str = explode(':', $str);
        if (!empty($str)) {
            foreach($str as $no) {
                if (($no == $value) || (strtolower($no) == strtolower($value))) {
                    return $return;
                }
            }
        }
    }

protected function _getLocalizedQuestion ( $ value , $ yes , $ locale ) { if ( $ yes == true ) { $ question = 'yes' ; $ return = true ; } else { $ question = 'no' ; $ return = false ; } $ str = Zend_Locale :: getTranslation ( $ question , 'question' , $ locale ) ; $ str = explode ( ':' , $ str ) ; if ( ! empty ( $ str ) ) { foreach ( $ str as $ no ) { if ( ( $ no == $ value ) || ( strtolower ( $ no ) == strtolower ( $ value ) ) ) { return $ return ; } } } }

Determine the value of a localized string, and compare it to a given value

@param  string $value
@param  boolean $yes
@param  array $locale
@return boolean

Determine the value of a localized string and compare it to a given value


protected function establishTunnel()
    {
        $donor   = new self;
        $connect = new HTTP_Request2(
            $this->request->getUrl(), HTTP_Request2::METHOD_CONNECT,
            array_merge($this->request->getConfig(), array('adapter' => $donor))
        );
        $response = $connect->send();
        // Need any successful (2XX) response
        if (200 > $response->getStatus() || 300 <= $response->getStatus()) {
            throw new HTTP_Request2_ConnectionException(
                'Failed to connect via HTTPS proxy. Proxy response: ' .
                $response->getStatus() . ' ' . $response->getReasonPhrase()
            );
        }
        $this->socket = $donor->socket;
        $this->socket->enableCrypto();
    }

Establishes a tunnel to a secure remote server via HTTP CONNECT request

This method will fail if 'ssl_verify_peer' is enabled. Probably because PHP
sees that we are connected to a proxy server (duh!) rather than the server
that presents its certificate.

@link     http://tools.ietf.org/html/rfc2817#section-5.2
@throws   HTTP_Request2_Exception


protected function canKeepAlive($requestKeepAlive, HTTP_Request2_Response $response)
    {
        // Do not close socket on successful CONNECT request
        if (HTTP_Request2::METHOD_CONNECT == $this->request->getMethod()
            && 200 <= $response->getStatus() && 300 > $response->getStatus()
        ) {
            return true;
        }

        $lengthKnown = 'chunked' == strtolower($response->getHeader('transfer-encoding'))
                       || null !== $response->getHeader('content-length')
                       // no body possible for such responses, see also request #17031
                       || HTTP_Request2::METHOD_HEAD == $this->request->getMethod()
                       || in_array($response->getStatus(), array(204, 304));
        $persistent  = 'keep-alive' == strtolower($response->getHeader('connection')) ||
                       (null === $response->getHeader('connection') &&
                        '1.1' == $response->getVersion());
        return $requestKeepAlive && $lengthKnown && $persistent;
    }

Checks whether current connection may be reused or should be closed

@param boolean                $requestKeepAlive whether connection could
be persistent in the first place
@param HTTP_Request2_Response $response         response object to check

@return   boolean


protected function disconnect()
    {
        if (!empty($this->socket)) {
            $this->socket = null;
            $this->request->setLastEvent('disconnect');
        }
    }

protected function disconnect ( ) { if ( ! empty ( $ this -> socket ) ) { $ this -> socket = null ; $ this -> request -> setLastEvent ( 'disconnect' ) ; } }


protected function handleRedirect(
        HTTP_Request2 $request, HTTP_Request2_Response $response
    ) {
        if (is_null($this->redirectCountdown)) {
            $this->redirectCountdown = $request->getConfig('max_redirects');
        }
        if (0 == $this->redirectCountdown) {
            $this->redirectCountdown = null;
            // Copying cURL behaviour
            throw new HTTP_Request2_MessageException(
                'Maximum (' . $request->getConfig('max_redirects') . ') redirects followed',
                HTTP_Request2_Exception::TOO_MANY_REDIRECTS
            );
        }
        $redirectUrl = new Net_URL2(
            $response->getHeader('location'),
            array(Net_URL2::OPTION_USE_BRACKETS => $request->getConfig('use_brackets'))
        );
        // refuse non-HTTP redirect
        if ($redirectUrl->isAbsolute()
            && !in_array($redirectUrl->getScheme(), array('http', 'https'))
        ) {
            $this->redirectCountdown = null;
            throw new HTTP_Request2_MessageException(
                'Refusing to redirect to a non-HTTP URL ' . $redirectUrl->__toString(),
                HTTP_Request2_Exception::NON_HTTP_REDIRECT
            );
        }
        // Theoretically URL should be absolute (see http://tools.ietf.org/html/rfc2616#section-14.30),
        // but in practice it is often not
        if (!$redirectUrl->isAbsolute()) {
            $redirectUrl = $request->getUrl()->resolve($redirectUrl);
        }
        $redirect = clone $request;
        $redirect->setUrl($redirectUrl);
        if (303 == $response->getStatus()
            || (!$request->getConfig('strict_redirects')
                && in_array($response->getStatus(), array(301, 302)))
        ) {
            $redirect->setMethod(HTTP_Request2::METHOD_GET);
            $redirect->setBody('');
        }

        if (0 < $this->redirectCountdown) {
            $this->redirectCountdown--;
        }
        return $this->sendRequest($redirect);
    }

Handles HTTP redirection

This method will throw an Exception if redirect to a non-HTTP(S) location
is attempted, also if number of redirects performed already is equal to
'max_redirects' configuration parameter.

@param HTTP_Request2          $request  Original request
@param HTTP_Request2_Response $response Response containing redirect

@return   HTTP_Request2_Response      Response from a new location
@throws   HTTP_Request2_Exception


protected function shouldUseServerDigestAuth(HTTP_Request2_Response $response)
    {
        // no sense repeating a request if we don't have credentials
        if (401 != $response->getStatus() || !$this->request->getAuth()) {
            return false;
        }
        if (!$challenge = $this->parseDigestChallenge($response->getHeader('www-authenticate'))) {
            return false;
        }

        $url    = $this->request->getUrl();
        $scheme = $url->getScheme();
        $host   = $scheme . '://' . $url->getHost();
        if ($port = $url->getPort()) {
            if ((0 == strcasecmp($scheme, 'http') && 80 != $port)
                || (0 == strcasecmp($scheme, 'https') && 443 != $port)
            ) {
                $host .= ':' . $port;
            }
        }

        if (!empty($challenge['domain'])) {
            $prefixes = array();
            foreach (preg_split('/\\s+/', $challenge['domain']) as $prefix) {
                // don't bother with different servers
                if ('/' == substr($prefix, 0, 1)) {
                    $prefixes[] = $host . $prefix;
                }
            }
        }
        if (empty($prefixes)) {
            $prefixes = array($host . '/');
        }

        $ret = true;
        foreach ($prefixes as $prefix) {
            if (!empty(self::$challenges[$prefix])
                && (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
            ) {
                // probably credentials are invalid
                $ret = false;
            }
            self::$challenges[$prefix] =& $challenge;
        }
        return $ret;
    }

Checks whether another request should be performed with server digest auth

Several conditions should be satisfied for it to return true:
- response status should be 401
- auth credentials should be set in the request object
- response should contain WWW-Authenticate header with digest challenge
- there is either no challenge stored for this URL or new challenge
contains stale=true parameter (in other case we probably just failed
due to invalid username / password)

The method stores challenge values in $challenges static property

@param HTTP_Request2_Response $response response to check

@return   boolean whether another request should be performed
@throws   HTTP_Request2_Exception in case of unsupported challenge parameters


protected function shouldUseProxyDigestAuth(HTTP_Request2_Response $response)
    {
        if (407 != $response->getStatus() || !$this->request->getConfig('proxy_user')) {
            return false;
        }
        if (!($challenge = $this->parseDigestChallenge($response->getHeader('proxy-authenticate')))) {
            return false;
        }

        $key = 'proxy://' . $this->request->getConfig('proxy_host') .
               ':' . $this->request->getConfig('proxy_port');

        if (!empty(self::$challenges[$key])
            && (empty($challenge['stale']) || strcasecmp('true', $challenge['stale']))
        ) {
            $ret = false;
        } else {
            $ret = true;
        }
        self::$challenges[$key] = $challenge;
        return $ret;
    }

protected function shouldUseProxyDigestAuth ( HTTP_Request2_Response $ response ) { if ( 407 != $ response -> getStatus ( ) || ! $ this -> request -> getConfig ( 'proxy_user' ) ) { return false ; } if ( ! ( $ challenge = $ this -> parseDigestChallenge ( $ response -> getHeader ( 'proxy-authenticate' ) ) ) ) { return false ; } $ key = 'proxy://' . $ this -> request -> getConfig ( 'proxy_host' ) . ':' . $ this -> request -> getConfig ( 'proxy_port' ) ; if ( ! empty ( self :: $ challenges [ $ key ] ) && ( empty ( $ challenge [ 'stale' ] ) || strcasecmp ( 'true' , $ challenge [ 'stale' ] ) ) ) { $ ret = false ; } else { $ ret = true ; } self :: $ challenges [ $ key ] = $ challenge ; return $ ret ; }

Checks whether another request should be performed with proxy digest auth

Several conditions should be satisfied for it to return true:
- response status should be 407
- proxy auth credentials should be set in the request object
- response should contain Proxy-Authenticate header with digest challenge
- there is either no challenge stored for this proxy or new challenge
contains stale=true parameter (in other case we probably just failed
due to invalid username / password)

The method stores challenge values in $challenges static property

@param HTTP_Request2_Response $response response to check

@return   boolean whether another request should be performed
@throws   HTTP_Request2_Exception in case of unsupported challenge parameters


protected function writeBody()
    {
        if (in_array($this->request->getMethod(), self::$bodyDisallowed)
            || 0 == $this->contentLength
        ) {
            return;
        }

        $position   = 0;
        $bufferSize = $this->request->getConfig('buffer_size');
        $headers    = $this->request->getHeaders();
        $chunked    = isset($headers['transfer-encoding']);
        while ($position < $this->contentLength) {
            if (is_string($this->requestBody)) {
                $str = substr($this->requestBody, $position, $bufferSize);
            } elseif (is_resource($this->requestBody)) {
                $str = fread($this->requestBody, $bufferSize);
            } else {
                $str = $this->requestBody->read($bufferSize);
            }
            if (!$chunked) {
                $this->socket->write($str);
            } else {
                $this->socket->write(dechex(strlen($str)) . "\r\n{$str}\r\n");
            }
            // Provide the length of written string to the observer, request #7630
            $this->request->setLastEvent('sentBodyPart', strlen($str));
            $position += strlen($str);
        }

        // write zero-length chunk
        if ($chunked) {
            $this->socket->write("0\r\n\r\n");
        }
        $this->request->setLastEvent('sentBody', $this->contentLength);
    }

Sends the request body

@throws   HTTP_Request2_MessageException


protected function readChunked($bufferSize)
    {
        // at start of the next chunk?
        if (0 == $this->chunkLength) {
            $line = $this->socket->readLine($bufferSize);
            if (!preg_match('/^([0-9a-f]+)/i', $line, $matches)) {
                throw new HTTP_Request2_MessageException(
                    "Cannot decode chunked response, invalid chunk length '{$line}'",
                    HTTP_Request2_Exception::DECODE_ERROR
                );
            } else {
                $this->chunkLength = hexdec($matches[1]);
                // Chunk with zero length indicates the end
                if (0 == $this->chunkLength) {
                    $this->socket->readLine($bufferSize);
                    return '';
                }
            }
        }
        $data = $this->socket->read(min($this->chunkLength, $bufferSize));
        $this->chunkLength -= strlen($data);
        if (0 == $this->chunkLength) {
            $this->socket->readLine($bufferSize); // Trailing CRLF
        }
        return $data;
    }

Reads a part of response body encoded with chunked Transfer-Encoding

@param int $bufferSize buffer size to use for reading

@return   string
@throws   HTTP_Request2_MessageException

Reads a part of response body encoded with chunked Transfer - Encoding


public static function sqlBuildSelect($arrSelect, $addSelect = false)
    {
        $select = null;

        if (is_array($arrSelect))
        {
            foreach ($arrSelect as $f => $v)
            {
                if ($select)  $select .= ', ';
                if (preg_match('/^(.+?):(literal)$/i', $f, $arrMatch))
                    $select .= $v;
                else
                    $select .= self::getDSN()->escape($v);
            }
        }

        if ($addSelect && $select)
            $addSelect = ' SELECT ' . $addSelect;

        return $select;
    }

public
static
function
sqlBuildSelect
(
$
arrSelect
,
$
addSelect
=
false
)
{
$
select
=
;
if
(
is_array
(
$
arrSelect
)
)
{
foreach
(
$
arrSelect
as
$
f
=>
$
v
)
{
if
(
$
select
)
$
select
.=
', '
;
if
(
preg_match
(
'/^(.+?):(literal)$/i'
,
$
f
,
$
arrMatch
)
)
$
select
.=
$
v
;
else
$
select
.=
self
::
getDSN
(
)
->
escape
(
$
v
)
;
}
}
if
(
$
addSelect
&&
$
select
)
$
addSelect
=
' SELECT '
.
$
addSelect
;
return
$
select
;
}


public static function sqlBuildWhere($arrWhere, $whereClause = true)
    {
        $where = null;
        if (is_array($arrWhere))
        {
            if ($whereClause)
                $where = ' WHERE 1 ';
            foreach ($arrWhere as $f => $v)
            {
                if ($where)
                    $where .= ' AND ';

                $field = $f;

                // special suff?
                if (preg_match('/^(.+?):(literal|int|string)$/i', $f, $arrMatch))
                {
                    $type = array_pop($arrMatch);
                    $f =  self::getDSN()->escape(array_pop($arrMatch));

                    // literal - becareful with these!!!!
                    if ($type == 'literal')
                    {
                        // make sure this literal was not passed in the URL (GET!!)
                        if (!empty($_GET['where'][$field]))
                            unset($_GET['where'][$field]);
                        else if (!empty($_POST['where'][$field]))
                            unset($_POST['where'][$field]);
                        else
                        {
                            $where .= $v;
                        }
                    }
                    else if ($type == 'int')
                        $where .= $f .' IN ('. self::getDSN()->escape($v) .') ';
                    else if ($type == 'string')
                        $where .= $f . self::sqlWhereSmartLike($v);

                    else
                        $where .= $f .' = "'. self::getDSN()->escape($v) .'" ';
                }
                else
                    $where .= $f .' = "' . self::getDSN()->escape($v) . '" ';
            }
        }

        return $where;
    }

Builds sql where criteria

@param array $arrWhere
@param bool $whereClause when true we will add where clause


public static function sqlBuildJoin($arrJoin)
    {
        $joins = null;
        if (is_array($arrJoin))
        {
            foreach ($arrJoin as $v)
            {
                $joins .= $v . " \n";
            }
            $joins = " \n" . $joins;
        }

        return  $joins;
    }

public
static
function
sqlBuildJoin
(
$
arrJoin
)
{
$
joins
=
;
if
(
is_array
(
$
arrJoin
)
)
{
foreach
(
$
arrJoin
as
$
v
)
{
$
joins
.=
$
v
.
" \n"
;
}
$
joins
=
" \n"
.
$
joins
;
}
return
$
joins
;
}

Builds sql join criters

@param array $arrJoin
ex: array('users' => 'INNER JOIN users u ON (u.user_id = f.user_id))


public static function sqlBuildGroupBy($arrGroup, $addGroup = false)
    {
        $groupBy = $group = null;

        if (is_array($arrGroup))
        {
            $group = '';
            foreach ($arrGroup as $k)
            {
                if ($group)  $group .= ', ';
                $group .= self::getDSN()->escape($k);
            }
        }

        if ($addGroup && $group)
            $groupBy = ' GROUP BY ' . $group;

        return $groupBy;
    }

public
static
function
sqlBuildGroupBy
(
$
arrGroup
,
$
addGroup
=
false
)
{
$
groupBy
=
$
group
=
;
if
(
is_array
(
$
arrGroup
)
)
{
$
group
=
''
;
foreach
(
$
arrGroup
as
$
k
)
{
if
(
$
group
)
$
group
.=
', '
;
$
group
.=
self
::
getDSN
(
)
->
escape
(
$
k
)
;
}
}
if
(
$
addGroup
&&
$
group
)
$
groupBy
=
' GROUP BY '
.
$
group
;
return
$
groupBy
;
}

Builds group by statement..

@param array $arrGroup
ex:
array('user_id' => 'user_id'),
array('user_id' => 'user_id', 'date' => 'date'),
@param bool $addGroup syntax


public static function prepareDependencyHandler($handleType, $field, &$arrField, &$arrGridPrepare, &$arrFormData)
    {
        // select fields?
        if (isset($arrField['dependency']['selectField']) && is_array($arrField['dependency']['selectField']))
        {
            foreach($arrField['dependency']['selectField'] as $f => $v)
            {
                $arrGridPrepare['selectField'][$f] = $v;
            }
        }

        // total joins
        if (isset($arrField['dependency']['joinTotal']) && is_array($arrField['dependency']['joinTotal']))
        {
            foreach($arrField['dependency']['joinTotal'] as $f => $v)
            {
                $arrGridPrepare['joinTotal'][$f] = $v;
            }
        }

        // row joins
        if (isset($arrField['dependency']['joinRow']) && is_array($arrField['dependency']['joinRow']))
        {
            foreach($arrField['dependency']['joinRow'] as $f => $v)
            {
                $arrGridPrepare['joinRow'][$f] = $v;
            }
        }

        // rowFunctions
        if (isset($arrField['dependency']['rowFunctions']) && is_array($arrField['dependency']['rowFunctions']))
        {
            foreach ($arrField['dependency']['rowFunctions'] as $f => $v)
            {
                $arrGridPrepare['rowFunctions'][$f] = $v;
            }
        }

        // total groups
        if (isset($arrField['dependency']['groupTotal']) && is_array($arrField['dependency']['groupTotal']))
        {
            foreach ($arrField['dependency']['groupTotal'] as $f => $v)
            {
                $arrGridPrepare['groupTotal'][$f] = $v;
            }
        }

        // row groups
        if (isset($arrField['dependency']['groupRow']) && is_array($arrField['dependency']['groupRow']))
        {
            foreach ($arrField['dependency']['groupRow'] as $f => $v)
            {
                $arrGridPrepare['groupRow'][$f] = $v;
            }
        }

        // dataFunctions
        if (isset($arrField['dependency']['dataFunctions']) && is_array($arrField['dependency']['dataFunctions']))
        {
            foreach ($arrField['dependency']['dataFunctions'] as $f => $v)
            {
                $arrGridPrepare['dataFunctions'][$f] = $v;
            }
        }
    }

public
static
function
prepareDependencyHandler
(
$
handleType
,
$
field
,
&
$
arrField
,
&
$
arrGridPrepare
,
&
$
arrFormData
)
{
// select fields?
if
(
isset
(
$
arrField
[
'dependency'
]
[
'selectField'
]
)
&&
is_array
(
$
arrField
[
'dependency'
]
[
'selectField'
]
)
)
{
foreach
(
$
arrField
[
'dependency'
]
[
'selectField'
]
as
$
f
=>
$
v
)
{
$
arrGridPrepare
[
'selectField'
]
[
$
f
]
=
$
v
;
}
}
// total joins
if
(
isset
(
$
arrField
[
'dependency'
]
[
'joinTotal'
]
)
&&
is_array
(
$
arrField
[
'dependency'
]
[
'joinTotal'
]
)
)
{
foreach
(
$
arrField
[
'dependency'
]
[
'joinTotal'
]
as
$
f
=>
$
v
)
{
$
arrGridPrepare
[
'joinTotal'
]
[
$
f
]
=
$
v
;
}
}
// row joins
if
(
isset
(
$
arrField
[
'dependency'
]
[
'joinRow'
]
)
&&
is_array
(
$
arrField
[
'dependency'
]
[
'joinRow'
]
)
)
{
foreach
(
$
arrField
[
'dependency'
]
[
'joinRow'
]
as
$
f
=>
$
v
)
{
$
arrGridPrepare
[
'joinRow'
]
[
$
f
]
=
$
v
;
}
}
// rowFunctions
if
(
isset
(
$
arrField
[
'dependency'
]
[
'rowFunctions'
]
)
&&
is_array
(
$
arrField
[
'dependency'
]
[
'rowFunctions'
]
)
)
{
foreach
(
$
arrField
[
'dependency'
]
[
'rowFunctions'
]
as
$
f
=>
$
v
)
{
$
arrGridPrepare
[
'rowFunctions'
]
[
$
f
]
=
$
v
;
}
}
// total groups
if
(
isset
(
$
arrField
[
'dependency'
]
[
'groupTotal'
]
)
&&
is_array
(
$
arrField
[
'dependency'
]
[
'groupTotal'
]
)
)
{
foreach
(
$
arrField
[
'dependency'
]
[
'groupTotal'
]
as
$
f
=>
$
v
)
{
$
arrGridPrepare
[
'groupTotal'
]
[
$
f
]
=
$
v
;
}
}
// row groups
if
(
isset
(
$
arrField
[
'dependency'
]
[
'groupRow'
]
)
&&
is_array
(
$
arrField
[
'dependency'
]
[
'groupRow'
]
)
)
{
foreach
(
$
arrField
[
'dependency'
]
[
'groupRow'
]
as
$
f
=>
$
v
)
{
$
arrGridPrepare
[
'groupRow'
]
[
$
f
]
=
$
v
;
}
}
// dataFunctions
if
(
isset
(
$
arrField
[
'dependency'
]
[
'dataFunctions'
]
)
&&
is_array
(
$
arrField
[
'dependency'
]
[
'dataFunctions'
]
)
)
{
foreach
(
$
arrField
[
'dependency'
]
[
'dataFunctions'
]
as
$
f
=>
$
v
)
{
$
arrGridPrepare
[
'dataFunctions'
]
[
$
f
]
=
$
v
;
}
}
}

Handles dependecies when certain fields are selected or searched

@param string $handleType column, where
@param string $field current field
@param array $arrField details about field
@param array $arrGridPrepare
@param array $arrFormData the form|GET|POST


public static function getDataFunctionMergeMapping(&$arrRows, &$arrResults, &$arrMapping, $arrRowsAdditonalKey = null)
    {
        if (is_array($arrResults))
        {
            foreach($arrResults as $mapId => $arrResult)
            {
                if (isset($arrMapping[$mapId]) && is_array($arrMapping[$mapId]))
                {
                    foreach($arrMapping[$mapId] as $rowId)
                    {
                        if (isset($arrRows[$rowId]))
                        {
                            if (isset($arrRowsAdditonalKey))
                                $arrRows[$rowId][$arrRowsAdditonalKey] = $arrResult;
                            else
                                $arrRows[$rowId] = array_merge($arrResult, $arrRows[$rowId]);
                        }
                    }
                }
            }
        }
    }

public static function getDataFunctionMergeMapping ( & $ arrRows , & $ arrResults , & $ arrMapping , $ arrRowsAdditonalKey = null ) { if ( is_array ( $ arrResults ) ) { foreach ( $ arrResults as $ mapId => $ arrResult ) { if ( isset ( $ arrMapping [ $ mapId ] ) && is_array ( $ arrMapping [ $ mapId ] ) ) { foreach ( $ arrMapping [ $ mapId ] as $ rowId ) { if ( isset ( $ arrRows [ $ rowId ] ) ) { if ( isset ( $ arrRowsAdditonalKey ) ) $ arrRows [ $ rowId ] [ $ arrRowsAdditonalKey ] = $ arrResult ; else $ arrRows [ $ rowId ] = array_merge ( $ arrResult , $ arrRows [ $ rowId ] ) ; } } } } } }

Helper function that merge mapping ids to arrRows

@param array $arrRows
@param array $arrResults sql results from $arrIds/$strIds usually. The key of this array is the $mapField from getDataFunctionIds()
@param array $arrMapping from getDataFunctionIds()


public static function cleanString($string)
    {
        $string = str_replace(array(' ', '
', '
'), ' ', $string);
        $string = strip_tags($string);
        $string = str_replace(' ', ' ', $string);

        return $string;
    }

public
static
function
cleanString
(
$
string
)
{
$
string
=
str_replace
(
array
(
' '
,
'
'
,
'
'
)
,
' '
,
$
string
)
;
$
string
=
strip_tags
(
$
string
)
;
$
string
=
str_replace
(
' '
,
' '
,
$
string
)
;
return
$
string
;
}

used to remove HTML|nonsense chars from THEAD TH of render table for csv output


public function check(array $calls, FunctionProphecy $prophecy)
    {
        if (count($calls)) {
            return;
        }

        $methodCalls = $prophecy->getNamespace()->findCalls($prophecy->getName(), new ArgumentsWildcard([new AnyValuesToken()]));

        if (count($methodCalls)) {
            throw new NoCallsException(sprintf(
                "No calls have been made that match:\n".
                "  %s(%s)\n".
                "but expected at least one.\n".
                "Recorded `%s(...)` calls:\n%s",

                $prophecy->getName(),
                $prophecy->getArgumentsWildcard(),
                $prophecy->getName(),
                $this->util->stringifyCalls($methodCalls)
            ));
        }

        throw new NoCallsException(sprintf(
            "No calls have been made that match:\n".
            "  %s(%s)\n".
            'but expected at least one.',

            $prophecy->getName(),
            $prophecy->getArgumentsWildcard()
        ));
    }

public
function
check
(
array
$
calls
,
FunctionProphecy
$
prophecy
)
{
if
(
count
(
$
calls
)
)
{
return
;
}
$
methodCalls
=
$
prophecy
->
getNamespace
(
)
->
findCalls
(
$
prophecy
->
getName
(
)
,
new
ArgumentsWildcard
(
[
new
AnyValuesToken
(
)
]
)
)
;
if
(
count
(
$
methodCalls
)
)
{
throw
new
NoCallsException
(
sprintf
(
"No calls have been made that match:\n"
.
"  %s(%s)\n"
.
"but expected at least one.\n"
.
"Recorded `%s(...)` calls:\n%s"
,
$
prophecy
->
getName
(
)
,
$
prophecy
->
getArgumentsWildcard
(
)
,
$
prophecy
->
getName
(
)
,
$
this
->
util
->
stringifyCalls
(
$
methodCalls
)
)
)
;
}
throw
new
NoCallsException
(
sprintf
(
"No calls have been made that match:\n"
.
"  %s(%s)\n"
.
'but expected at least one.'
,
$
prophecy
->
getName
(
)
,
$
prophecy
->
getArgumentsWildcard
(
)
)
)
;
}

Tests that there was at least one call.

@param Call[]         $calls
@param FunctionProphecy $prophecy

@throws NoCallsException

Tests that there was at least one call .


protected static function _decodeYaml($currentIndent, &$lines)
    {
        $config   = array();
        $inIndent = false;
        while (list($n, $line) = each($lines)) {
            $lineno = $n + 1;

            $line = rtrim(preg_replace("/#.*$/", "", $line));
            if (strlen($line) == 0) {
                continue;
            }

            $indent = strspn($line, " ");

            // line without the spaces
            $line = trim($line);
            if (strlen($line) == 0) {
                continue;
            }

            if ($indent < $currentIndent) {
                // this level is done
                prev($lines);
                return $config;
            }

            if (!$inIndent) {
                $currentIndent = $indent;
                $inIndent      = true;
            }

            if (preg_match("/(?!-)([\w\-]+):\s*(.*)/", $line, $m)) {
                // key: value
                if (strlen($m[2])) {
                    // simple key: value
                    $value = preg_replace("/#.*$/", "", $m[2]);
                    $value = self::_parseValue($value);
                } else {
                    // key: and then values on new lines
                    $value = self::_decodeYaml($currentIndent + 1, $lines);
                    if (is_array($value) && !count($value)) {
                        $value = "";
                    }
                }
                $config[$m[1]] = $value;
            } elseif ($line[0] == "-") {
                // item in the list:
                // - FOO
                if (strlen($line) > 2) {
                    $value = substr($line, 2);

                    $config[] = self::_parseValue($value);
                } else {
                    $config[] = self::_decodeYaml($currentIndent + 1, $lines);
                }
            } else {

                throw new Zend_Config_Exception(sprintf(
                    'Error parsing YAML at line %d - unsupported syntax: "%s"',
                    $lineno, $line
                ));
            }
        }
        return $config;
    }

Service function to decode YAML

@param  int $currentIndent Current indent level
@param  array $lines  YAML lines
@return array|string


function startSession($pkg, $contents, $dest)
    {
        $subst_from = $subst_to = array();
        foreach ($this->_replacements as $a) {
            $a = $a['attribs'];
            $to = '';
            if ($a['type'] == 'pear-config') {
                if ($this->installphase == PEAR_TASK_PACKAGE) {
                    return false;
                }
                if ($a['to'] == 'master_server') {
                    $chan = $this->registry->getChannel($pkg->getChannel());
                    if (!PEAR::isError($chan)) {
                        $to = $chan->getServer();
                    } else {
                        $this->logger->log(0, "$dest: invalid pear-config replacement: $a[to]");
                        return false;
                    }
                } else {
                    if ($this->config->isDefinedLayer('ftp')) {
                        // try the remote config file first
                        $to = $this->config->get($a['to'], 'ftp', $pkg->getChannel());
                        if (is_null($to)) {
                            // then default to local
                            $to = $this->config->get($a['to'], null, $pkg->getChannel());
                        }
                    } else {
                        $to = $this->config->get($a['to'], null, $pkg->getChannel());
                    }
                }
                if (is_null($to)) {
                    $this->logger->log(0, "$dest: invalid pear-config replacement: $a[to]");
                    return false;
                }
            } elseif ($a['type'] == 'php-const') {
                if ($this->installphase == PEAR_TASK_PACKAGE) {
                    return false;
                }
                if (defined($a['to'])) {
                    $to = constant($a['to']);
                } else {
                    $this->logger->log(0, "$dest: invalid php-const replacement: $a[to]");
                    return false;
                }
            } else {
                if ($t = $pkg->packageInfo($a['to'])) {
                    $to = $t;
                } else {
                    $this->logger->log(0, "$dest: invalid package-info replacement: $a[to]");
                    return false;
                }
            }
            if (!is_null($to)) {
                $subst_from[] = $a['from'];
                $subst_to[] = $to;
            }
        }
        $this->logger->log(3, "doing " . sizeof($subst_from) .
            " substitution(s) for $dest");
        if (sizeof($subst_from)) {
            $contents = str_replace($subst_from, $subst_to, $contents);
        }
        return $contents;
    }

Do a package.xml 1.0 replacement, with additional package-info fields available

See validateXml() source for the complete list of allowed fields
@param PEAR_PackageFile_v1|PEAR_PackageFile_v2
@param string file contents
@param string the eventual final file location (informational only)
@return string|false|PEAR_Error false to skip this file, PEAR_Error to fail
(use $this->throwError), otherwise return the new contents

Do a package . xml 1 . 0 replacement with additional package - info fields available


public function exec($query, $values = array())
    {
        if ($stmt = $this->prepare($query)) {
            $result = $this->execute($stmt, $values);
            $this->close($stmt);
        }

        return (isset($result)) ? $result : false;
    }

public function exec ( $ query , $ values = array ( ) ) { if ( $ stmt = $ this -> prepare ( $ query ) ) { $ result = $ this -> execute ( $ stmt , $ values ) ; $ this -> close ( $ stmt ) ; } return ( isset ( $ result ) ) ? $ result : false ; }

Prepare and execute a query.

@param string|array $query  An SQL statement.
@param string|array $values The query parameters.

@return mixed Either ``false`` if there was a problem, or whatever the ``$db->execute()``d.

```php
$db->exec(array(
'CREATE TABLE employees (',
'  id INTEGER PRIMARY KEY,',
'  name TEXT NOT NULL DEFAULT "",',
'  title TEXT NOT NULL DEFAULT ""',
')',
));
```


public function insert($table, array $data, $and = '')
    {
        if (isset($this->prepared[$table])) {
            return $this->execute($table, $data);
        }
        $single = (count(array_filter(array_keys($data), 'is_string')) > 0) ? $data : false;
        if ($single) {
            $data = array_keys($data);
        }
        if (stripos($table, ' INTO ') !== false) { // eg. 'OR IGNORE INTO table'
            $query = "INSERT {$table} ";
        } else {
            $query = "INSERT INTO {$table} ";
        }
        $query .= '('.implode(', ', $data).') VALUES ('.implode(', ', array_fill(0, count($data), '?')).') '.$and;
        $stmt = $this->prepare($query);
        if ($single && $stmt) {
            $id = $this->insert($stmt, array_values($single));
            $this->close($stmt);

            return $id;
        }

        return $stmt;
    }

public
function
insert
(
$
table
,
array
$
data
,
$
and
=
''
)
{
if
(
isset
(
$
this
->
prepared
[
$
table
]
)
)
{
return
$
this
->
execute
(
$
table
,
$
data
)
;
}
$
single
=
(
count
(
array_filter
(
array_keys
(
$
data
)
,
'is_string'
)
)
>
0
)
$
data
:
false
;
if
(
$
single
)
{
$
data
=
array_keys
(
$
data
)
;
}
if
(
stripos
(
$
table
,
' INTO '
)
!==
false
)
{
// eg. 'OR IGNORE INTO table'
$
query
=
"INSERT {$table} "
;
}
else
{
$
query
=
"INSERT INTO {$table} "
;
}
$
query
.=
'('
.
implode
(
', '
,
$
data
)
.
') VALUES ('
.
implode
(
', '
,
array_fill
(
0
,
count
(
$
data
)
,
'?'
)
)
.
') '
.
$
and
;
$
stmt
=
$
this
->
prepare
(
$
query
)
;
if
(
$
single
&&
$
stmt
)
{
$
id
=
$
this
->
insert
(
$
stmt
,
array_values
(
$
single
)
)
;
$
this
->
close
(
$
stmt
)
;
return
$
id
;
}
return
$
stmt
;
}

Insert new records into a database table.

@param string|int $table Either the database table name, or the prepared statement id you got from calling this the first time.  You can also include *'INTO'* here which is handy for prepending a qualifier eg. *'OR IGNORE INTO table'*.
@param array      $data  Either the table column names (when preparing a statement), or a row of values (to insert).  If you are only inserting one record and want to save yourself some typing, then make this an ``array(name => value, ...)`` of columns.
@param string     $and   Anything you would like to add at the end of the query eg. *'ON DUPLICATE KEY UPDATE ...'*.

@return bool|int Either ``false`` if there was an error, a prepared ``$stmt`` to keep passing off as the **$table**, or the ``$id`` of the row you just inserted.  Don't forget to ``$db->close($stmt)``.

```php
if ($stmt = $db->insert('employees', array('id', 'name', 'title'))) {
$db->insert($stmt, array(101, 'John Smith', 'CEO'));
$db->insert($stmt, array(102, 'Raj Reddy', 'Sysadmin'));
$db->insert($stmt, array(103, 'Jason Bourne', 'Developer'));
$db->insert($stmt, array(104, 'Jane Smith', 'Sales Manager'));
$db->insert($stmt, array(105, 'Rita Patel', 'DBA'));
$db->close($stmt);
}

if ($db->insert('OR IGNORE INTO employees', array(
'id' => 106,
'name' => "Little Bobby'); DROP TABLE employees;--",
'title' => 'Intern',
))) {
echo $db->log('count'); // 1 - It worked!
}
```

Insert new records into a database table .


public function update($table, $id, array $data, $and = '')
    {
        if (isset($this->prepared[$table])) {
            $data[] = $id;

            return $this->execute($table, $data);
        }
        $first = each($data);
        $single = (is_array($first['value'])) ? $first['value'] : false;
        if ($single) {
            $data = array_keys($single);
        }
        if (stripos($table, ' SET ') !== false) { // eg. 'table SET date = NOW(),'
            $query = "UPDATE {$table} ";
        } else {
            $query = "UPDATE {$table} SET ";
        }
        $query .= implode(' = ?, ', $data).' = ? WHERE '.$id.' = ? '.$and;
        $stmt = $this->prepare($query);
        if ($single && $stmt) {
            $affected = $this->update($stmt, $first['key'], array_values($single));
            $this->close($stmt);

            return $affected;
        }

        return $stmt;
    }

public
function
update
(
$
table
,
$
id
,
array
$
data
,
$
and
=
''
)
{
if
(
isset
(
$
this
->
prepared
[
$
table
]
)
)
{
$
data
[
]
=
$
id
;
return
$
this
->
execute
(
$
table
,
$
data
)
;
}
$
first
=
each
(
$
data
)
;
$
single
=
(
is_array
(
$
first
[
'value'
]
)
)
$
first
[
'value'
]
:
false
;
if
(
$
single
)
{
$
data
=
array_keys
(
$
single
)
;
}
if
(
stripos
(
$
table
,
' SET '
)
!==
false
)
{
// eg. 'table SET date = NOW(),'
$
query
=
"UPDATE {$table} "
;
}
else
{
$
query
=
"UPDATE {$table} SET "
;
}
$
query
.=
implode
(
' = ?, '
,
$
data
)
.
' = ? WHERE '
.
$
id
.
' = ? '
.
$
and
;
$
stmt
=
$
this
->
prepare
(
$
query
)
;
if
(
$
single
&&
$
stmt
)
{
$
affected
=
$
this
->
update
(
$
stmt
,
$
first
[
'key'
]
,
array_values
(
$
single
)
)
;
$
this
->
close
(
$
stmt
)
;
return
$
affected
;
}
return
$
stmt
;
}

Modify records in a database table.

@param string|int $table Either the database table name, or the prepared statement id you got from calling this the first time.  You can also include *'SET'* here which is handy for getting some updates in that we can't otherwise do eg. *'table SET date = NOW(),'*.
@param array      $id    Either the name of the column with the unique identifier you will be referencing (when preparing a statement), or the unique identifier of the column you are updating.
@param array      $data  Either the table column names (when preparing a statement), or a row of values (to update).  If you are only updating one record and want to save yourself some typing, then make this an ``array(name => value, ...)`` of columns.
@param string     $and   Anything you would like to add at the end of the query after the WHERE eg. *'AND approved = "Y"'*.

@return bool|int Either ``false`` if there was an error, a prepared ``$stmt`` to keep passing off as the **$table**, or the ``$num`` of rows affected.  Don't forget to ``$db->close($stmt)``.

```php
if (!$db->update('employees SET id = 101', 'id', array(
106 => array(
'name' => 'Roberto Cratchit',
'title' => 'CEO',
)
))) {
echo $db->log('error'); // A unique id constraint
}

if ($stmt = $db->update('employees', 'id', array('title'))) {
$db->update($stmt, 103, array('Janitor'));
$db->update($stmt, 99, array('Quality Control'));
$db->close($stmt);
}
```


public function upsert($table, $id, array $data)
    {
        if (isset($this->prepared[$table]['ref']) && $this->execute($table, $id)) {
            $data[] = $id;
            if ($row = $this->fetch($table)) {
                return ($this->execute($this->prepared[$table]['ref']['update'], $data)) ? array_shift($row) : false;
            } else {
                return $this->execute($this->prepared[$table]['ref']['insert'], $data);
            }
        }
        $first = each($data);
        $single = (is_array($first['value'])) ? $first['value'] : false;
        if ($single) {
            $data = array_keys($single);
        }
        if ($stmt = $this->prepare("SELECT {$id} FROM {$table} WHERE {$id} = ?", 'row')) {
            $this->prepared[$stmt]['ref']['update'] = $this->update($table, $id, $data);
            $this->prepared[$stmt]['ref']['insert'] = $this->insert($table, array_merge($data, array($id)));
        }
        if ($single && $stmt) {
            $id = $this->upsert($stmt, $first['key'], array_values($single));
            $this->close($stmt);

            return $id;
        }

        return $stmt;
    }

Either update or insert records depending on whether they already exist or not.

@param string|int $table Either the database table name, or the prepared statement id you got from calling this the first time.  You cannot include *'SET'* or *'INTO'* here.
@param array      $id    Either the name of the column with the unique identifier you will be referencing (when preparing a statement), or the unique identifier of the column you are upserting.
@param array      $data  Either the table column names (when preparing a statement), or a row of values (to upsert).  If you are only upserting one record and want to save yourself some typing, then make this an ``array(name => value, ...)`` of columns.

@return bool|int Either ``false`` if there was an error, a prepared ``$stmt`` to keep passing off as the **$table**, or the ``$id`` of the row that was upserted.  Don't forget to ``$db->close($stmt)``.

```php
if ($stmt = $db->upsert('employees', 'id', array('name', 'title'))) {
$db->upsert($stmt, 101, array('Roberto Cratchit', 'CEO'));
$db->upsert($stmt, 106, array('John Smith', 'Developer'));
$db->close($stmt);
}

$db->upsert('employees', 'id', array(
107 => array(
'name' => 'Ella Minnow Pea',
'title' => 'Executive Assistant',
),
));
```

Either update or insert records depending on whether they already exist or not .


public function query($select, $values = array(), $fetch = 'row')
    {
        if ($stmt = $this->prepare($select, $fetch)) {
            if ($this->prepared[$stmt]['type'] == 'SELECT' && $this->execute($stmt, $values)) {
                return $stmt;
            }
            $this->close($stmt);
        }

        return false;
    }

public function query ( $ select , $ values = array ( ) , $ fetch = 'row' ) { if ( $ stmt = $ this -> prepare ( $ select , $ fetch ) ) { if ( $ this -> prepared [ $ stmt ] [ 'type' ] == 'SELECT' && $ this -> execute ( $ stmt , $ values ) ) { return $ stmt ; } $ this -> close ( $ stmt ) ; } return false ; }

Select data from the database.

@param string|array $select A SELECT statement.
@param string|array $values The query parameters.
@param string       $fetch  How you would like your row.

@return bool|int Either ``false`` if there was a problem, or a statement that you can ``$db->fetch($result)`` rows from.  Don't forget to ``$db->close($result)``.

```php
if ($result = $db->query('SELECT name, title FROM employees', '', 'assoc')) {
while ($row = $db->fetch($result)) {
print_r($row);
// array('name'=>'Roberto Cratchit', 'title'=>'CEO')
// array('name'=>'Raj Reddy', 'title'=>'Sysadmin')
// array('name'=>'Jason Bourne', 'title'=>'Janitor')
// array('name'=>'Jane Smith', 'title'=>'Sales Manager')
// array('name'=>'Rita Patel', 'title'=>'DBA')
// array('name'=>'John Smith', 'title'=>'Developer')
// array('name'=>'Ella Minnow Pea', 'title'=>'Executive Assistant')
}
$db->close($result);
}
```


public function all($select, $values = array(), $fetch = 'row')
    {
        $rows = array();
        if ($stmt = $this->query($select, $values, $fetch)) {
            while ($row = $this->fetch($stmt)) {
                $rows[] = $row;
            }
            $this->close($stmt);
        }

        return $rows;
    }

public function all ( $ select , $ values = array ( ) , $ fetch = 'row' ) { $ rows = array ( ) ; if ( $ stmt = $ this -> query ( $ select , $ values , $ fetch ) ) { while ( $ row = $ this -> fetch ( $ stmt ) ) { $ rows [ ] = $ row ; } $ this -> close ( $ stmt ) ; } return $ rows ; }

Get all of the selected rows from your query at once.

@param string|array $select A SELECT statement.
@param string|array $values The query parameters.
@param string       $fetch  How you would like your row.

@return array No false heads up here.  You either have rows, or you don't.

```php
foreach ($db->all('SELECT id, name, title FROM employees') as $row) {
list($id, $name, $title) = $row;
}
```

Get all of the selected rows from your query at once .


public function ids($select, $values = array())
    {
        $ids = array();
        if ($stmt = $this->query($select, $values, 'row')) {
            while ($row = $this->fetch($stmt)) {
                $ids[] = (int) array_shift($row);
            }
            $this->close($stmt);
        }

        return (!empty($ids)) ? $ids : false;
    }

public function ids ( $ select , $ values = array ( ) ) { $ ids = array ( ) ; if ( $ stmt = $ this -> query ( $ select , $ values , 'row' ) ) { while ( $ row = $ this -> fetch ( $ stmt ) ) { $ ids [ ] = ( int ) array_shift ( $ row ) ; } $ this -> close ( $ stmt ) ; } return ( ! empty ( $ ids ) ) ? $ ids : false ; }

Get all of the id's from your query, or whatever the first column you requested is.

@param string|array $select A SELECT statement.
@param string|array $values The query parameters.

@return bool|array Either ``false`` if there were no rows, or an ``array()`` of every rows first value.

```php
if ($ids = $db->ids('SELECT id FROM employees WHERE title = ?', 'Intern')) {
// Then Little Bobby Tables isn't as good as we thought.
}
```

Get all of the id s from your query or whatever the first column you requested is .


public function row($select, $values = array(), $fetch = 'row')
    {
        if ($stmt = $this->query($select, $values, $fetch)) {
            $row = $this->fetch($stmt);
            $this->close($stmt);
        }

        return (isset($row) && !empty($row)) ? $row : false;
    }

public function row ( $ select , $ values = array ( ) , $ fetch = 'row' ) { if ( $ stmt = $ this -> query ( $ select , $ values , $ fetch ) ) { $ row = $ this -> fetch ( $ stmt ) ; $ this -> close ( $ stmt ) ; } return ( isset ( $ row ) && ! empty ( $ row ) ) ? $ row : false ; }

Get only the first row from your query.

@param string|array $select A SELECT statement.
@param string|array $values The query parameters.
@param string       $fetch  How you would like your row.

@return bool|array Either ``false`` if there was no row, or an ``array()`` of the first one fetched.

```php
if ($janitor = $db->row('SELECT id, name FROM employees WHERE title = ?', 'Janitor', 'assoc')) {
// array('id'=>103, 'name'=>'Jason Bourne')
}
```

Get only the first row from your query .