public function renameCollection($collection, $newName)
    {
        try {
            return $this->_toolbox->getCollectionHandler()->rename($collection, $newName);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new CollectionManagerException($normalised['message'], $normalised['code']);
        }
    }

public function renameCollection ( $ collection , $ newName ) { try { return $ this -> _toolbox -> getCollectionHandler ( ) -> rename ( $ collection , $ newName ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new CollectionManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Renames a collection.
@param  string                     $collection The collection we wish to rename.
@param  string                     $newName    The new name of the collection.
@throws CollectionManagerException


public function wipe($collection)
    {
        try {
            return $this->_toolbox->getCollectionHandler()->truncate($collection);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new CollectionManagerException($normalised['message'], $normalised['code']);
        }
    }

public function wipe ( $ collection ) { try { return $ this -> _toolbox -> getCollectionHandler ( ) -> truncate ( $ collection ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new CollectionManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Deletes all the documents inside the collection, but leaves the indexes and metadata intact.
@param  string                     $collection The name of the collection.
@throws CollectionManagerException

Deletes all the documents inside the collection but leaves the indexes and metadata intact .


public function getCollectionInfo($collection)
    {
        try {
            $collection = $this->_toolbox->getCollectionHandler()->getProperties($collection);

            $result = $collection->getAll();

            switch ($result['type']) {
                case 2:
                    $result['type'] = "documents";
                    break;

                case 3:
                    $result['type'] = "edges";
                    break;
            }

            return $result;

        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new CollectionManagerException($normalised['message'], $normalised['code']);
        }
    }

public function getCollectionInfo ( $ collection ) { try { $ collection = $ this -> _toolbox -> getCollectionHandler ( ) -> getProperties ( $ collection ) ; $ result = $ collection -> getAll ( ) ; switch ( $ result [ 'type' ] ) { case 2 : $ result [ 'type' ] = "documents" ; break ; case 3 : $ result [ 'type' ] = "edges" ; break ; } return $ result ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new CollectionManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Get information about a collection.
@param  string                     $collection The name of the collection.
@throws CollectionManagerException
@return array


public function getCollectionStatistics($collection)
    {
        try {
            return $this->_toolbox->getCollectionHandler()->getFigures($collection);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new CollectionManagerException($normalised['message'], $normalised['code']);
        }
    }

public function getCollectionStatistics ( $ collection ) { try { return $ this -> _toolbox -> getCollectionHandler ( ) -> getFigures ( $ collection ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new CollectionManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Get statistics from a collection.
@param  string                     $collection The name of the collection.
@throws CollectionManagerException
@return array


public function count($collection)
    {
        try {
            return $this->_toolbox->getCollectionHandler()->count($collection);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new CollectionManagerException($normalised['message'], $normalised['code']);
        }
    }

public function count ( $ collection ) { try { return $ this -> _toolbox -> getCollectionHandler ( ) -> count ( $ collection ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new CollectionManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Counts the number of documents in a collection.
@param  string                     $collection The collection.
@throws CollectionManagerException
@return integer

Counts the number of documents in a collection .


public function loadCollection($collection)
    {
        try {
            return $this->_toolbox->getCollectionHandler()->load($collection);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new CollectionManagerException($normalised['message'], $normalised['code']);
        }
    }

public function loadCollection ( $ collection ) { try { return $ this -> _toolbox -> getCollectionHandler ( ) -> load ( $ collection ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new CollectionManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Load a collection on the server.
@param  string                     $collection The name of the collection.
@throws CollectionManagerException


public function unloadCollection($collection)
    {
        try {
            return $this->_toolbox->getCollectionHandler()->unload($collection);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new CollectionManagerException($normalised['message'], $normalised['code']);
        }
    }

public function unloadCollection ( $ collection ) { try { return $ this -> _toolbox -> getCollectionHandler ( ) -> unload ( $ collection ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new CollectionManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Unload a collection on the server.
@param  string                     $collection The name of the collection.
@throws CollectionManagerException


public function getIndexInfo($collection, $indexId)
    {
        $result = $this->listIndices($collection, true);

        return isset($result[$collection . '/' . $indexId]) ? $result[$collection . '/' . $indexId] : null;
    }

public function getIndexInfo ( $ collection , $ indexId ) { $ result = $ this -> listIndices ( $ collection , true ) ; return isset ( $ result [ $ collection . '/' . $ indexId ] ) ? $ result [ $ collection . '/' . $ indexId ] : null ; }

Get information about an index. Returns null if the index does not exist and returns an array of index information if it does.
@param  string     $collection The name of the collection.
@param  string     $indexId    The id of the index.
@return null|array

Get information about an index . Returns null if the index does not exist and returns an array of index information if it does .


public function getGeoFieldsForAQL($collection)
    {
        $indices = $this->_toolbox->getCollectionManager()->listIndices($collection, true);

        foreach ($indices as $index => $info) {

            //If this is the first geo index we encounter
            if ($info['type'] == "geo1" || $info['type'] == "geo2") {
                return $info['fields'];
            }
        }

        return null;
    }

Get the fields that are used to store geo coordinates for the first index for this collection.
@param  string          $collection The name of the collection
@throws FinderException
@return array|null

Get the fields that are used to store geo coordinates for the first index for this collection .


public function any($type)
    {
        if ($this->_toolbox->getTransactionManager()->hasTransaction()) {
            $this->_toolbox->getTransactionManager()->addReadCollection($type);
            $this->_toolbox->getTransactionManager()->addCommand("db.$type.any();" , "Finder:any", null, false, array('type' => $type));
        } else {
            try {
                $result = $this->_toolbox->getCollectionHandler()->any($type);

                if (!$result) {
                    return null;
                }

                $converted = $this->convertToPods($type, array($result));

                return reset($converted);

            } catch (\Exception $e) {
                $normalised = $this->_toolbox->normaliseDriverExceptions($e);
                throw new FinderException($normalised['message'], $normalised['code']);
            }
        }
    }

public function any ( $ type ) { if ( $ this -> _toolbox -> getTransactionManager ( ) -> hasTransaction ( ) ) { $ this -> _toolbox -> getTransactionManager ( ) -> addReadCollection ( $ type ) ; $ this -> _toolbox -> getTransactionManager ( ) -> addCommand ( "db.$type.any();" , "Finder:any" , null , false , array ( 'type' => $ type ) ) ; } else { try { $ result = $ this -> _toolbox -> getCollectionHandler ( ) -> any ( $ type ) ; if ( ! $ result ) { return null ; } $ converted = $ this -> convertToPods ( $ type , array ( $ result ) ) ; return reset ( $ converted ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new FinderException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } } }

Returns a random document from a collection.
@param  string          $type The collection we want to get the document from.
@throws FinderException
@return AModel

Returns a random document from a collection .


private function getCollectionName($type)
    {
        if ($this->_toolbox->isGraph()) {

            if (!$this->_toolbox->getPodManager()->validateType($type)) {
                throw new FinderException("When finding documents in graphs, only the types 'vertex' and 'edge' are allowed.");
            }

            //Is a vertex
            if (strtolower($type) == "vertex") {
                return $this->_toolbox->getVertexCollectionName();

            //Is an edge
            } else {
                return $this->_toolbox->getEdgeCollectionName();
            }

        } else {
            return $type;
        }
    }

Determines the collection name to use. For graphs, it converts "vertex" and "edge" into the appropriate collection names on the server.
@param  string          $type The collection name.
@throws FinderException
@return string

Determines the collection name to use . For graphs it converts vertex and edge into the appropriate collection names on the server .


public function deleteUser($username)
    {
        try {
            $this->_toolbox->getUserHandler()->removeUser($username);

            return true;
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new ServerException($normalised['message'], $normalised['code']);
        }
    }

public function deleteUser ( $ username ) { try { $ this -> _toolbox -> getUserHandler ( ) -> removeUser ( $ username ) ; return true ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new ServerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Delete a user from the server.
@param  string          $username The user we want to delete.
@throws ServerException
@return boolean


public function getUserInfo($username)
    {
        try {
            $details = $this->_toolbox->getUserHandler()->get($username);

            $result = array();
            $result['username'] = $details->get('user');
            $result['active'] = $details->get('active');
            $result['data'] = $details->get('extra');

            return $result;

        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new ServerException($normalised['message'], $normalised['code']);
        }
    }

public function getUserInfo ( $ username ) { try { $ details = $ this -> _toolbox -> getUserHandler ( ) -> get ( $ username ) ; $ result = array ( ) ; $ result [ 'username' ] = $ details -> get ( 'user' ) ; $ result [ 'active' ] = $ details -> get ( 'active' ) ; $ result [ 'data' ] = $ details -> get ( 'extra' ) ; return $ result ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new ServerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Get information about a user.
@param  string          $username The user we want information about.
@throws ServerException
@return array


public function deleteAQLFunctionsByNamespace($namespace)
    {
        try {
            $userFunction = new AqlUserFunction($this->_toolbox->getConnection());
            $userFunction->unregister($namespace, true);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new ServerException($normalised['message'], $normalised['code']);
        }

        return true;
    }

public function deleteAQLFunctionsByNamespace ( $ namespace ) { try { $ userFunction = new AqlUserFunction ( $ this -> _toolbox -> getConnection ( ) ) ; $ userFunction -> unregister ( $ namespace , true ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new ServerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } return true ; }

Delete all the AQL functions within a namespace.
@param  string          $namespace The name of the namespace to delete.
@throws ServerException

Delete all the AQL functions within a namespace .


public function listAQLFunctions($namespace = null)
    {
        try {
            $userFunction = new AqlUserFunction($this->_toolbox->getConnection());
            $functions = $userFunction->getRegisteredUserFunctions($namespace);

            $result = array();

            foreach ($functions as $function) {
                $result[$function['name']] = $function['code'];
            }

            return $result;

        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new ServerException($normalised['message'], $normalised['code']);
        }
    }

public function listAQLFunctions ( $ namespace = null ) { try { $ userFunction = new AqlUserFunction ( $ this -> _toolbox -> getConnection ( ) ) ; $ functions = $ userFunction -> getRegisteredUserFunctions ( $ namespace ) ; $ result = array ( ) ; foreach ( $ functions as $ function ) { $ result [ $ function [ 'name' ] ] = $ function [ 'code' ] ; } return $ result ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new ServerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

List the AQL functions registered on the server and optionally, filter by namespace.
@param  string          $namespace The optional namespace to filter the list of AQL functions on.
@throws ServerException

List the AQL functions registered on the server and optionally filter by namespace .


public function getVersion()
    {
        try {
            return $this->_toolbox->getAdminHandler()->getServerVersion();
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new ServerException($normalised['message'], $normalised['code']);
        }
    }

public function getVersion ( ) { try { return $ this -> _toolbox -> getAdminHandler ( ) -> getServerVersion ( ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new ServerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Get the server version.
@throws ServerException
@return string


public function getServerInfo()
    {
        try {
            return $this->_toolbox->getAdminHandler()->getServerVersion(true);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new ServerException($normalised['message'], $normalised['code']);
        }
    }

public function getServerInfo ( ) { try { return $ this -> _toolbox -> getAdminHandler ( ) -> getServerVersion ( true ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new ServerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Get detailed information about the server.
@throws ServerException
@return array

Get detailed information about the server .


public function getTime()
    {
        try {
            return $this->_toolbox->getAdminHandler()->getServerTime();
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new ServerException($normalised['message'], $normalised['code']);
        }
    }

public function getTime ( ) { try { return $ this -> _toolbox -> getAdminHandler ( ) -> getServerTime ( ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new ServerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Get the unix timestamp of the server with microsecond precision
@throws ServerException
@return float


public function set($key, $value)
    {
        if (in_array($key, $this->getReservedFields())) {
            throw new PodException("You cannot set the property $key. This is reserved for system use.");
        }

        $this->_changed = true;

        $this->_data[$key] = $value;
    }

Set a property for this pod.
@param  string       $key   The property we wish to set.
@param  string       $value The value we wish to set.
@throws PodException


public function remove($key)
    {
        if (in_array($key, $this->getReservedFields())) {
            throw new PodException("You cannot set the property $key. This is reserved for system use.");
        }

        $this->_changed = true;

        unset($this->_data[$key]);
    }

Remove a property for this pod.
@param  string       $key The property we wish to unset.
@throws PodException


public function get($key)
    {
        if (in_array($key, $this->getReservedFields())) {

            throw new PodException("You cannot get the system property '$key'. Use the appropriate getter for it.");
        }

        return isset($this->_data[$key]) ? $this->_data[$key] : null;
    }

Get the value of a property from the pod.
@param  string       $key
@throws PodException
@return mixed

Get the value of a property from the pod .


public function setId($id)
    {
        if ($this->_id !== null && $this->_id != $id) {
            throw new PodException('Cannot update the id of an existing document');
        }

        if (!preg_match('/^\w+\/\w+$/', $id)) {
            throw new PodException('Invalid format for document id');
        }

        @list(, $documentId) = explode('/', $id, 2);
        $this->_key = $documentId;
        $this->_id = (string) $id;
    }

Set the id for this pod. The id is only allowed to be set once, because once saved to the server, the id can't be changed.
@param  string       $id
@throws PodException

Set the id for this pod . The id is only allowed to be set once because once saved to the server the id can t be changed .


public function setDistanceInfo($latitude, $longitude, $podId = null)
    {
        if (isset($this->_distance) || isset($this->_referenceCoordinates) || isset($this->_referencePodId)) {
            throw new PodException("Cannot update the distance info from an existing query.");
        }

        $this->_distance = $this->_data['_paradox_distance_parameter'];
        unset($this->_data['_paradox_distance_parameter']);

        $this->_referenceCoordinates = array('latitude' => $latitude, 'longitude' => $longitude);
        $this->_referencePodId = $podId;
    }

Sets the distance information to the pod. This is intended to be used by the API and is not for public comsumption.
@param  float        $distance  The distance from this pod to the reference pod in meters.
@param  float        $latitude  The latitude of the reference point.
@param  float        $longitude The longitude of the reference point.
@param  string       $podId     If the reference point is a pod, the pod id.
@throws PodException

Sets the distance information to the pod . This is intended to be used by the API and is not for public comsumption .


public function resetMeta()
    {
        $this->_new = true;
        $this->_changed = true;
        $this->_id = null;
        $this->_key = null;
        $this->_rev = null;
    }

public function resetMeta ( ) { $ this -> _new = true ; $ this -> _changed = true ; $ this -> _id = null ; $ this -> _key = null ; $ this -> _rev = null ; }

Reset the meta data of the pod so that it appears as a new one.
The existing user added data is not reset.

Reset the meta data of the pod so that it appears as a new one . The existing user added data is not reset .


public function toArray()
    {
        $result = array('_id' => $this->getId(), '_key' => $this->getKey(), '_rev' => $this->getRevision());

        return array_merge($result, $this->_data);
    }

public function toArray ( ) { $ result = array ( '_id' => $ this -> getId ( ) , '_key' => $ this -> getKey ( ) , '_rev' => $ this -> getRevision ( ) ) ; return array_merge ( $ result , $ this -> _data ) ; }

Return an associative array representation of this document.
@return array

Return an associative array representation of this document .


public function toJSON()
    {
        $result = array('_id' => $this->getId(), '_key' => $this->getKey(), '_rev' => $this->getRevision());

        return json_encode(array_merge($result, $this->_data), JSON_FORCE_OBJECT);
    }

public function toJSON ( ) { $ result = array ( '_id' => $ this -> getId ( ) , '_key' => $ this -> getKey ( ) , '_rev' => $ this -> getRevision ( ) ) ; return json_encode ( array_merge ( $ result , $ this -> _data ) , JSON_FORCE_OBJECT ) ; }

Returns a JSON representation of this document.
@return string

Returns a JSON representation of this document .


public function toTransactionJSON()
    {
        $result = array('_rev' => $this->getRevision());

        return json_encode(array_merge($result, $this->_data), JSON_FORCE_OBJECT);
    }

public function toTransactionJSON ( ) { $ result = array ( '_rev' => $ this -> getRevision ( ) ) ; return json_encode ( array_merge ( $ result , $ this -> _data ) , JSON_FORCE_OBJECT ) ; }

Returns a JSON representation of this document for transactions.
@return string

Returns a JSON representation of this document for transactions .


public function toDriverDocument()
    {
        $document = new \triagens\ArangoDb\Document;

        foreach ($this->_data as $key => $value) {
            $document->set($key, $value);
        }

        if ($this->_id) {
            $document->setInternalId($this->_id);
        }

        if ($this->_key) {
            $document->setInternalKey($this->_key);
        }

        if ($this->_rev) {
            $document->setRevision($this->_rev);
        }

        return $document;
    }

public function toDriverDocument ( ) { $ document = new \ triagens \ ArangoDb \ Document ; foreach ( $ this -> _data as $ key => $ value ) { $ document -> set ( $ key , $ value ) ; } if ( $ this -> _id ) { $ document -> setInternalId ( $ this -> _id ) ; } if ( $ this -> _key ) { $ document -> setInternalKey ( $ this -> _key ) ; } if ( $ this -> _rev ) { $ document -> setRevision ( $ this -> _rev ) ; } return $ document ; }

Returns an ArangoDB-PHP document object representing this pod.
@return \triagens\ArangoDb\Document

Returns an ArangoDB - PHP document object representing this pod .


public function loadFromDriver(\triagens\ArangoDb\Document $driverDocument)
    {
        $values = $driverDocument->getAll(array('_includeInternals' => true));

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

            if (!in_array($key, array('_id', '_key', '_rev'))) {
                $this->_data[$key] = $value;
            }
        }

        $this->setId($driverDocument->getInternalId());
        $this->setRevision($driverDocument->getRevision());
        $this->setSaved();
    }

public function loadFromDriver ( \ triagens \ ArangoDb \ Document $ driverDocument ) { $ values = $ driverDocument -> getAll ( array ( '_includeInternals' => true ) ) ; foreach ( $ values as $ key => $ value ) { if ( ! in_array ( $ key , array ( '_id' , '_key' , '_rev' ) ) ) { $ this -> _data [ $ key ] = $ value ; } } $ this -> setId ( $ driverDocument -> getInternalId ( ) ) ; $ this -> setRevision ( $ driverDocument -> getRevision ( ) ) ; $ this -> setSaved ( ) ; }

Load this pod with document data from a ArangoDB-PHP document object.
@param \triagens\ArangoDb\Document $driverDocument

Load this pod with document data from a ArangoDB - PHP document object .


public function loadFromArray($data)
    {
        foreach ($data as $property => $value) {

            switch ($property) {

                case "_id":
                    $this->setId($value);
                    break;

                case "_key":
                    break;

                case "_rev":
                    $this->setRevision($value);
                    break;

                default:
                    $this->_data[$property] = $value;
                    break;
            }
        }
    }

public function loadFromArray ( $ data ) { foreach ( $ data as $ property => $ value ) { switch ( $ property ) { case "_id" : $ this -> setId ( $ value ) ; break ; case "_key" : break ; case "_rev" : $ this -> setRevision ( $ value ) ; break ; default : $ this -> _data [ $ property ] = $ value ; break ; } } }

Load this pod with document data from an array.
@param array $data

Load this pod with document data from an array .


public function onEvent(Event $eventObject)
    {
        if ($eventObject->getObject() === $this) {

            switch ($eventObject->getEvent()) {

                case 'after_dispense':
                    $this->getModel()->afterDispense();
                    break;

                case 'after_open':
                    $this->getModel()->afterOpen();
                    break;

                case 'before_store':
                    $this->getModel()->beforeStore();
                    break;

                case 'after_store':
                    $this->getModel()->afterStore();
                    break;

                case 'before_delete':
                    $this->getModel()->beforeDelete();
                    break;

                case 'after_delete':
                    $this->getModel()->afterDelete();
                    break;
            }

        }
    }

public function onEvent ( Event $ eventObject ) { if ( $ eventObject -> getObject ( ) === $ this ) { switch ( $ eventObject -> getEvent ( ) ) { case 'after_dispense' : $ this -> getModel ( ) -> afterDispense ( ) ; break ; case 'after_open' : $ this -> getModel ( ) -> afterOpen ( ) ; break ; case 'before_store' : $ this -> getModel ( ) -> beforeStore ( ) ; break ; case 'after_store' : $ this -> getModel ( ) -> afterStore ( ) ; break ; case 'before_delete' : $ this -> getModel ( ) -> beforeDelete ( ) ; break ; case 'after_delete' : $ this -> getModel ( ) -> afterDelete ( ) ; break ; } } }

When this pod recieves an event, process it accordingly.
In this case, the pod simply calls the various functions in model before and after each event.
@param Event $eventObject The event object.

When this pod recieves an event process it accordingly . In this case the pod simply calls the various functions in model before and after each event .


public function setTo(AModel $to)
    {
        $this->_to = $to;
        $this->setInternalTo($to->getPod()->getId());
    }

public function setTo ( AModel $ to ) { $ this -> _to = $ to ; $ this -> setInternalTo ( $ to -> getPod ( ) -> getId ( ) ) ; }

Set the "to" vertex of the edge.
@param AModel $to


public function getToId()
    {
        if (isset($this->_to)) {
            return $this->_to->getPod()->getId();
        } elseif (isset($this->_data['_to'])) {
            return $this->_data['_to'];
        } else {
            return null;
        }
    }

public function getToId ( ) { if ( isset ( $ this -> _to ) ) { return $ this -> _to -> getPod ( ) -> getId ( ) ; } elseif ( isset ( $ this -> _data [ '_to' ] ) ) { return $ this -> _data [ '_to' ] ; } else { return null ; } }

Get the id of the to node by checking for it in the actual _to property or checking an internal property.
This is used because when documents are retrieved from the server, we will not have a model in the _to property.
This allows us to lazy load any vertices we need later.
@return null|string

Get the id of the to node by checking for it in the actual _to property or checking an internal property . This is used because when documents are retrieved from the server we will not have a model in the _to property . This allows us to lazy load any vertices we need later .


public function setFrom(AModel $from)
    {
        $this->_from = $from;
        $this->setInternalFrom($from->getPod()->getId());
    }

public function setFrom ( AModel $ from ) { $ this -> _from = $ from ; $ this -> setInternalFrom ( $ from -> getPod ( ) -> getId ( ) ) ; }

Set the "from" vertex of the edge.
@param AModel $from


public function getFromId()
    {
        if (isset($this->_from)) {
            return $this->_from->getPod()->getId();
        } elseif (isset($this->_data['_from'])) {
            return $this->_data['_from'];
        } else {
            return null;
        }
    }

public function getFromId ( ) { if ( isset ( $ this -> _from ) ) { return $ this -> _from -> getPod ( ) -> getId ( ) ; } elseif ( isset ( $ this -> _data [ '_from' ] ) ) { return $ this -> _data [ '_from' ] ; } else { return null ; } }

Get the id of the to node by checking for it in the actual _from property or checking an internal property.
This is used because when documents are retrieved from the server, we will not have a model in the _from property.
This allows us to lazy load any vertices we need later.
@return null|string

Get the id of the to node by checking for it in the actual _from property or checking an internal property . This is used because when documents are retrieved from the server we will not have a model in the _from property . This allows us to lazy load any vertices we need later .


public function toDriverDocument()
    {
        $edge = new \triagens\ArangoDb\Edge;

        foreach ($this->_data as $key => $value) {
            $edge->set($key, $value);
        }

        if ($this->_id) {
            $edge->setInternalId($this->_id);
        }

        if ($this->_key) {
            $edge->setInternalKey($this->_key);
        }

        if ($this->_rev) {
            $edge->setRevision($this->_rev);
        }

        return $edge;
    }

public function toDriverDocument ( ) { $ edge = new \ triagens \ ArangoDb \ Edge ; foreach ( $ this -> _data as $ key => $ value ) { $ edge -> set ( $ key , $ value ) ; } if ( $ this -> _id ) { $ edge -> setInternalId ( $ this -> _id ) ; } if ( $ this -> _key ) { $ edge -> setInternalKey ( $ this -> _key ) ; } if ( $ this -> _rev ) { $ edge -> setRevision ( $ this -> _rev ) ; } return $ edge ; }

Returns an ArangoDB-PHP edge object representing this edge.
@return \triagens\ArangoDb\Edge

Returns an ArangoDB - PHP edge object representing this edge .


public function begin()
    {
        if ($this->_activeTransaction) {
            throw new TransactionManagerException("An active transaction already exists.");
        }

        $this->_activeTransaction = true;
        $this->_transactionPaused = false;

        return true;
    }

public
function
begin
(
)
{
if
(
$
this
->
_activeTransaction
)
{
throw
new
TransactionManagerException
(
"An active transaction already exists."
)
;
}
$
this
->
_activeTransaction
=
true
;
$
this
->
_transactionPaused
=
false
;
return
true
;
}


public function commit()
    {
        if (!$this->_activeTransaction) {
            throw new TransactionManagerException("There is no active transaction to commit.");
        }

        if (empty($this->_commands)) {
            throw new TransactionManagerException("There is no transaction operations to commit.");
        }

        $commandText = 'function () { var db = require("internal").db; ';

        //Check if there are graph operations
        foreach ($this->_commands as $command) {

            if ($command['isGraph']) {
                $commandText .= "var g = require('org/arangodb/graph').Graph; var graph = new g('{$this->_toolbox->getGraph()}'); ";
                break;
            }
        }

        $commandText .= 'var result = {}; ';

        //Now, add the commands
        foreach ($this->_commands as $id => $command) {

            $commandText .= "result.$id = {$command['command']} ";
        }

        $commandText .= "return result; }";

        //Send the transaction
        $result = $this->executeTransaction($commandText, $this->_collections['read'], $this->_collections['write']);

        //Process the result
        $processed = $this->processResult($result);

        $this->clearTransactionInfo();

        return $processed;
    }


private function clearTransactionInfo()
    {
        $this->_activeTransaction = false;
        $this->_transactionPaused = true;
        $this->_collections = array('write' => array(), 'read' => array());
        $this->_commands = array();
        $this->_registeredResults = array();
    }

private function clearTransactionInfo ( ) { $ this -> _activeTransaction = false ; $ this -> _transactionPaused = true ; $ this -> _collections = array ( 'write' => array ( ) , 'read' => array ( ) ) ; $ this -> _commands = array ( ) ; $ this -> _registeredResults = array ( ) ; }

Clear the saved information for the transaction.

Clear the saved information for the transaction .


public function addReadCollection($collection)
    {
        if (!$this->_activeTransaction) {
            throw new TransactionManagerException("There is no active transaction.");
        }

        if (!in_array($collection, $this->_collections['read'])) {
            $this->_collections['read'][] = $collection;
        }
    }

public
function
addReadCollection
(
$
collection
)
{
if
(
!
$
this
->
_activeTransaction
)
{
throw
new
TransactionManagerException
(
"There is no active transaction."
)
;
}
if
(
!
in_array
(
$
collection
,
$
this
->
_collections
[
'read'
]
)
)
{
$
this
->
_collections
[
'read'
]
[
]
=
$
collection
;
}
}

Add a collection that will be locked for reading.
@param string $collection The name of the collection.

Add a collection that will be locked for reading .


public function addWriteCollection($collection)
    {
        if (!$this->_activeTransaction) {
            throw new TransactionManagerException("There is no active transaction.");
        }

        if (!in_array($collection, $this->_collections['write'])) {
            $this->_collections['write'][] = $collection;
        }
    }

public
function
addWriteCollection
(
$
collection
)
{
if
(
!
$
this
->
_activeTransaction
)
{
throw
new
TransactionManagerException
(
"There is no active transaction."
)
;
}
if
(
!
in_array
(
$
collection
,
$
this
->
_collections
[
'write'
]
)
)
{
$
this
->
_collections
[
'write'
]
[
]
=
$
collection
;
}
}

Add a collection that will be locked for writing.
@param string $collection The name of the collection.

Add a collection that will be locked for writing .


public function pause()
    {
        if (!$this->_activeTransaction) {
            throw new TransactionManagerException("There is no active transaction.");
        }

        if ($this->_transactionPaused) {
            throw new TransactionManagerException("The transaction is already paused.");
        }

        $this->_transactionPaused = true;
    }

public
function
pause
(
)
{
if
(
!
$
this
->
_activeTransaction
)
{
throw
new
TransactionManagerException
(
"There is no active transaction."
)
;
}
if
(
$
this
->
_transactionPaused
)
{
throw
new
TransactionManagerException
(
"The transaction is already paused."
)
;
}
$
this
->
_transactionPaused
=
true
;
}

Pause the transaction, so that operations after this point are not part of the transaction.

Pause the transaction so that operations after this point are not part of the transaction .


public function resume()
    {
        if (!$this->_activeTransaction) {
            throw new TransactionManagerException("There is no active transaction.");
        }

        if (!$this->_transactionPaused) {
            throw new TransactionManagerException("The transaction is not paused.");
        }

        $this->_transactionPaused = false;
    }

public
function
resume
(
)
{
if
(
!
$
this
->
_activeTransaction
)
{
throw
new
TransactionManagerException
(
"There is no active transaction."
)
;
}
if
(
!
$
this
->
_transactionPaused
)
{
throw
new
TransactionManagerException
(
"The transaction is not paused."
)
;
}
$
this
->
_transactionPaused
=
false
;
}

Resume the transaction, so that operations after this point are part of the transaction.

Resume the transaction so that operations after this point are part of the transaction .


public function addCommand($command, $action, $object = null, $isGraph = false, $data = array())
    {
        if (!$this->_activeTransaction) {
            throw new TransactionManagerException("There is no active transaction.");
        }

        $id = $this->random();
        $this->_commands[$id] = array('command' => $command, 'action' => $action, 'object' => $object, 'isGraph' => $isGraph, 'data' => $data);

        return $id;
    }

public
function
addCommand
(
$
command
,
$
action
,
$
object
=
,
$
isGraph
=
false
,
$
data
=
array
(
)
)
{
if
(
!
$
this
->
_activeTransaction
)
{
throw
new
TransactionManagerException
(
"There is no active transaction."
)
;
}
$
id
=
$
this
->
random
(
)
;
$
this
->
_commands
[
$
id
]
=
array
(
'command'
=>
$
command
,
'action'
=>
$
action
,
'object'
=>
$
object
,
'isGraph'
=>
$
isGraph
,
'data'
=>
$
data
)
;
return
$
id
;
}

Add a command to be executed for the transaction.
@param  string $command The javascript command for the transaction.
@param  string $action  The name of the operation.
@param  string $object  An optional object or model that can be used to process results after committing the transaction.
@param  string $isGraph Whether this command is for a graph or not.
@param  array  $data    Any other data that should be stored with this command.
@return string $id The id of this command.

Add a command to be executed for the transaction .


public function searchCommandsByActionAndObject($action, $object)
    {
        $position = 0;
        $length = count($this->_commands);
        foreach (array_reverse($this->_commands) as $id => $command) {

            if ($command['action'] == $action && $command['object'] === $object) {
                return array('position' => $length - 1 - $position, 'id' => $id);
            }

            $position++;
        }

        return null;
    }

public function searchCommandsByActionAndObject ( $ action , $ object ) { $ position = 0 ; $ length = count ( $ this -> _commands ) ; foreach ( array_reverse ( $ this -> _commands ) as $ id => $ command ) { if ( $ command [ 'action' ] == $ action && $ command [ 'object' ] === $ object ) { return array ( 'position' => $ length - 1 - $ position , 'id' => $ id ) ; } $ position ++ ; } return null ; }

Search the commands for an action and its object. If a match is found, the position and id is returned.
The search starts in reverse direction.
@param  string $action The action to search on
@param  mixed  $object The object to match.
@return array

Search the commands for an action and its object . If a match is found the position and id is returned . The search starts in reverse direction .


private function random()
    {
        $characters = 'abcdefghijklmnopqrstuvwxyz';

        $id = '';

        while (strlen($id) < 7 || in_array($id, array_keys($this->_commands))) {
            $id .= $characters[rand(0, strlen($characters) - 1)];
        }

        return $id;
    }

private function random ( ) { $ characters = 'abcdefghijklmnopqrstuvwxyz' ; $ id = '' ; while ( strlen ( $ id ) < 7 || in_array ( $ id , array_keys ( $ this -> _commands ) ) ) { $ id .= $ characters [ rand ( 0 , strlen ( $ characters ) - 1 ) ] ; } return $ id ; }

Convinence function to generate a random name for each command that will be sent to the server.
@return string

Convinence function to generate a random name for each command that will be sent to the server .


public function createGraph($name)
    {
        try {
            $graph = new \triagens\ArangoDb\Graph($name);
            $graph->setVerticesCollection($name . 'VertexCollection');
            $graph->setEdgesCollection($name . 'EdgeCollection');

            return $this->_toolbox->getGraphHandler()->createGraph($graph);

        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new GraphManagerException($normalised['message'], $normalised['code']);
        }
    }

public function createGraph ( $ name ) { try { $ graph = new \ triagens \ ArangoDb \ Graph ( $ name ) ; $ graph -> setVerticesCollection ( $ name . 'VertexCollection' ) ; $ graph -> setEdgesCollection ( $ name . 'EdgeCollection' ) ; return $ this -> _toolbox -> getGraphHandler ( ) -> createGraph ( $ graph ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new GraphManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Create a graph using the current connection's settings and add it as a connection.
You do not need to set the vertex and edge collections. They are automatically named for you.
@param  string                $name The name of the graph.
@throws GraphManagerException
@return boolean

Create a graph using the current connection s settings and add it as a connection . You do not need to set the vertex and edge collections . They are automatically named for you .


public function deleteGraph($name)
    {
        try {
            $graphHandler = $this->_toolbox->getGraphHandler();

            return $graphHandler->dropGraph($name);
        } catch (\Exception $e) {
            $normalised = $this->_toolbox->normaliseDriverExceptions($e);
            throw new GraphManagerException($normalised['message'], $normalised['code']);
        }
    }

public function deleteGraph ( $ name ) { try { $ graphHandler = $ this -> _toolbox -> getGraphHandler ( ) ; return $ graphHandler -> dropGraph ( $ name ) ; } catch ( \ Exception $ e ) { $ normalised = $ this -> _toolbox -> normaliseDriverExceptions ( $ e ) ; throw new GraphManagerException ( $ normalised [ 'message' ] , $ normalised [ 'code' ] ) ; } }

Delete a graph.
@param  string                $name The name of the graph.
@throws GraphManagerException


public function getGraphInfo($name)
    {
        $graphHandler = $this->_toolbox->getGraphHandler();

        $graph = $graphHandler->getGraph($name);

        if(!$graph){
            throw new GraphManagerException("Graph does not exist");
        }

        $result = array();

        $result['id'] = $graph->getKey();
        $result['name'] = $graph->getKey();
        $result['revision'] = $graph->getRevision();
        $result['verticesCollection'] = $graph->getVerticesCollection();
        $result['edgesCollection'] = $graph->getEdgesCollection();

        return $result;

    }

public
function
getGraphInfo
(
$
name
)
{
$
graphHandler
=
$
this
->
_toolbox
->
getGraphHandler
(
)
;
$
graph
=
$
graphHandler
->
getGraph
(
$
name
)
;
if
(
!
$
graph
)
{
throw
new
GraphManagerException
(
"Graph does not exist"
)
;
}
$
result
=
array
(
)
;
$
result
[
'id'
]
=
$
graph
->
getKey
(
)
;
$
result
[
'name'
]
=
$
graph
->
getKey
(
)
;
$
result
[
'revision'
]
=
$
graph
->
getRevision
(
)
;
$
result
[
'verticesCollection'
]
=
$
graph
->
getVerticesCollection
(
)
;
$
result
[
'edgesCollection'
]
=
$
graph
->
getEdgesCollection
(
)
;
return
$
result
;
}

Get information about a graph.
@param  string                $name The name of the graph.
@throws GraphManagerException
@return array


public function getOutboundEdges($model, $label = null, $aql = "", $params = array(), $placeholder = "doc")
    {
        $id = $this->getVertexId($model);

        if (!$id) {
            return array();
        }

        $collectionParameter = $this->_toolbox->generateBindingParameter('@collection', $params);
        $vertexParameter = $this->_toolbox->generateBindingParameter('vertexid', $params);
        $directionParameter = $this->_toolbox->generateBindingParameter('direction', $params);

        if (!$label) {
            $query = "FOR $placeholder in EDGES(@$collectionParameter, @$vertexParameter, @$directionParameter) " . $aql . " return $placeholder";
        } else {
            $labelParameter = $this->_toolbox->generateBindingParameter('label', $params);
            $params[$labelParameter] = $label;
            $query = "FOR $placeholder in EDGES(@$collectionParameter, @$vertexParameter, @$directionParameter, [{'\$label': @$labelParameter}]) " . $aql . " return $placeholder";
        }

        $params[$collectionParameter] = $this->_toolbox->getEdgeCollectionName();
        $params[$vertexParameter] = $id;
        $params[$directionParameter] = "outbound";

        if ($this->_toolbox->getTransactionManager()->hasTransaction()) {
            $this->_toolbox->getTransactionManager()->addReadCollection($this->_toolbox->getEdgeCollectionName());
            $statement = json_encode(array('query' => $query, 'bindVars' => $params), JSON_FORCE_OBJECT);
            $this->_toolbox->getTransactionManager()->addCommand("db._createStatement($statement).execute().elements();", "GraphManager:getOutboundEdges", null, true);

        } else {
            try {
                $result = $this->_toolbox->getQuery()->getAll($query, $params);
            } catch (\Exception $e) {
                throw new GraphManagerException($e->getMessage(), $e->getCode());
            }

            if (empty($result)) {
                return array();
            }

            return $this->convertToPods("edge", $result);
        }
    }

Get all outbound edges to this vertex. The edges can be filtered by their labels and AQL.
@param Document|Model|string A vertex pod, model or string of the vertex id.
@param  string $label       A string representing one label or an array of labels we want the inbound edges to have.
@param  string $aql         An optional AQL fragment if we want to filter the edges, for example: FILTER doc.someproperty == "somevalue"
@param  array  $params      An optional associative array containing parameters to bind to the query.
@param  string $placeholder Set this to something else if you do not wish to use "doc" to refer to documents in your query.
@return array

Get all outbound edges to this vertex . The edges can be filtered by their labels and AQL .


public function getFilters()
    {
        if ($this->_filters) {
            return $this->_filters;
        } elseif (isset($this->_View->viewVars['filters'])) {
            return $this->_View->viewVars['filters'];
        }

        return [];
    }

public function getFilters ( ) { if ( $ this -> _filters ) { return $ this -> _filters ; } elseif ( isset ( $ this -> _View -> viewVars [ 'filters' ] ) ) { return $ this -> _View -> viewVars [ 'filters' ] ; } return [ ] ; }

Returns the filter config

@return array


public function renderFilterbox($filters = null)
    {
        if ($filters) {
            $this->_filters = $filters;
        }

        $filterBox = $this->openContainer();
        $filterBox .= $this->openForm();
        $filterBox .= $this->renderAll();
        $filterBox .= $this->closeForm();
        $filterBox .= $this->closeContainer();

        $ret = $this->_View->element('ListFilter.wrapper', [
            'filterBox' => $filterBox,
            'options' => $this->config()
        ]);

        return $ret;
    }

public function renderFilterbox ( $ filters = null ) { if ( $ filters ) { $ this -> _filters = $ filters ; } $ filterBox = $ this -> openContainer ( ) ; $ filterBox .= $ this -> openForm ( ) ; $ filterBox .= $ this -> renderAll ( ) ; $ filterBox .= $ this -> closeForm ( ) ; $ filterBox .= $ this -> closeContainer ( ) ; $ ret = $ this -> _View -> element ( 'ListFilter.wrapper' , [ 'filterBox' => $ filterBox , 'options' => $ this -> config ( ) ] ) ; return $ ret ; }

Render the complete filter widget

@param array $filters Filters to render. If none given, it uses a viewVar called "filters"
@return string


public function renderAll()
    {
        $widgets = [];

        foreach ($this->getFilters() as $field => $options) {
            $w = $this->filterWidget($field, $options, false);
            if ($w) {
                $widgets = array_merge($widgets, $w);
            }
        }
        // FIXME allow column-layout to be configured with templates.
        $ret = '
';
        foreach ($widgets as $i => $widget) {
            $ret .= '
';
            $ret .= $widget;
            $ret .= '
';
            if (($i + 1) % 2 === 0) {
                $ret .= '

';
            }
        }
        $ret .= '
';

        return $ret;
    }

Render all filter widgets

@return string


public function openContainer()
    {
        $classes = $this->config('containerClasses');

        $title = __d('list_filter', 'list_filter.filter_fieldset_title');

        if ($this->filterActive()) {
            $classes .= ' opened';
        } else {
            $classes .= ' closed';
        }

        $ret = $this->templater()->format('containerStart', [
            'attrs' => $this->templater()->formatAttributes([
                'class' => $classes
            ])
        ]);
        $ret .= $this->header();
        $ret .= $this->templater()->format('contentStart', [
            'attrs' => $this->templater()->formatAttributes([
                'class' => $this->config('contentClasses')
            ])
        ]);

        return $ret;
    }

public
function
openContainer
(
)
{
$
classes
=
$
this
->
config
(
'containerClasses'
)
;
$
title
=
__d
(
'list_filter'
,
'list_filter.filter_fieldset_title'
)
;
if
(
$
this
->
filterActive
(
)
)
{
$
classes
.=
' opened'
;
}
else
{
$
classes
.=
' closed'
;
}
$
ret
=
$
this
->
templater
(
)
->
format
(
'containerStart'
,
[
'attrs'
=>
$
this
->
templater
(
)
->
formatAttributes
(
[
'class'
=>
$
classes
]
)
]
)
;
$
ret
.=
$
this
->
header
(
)
;
$
ret
.=
$
this
->
templater
(
)
->
format
(
'contentStart'
,
[
'attrs'
=>
$
this
->
templater
(
)
->
formatAttributes
(
[
'class'
=>
$
this
->
config
(
'contentClasses'
)
]
)
]
)
;
return
$
ret
;
}


public function closeContainer()
    {
        $ret = $this->templater()->format('contentEnd', []);
        $ret .= $this->templater()->format('containerEnd', []);

        return $ret;
    }

public function closeContainer ( ) { $ ret = $ this -> templater ( ) -> format ( 'contentEnd' , [ ] ) ; $ ret .= $ this -> templater ( ) -> format ( 'containerEnd' , [ ] ) ; return $ ret ; }

Closes the HTML container

@return string


public function openForm()
    {
        $options = Hash::merge(['url' => $this->here], $this->config('formOptions'));
        $ret = $this->Form->create('Filter', $options);

        return $ret;
    }

public function openForm ( ) { $ options = Hash :: merge ( [ 'url' => $ this -> here ] , $ this -> config ( 'formOptions' ) ) ; $ ret = $ this -> Form -> create ( 'Filter' , $ options ) ; return $ ret ; }

Opens the listfilter form

@return string


public function closeForm($includeFilterButton = true, $includeResetButton = true)
    {
        $buttons = '';
        if ($includeFilterButton) {
            $buttons .= $this->filterButton();
        }
        if ($includeResetButton) {
            $buttons .= ' ' . $this->resetButton();
        }
        $ret = $this->templater()->format('buttons', [
            'buttons' => $buttons
        ]);
        $ret .= $this->Form->end();

        return $ret;
    }

public
function
closeForm
(
$
includeFilterButton
=
true
,
$
includeResetButton
=
true
)
{
$
buttons
=
''
;
if
(
$
includeFilterButton
)
{
$
buttons
.=
$
this
->
filterButton
(
)
;
}
if
(
$
includeResetButton
)
{
$
buttons
.=
' '
.
$
this
->
resetButton
(
)
;
}
$
ret
=
$
this
->
templater
(
)
->
format
(
'buttons'
,
[
'buttons'
=>
$
buttons
]
)
;
$
ret
.=
$
this
->
Form
->
end
(
)
;
return
$
ret
;
}

Closes the listfilter form

@param bool $includeFilterButton add the search button
@param bool $includeResetButton add the reset button
@return string


public function filterActive()
    {
        $filterActive = (isset($this->_View->viewVars['filterActive'])
                        && $this->_View->viewVars['filterActive'] === true);

        return $filterActive;
    }

public function filterActive ( ) { $ filterActive = ( isset ( $ this -> _View -> viewVars [ 'filterActive' ] ) && $ this -> _View -> viewVars [ 'filterActive' ] === true ) ; return $ filterActive ; }

Determines if any ListFilter parameters are set

@return bool


public function filterButton($title = null, array $options = [])
    {
        if (!$title) {
            $title = __d('list_filter', 'list_filter.search');
        }
        $options = Hash::merge($this->config('filterButtonOptions'), $options);

        return $this->Form->button($title, $options);
    }

public function filterButton ( $ title = null , array $ options = [ ] ) { if ( ! $ title ) { $ title = __d ( 'list_filter' , 'list_filter.search' ) ; } $ options = Hash :: merge ( $ this -> config ( 'filterButtonOptions' ) , $ options ) ; return $ this -> Form -> button ( $ title , $ options ) ; }

Outputs the search button

@param string $title button caption
@param array $options Options
@return string


public function resetButton($title = null, array $options = [])
    {
        if (!$title) {
            $title = __d('list_filter', 'list_filter.reset');
        }
        $params = $this->_View->request->query;
        if (!empty($params)) {
            foreach ($params as $field => $value) {
                if (substr($field, 0, 7) == 'Filter-') {
                    unset($params[$field]);
                }
            }
        }
        $options = Hash::merge($this->config('resetButtonOptions'), $options);
        $url = Hash::merge($this->request->params, [
            'resetFilter' => true
        ]);

        return $this->Html->link($title, Router::reverse($url), $options);
    }

public function resetButton ( $ title = null , array $ options = [ ] ) { if ( ! $ title ) { $ title = __d ( 'list_filter' , 'list_filter.reset' ) ; } $ params = $ this -> _View -> request -> query ; if ( ! empty ( $ params ) ) { foreach ( $ params as $ field => $ value ) { if ( substr ( $ field , 0 , 7 ) == 'Filter-' ) { unset ( $ params [ $ field ] ) ; } } } $ options = Hash :: merge ( $ this -> config ( 'resetButtonOptions' ) , $ options ) ; $ url = Hash :: merge ( $ this -> request -> params , [ 'resetFilter' => true ] ) ; return $ this -> Html -> link ( $ title , Router :: reverse ( $ url ) , $ options ) ; }

Outputs the filter reset link

@param string $title caption for the reset button
@param array $options Options
@return string


public function backToListButton($title = null, array $url = null, array $options = [])
    {
        if (empty($url)) {
            $url = [
                'action' => 'index'
            ];
        }
        $options = Hash::merge([
            'class' => 'btn btn-default btn-xs',
            'escape' => false,
            'additionalClasses' => null,
            'useReferer' => false
        ], $options);

        if (!empty($options['useReferer']) && $this->request->referer(true) != '/' && $this->request->referer(true) != $this->request->here) {
            $url = $this->request->referer(true);
        }

        if (!$title) {
            $title = '' . __d('list_filter', 'forms.back_to_list') . '';
        }

        if ($options['additionalClasses']) {
            $options['class'] .= ' ' . $options['additionalClasses'];
        }

        if (empty($options['useReferer'])) {
            $url = $this->addListFilterParams($url);
        }
        $button = $this->Html->link(' ' . $title, $url, $options);

        return $button;
    }

public
function
backToListButton
(
$
title
=
,
array
$
url
=
,
array
$
options
=
[
]
)
{
if
(
empty
(
$
url
)
)
{
$
url
=
[
'action'
=>
'index'
]
;
}
$
options
=
Hash
::
merge
(
[
'class'
=>
'btn btn-default btn-xs'
,
'escape'
=>
false
,
'additionalClasses'
=>
,
'useReferer'
=>
false
]
,
$
options
)
;
if
(
!
empty
(
$
options
[
'useReferer'
]
)
&&
$
this
->
request
->
referer
(
true
)
!=
'/'
&&
$
this
->
request
->
referer
(
true
)
!=
$
this
->
request
->
here
)
{
$
url
=
$
this
->
request
->
referer
(
true
)
;
}
if
(
!
$
title
)
{
$
title
=
''
.
__d
(
'list_filter'
,
'forms.back_to_list'
)
.
''
;
}
if
(
$
options
[
'additionalClasses'
]
)
{
$
options
[
'class'
]
.=
' '
.
$
options
[
'additionalClasses'
]
;
}
if
(
empty
(
$
options
[
'useReferer'
]
)
)
{
$
url
=
$
this
->
addListFilterParams
(
$
url
)
;
}
$
button
=
$
this
->
Html
->
link
(
' '
.
$
title
,
$
url
,
$
options
)
;
return
$
button
;
}

Renders a back-to-list button using the ListFilter-relevant named params

@param string $title button caption
@param array $url url to link to
@param array $options link() config
@return string

Renders a back - to - list button using the ListFilter - relevant named params


protected function _getPersistendStorageKey($key)
    {
        if (!isset($this->config[$key]['namespace'])) {
            $namespace = 'ListFilter';
        } else {
            $namespace = $this->config[$key]['namespace'];
        }
        $sessionKey = [
            'namespace' => $namespace,
            'plugin' => 'App',
            'controller' => $this->_controller->request->controller,
            'action' => $this->_controller->request->action
        ];
        if (!empty($this->_controller->request->plugin)) {
            $sessionKey['plugin'] = $this->_controller->request->plugin;
        }
        $sessionKey = implode('.', $sessionKey);

        return $sessionKey;
    }

protected function _getPersistendStorageKey ( $ key ) { if ( ! isset ( $ this -> config [ $ key ] [ 'namespace' ] ) ) { $ namespace = 'ListFilter' ; } else { $ namespace = $ this -> config [ $ key ] [ 'namespace' ] ; } $ sessionKey = [ 'namespace' => $ namespace , 'plugin' => 'App' , 'controller' => $ this -> _controller -> request -> controller , 'action' => $ this -> _controller -> request -> action ] ; if ( ! empty ( $ this -> _controller -> request -> plugin ) ) { $ sessionKey [ 'plugin' ] = $ this -> _controller -> request -> plugin ; } $ sessionKey = implode ( '.' , $ sessionKey ) ; return $ sessionKey ; }

Get persistent storage key for ListFilter form handling

@param  string  $key  The storage key defined in config
@return array


public function filterUrlParameterStatus()
    {
        foreach ($this->_controller->request->query as $arg => $value) {
            if (substr($arg, 0, 7) == 'Filter-') {
                return true;
            }
        }

        return false;
    }

public function filterUrlParameterStatus ( ) { foreach ( $ this -> _controller -> request -> query as $ arg => $ value ) { if ( substr ( $ arg , 0 , 7 ) == 'Filter-' ) { return true ; } } return false ; }

checks URL for any Filter Parameter

@return bool


protected function _getFulltextSearchConditions($conditionField, $value, array $options)
    {
        $searchTerms = explode(' ', $value);
        $searchTerms = array_map('trim', $searchTerms);
        $searchTerms = array_map('mb_strtolower', $searchTerms);

        if (isset($options['termsCallback']) && is_callable($options['termsCallback'])) {
            $searchTerms = $options['termsCallback']($searchTerms);
        }

        $searchFields = [$conditionField];
        if (!empty($options['searchFields'])) {
            $searchFields = $options['searchFields'];
        }
        $conditions = [];
        $conjunction = $this->config['searchTermsConjunction'];
        foreach ($searchTerms as $key => $term) {
            $searchFieldConditions = [];

            if (is_array($term)) {
                foreach ($term as $item) {
                    foreach ($searchFields as $searchField) {
                        $searchFieldConditions["{$searchField} LIKE"] = "%{$item}%";
                    }

                    $conditions[$conjunction][$key]['OR'][] = [
                        'OR' => $searchFieldConditions
                    ];
                }
            } else {
                foreach ($searchFields as $searchField) {
                    $searchFieldConditions["{$searchField} LIKE"] = "%{$term}%";
                }

                $conditions[$conjunction][$key] = [
                    'OR' => $searchFieldConditions
                ];
            }
        }

        return $conditions;
    }

protected
function
_getFulltextSearchConditions
(
$
conditionField
,
$
value
,
array
$
options
)
{
$
searchTerms
=
explode
(
' '
,
$
value
)
;
$
searchTerms
=
array_map
(
'trim'
,
$
searchTerms
)
;
$
searchTerms
=
array_map
(
'mb_strtolower'
,
$
searchTerms
)
;
if
(
isset
(
$
options
[
'termsCallback'
]
)
&&
is_callable
(
$
options
[
'termsCallback'
]
)
)
{
$
searchTerms
=
$
options
[
'termsCallback'
]
(
$
searchTerms
)
;
}
$
searchFields
=
[
$
conditionField
]
;
if
(
!
empty
(
$
options
[
'searchFields'
]
)
)
{
$
searchFields
=
$
options
[
'searchFields'
]
;
}
$
conditions
=
[
]
;
$
conjunction
=
$
this
->
config
[
'searchTermsConjunction'
]
;
foreach
(
$
searchTerms
as
$
key
=>
$
term
)
{
$
searchFieldConditions
=
[
]
;
if
(
is_array
(
$
term
)
)
{
foreach
(
$
term
as
$
item
)
{
foreach
(
$
searchFields
as
$
searchField
)
{
$
searchFieldConditions
[
"{$searchField} LIKE"
]
=
"%{$item}%"
;
}
$
conditions
[
$
conjunction
]
[
$
key
]
[
'OR'
]
[
]
=
[
'OR'
=>
$
searchFieldConditions
]
;
}
}
else
{
foreach
(
$
searchFields
as
$
searchField
)
{
$
searchFieldConditions
[
"{$searchField} LIKE"
]
=
"%{$term}%"
;
}
$
conditions
[
$
conjunction
]
[
$
key
]
=
[
'OR'
=>
$
searchFieldConditions
]
;
}
}
return
$
conditions
;
}

Splits the search term in value to multiple terms and constructs a OR-style
conditions array for each term, for each field to be searched.

@param string $conditionField Primary field to search in
@param string $value Search Term
@param array $options Filter configuration
@return array

Splits the search term in value to multiple terms and constructs a OR - style conditions array for each term for each field to be searched .


protected function _flattenValueOptions(array $options)
    {
        $flatOptions = $options;
        if (is_array(current($options))) {
            $flatOptions = [];
            foreach ($options as $group => $valueGroup) {
                $flatOptions = $flatOptions + $valueGroup;
            }
        }

        return $flatOptions;
    }

protected function _flattenValueOptions ( array $ options ) { $ flatOptions = $ options ; if ( is_array ( current ( $ options ) ) ) { $ flatOptions = [ ] ; foreach ( $ options as $ group => $ valueGroup ) { $ flatOptions = $ flatOptions + $ valueGroup ; } } return $ flatOptions ; }

Make sure options arrays are flattened and consolidated before they are used for value
checking. This applies to optgroup-style arrays currently

@param array $options Options Config
@return array

Make sure options arrays are flattened and consolidated before they are used for value checking . This applies to optgroup - style arrays currently


public function getFilters()
    {
        $filters = [];
        if (method_exists($this->_controller, 'getListFilters')) {
            $filters = $this->_controller->getListFilters($this->_controller->request->action);
        } elseif (isset($this->_controller->listFilters) && !empty($this->_controller->listFilters[$this->_controller->request->action])) {
            $filters = $this->_controller->listFilters[$this->_controller->request->action];
        }
        if (empty($filters)) {
            return [];
        }
        foreach ($filters['fields'] as $field => &$fieldConfig) {
            if (isset($fieldConfig['type']) && $fieldConfig['type'] == 'select'
                && !isset($fieldConfig['searchType'])
            ) {
                $fieldConfig['searchType'] = 'select';
                $fieldConfig['inputOptions']['type'] = 'select';
                unset($fieldConfig['type']);
            }
            // backwards compatibility
            if (isset($fieldConfig['type'])) {
                $fieldConfig['inputOptions']['type'] = $fieldConfig['type'];
                unset($fieldConfig['type']);
            }
            if (isset($fieldConfig['label'])) {
                $fieldConfig['inputOptions']['label'] = $fieldConfig['label'];
                unset($fieldConfig['label']);
            }
            if (isset($fieldConfig['searchType'])
                && in_array($fieldConfig['searchType'], ['select', 'multipleselect'])
            ) {
                if (!isset($fieldConfig['inputOptions']['type'])) {
                    $fieldConfig['inputOptions']['type'] = 'select';
                }
                if (!isset($fieldConfig['inputOptions']['empty'])) {
                    $fieldConfig['inputOptions']['empty'] = true;
                }
            }
            $fieldConfig = Hash::merge($this->defaultListFilter, $fieldConfig);
        }

        return $filters;
    }

public
function
getFilters
(
)
{
$
filters
=
[
]
;
if
(
method_exists
(
$
this
->
_controller
,
'getListFilters'
)
)
{
$
filters
=
$
this
->
_controller
->
getListFilters
(
$
this
->
_controller
->
request
->
action
)
;
}
elseif
(
isset
(
$
this
->
_controller
->
listFilters
)
&&
!
empty
(
$
this
->
_controller
->
listFilters
[
$
this
->
_controller
->
request
->
action
]
)
)
{
$
filters
=
$
this
->
_controller
->
listFilters
[
$
this
->
_controller
->
request
->
action
]
;
}
if
(
empty
(
$
filters
)
)
{
return
[
]
;
}
foreach
(
$
filters
[
'fields'
]
as
$
field
=>
&
$
fieldConfig
)
{
if
(
isset
(
$
fieldConfig
[
'type'
]
)
&&
$
fieldConfig
[
'type'
]
==
'select'
&&
!
isset
(
$
fieldConfig
[
'searchType'
]
)
)
{
$
fieldConfig
[
'searchType'
]
=
'select'
;
$
fieldConfig
[
'inputOptions'
]
[
'type'
]
=
'select'
;
unset
(
$
fieldConfig
[
'type'
]
)
;
}
// backwards compatibility
if
(
isset
(
$
fieldConfig
[
'type'
]
)
)
{
$
fieldConfig
[
'inputOptions'
]
[
'type'
]
=
$
fieldConfig
[
'type'
]
;
unset
(
$
fieldConfig
[
'type'
]
)
;
}
if
(
isset
(
$
fieldConfig
[
'label'
]
)
)
{
$
fieldConfig
[
'inputOptions'
]
[
'label'
]
=
$
fieldConfig
[
'label'
]
;
unset
(
$
fieldConfig
[
'label'
]
)
;
}
if
(
isset
(
$
fieldConfig
[
'searchType'
]
)
&&
in_array
(
$
fieldConfig
[
'searchType'
]
,
[
'select'
,
'multipleselect'
]
)
)
{
if
(
!
isset
(
$
fieldConfig
[
'inputOptions'
]
[
'type'
]
)
)
{
$
fieldConfig
[
'inputOptions'
]
[
'type'
]
=
'select'
;
}
if
(
!
isset
(
$
fieldConfig
[
'inputOptions'
]
[
'empty'
]
)
)
{
$
fieldConfig
[
'inputOptions'
]
[
'empty'
]
=
true
;
}
}
$
fieldConfig
=
Hash
::
merge
(
$
this
->
defaultListFilter
,
$
fieldConfig
)
;
}
return
$
filters
;
}

Formats and enriches field configs

@return array


public function getRedirectUrlFromPostData(array $postData)
    {
        $urlParams = [];
        foreach ($postData['Filter'] as $model => $fields) {
            foreach ($fields as $field => $value) {
                if (is_array($value) && isset($value['year'])) {
                    $value = "{$value['year']}-{$value['month']}-{$value['day']}";
                    if ($value == '--') {
                        continue;
                    }
                }
                if ($value !== 0 && $value !== '0' && empty($value)) {
                    continue;
                }
                $urlParams["Filter-{$model}-{$field}"] = $value;
            }
        }
        $passedArgs = $this->_controller->passedArgs;
        if (!empty($passedArgs)) {
            $urlParams = Hash::merge($passedArgs, $urlParams);
        }
        $params = $this->_controller->request->query;
        if (!empty($params)) {
            $cleanParams = [];
            foreach ($params as $key => $value) {
                if (substr($key, 0, 7) != 'Filter-') {
                    $cleanParams[$key] = $value;
                }
            }
            $urlParams = Hash::merge($cleanParams, $urlParams);
        }

        return $urlParams;
    }

Converts POST filter data in array format to a URL

@param array $postData Array with Postdata
@return array


public function addListFilterParams(array $url)
    {
        foreach ($this->request->query as $key => $value) {
            if (substr($key, 0, 7) == 'Filter-' || in_array($key, ['page', 'sort', 'direction'])) {
                $url[$key] = $value;
            }
        }

        return $url;
    }

public function addListFilterParams ( array $ url ) { foreach ( $ this -> request -> query as $ key => $ value ) { if ( substr ( $ key , 0 , 7 ) == 'Filter-' || in_array ( $ key , [ 'page' , 'sort' , 'direction' ] ) ) { $ url [ $ key ] = $ value ; } } return $ url ; }

Adds ListFilter-relevant named params to the given url. Used for detail links

@param array $url URL to link to
@return array

Adds ListFilter - relevant named params to the given url . Used for detail links


public function defaultFilters($filters = [])
    {
        if (empty($filters)) {
            return false;
        }
        foreach ($filters as $key => $value) {
            $filterName = 'Filter-' . str_replace('.', '-', $key);
            $explodedFilterName = explode('-', $filterName);
            if (count($explodedFilterName) !== 3) {
                return false;
            }
            if (empty($this->_controller->request->query[$filterName])) {
                // set request POST data so the inputs will be filled
                $this->_controller->request->data[$explodedFilterName[0]][$explodedFilterName[1]][$explodedFilterName[2]] = $value;
                $this->_controller->paginate['conditions'][$key] = $value;
            } elseif ($this->_controller->request->query[$filterName] == 'all') {
                unset($this->_controller->request->data[$explodedFilterName[0]][$explodedFilterName[1]][$explodedFilterName[2]]);
                unset($this->_controller->paginate['conditions'][$key]);
            }
        }

        return true;
    }

Set fields given as keys in FilterList and paginator conditions to given values if not set by URL.

To reset a default value (normally the empty option), an option with key 'all' must be selected.
To imitate the behaviour of empty, set empty in inputOptions to false and add ['all' => ''] to options

Array syntax of $filters has to be:
[
'{$Tables}.{$field}' => {$defaultValue}
]

@param  array  $filters array of fields and their default values like described above
@return bool   false if anything goes wrong, else true

Set fields given as keys in FilterList and paginator conditions to given values if not set by URL .


public static function build($pdo, $sql, array $params)
    {
        $bind_values = [];
        $sql = strtr($sql, "\n", ' ');
        $sql = preg_replace_callback(
            '/'.Query::RE_HOLDER.'/',
            function ($m) use ($pdo, $params, &$bind_values) {
                $key  = $m['key'];
                $type = $m['type'];

                if (!isset($params[$key])) {
                    throw new \OutOfRangeException(sprintf('param "%s" expected but not assigned', $key));
                }

                return self::replaceHolder($pdo, $key, $type, $params[$key], $bind_values);
            },
            $sql
        );

        $stmt = $pdo->prepare($sql);

        foreach ($bind_values as $key => list($type, $value)) {
            $stmt->bindParam($key, $value, $type);
        }

        return $stmt;
    }

public
static
function
build
(
$
pdo
,
$
sql
,
array
$
params
)
{
$
bind_values
=
[
]
;
$
sql
=
strtr
(
$
sql
,
"\n"
,
' '
)
;
$
sql
=
preg_replace_callback
(
'/'
.
Query
::
RE_HOLDER
.
'/'
,
function
(
$
m
)
use
(
$
pdo
,
$
params
,
&
$
bind_values
)
{
$
key
=
$
m
[
'key'
]
;
$
type
=
$
m
[
'type'
]
;
if
(
!
isset
(
$
params
[
$
key
]
)
)
{
throw
new
\
OutOfRangeException
(
sprintf
(
'param "%s" expected but not assigned'
,
$
key
)
)
;
}
return
self
::
replaceHolder
(
$
pdo
,
$
key
,
$
type
,
$
params
[
$
key
]
,
$
bind_values
)
;
}
,
$
sql
)
;
$
stmt
=
$
pdo
->
prepare
(
$
sql
)
;
foreach
(
$
bind_values
as
$
key
=>
list
(
$
type
,
$
value
)
)
{
$
stmt
->
bindParam
(
$
key
,
$
value
,
$
type
)
;
}
return
$
stmt
;
}

Build SQL query

@param \PDO|PDOInterface $pdo
@param string $sql
@param array  $params


public function reduce(callable $callback, $initial = null)
    {
        return i\iterable_reduce($this->iterable, $callback, $initial);
    }

public function reduce ( callable $ callback , $ initial = null ) { return i \ iterable_reduce ( $ this -> iterable , $ callback , $ initial ) ; }

Reduce all elements to a single value using a callback.

@param callable  $callback
@param mixed     $initial
@return mixed

Reduce all elements to a single value using a callback .


public function typeCheck($type, ?\Throwable $throwable = null)
    {
        return $this->then(i\iterable_type_check, $type, $throwable);
    }

public function typeCheck ( $ type , ? \ Throwable $ throwable = null ) { return $ this -> then ( i \ iterable_type_check , $ type , $ throwable ) ; }

Validate that a value has a specific type.

@param string|string[] $type
@param \Throwable|null $throwable
@return static

Validate that a value has a specific type .


public function typeCast(string $type, ?\Throwable $throwable = null)
    {
        return $this->then(i\iterable_type_cast, $type, $throwable);
    }

public function typeCast ( string $ type , ? \ Throwable $ throwable = null ) { return $ this -> then ( i \ iterable_type_cast , $ type , $ throwable ) ; }

Cast a value to the specific type or throw an error.

@param string          $type
@param \Throwable|null $throwable
@return static

Cast a value to the specific type or throw an error .


public function register(Container $app)
    {
        $app['bugsnag.resolver'] = function () {
            return new SilexResolver();
        };

        $app['bugsnag'] = function () use ($app) {
            return $this->makeClient($app);
        };

        $app['bugsnag.notifier'] = function() use ($app) {
            return function($error) use ($app) {
                $this->autoNotify($app['bugsnag'], $error);
            };
        };

        $app->before(function (Request $request) use ($app) {
            $app['bugsnag']->setFallbackType('HTTP');
            $app['bugsnag.resolver']->set($request);
        }, Application::EARLY_EVENT);
    }

public function register ( Container $ app ) { $ app [ 'bugsnag.resolver' ] = function ( ) { return new SilexResolver ( ) ; } ; $ app [ 'bugsnag' ] = function ( ) use ( $ app ) { return $ this -> makeClient ( $ app ) ; } ; $ app [ 'bugsnag.notifier' ] = function ( ) use ( $ app ) { return function ( $ error ) use ( $ app ) { $ this -> autoNotify ( $ app [ 'bugsnag' ] , $ error ) ; } ; } ; $ app -> before ( function ( Request $ request ) use ( $ app ) { $ app [ 'bugsnag' ] -> setFallbackType ( 'HTTP' ) ; $ app [ 'bugsnag.resolver' ] -> set ( $ request ) ; } , Application :: EARLY_EVENT ) ; }

Registers services on the container.

@param \Pimple\Container $app

@return void


protected function makeClient(Application $app)
    {
        try {
            $config = $app['bugsnag.options'];
        } catch (InvalidArgumentException $e) {
            $config = [];
        }

        $key = isset($config['api_key']) ? $config['api_key'] : getenv('BUGSNAG_API_KEY');

        $guzzle = Client::makeGuzzle(isset($config['endpoint']) ? $config['endpoint'] : null);

        $client = new Client(new Configuration($key), $app['bugsnag.resolver'], $guzzle);

        if (!isset($config['callbacks']) || $config['callbacks']) {
            $client->registerDefaultCallbacks();
        }

        if (!isset($config['user']) || $config['user']) {
            $this->setupUserDetection($client, $app);
        }

        $this->setupPaths($client, isset($config['strip_path']) ? $config['strip_path'] : null, isset($config['project_root']) ? $config['project_root'] : null);

        $env = getenv('SYMFONY_ENV') ?: null;
        $stage = isset($config['release_stage']) ? $config['release_stage'] : null;
        $client->setReleaseStage($stage ?: ($env === 'prod' ? 'production' : $env));
        $client->setHostname(isset($config['hostname']) ? $config['hostname'] : null);

        $client->setFallbackType('Console');
        $client->setAppType(isset($config['app_type']) ? $config['app_type'] : null);
        $client->setAppVersion(isset($config['app_version']) ? $config['app_version'] : null);
        $client->setBatchSending(isset($config['batch_sending']) ? $config['batch_sending'] : true);
        $client->setSendCode(isset($config['send_code']) ? $config['send_code'] : true);

        $client->setNotifier([
            'name' => 'Bugsnag Silex',
            'version' => static::VERSION,
            'url' => 'https://github.com/bugsnag/bugsnag-silex',
        ]);

        if (isset($config['notify_release_stages']) && is_array($config['notify_release_stages'])) {
            $client->setNotifyReleaseStages($config['notify_release_stages']);
        }
        if (isset($config['filters']) && is_array($config['filters'])) {
            $client->setFilters($config['filters']);
        }

        return $client;
    }

Make a new bugsnag client instance.

@param \Silex\Application $app

@return \Bugsnag\Client


protected function setupUserDetection(Client $client, Application $app)
    {
        try {
            $tokens = $app['security.token_storage'];
            $checker = $app['security.authorization_checker'];
        } catch (InvalidArgumentException $e) {
            return;
        }

        $client->registerCallback(new CustomUser(function () use ($tokens, $checker) {
            $token = $tokens->getToken();

            if (!$token || !$checker->isGranted('IS_AUTHENTICATED_REMEMBERED')) {
                return;
            }

            $user = $token->getUser();

            if ($user instanceof UserInterface) {
                return ['id' => $user->getUsername()];
            }

            return ['id' => (string) $user];
        }));
    }

protected function setupUserDetection ( Client $ client , Application $ app ) { try { $ tokens = $ app [ 'security.token_storage' ] ; $ checker = $ app [ 'security.authorization_checker' ] ; } catch ( InvalidArgumentException $ e ) { return ; } $ client -> registerCallback ( new CustomUser ( function ( ) use ( $ tokens , $ checker ) { $ token = $ tokens -> getToken ( ) ; if ( ! $ token || ! $ checker -> isGranted ( 'IS_AUTHENTICATED_REMEMBERED' ) ) { return ; } $ user = $ token -> getUser ( ) ; if ( $ user instanceof UserInterface ) { return [ 'id' => $ user -> getUsername ( ) ] ; } return [ 'id' => ( string ) $ user ] ; } ) ) ; }

Setup user detection.

@param \Bugsnag\Client    $client
@param \Silex\Application $app

@return void


protected function setupPaths(Client $client, $strip, $project)
    {
        if ($strip) {
            $client->setStripPath($strip);

            if (!$project) {
                $client->setProjectRoot("{$strip}/src");
            }

            return;
        }

        $base = realpath(__DIR__.'/../../../../');

        if ($project) {
            if ($base && substr($project, 0, strlen($base)) === $base) {
                $client->setStripPath($base);
            }

            $client->setProjectRoot($project);

            return;
        }

        if ($base) {
            $client->setStripPath($base);

            if ($root = realpath("{$base}/src")) {
                $client->setProjectRoot($root);
            }
        }
    }

protected function setupPaths ( Client $ client , $ strip , $ project ) { if ( $ strip ) { $ client -> setStripPath ( $ strip ) ; if ( ! $ project ) { $ client -> setProjectRoot ( "{$strip}/src" ) ; } return ; } $ base = realpath ( __DIR__ . '/../../../../' ) ; if ( $ project ) { if ( $ base && substr ( $ project , 0 , strlen ( $ base ) ) === $ base ) { $ client -> setStripPath ( $ base ) ; } $ client -> setProjectRoot ( $ project ) ; return ; } if ( $ base ) { $ client -> setStripPath ( $ base ) ; if ( $ root = realpath ( "{$base}/src" ) ) { $ client -> setProjectRoot ( $ root ) ; } } }

Setup the client paths.

@param \Bugsnag\Client $client
@param string|null     $strip
@param string|null     $project

@return void


public function stub(string $name): self
    {
        $hasStub = i\iterable_has_any($this->steps, function ($step) use ($name) {
            return $step[0] instanceof Stub && $step[0]->getName() === $name;
        });

        if ($hasStub) {
            throw new \BadMethodCallException("Pipeline builder already has '$name' stub");
        }

        return $this->then(new Stub($name));
    }

Add a stub, which does nothing but can be replaced later.

@param string $name
@return static
@throw \BadMethodCallException if stub already exists

Add a stub which does nothing but can be replaced later .


public function unstub(string $name, callable $callable, ...$args): self
    {
        $index = i\iterable_find_key($this->steps, function ($step) use ($name) {
            return $step[0] instanceof Stub && $step[0]->getName() === $name;
        });

        if ($index === null) {
            throw new \BadMethodCallException("Pipeline builder doesn't have '$name' stub");
        }

        $clone = clone $this;
        $clone->steps[$index] = [$callable, $args];

        return $clone;
    }

Get a pipeline builder where a stub is replaced.

@param string   $name
@param callable $callable
@param mixed    ...$args
@return static

Get a pipeline builder where a stub is replaced .


public function with(iterable $iterable): Pipeline
    {
        $pipeline = new Pipeline($iterable);

        foreach ($this->steps as [$callback, $args]) {
            $pipeline = $pipeline->then($callback, ...$args);
        }

        return $pipeline;
    }

public function with ( iterable $ iterable ) : Pipeline { $ pipeline = new Pipeline ( $ iterable ) ; foreach ( $ this -> steps as [ $ callback , $ args ] ) { $ pipeline = $ pipeline -> then ( $ callback , ... $ args ) ; } return $ pipeline ; }

Create a new pipeline

@param iterable $iterable
@return Pipeline


public function setKeys(iterable $keys)
    {
        $combine = function ($values, $keys) {
            return new CombineIterator($keys, $values);
        };

        return $this->then($combine, i\iterable_to_array($keys));
    }

public function setKeys ( iterable $ keys ) { $ combine = function ( $ values , $ keys ) { return new CombineIterator ( $ keys , $ values ) ; } ; return $ this -> then ( $ combine , i \ iterable_to_array ( $ keys ) ) ; }

Use another iterator as keys and the current iterator as values.

@param iterable $keys  Keys will be turned into an array.
@return static

Use another iterator as keys and the current iterator as values .


public function slice(int $offset, ?int $size = null)
    {
        return $this->then(i\iterable_slice, $offset, $size);
    }

public function slice ( int $ offset , ? int $ size = null ) { return $ this -> then ( i \ iterable_slice , $ offset , $ size ) ; }

Get a limited subset of the elements using an offset.

@param int      $offset
@param int|null $size    size limit
@return static

Get a limited subset of the elements using an offset .


public function sort($compare, bool $preserveKeys = true)
    {
        return $this->then(i\iterable_sort, $compare, $preserveKeys);
    }

public function sort ( $ compare , bool $ preserveKeys = true ) { return $ this -> then ( i \ iterable_sort , $ compare , $ preserveKeys ) ; }

Sort all elements of an iterator.

@param callable|int $compare       SORT_* flags as binary set or callback comparator function
@param bool         $preserveKeys
@return static


public function setVariables($variables)
    {
        if (!is_array($variables)) {
            return $this;
        }
        foreach ($variables as $key => $value) {
            $this->setVariable($key, $value);
        }

        return $this;
    }

public function setVariables ( $ variables ) { if ( ! is_array ( $ variables ) ) { return $ this ; } foreach ( $ variables as $ key => $ value ) { $ this -> setVariable ( $ key , $ value ) ; } return $ this ; }

Set variables.

@param array $variables

@throws Exception

@return $this


public function setVariable($name, $value)
    {
        switch ($name) {
            case 'date':
                try {
                    if ($value instanceof \DateTime) {
                        $this->offsetSet('date', $value);
                    } else {
                        if (is_numeric($value)) {
                            $this->offsetSet('date', (new \DateTime())->setTimestamp($value));
                        } else {
                            if (is_string($value)) {
                                $this->offsetSet('date', new \DateTime($value));
                            }
                        }
                    }
                } catch (Exception $e) {
                    throw new Exception(sprintf("Expected date string in page ID: '%s'", $this->getId()));
                }
                break;
            case 'draft':
                if ($value === true) {
                    $this->offsetSet('published', false);
                }
                break;
            default:
                $this->offsetSet($name, $value);
        }

        return $this;
    }

public
function
setVariable
(
$
name
,
$
value
)
{
switch
(
$
name
)
{
case
'date'
:
try
{
if
(
$
value
instanceof
\
DateTime
)
{
$
this
->
offsetSet
(
'date'
,
$
value
)
;
}
else
{
if
(
is_numeric
(
$
value
)
)
{
$
this
->
offsetSet
(
'date'
,
(
new
\
DateTime
(
)
)
->
setTimestamp
(
$
value
)
)
;
}
else
{
if
(
is_string
(
$
value
)
)
{
$
this
->
offsetSet
(
'date'
,
new
\
DateTime
(
$
value
)
)
;
}
}
}
}
catch
(
Exception
$
e
)
{
throw
new
Exception
(
sprintf
(
"Expected date string in page ID: '%s'"
,
$
this
->
getId
(
)
)
)
;
}
break
;
case
'draft'
:
if
(
$
value
===
true
)
{
$
this
->
offsetSet
(
'published'
,
false
)
;
}
break
;
default
:
$
this
->
offsetSet
(
$
name
,
$
value
)
;
}
return
$
this
;
}

Set a variable.

@param $name
@param $value

@throws Exception

@return $this


protected function getPathname(Page $page)
    {
        // force pathname of a file node page (ie: "section/index.md")
        if ($page->getName() == 'index') {
            return $page->getPath().'/'.$this->config->get('output.filename');
        } else {
            // custom extension, ex: 'manifest.json'
            if (!empty(pathinfo($page->getPermalink(), PATHINFO_EXTENSION))) {
                return $page->getPermalink();
            }
            // underscore prefix, ex: '_redirects'
            if (strpos($page->getPermalink(), '_') === 0) {
                return $page->getPermalink();
            }

            return $page->getPermalink().'/'.$this->config->get('output.filename');
        }
    }

Return output pathname.

@param Page $page

@return string


private static function getScriptTag( $name ) {
		$name = "SCRIPT_" . strtoupper( trim( $name ) );
		// Linear search
		foreach ( self::$script_ranges as $range ) {
			if ( $name == $range[2] ) {
				return $range[2];
			}
		}
		// Otherwise...
		return null;
	}

private
static
function
getScriptTag
(
$
name
)
{
$
name
=
"SCRIPT_"
.
strtoupper
(
trim
(
$
name
)
)
;
// Linear search
foreach
(
self
::
$
script_ranges
as
$
range
)
{
if
(
$
name
==
$
range
[
2
]
)
{
return
$
range
[
2
]
;
}
}
// Otherwise...
return
;
}

From the name of a script, get a script descriptor, if valid,
otherwise return None

@param string $name
@return null|string

From the name of a script get a script descriptor if valid otherwise return None


private static function isAllowedScriptCombination( $scriptList ) {
		$allowedScriptCombinations = [
			[ "SCRIPT_COPTIC", "SCRIPT_COPTIC_EXTRAS" ], # Coptic, using old Greek chars
			[ "SCRIPT_GREEK", "SCRIPT_COPTIC_EXTRAS" ], # Coptic, using new Coptic chars
			[ "SCRIPT_HAN", "SCRIPT_BOPOMOFO" ], # Chinese
			[ "SCRIPT_HAN", "SCRIPT_HANGUL" ], # Korean
			[ "SCRIPT_HAN", "SCRIPT_KATAKANA", "SCRIPT_HIRAGANA" ] # Japanese
		];
		foreach ( $allowedScriptCombinations as $allowedCombo ) {
			if ( self::isSubsetOf( $scriptList, $allowedCombo ) ) {
				return true;
			}
		}
		return false;
	}

private
static
function
isAllowedScriptCombination
(
$
scriptList
)
{
$
allowedScriptCombinations
=
[
[
"SCRIPT_COPTIC"
,
"SCRIPT_COPTIC_EXTRAS"
]
,
# Coptic, using old Greek chars
[
"SCRIPT_GREEK"
,
"SCRIPT_COPTIC_EXTRAS"
]
,
# Coptic, using new Coptic chars
[
"SCRIPT_HAN"
,
"SCRIPT_BOPOMOFO"
]
,
# Chinese
[
"SCRIPT_HAN"
,
"SCRIPT_HANGUL"
]
,
# Korean
[
"SCRIPT_HAN"
,
"SCRIPT_KATAKANA"
,
"SCRIPT_HIRAGANA"
]
# Japanese
]
;
foreach
(
$
allowedScriptCombinations
as
$
allowedCombo
)
{
if
(
self
::
isSubsetOf
(
$
scriptList
,
$
allowedCombo
)
)
{
return
true
;
}
}
return
false
;
}

Is this an allowed script mixture?

@param array $scriptList
@return bool


public static function stringToList( $str ) {
		$ar = [];
		if ( !preg_match_all( '/./us', $str, $ar ) ) {
			return [];
		}
		$out = [];
		foreach ( $ar[0] as $char ) {
			$out[] = Utils::utf8ToCodepoint( $char );
		}
		return $out;
	}

public static function stringToList ( $ str ) { $ ar = [ ] ; if ( ! preg_match_all ( '/./us' , $ str , $ ar ) ) { return [ ] ; } $ out = [ ] ; foreach ( $ ar [ 0 ] as $ char ) { $ out [ ] = Utils :: utf8ToCodepoint ( $ char ) ; } return $ out ; }

Convert string into array of Unicode code points as integers
@param string $str
@return array


public function execute() {
		$this->output( "Creating username spoofs...\n" );

		$userCol = $this->getUserColumn();
		$iterator = new BatchRowIterator( $this->getDB( DB_MASTER ),
			$this->getTableName(),
			$this->getPrimaryKey(),
			$this->getBatchSize()
		);
		$iterator->setFetchColumns( [ $userCol ] );

		$n = 0;
		foreach ( $iterator as $batch ) {
			$items = [];
			foreach ( $batch as $row ) {
				$items[] = $this->makeSpoofUser( $row->$userCol );
			}

			$n += count( $items );
			$this->output( "...$n\n" );
			$this->batchRecord( $items );
			$this->waitForSlaves();
		}

		$this->output( "$n user(s) done.\n" );
	}

public
function
execute
(
)
{
$
this
->
output
(
"Creating username spoofs...\n"
)
;
$
userCol
=
$
this
->
getUserColumn
(
)
;
$
iterator
=
new
BatchRowIterator
(
$
this
->
getDB
(
DB_MASTER
)
,
$
this
->
getTableName
(
)
,
$
this
->
getPrimaryKey
(
)
,
$
this
->
getBatchSize
(
)
)
;
$
iterator
->
setFetchColumns
(
[
$
userCol
]
)
;
$
n
=
0
;
foreach
(
$
iterator
as
$
batch
)
{
$
items
=
[
]
;
foreach
(
$
batch
as
$
row
)
{
$
items
[
]
=
$
this
->
makeSpoofUser
(
$
row
->
$
userCol
)
;
}
$
n
+=
count
(
$
items
)
;
$
this
->
output
(
"...$n\n"
)
;
$
this
->
batchRecord
(
$
items
)
;
$
this
->
waitForSlaves
(
)
;
}
$
this
->
output
(
"$n user(s) done.\n"
)
;
}

Do the actual work. All child classes will need to implement this

Do the actual work . All child classes will need to implement this


protected function getAllLayoutsPaths()
    {
        $paths = [];

        // layouts/
        if (is_dir($this->config->getLayoutsPath())) {
            $paths[] = $this->config->getLayoutsPath();
        }
        // <theme>/layouts/
        if ($this->config->hasTheme()) {
            $themes = $this->config->getTheme();
            foreach ($themes as $theme) {
                $paths[] = $this->config->getThemeDirPath($theme);
            }
        }
        // res/layouts/
        if (is_dir($this->config->getInternalLayoutsPath())) {
            $paths[] = $this->config->getInternalLayoutsPath();
        }

        return $paths;
    }

protected
function
getAllLayoutsPaths
(
)
{
$
paths
=
[
]
;
// layouts/
if
(
is_dir
(
$
this
->
config
->
getLayoutsPath
(
)
)
)
{
$
paths
[
]
=
$
this
->
config
->
getLayoutsPath
(
)
;
}
// <theme>/layouts/
if
(
$
this
->
config
->
hasTheme
(
)
)
{
$
themes
=
$
this
->
config
->
getTheme
(
)
;
foreach
(
$
themes
as
$
theme
)
{
$
paths
[
]
=
$
this
->
config
->
getThemeDirPath
(
$
theme
)
;
}
}
// res/layouts/
if
(
is_dir
(
$
this
->
config
->
getInternalLayoutsPath
(
)
)
)
{
$
paths
[
]
=
$
this
->
config
->
getInternalLayoutsPath
(
)
;
}
return
$
paths
;
}

Return an array of layouts directories.

@return array Layouts directory

Return an array of layouts directories .


protected function addGlobals()
    {
        // adds global variables
        $this->phpoole->getRenderer()->addGlobal('site', array_merge(
            $this->config->get('site'),
            ['menus' => $this->phpoole->getMenus()],
            ['pages' => $this->phpoole->getPages()->filter(function (Page $page) {
                return $page->getVariable('published');
            })],
            ['time' => time()]
        ));
        $this->phpoole->getRenderer()->addGlobal('cecil', [
            'url'       => sprintf('https://cecil.app/#%s', $this->phpoole->getVersion()),
            'version'   => $this->phpoole->getVersion(),
            'poweredby' => sprintf('Cecil/PHPoole v%s', $this->phpoole->getVersion()),
        ]);
    }

protected
function
addGlobals
(
)
{
// adds global variables
$
this
->
phpoole
->
getRenderer
(
)
->
addGlobal
(
'site'
,
array_merge
(
$
this
->
config
->
get
(
'site'
)
,
[
'menus'
=>
$
this
->
phpoole
->
getMenus
(
)
]
,
[
'pages'
=>
$
this
->
phpoole
->
getPages
(
)
->
filter
(
function
(
Page
$
page
)
{
return
$
page
->
getVariable
(
'published'
)
;
}
)
]
,
[
'time'
=>
time
(
)
]
)
)
;
$
this
->
phpoole
->
getRenderer
(
)
->
addGlobal
(
'cecil'
,
[
'url'
=>
sprintf
(
'https://cecil.app/#%s'
,
$
this
->
phpoole
->
getVersion
(
)
)
,
'version'
=>
$
this
->
phpoole
->
getVersion
(
)
,
'poweredby'
=>
sprintf
(
'Cecil/PHPoole v%s'
,
$
this
->
phpoole
->
getVersion
(
)
)
,
]
)
;
}


public function process(PageCollection $pageCollection, \Closure $messageCallback)
    {
        $max = $this->count();

        if ($max > 0) {
            $this->top();
            while ($this->valid()) {
                /* @var GeneratorInterface $generator */
                $generator = $this->current();
                /* @var $generatedPages PageCollection */
                $generatedPages = $generator->generate($pageCollection, $messageCallback);
                foreach ($generatedPages as $page) {
                    /* @var $page \PHPoole\Collection\Page\Page */
                    if ($pageCollection->has($page->getId())) {
                        $pageCollection->replace($page->getId(), $page);
                    } else {
                        $pageCollection->add($page);
                    }
                }
                $message = substr(strrchr(get_class($generator), '\\'), 1).': '.count($generatedPages);
                $count = ($max - $this->key());
                call_user_func_array($messageCallback, ['GENERATE_PROGRESS', $message, $count, $max]);
                $this->next();
            }
        }

        return $pageCollection;
    }

Process each generators.

@param PageCollection $pageCollection
@param \Closure       $messageCallback

@return PageCollection


protected function setParam(\SimpleXMLElement $element, Feed $feed)
    {
        if (count($element) === 0) {
            $feed->set($element->getName(), (string)$element);
        } else {
            $feed->set($element->getName(), $this->extractParam($element));
        }
    }

protected function setParam ( \ SimpleXMLElement $ element , Feed $ feed ) { if ( count ( $ element ) === 0 ) { $ feed -> set ( $ element -> getName ( ) , ( string ) $ element ) ; } else { $ feed -> set ( $ element -> getName ( ) , $ this -> extractParam ( $ element ) ) ; } }

Set a feed param

@param \SimpleXMLElement        $element
@param \Nekland\Bundle\FeedBundle\Feed $feed
@return void


protected function extractParam(\SimpleXMLElement $element)
    {
        $param = array();
        foreach ($element as $subElement) {
            if (count($subElement) === 0) {
                $param[$subElement->getName()] = (string)$subElement;
            } else {
                $param[$subElement->getName()] = $this->extractParam($subElement);
            }
        }

        return $param;
    }

protected function extractParam ( \ SimpleXMLElement $ element ) { $ param = array ( ) ; foreach ( $ element as $ subElement ) { if ( count ( $ subElement ) === 0 ) { $ param [ $ subElement -> getName ( ) ] = ( string ) $ subElement ; } else { $ param [ $ subElement -> getName ( ) ] = $ this -> extractParam ( $ subElement ) ; } } return $ param ; }

Extract array params

@param \SimpleXMLElement $element
@return array


public static function runGitCommand($command)
    {
        try {
            $process = new Process($command, __DIR__);
            if (0 === $process->run()) {
                return trim($process->getOutput());
            }

            throw new \RuntimeException(
                sprintf(
                    'The tag or commit hash could not be retrieved from "%s": %s',
                    __DIR__,
                    $process->getErrorOutput()
                )
            );
        } catch (\RuntimeException $exception) {
            throw new \RuntimeException('Process error');
        }
    }

Runs a Git command on the repository.

@param string $command The command.

@throws \RuntimeException If the command failed.

@return string The trimmed output from the command.


public static function sortByDate($a, $b)
    {
        if (!isset($a['date'])) {
            return -1;
        }
        if (!isset($b['date'])) {
            return 1;
        }
        if ($a['date'] == $b['date']) {
            return 0;
        }

        return ($a['date'] > $b['date']) ? -1 : 1;
    }

public static function sortByDate ( $ a , $ b ) { if ( ! isset ( $ a [ 'date' ] ) ) { return - 1 ; } if ( ! isset ( $ b [ 'date' ] ) ) { return 1 ; } if ( $ a [ 'date' ] == $ b [ 'date' ] ) { return 0 ; } return ( $ a [ 'date' ] > $ b [ 'date' ] ) ? - 1 : 1 ; }

Sort array by 'date' item.

@param $a
@param $b

@return int