public function getGridFilter(Twig_Environment $environment, $column, $grid, $submitOnChange = true)
    {
        $id = $this->names[$grid->getHash()];

        if (($id != '' && ($this->hasBlock($environment, $block = 'grid_' . $id . '_column_' . $column->getRenderBlockId() . '_filter')
                    || $this->hasBlock($environment, $block = 'grid_' . $id . '_column_id_' . $column->getRenderBlockId() . '_filter')
                    || $this->hasBlock($environment, $block = 'grid_' . $id . '_column_type_' . $column->getType() . '_filter')
                    || $this->hasBlock($environment, $block = 'grid_' . $id . '_column_type_' . $column->getParentType() . '_filter'))
                || $this->hasBlock($environment, $block = 'grid_' . $id . '_column_filter_type_' . $column->getFilterType()))
            || $this->hasBlock($environment, $block = 'grid_column_' . $column->getRenderBlockId() . '_filter')
            || $this->hasBlock($environment, $block = 'grid_column_id_' . $column->getRenderBlockId() . '_filter')
            || $this->hasBlock($environment, $block = 'grid_column_type_' . $column->getType() . '_filter')
            || $this->hasBlock($environment, $block = 'grid_column_type_' . $column->getParentType() . '_filter')
            || $this->hasBlock($environment, $block = 'grid_column_filter_type_' . $column->getFilterType())
        ) {
            return $this->renderBlock($environment, $block, ['grid' => $grid, 'column' => $column, 'submitOnChange' => $submitOnChange && $column->isFilterSubmitOnChange()]);
        }

        return '';
    }

public function getGridFilter ( Twig_Environment $ environment , $ column , $ grid , $ submitOnChange = true ) { $ id = $ this -> names [ $ grid -> getHash ( ) ] ; if ( ( $ id != '' && ( $ this -> hasBlock ( $ environment , $ block = 'grid_' . $ id . '_column_' . $ column -> getRenderBlockId ( ) . '_filter' ) || $ this -> hasBlock ( $ environment , $ block = 'grid_' . $ id . '_column_id_' . $ column -> getRenderBlockId ( ) . '_filter' ) || $ this -> hasBlock ( $ environment , $ block = 'grid_' . $ id . '_column_type_' . $ column -> getType ( ) . '_filter' ) || $ this -> hasBlock ( $ environment , $ block = 'grid_' . $ id . '_column_type_' . $ column -> getParentType ( ) . '_filter' ) ) || $ this -> hasBlock ( $ environment , $ block = 'grid_' . $ id . '_column_filter_type_' . $ column -> getFilterType ( ) ) ) || $ this -> hasBlock ( $ environment , $ block = 'grid_column_' . $ column -> getRenderBlockId ( ) . '_filter' ) || $ this -> hasBlock ( $ environment , $ block = 'grid_column_id_' . $ column -> getRenderBlockId ( ) . '_filter' ) || $ this -> hasBlock ( $ environment , $ block = 'grid_column_type_' . $ column -> getType ( ) . '_filter' ) || $ this -> hasBlock ( $ environment , $ block = 'grid_column_type_' . $ column -> getParentType ( ) . '_filter' ) || $ this -> hasBlock ( $ environment , $ block = 'grid_column_filter_type_' . $ column -> getFilterType ( ) ) ) { return $ this -> renderBlock ( $ environment , $ block , [ 'grid' => $ grid , 'column' => $ column , 'submitOnChange' => $ submitOnChange && $ column -> isFilterSubmitOnChange ( ) ] ) ; } return '' ; }

Filter Drawing override.

@param Twig_Environment                       $environment
@param \APY\DataGridBundle\Grid\Column\Column $column
@param \APY\DataGridBundle\Grid\Grid          $grid

@return string


public function getGridColumnOperator(Twig_Environment $environment, $column, $grid, $operator, $submitOnChange = true)
    {
        return $this->renderBlock($environment, 'grid_column_operator', ['grid' => $grid, 'column' => $column, 'submitOnChange' => $submitOnChange, 'op' => $operator]);
    }

public function getGridColumnOperator ( Twig_Environment $ environment , $ column , $ grid , $ operator , $ submitOnChange = true ) { return $ this -> renderBlock ( $ environment , 'grid_column_operator' , [ 'grid' => $ grid , 'column' => $ column , 'submitOnChange' => $ submitOnChange , 'op' => $ operator ] ) ; }

Column Operator Drawing override.

@param Twig_Environment                       $environment
@param \APY\DataGridBundle\Grid\Column\Column $column
@param \APY\DataGridBundle\Grid\Grid          $grid

@return string


protected function hasBlock(Twig_Environment $environment, $name)
    {
        foreach ($this->getTemplates($environment) as $template) {
            /** @var $template Twig_Template */
            if ($template->hasBlock($name, [])) {
                return true;
            }
        }

        return false;
    }

protected
function
hasBlock
(
Twig_Environment
$
environment
,
$
name
)
{
foreach
(
$
this
->
getTemplates
(
$
environment
)
as
$
template
)
{
/** @var $template Twig_Template */
if
(
$
template
->
hasBlock
(
$
name
,
[
]
)
)
{
return
true
;
}
}
return
false
;
}

Has block.

@param Twig_Environment $environment
@param $name string

@return bool


public function walkSelectStatement(SelectStatement $AST)
    {
        $rootComponents = [];
        foreach ($this->_getQueryComponents() as $dqlAlias => $qComp) {
            if (array_key_exists('parent', $qComp) && $qComp['parent'] === null && $qComp['nestingLevel'] == 0) {
                $rootComponents[] = [$dqlAlias => $qComp];
            }
        }

        if (count($rootComponents) > 1) {
            throw new \RuntimeException('Cannot count query which selects two FROM components, cannot make distinction');
        }

        $root = reset($rootComponents);
        $parentName = key($root);
        $parent = current($root);

        $pathExpression = new PathExpression(
            PathExpression::TYPE_STATE_FIELD | PathExpression::TYPE_SINGLE_VALUED_ASSOCIATION, $parentName,
            $parent['metadata']->getSingleIdentifierFieldName()
        );
        $pathExpression->type = PathExpression::TYPE_STATE_FIELD;

        // Remove the variables which are not used by other clauses
        foreach ($AST->selectClause->selectExpressions as $key => $selectExpression) {
            if ($selectExpression->fieldIdentificationVariable === null) {
                unset($AST->selectClause->selectExpressions[$key]);
            } elseif ($selectExpression->expression instanceof PathExpression) {
                $groupByClause[] = $selectExpression->expression;
            }
        }

        // Put the count expression in the first position
        $distinct = $this->_getQuery()->getHint(self::HINT_DISTINCT);
        array_unshift($AST->selectClause->selectExpressions,
            new SelectExpression(
                new AggregateExpression('count', $pathExpression, $distinct), null
            )
        );

        $groupByClause[] = $pathExpression;
        $AST->groupByClause = new \Doctrine\ORM\Query\AST\GroupByClause($groupByClause);

        // ORDER BY is not needed, only increases query execution through unnecessary sorting.
        $AST->orderByClause = null;
    }

Walks down a SelectStatement AST node, modifying it to retrieve a COUNT.

@param SelectStatement $AST

@throws \RuntimeException

Walks down a SelectStatement AST node modifying it to retrieve a COUNT .


public function setSource(Source $source)
    {
        if ($this->source !== null) {
            throw new \InvalidArgumentException(self::SOURCE_ALREADY_SETTED_EX_MSG);
        }

        $this->source = $source;

        $this->source->initialise($this->container);

        // Get columns from the source
        $this->source->getColumns($this->columns);

        return $this;
    }

public
function
setSource
(
Source
$
source
)
{
if
(
$
this
->
source
!==
)
{
throw
new
\
InvalidArgumentException
(
self
::
SOURCE_ALREADY_SETTED_EX_MSG
)
;
}
$
this
->
source
=
$
source
;
$
this
->
source
->
initialise
(
$
this
->
container
)
;
// Get columns from the source
$
this
->
source
->
getColumns
(
$
this
->
columns
)
;
return
$
this
;
}

Sets Source to the Grid.

@param $source

@throws \InvalidArgumentException

@return self


public function isReadyForRedirect()
    {
        if ($this->source === null) {
            throw new \Exception(self::SOURCE_NOT_SETTED_EX_MSG);
        }

        if ($this->redirect !== null) {
            return $this->redirect;
        }

        $this->createHash();

        $this->requestData = (array) $this->request->get($this->hash);

        $this->processPersistence();

        $this->sessionData = (array) $this->session->get($this->hash);

        $this->processLazyParameters();

        // isReadyForRedirect ?
        if (!empty($this->requestData)) {
            $this->processRequestData();

            $this->redirect = true;
        }

        if ($this->redirect === null || ($this->request->isXmlHttpRequest() && !$this->isReadyForExport)) {
            if ($this->newSession) {
                $this->setDefaultSessionData();
            }

            $this->processPermanentFilters();

            //Configures the grid with the data read from the session.
            $this->processSessionData();

            $this->prepare();

            $this->redirect = false;
        }

        return $this->redirect;
    }

Handle the grid redirection, export, etc..

Handle the grid redirection export etc ..


protected function processRequestData()
    {
        $this->processMassActions($this->getFromRequest(self::REQUEST_QUERY_MASS_ACTION));

        if ($this->processExports($this->getFromRequest(self::REQUEST_QUERY_EXPORT))
            || $this->processTweaks($this->getFromRequest(self::REQUEST_QUERY_TWEAK))) {
            return;
        }

        $filtering = $this->processRequestFilters();

        $this->processPage($this->getFromRequest(self::REQUEST_QUERY_PAGE), $filtering);

        $this->processOrder($this->getFromRequest(self::REQUEST_QUERY_ORDER));

        $this->processLimit($this->getFromRequest(self::REQUEST_QUERY_LIMIT));

        $this->saveSession();
    }

protected function processRequestData ( ) { $ this -> processMassActions ( $ this -> getFromRequest ( self :: REQUEST_QUERY_MASS_ACTION ) ) ; if ( $ this -> processExports ( $ this -> getFromRequest ( self :: REQUEST_QUERY_EXPORT ) ) || $ this -> processTweaks ( $ this -> getFromRequest ( self :: REQUEST_QUERY_TWEAK ) ) ) { return ; } $ filtering = $ this -> processRequestFilters ( ) ; $ this -> processPage ( $ this -> getFromRequest ( self :: REQUEST_QUERY_PAGE ) , $ filtering ) ; $ this -> processOrder ( $ this -> getFromRequest ( self :: REQUEST_QUERY_ORDER ) ) ; $ this -> processLimit ( $ this -> getFromRequest ( self :: REQUEST_QUERY_LIMIT ) ) ; $ this -> saveSession ( ) ; }

Reads data from the request and write this data to the session.

Reads data from the request and write this data to the session .


protected function processMassActions($actionId)
    {
        if ($actionId > -1 && '' !== $actionId) {
            if (array_key_exists($actionId, $this->massActions)) {
                $action = $this->massActions[$actionId];
                $actionAllKeys = (boolean) $this->getFromRequest(self::REQUEST_QUERY_MASS_ACTION_ALL_KEYS_SELECTED);
                $actionKeys = $actionAllKeys === false ? array_keys((array) $this->getFromRequest(MassActionColumn::ID)) : [];

                $this->processSessionData();
                if ($actionAllKeys) {
                    $this->page = 0;
                    $this->limit = 0;
                }

                $this->prepare();

                if ($actionAllKeys === true) {
                    foreach ($this->rows as $row) {
                        $actionKeys[] = $row->getPrimaryFieldValue();
                    }
                }

                if (is_callable($action->getCallback())) {
                    $this->massActionResponse = call_user_func($action->getCallback(), $actionKeys, $actionAllKeys, $this->session, $action->getParameters());
                } elseif (strpos($action->getCallback(), ':') !== false) {
                    $path = array_merge(
                        [
                            'primaryKeys'    => $actionKeys,
                            'allPrimaryKeys' => $actionAllKeys,
                            '_controller'    => $action->getCallback(),
                        ],
                        $action->getParameters()
                    );

                    $subRequest = $this->request->duplicate([], null, $path);

                    $this->massActionResponse = $this->container->get('http_kernel')->handle($subRequest, \Symfony\Component\HttpKernel\HttpKernelInterface::SUB_REQUEST);
                } else {
                    throw new \RuntimeException(sprintf(self::MASS_ACTION_CALLBACK_NOT_VALID_EX_MSG, $action->getCallback()));
                }
            } else {
                throw new \OutOfBoundsException(sprintf(self::MASS_ACTION_NOT_DEFINED_EX_MSG, $actionId));
            }
        }
    }

Process mass actions.

@param int $actionId

@throws \RuntimeException
@throws \OutOfBoundsException


protected function processExports($exportId)
    {
        if ($exportId > -1 && '' !== $exportId) {
            if (array_key_exists($exportId, $this->exports)) {
                $this->isReadyForExport = true;

                $this->processSessionData();
                $this->page = 0;
                $this->limit = 0;
                $this->prepare();

                $export = $this->exports[$exportId];
                if ($export instanceof ContainerAwareInterface) {
                    $export->setContainer($this->container);
                }
                $export->computeData($this);

                $this->exportResponse = $export->getResponse();

                return true;
            } else {
                throw new \OutOfBoundsException(sprintf(self::EXPORT_NOT_DEFINED_EX_MSG, $exportId));
            }
        }

        return false;
    }

protected function processExports ( $ exportId ) { if ( $ exportId > - 1 && '' !== $ exportId ) { if ( array_key_exists ( $ exportId , $ this -> exports ) ) { $ this -> isReadyForExport = true ; $ this -> processSessionData ( ) ; $ this -> page = 0 ; $ this -> limit = 0 ; $ this -> prepare ( ) ; $ export = $ this -> exports [ $ exportId ] ; if ( $ export instanceof ContainerAwareInterface ) { $ export -> setContainer ( $ this -> container ) ; } $ export -> computeData ( $ this ) ; $ this -> exportResponse = $ export -> getResponse ( ) ; return true ; } else { throw new \ OutOfBoundsException ( sprintf ( self :: EXPORT_NOT_DEFINED_EX_MSG , $ exportId ) ) ; } } return false ; }

Process exports.

@param int $exportId

@throws \OutOfBoundsException

@return bool


protected function processFilters($permanent = true)
    {
        foreach (($permanent ? $this->permanentFilters : $this->defaultFilters) as $columnId => $value) {
            /* @var $column Column */
            $column = $this->columns->getColumnById($columnId);

            if ($permanent) {
                // Disable the filter capability for the column
                $column->setFilterable(false);
            }

            // Convert simple value
            if (!is_array($value) || !is_string(key($value))) {
                $value = ['from' => $value];
            }

            // Convert boolean value
            if (isset($value['from']) && is_bool($value['from'])) {
                $value['from'] = $value['from'] ? '1' : '0';
            }

            // Convert simple value with select filter
            if ($column->getFilterType() === 'select') {
                if (isset($value['from']) && !is_array($value['from'])) {
                    $value['from'] = [$value['from']];
                }

                if (isset($value['to']) && !is_array($value['to'])) {
                    $value['to'] = [$value['to']];
                }
            }

            // Store in the session
            $this->set($columnId, $value);
        }
    }

Store permanent filters to the session and disable the filter capability for the column if there are permanent filters.

Store permanent filters to the session and disable the filter capability for the column if there are permanent filters .


protected function processSessionData()
    {
        // Filters
        foreach ($this->columns as $column) {
            if (($data = $this->get($column->getId())) !== null) {
                $column->setData($data);
            }
        }

        // Page
        if (($page = $this->get(self::REQUEST_QUERY_PAGE)) !== null) {
            $this->setPage($page);
        } else {
            $this->setPage(0);
        }

        // Order
        if (($order = $this->get(self::REQUEST_QUERY_ORDER)) !== null) {
            list($columnId, $columnOrder) = explode('|', $order);

            $this->columns->getColumnById($columnId)->setOrder($columnOrder);
        }

        // Limit
        if (($limit = $this->get(self::REQUEST_QUERY_LIMIT)) !== null) {
            $this->limit = $limit;
        } else {
            $this->limit = key($this->limits);
        }
    }

protected
function
processSessionData
(
)
{
// Filters
foreach
(
$
this
->
columns
as
$
column
)
{
if
(
(
$
data
=
$
this
->
get
(
$
column
->
getId
(
)
)
)
!==
)
{
$
column
->
setData
(
$
data
)
;
}
}
// Page
if
(
(
$
page
=
$
this
->
get
(
self
::
REQUEST_QUERY_PAGE
)
)
!==
)
{
$
this
->
setPage
(
$
page
)
;
}
else
{
$
this
->
setPage
(
0
)
;
}
// Order
if
(
(
$
order
=
$
this
->
get
(
self
::
REQUEST_QUERY_ORDER
)
)
!==
)
{
list
(
$
columnId
,
$
columnOrder
)
=
explode
(
'|'
,
$
order
)
;
$
this
->
columns
->
getColumnById
(
$
columnId
)
->
setOrder
(
$
columnOrder
)
;
}
// Limit
if
(
(
$
limit
=
$
this
->
get
(
self
::
REQUEST_QUERY_LIMIT
)
)
!==
)
{
$
this
->
limit
=
$
limit
;
}
else
{
$
this
->
limit
=
key
(
$
this
->
limits
)
;
}
}

Configures the grid with the data read from the session.

Configures the grid with the data read from the session .


protected function prepare()
    {
        if ($this->prepared) {
            return $this;
        }

        if ($this->source->isDataLoaded()) {
            $this->rows = $this->source->executeFromData($this->columns->getIterator(true), $this->page, $this->limit, $this->maxResults);
        } else {
            $this->rows = $this->source->execute($this->columns->getIterator(true), $this->page, $this->limit, $this->maxResults, $this->dataJunction);
        }

        if (!$this->rows instanceof Rows) {
            throw new \Exception(self::NO_ROWS_RETURNED_EX_MSG);
        }

        if (count($this->rows) == 0 && $this->page > 0) {
            $this->page = 0;
            $this->prepare();

            return $this;
        }

        //add row actions column
        if (count($this->rowActions) > 0) {
            foreach ($this->rowActions as $column => $rowActions) {
                if (($actionColumn = $this->columns->hasColumnById($column, true))) {
                    $actionColumn->setRowActions($rowActions);
                } else {
                    $actionColumn = new ActionsColumn($column, $this->actionsColumnTitle, $rowActions);
                    if ($this->actionsColumnSize > -1) {
                        $actionColumn->setSize($this->actionsColumnSize);
                    }

                    $this->columns->addColumn($actionColumn);
                }
            }
        }

        //add mass actions column
        if (count($this->massActions) > 0) {
            $this->columns->addColumn(new MassActionColumn(), 1);
        }

        $primaryColumnId = $this->columns->getPrimaryColumn()->getId();

        foreach ($this->rows as $row) {
            $row->setPrimaryField($primaryColumnId);
        }

        //get size
        if ($this->source->isDataLoaded()) {
            $this->source->populateSelectFiltersFromData($this->columns);
            $this->totalCount = $this->source->getTotalCountFromData($this->maxResults);
        } else {
            $this->source->populateSelectFilters($this->columns);
            $this->totalCount = $this->source->getTotalCount($this->maxResults);
        }

        if (!is_int($this->totalCount)) {
            throw new \Exception(sprintf(self::INVALID_TOTAL_COUNT_EX_MSG, gettype($this->totalCount)));
        }

        $this->prepared = true;

        return $this;
    }

protected
function
prepare
(
)
{
if
(
$
this
->
prepared
)
{
return
$
this
;
}
if
(
$
this
->
source
->
isDataLoaded
(
)
)
{
$
this
->
rows
=
$
this
->
source
->
executeFromData
(
$
this
->
columns
->
getIterator
(
true
)
,
$
this
->
page
,
$
this
->
limit
,
$
this
->
maxResults
)
;
}
else
{
$
this
->
rows
=
$
this
->
source
->
execute
(
$
this
->
columns
->
getIterator
(
true
)
,
$
this
->
page
,
$
this
->
limit
,
$
this
->
maxResults
,
$
this
->
dataJunction
)
;
}
if
(
!
$
this
->
rows
instanceof
Rows
)
{
throw
new
\
Exception
(
self
::
NO_ROWS_RETURNED_EX_MSG
)
;
}
if
(
count
(
$
this
->
rows
)
==
0
&&
$
this
->
page
>
0
)
{
$
this
->
page
=
0
;
$
this
->
prepare
(
)
;
return
$
this
;
}
//add row actions column
if
(
count
(
$
this
->
rowActions
)
>
0
)
{
foreach
(
$
this
->
rowActions
as
$
column
=>
$
rowActions
)
{
if
(
(
$
actionColumn
=
$
this
->
columns
->
hasColumnById
(
$
column
,
true
)
)
)
{
$
actionColumn
->
setRowActions
(
$
rowActions
)
;
}
else
{
$
actionColumn
=
new
ActionsColumn
(
$
column
,
$
this
->
actionsColumnTitle
,
$
rowActions
)
;
if
(
$
this
->
actionsColumnSize
>
1
)
{
$
actionColumn
->
setSize
(
$
this
->
actionsColumnSize
)
;
}
$
this
->
columns
->
addColumn
(
$
actionColumn
)
;
}
}
}
//add mass actions column
if
(
count
(
$
this
->
massActions
)
>
0
)
{
$
this
->
columns
->
addColumn
(
new
MassActionColumn
(
)
,
1
)
;
}
$
primaryColumnId
=
$
this
->
columns
->
getPrimaryColumn
(
)
->
getId
(
)
;
foreach
(
$
this
->
rows
as
$
row
)
{
$
row
->
setPrimaryField
(
$
primaryColumnId
)
;
}
//get size
if
(
$
this
->
source
->
isDataLoaded
(
)
)
{
$
this
->
source
->
populateSelectFiltersFromData
(
$
this
->
columns
)
;
$
this
->
totalCount
=
$
this
->
source
->
getTotalCountFromData
(
$
this
->
maxResults
)
;
}
else
{
$
this
->
source
->
populateSelectFilters
(
$
this
->
columns
)
;
$
this
->
totalCount
=
$
this
->
source
->
getTotalCount
(
$
this
->
maxResults
)
;
}
if
(
!
is_int
(
$
this
->
totalCount
)
)
{
throw
new
\
Exception
(
sprintf
(
self
::
INVALID_TOTAL_COUNT_EX_MSG
,
gettype
(
$
this
->
totalCount
)
)
)
;
}
$
this
->
prepared
=
true
;
return
$
this
;
}

Prepare Grid for Drawing.

@throws \Exception

@return self


protected function set($key, $data)
    {
        // Only the filters values are removed from the session
        $fromIsEmpty = isset($data['from']) && ((is_string($data['from']) && $data['from'] === '') || (is_array($data['from']) && $data['from'][0] === ''));
        $toIsSet = isset($data['to']) && (is_string($data['to']) && $data['to'] !== '');
        if ($fromIsEmpty && !$toIsSet) {
            if (array_key_exists($key, $this->sessionData)) {
                unset($this->sessionData[$key]);
            }
        } elseif ($data !== null) {
            $this->sessionData[$key] = $data;
        }
    }

Writes data to the session.

@param string $key  A unique key identifying the data
@param mixed  $data Data associated with the key


public function getColumn($columnId)
    {
        foreach ($this->lazyAddColumn as $column) {
            if ($column['column']->getId() == $columnId) {
                return $column['column'];
            }
        }

        return $this->columns->getColumnById($columnId);
    }

public function getColumn ( $ columnId ) { foreach ( $ this -> lazyAddColumn as $ column ) { if ( $ column [ 'column' ] -> getId ( ) == $ columnId ) { return $ column [ 'column' ] ; } } return $ this -> columns -> getColumnById ( $ columnId ) ; }

Get a column by its identifier.

@param $columnId

@return Column


public function hasColumn($columnId)
    {
        foreach ($this->lazyAddColumn as $column) {
            if ($column['column']->getId() == $columnId) {
                return true;
            }
        }

        return $this->columns->hasColumnById($columnId);
    }

public function hasColumn ( $ columnId ) { foreach ( $ this -> lazyAddColumn as $ column ) { if ( $ column [ 'column' ] -> getId ( ) == $ columnId ) { return true ; } } return $ this -> columns -> hasColumnById ( $ columnId ) ; }

Returns true if column exists in columns and lazyAddColumn properties.

@param $columnId

@return bool

Returns true if column exists in columns and lazyAddColumn properties .


public function setColumnsOrder(array $columnIds, $keepOtherColumns = true)
    {
        $this->columns->setColumnsOrder($columnIds, $keepOtherColumns);

        return $this;
    }

public function setColumnsOrder ( array $ columnIds , $ keepOtherColumns = true ) { $ this -> columns -> setColumnsOrder ( $ columnIds , $ keepOtherColumns ) ; return $ this ; }

Sets order of Columns passing an array of column ids
If the list of ids is uncomplete, the remaining columns will be
placed after.

@param array $columnIds
@param bool  $keepOtherColumns

@return self

Sets order of Columns passing an array of column ids If the list of ids is uncomplete the remaining columns will be placed after .


public function addMassAction(MassActionInterface $action)
    {
        if ($action->getRole() === null || $this->securityContext->isGranted($action->getRole())) {
            $this->massActions[] = $action;
        }

        return $this;
    }

public function addMassAction ( MassActionInterface $ action ) { if ( $ action -> getRole ( ) === null || $ this -> securityContext -> isGranted ( $ action -> getRole ( ) ) ) { $ this -> massActions [ ] = $ action ; } return $ this ; }

Adds Mass Action.

@param Action\MassActionInterface $action

@return self


public function addTweak($title, array $tweak, $id = null, $group = null)
    {
        if ($id !== null && !preg_match('/^[0-9a-zA-Z_\+-]+$/', $id)) {
            throw new \InvalidArgumentException(sprintf(self::TWEAK_MALFORMED_ID_EX_MSG, $id));
        }

        $tweak = array_merge(['id' => $id, 'title' => $title, 'group' => $group], $tweak);
        if (isset($id)) {
            $this->tweaks[$id] = $tweak;
        } else {
            $this->tweaks[] = $tweak;
        }

        return $this;
    }

public function addTweak ( $ title , array $ tweak , $ id = null , $ group = null ) { if ( $ id !== null && ! preg_match ( '/^[0-9a-zA-Z_\+-]+$/' , $ id ) ) { throw new \ InvalidArgumentException ( sprintf ( self :: TWEAK_MALFORMED_ID_EX_MSG , $ id ) ) ; } $ tweak = array_merge ( [ 'id' => $ id , 'title' => $ title , 'group' => $ group ] , $ tweak ) ; if ( isset ( $ id ) ) { $ this -> tweaks [ $ id ] = $ tweak ; } else { $ this -> tweaks [ ] = $ tweak ; } return $ this ; }

Add a tweak.

@param string $title title of the tweak
@param array  $tweak array('filters' => array, 'order' => 'colomunId|order', 'page' => integer, 'limit' => integer, 'export' => integer, 'massAction' => integer)
@param string $id    id of the tweak matching the regex ^[0-9a-zA-Z_\+-]+
@param string $group group of the tweak

@return self


public function getTweaks()
    {
        $separator = strpos($this->getRouteUrl(), '?') ? '&' : '?';
        $url = $this->getRouteUrl() . $separator . $this->getHash() . '[' . self::REQUEST_QUERY_TWEAK . ']=';

        foreach ($this->tweaks as $id => $tweak) {
            $this->tweaks[$id] = array_merge($tweak, ['url' => $url . $id]);
        }

        return $this->tweaks;
    }

public function getTweaks ( ) { $ separator = strpos ( $ this -> getRouteUrl ( ) , '?' ) ? '&' : '?' ; $ url = $ this -> getRouteUrl ( ) . $ separator . $ this -> getHash ( ) . '[' . self :: REQUEST_QUERY_TWEAK . ']=' ; foreach ( $ this -> tweaks as $ id => $ tweak ) { $ this -> tweaks [ $ id ] = array_merge ( $ tweak , [ 'url' => $ url . $ id ] ) ; } return $ this -> tweaks ; }

Returns tweaks
Add the url of the tweak.

@return array

Returns tweaks Add the url of the tweak .


public function getTweak($id)
    {
        $tweaks = $this->getTweaks();
        if (isset($tweaks[$id])) {
            return $tweaks[$id];
        }

        throw new \InvalidArgumentException(sprintf(self::NOT_VALID_TWEAK_ID_EX_MSG, $id));
    }

public function getTweak ( $ id ) { $ tweaks = $ this -> getTweaks ( ) ; if ( isset ( $ tweaks [ $ id ] ) ) { return $ tweaks [ $ id ] ; } throw new \ InvalidArgumentException ( sprintf ( self :: NOT_VALID_TWEAK_ID_EX_MSG , $ id ) ) ; }


public function getTweaksGroup($group)
    {
        $tweaksGroup = $this->getTweaks();

        foreach ($tweaksGroup as $id => $tweak) {
            if ($tweak['group'] != $group) {
                unset($tweaksGroup[$id]);
            }
        }

        return $tweaksGroup;
    }

public function getTweaksGroup ( $ group ) { $ tweaksGroup = $ this -> getTweaks ( ) ; foreach ( $ tweaksGroup as $ id => $ tweak ) { if ( $ tweak [ 'group' ] != $ group ) { unset ( $ tweaksGroup [ $ id ] ) ; } } return $ tweaksGroup ; }

Returns tweaks with a specific group.

@return array


public function addRowAction(RowActionInterface $action)
    {
        if ($action->getRole() === null || $this->securityContext->isGranted($action->getRole())) {
            $this->rowActions[$action->getColumn()][] = $action;
        }

        return $this;
    }

public function addRowAction ( RowActionInterface $ action ) { if ( $ action -> getRole ( ) === null || $ this -> securityContext -> isGranted ( $ action -> getRole ( ) ) ) { $ this -> rowActions [ $ action -> getColumn ( ) ] [ ] = $ action ; } return $ this ; }

Adds Row Action.

@param Action\RowActionInterface $action

@return self


public function setTemplate($template)
    {
        if ($template !== null) {
            if ($template instanceof \Twig_Template) {
                $template = '__SELF__' . $template->getTemplateName();
            } elseif (!is_string($template)) {
                throw new \Exception(self::TWIG_TEMPLATE_LOAD_EX_MSG);
            }

            $this->set(self::REQUEST_QUERY_TEMPLATE, $template);
            $this->saveSession();
        }

        return $this;
    }

public function setTemplate ( $ template ) { if ( $ template !== null ) { if ( $ template instanceof \ Twig_Template ) { $ template = '__SELF__' . $ template -> getTemplateName ( ) ; } elseif ( ! is_string ( $ template ) ) { throw new \ Exception ( self :: TWIG_TEMPLATE_LOAD_EX_MSG ) ; } $ this -> set ( self :: REQUEST_QUERY_TEMPLATE , $ template ) ; $ this -> saveSession ( ) ; } return $ this ; }

Sets template for export.

@param \Twig_Template|string $template

@throws \Exception

@return self


public function addExport(ExportInterface $export)
    {
        if ($export->getRole() === null || $this->securityContext->isGranted($export->getRole())) {
            $this->exports[] = $export;
        }

        return $this;
    }

public function addExport ( ExportInterface $ export ) { if ( $ export -> getRole ( ) === null || $ this -> securityContext -> isGranted ( $ export -> getRole ( ) ) ) { $ this -> exports [ ] = $ export ; } return $ this ; }

Adds Export.

@param ExportInterface $export

@return self


public function getRouteUrl()
    {
        if ($this->routeUrl === null) {
            $this->routeUrl = $this->router->generate($this->request->get('_route'), $this->getRouteParameters());
        }

        return $this->routeUrl;
    }

public function getRouteUrl ( ) { if ( $ this -> routeUrl === null ) { $ this -> routeUrl = $ this -> router -> generate ( $ this -> request -> get ( '_route' ) , $ this -> getRouteParameters ( ) ) ; } return $ this -> routeUrl ; }


protected function setFilters(array $filters, $permanent = true)
    {
        foreach ($filters as $columnId => $value) {
            if ($permanent) {
                $this->permanentFilters[$columnId] = $value;
            } else {
                $this->defaultFilters[$columnId] = $value;
            }
        }

        return $this;
    }

protected function setFilters ( array $ filters , $ permanent = true ) { foreach ( $ filters as $ columnId => $ value ) { if ( $ permanent ) { $ this -> permanentFilters [ $ columnId ] = $ value ; } else { $ this -> defaultFilters [ $ columnId ] = $ value ; } } return $ this ; }

Set value for filters.

@param array $filters   Hash of columnName => initValue
@param bool  $permanent filters ?

@return self


public function setLimits($limits)
    {
        if (is_array($limits)) {
            if ((int) key($limits) === 0) {
                $this->limits = array_combine($limits, $limits);
            } else {
                $this->limits = $limits;
            }
        } elseif (is_int($limits)) {
            $this->limits = [$limits => (string) $limits];
        } else {
            throw new \InvalidArgumentException(self::NOT_VALID_LIMIT_EX_MSG);
        }

        return $this;
    }

public function setLimits ( $ limits ) { if ( is_array ( $ limits ) ) { if ( ( int ) key ( $ limits ) === 0 ) { $ this -> limits = array_combine ( $ limits , $ limits ) ; } else { $ this -> limits = $ limits ; } } elseif ( is_int ( $ limits ) ) { $ this -> limits = [ $ limits => ( string ) $ limits ] ; } else { throw new \ InvalidArgumentException ( self :: NOT_VALID_LIMIT_EX_MSG ) ; } return $ this ; }

Sets Limits.

@param mixed $limits e.g. 10, array(10, 1000) or array(10 => '10', 1000 => '1000')

@throws \InvalidArgumentException

@return self


public function getPageCount()
    {
        $pageCount = 1;
        if ($this->getLimit() > 0) {
            $pageCount = ceil($this->getTotalCount() / $this->getLimit());
        }

        // @todo why this should be a float?
        return $pageCount;
    }

public
function
getPageCount
(
)
{
$
pageCount
=
1
;
if
(
$
this
->
getLimit
(
)
>
0
)
{
$
pageCount
=
ceil
(
$
this
->
getTotalCount
(
)
/
$
this
->
getLimit
(
)
)
;
}
// @todo why this should be a float?
return
$
pageCount
;
}

Return count of available pages.

@return float


public function setMaxResults($maxResults = null)
    {
        if ((is_int($maxResults) && $maxResults < 0) && $maxResults !== null) {
            throw new \InvalidArgumentException(self::NOT_VALID_MAX_RESULT_EX_MSG);
        }

        $this->maxResults = $maxResults;

        return $this;
    }

public function setMaxResults ( $ maxResults = null ) { if ( ( is_int ( $ maxResults ) && $ maxResults < 0 ) && $ maxResults !== null ) { throw new \ InvalidArgumentException ( self :: NOT_VALID_MAX_RESULT_EX_MSG ) ; } $ this -> maxResults = $ maxResults ; return $ this ; }

Sets the max results of the grid.

@param int $maxResults

@throws \InvalidArgumentException

@return self


public function isTitleSectionVisible()
    {
        if ($this->showTitles === true) {
            foreach ($this->columns as $column) {
                if ($column->getTitle() != '') {
                    return true;
                }
            }
        }

        return false;
    }

public function isTitleSectionVisible ( ) { if ( $ this -> showTitles === true ) { foreach ( $ this -> columns as $ column ) { if ( $ column -> getTitle ( ) != '' ) { return true ; } } } return false ; }

Return true if if title panel is visible in template - internal helper.

@return bool

Return true if if title panel is visible in template - internal helper .


public function isFilterSectionVisible()
    {
        if ($this->showFilters === true) {
            foreach ($this->columns as $column) {
                if ($column->isFilterable() && $column->getType() != 'massaction' && $column->getType() != 'actions') {
                    return true;
                }
            }
        }

        return false;
    }

public function isFilterSectionVisible ( ) { if ( $ this -> showFilters === true ) { foreach ( $ this -> columns as $ column ) { if ( $ column -> isFilterable ( ) && $ column -> getType ( ) != 'massaction' && $ column -> getType ( ) != 'actions' ) { return true ; } } } return false ; }

Return true if filter panel is visible in template - internal helper.

@return bool

Return true if filter panel is visible in template - internal helper .


public function isPagerSectionVisible()
    {
        $limits = $this->getLimits();

        if (empty($limits)) {
            return false;
        }

        // true when totalCount rows exceed the minimum pager limit
        return min(array_keys($limits)) < $this->totalCount;
    }

Return true if pager panel is visible in template - internal helper.

@return bool return true if pager is visible

Return true if pager panel is visible in template - internal helper .


public function showColumns($columnIds)
    {
        foreach ((array) $columnIds as $columnId) {
            $this->lazyHideShowColumns[$columnId] = true;
        }

        return $this;
    }

public function showColumns ( $ columnIds ) { foreach ( ( array ) $ columnIds as $ columnId ) { $ this -> lazyHideShowColumns [ $ columnId ] = true ; } return $ this ; }

Sets on the visibility of columns.

@param string|array $columnIds

@return self


public function hideColumns($columnIds)
    {
        foreach ((array) $columnIds as $columnId) {
            $this->lazyHideShowColumns[$columnId] = false;
        }

        return $this;
    }

public function hideColumns ( $ columnIds ) { foreach ( ( array ) $ columnIds as $ columnId ) { $ this -> lazyHideShowColumns [ $ columnId ] = false ; } return $ this ; }

Sets off the visiblilty of columns.

@param string|array $columnIds

@return self


public function getGridResponse($param1 = null, $param2 = null, Response $response = null)
    {
        $isReadyForRedirect = $this->isReadyForRedirect();

        if ($this->isReadyForExport()) {
            return $this->getExportResponse();
        }

        if ($this->isMassActionRedirect()) {
            return $this->getMassActionResponse();
        }

        if ($isReadyForRedirect) {
            return new RedirectResponse($this->getRouteUrl());
        } else {
            if (is_array($param1) || $param1 === null) {
                $parameters = (array) $param1;
                $view = $param2;
            } else {
                $parameters = (array) $param2;
                $view = $param1;
            }

            $parameters = array_merge(['grid' => $this], $parameters);

            if ($view === null) {
                return $parameters;
            } else {
                return $this->container->get('templating')->renderResponse($view, $parameters, $response);
            }
        }
    }

public function getGridResponse ( $ param1 = null , $ param2 = null , Response $ response = null ) { $ isReadyForRedirect = $ this -> isReadyForRedirect ( ) ; if ( $ this -> isReadyForExport ( ) ) { return $ this -> getExportResponse ( ) ; } if ( $ this -> isMassActionRedirect ( ) ) { return $ this -> getMassActionResponse ( ) ; } if ( $ isReadyForRedirect ) { return new RedirectResponse ( $ this -> getRouteUrl ( ) ) ; } else { if ( is_array ( $ param1 ) || $ param1 === null ) { $ parameters = ( array ) $ param1 ; $ view = $ param2 ; } else { $ parameters = ( array ) $ param2 ; $ view = $ param1 ; } $ parameters = array_merge ( [ 'grid' => $ this ] , $ parameters ) ; if ( $ view === null ) { return $ parameters ; } else { return $ this -> container -> get ( 'templating' ) -> renderResponse ( $ view , $ parameters , $ response ) ; } } }

Redirects or Renders a view - helper function.

@param string|array $param1   The view name or an array of parameters to pass to the view
@param string|array $param2   The view name or an array of parameters to pass to the view
@param Response     $response A response instance

@return Response A Response instance

Redirects or Renders a view - helper function .


public function getRawData($columnNames = null, $namedIndexes = true)
    {
        if ($columnNames === null) {
            foreach ($this->getColumns() as $column) {
                $columnNames[] = $column->getId();
            }
        }

        $columnNames = (array) $columnNames;
        $result = [];
        foreach ($this->rows as $row) {
            $resultRow = [];
            foreach ($columnNames as $columnName) {
                if ($namedIndexes) {
                    $resultRow[$columnName] = $row->getField($columnName);
                } else {
                    $resultRow[] = $row->getField($columnName);
                }
            }

            $result[] = $resultRow;
        }

        return $result;
    }

public function getRawData ( $ columnNames = null , $ namedIndexes = true ) { if ( $ columnNames === null ) { foreach ( $ this -> getColumns ( ) as $ column ) { $ columnNames [ ] = $ column -> getId ( ) ; } } $ columnNames = ( array ) $ columnNames ; $ result = [ ] ; foreach ( $ this -> rows as $ row ) { $ resultRow = [ ] ; foreach ( $ columnNames as $ columnName ) { if ( $ namedIndexes ) { $ resultRow [ $ columnName ] = $ row -> getField ( $ columnName ) ; } else { $ resultRow [ ] = $ row -> getField ( $ columnName ) ; } } $ result [ ] = $ resultRow ; } return $ result ; }

Extract raw data of columns.

@param string|array $columnNames  The name of the extract columns. If null, all the columns are return.
@param bool         $namedIndexes If sets to true, named indexes will be used

@return array Raw data of columns


public function getFilters()
    {
        if ($this->hash === null) {
            throw new \Exception(self::GET_FILTERS_NO_REQUEST_HANDLED_EX_MSG);
        }

        if ($this->sessionFilters === null) {
            $this->sessionFilters = [];
            $session = $this->sessionData;

            $requestQueries = [
                self::REQUEST_QUERY_MASS_ACTION_ALL_KEYS_SELECTED,
                self::REQUEST_QUERY_MASS_ACTION,
                self::REQUEST_QUERY_EXPORT,
                self::REQUEST_QUERY_PAGE,
                self::REQUEST_QUERY_LIMIT,
                self::REQUEST_QUERY_ORDER,
                self::REQUEST_QUERY_TEMPLATE,
                self::REQUEST_QUERY_RESET,
                MassActionColumn::ID,
            ];

            foreach ($requestQueries as $request_query) {
                unset($session[$request_query]);
            }

            foreach ($session as $columnId => $sessionFilter) {
                if (isset($sessionFilter['operator'])) {
                    $operator = $sessionFilter['operator'];
                    unset($sessionFilter['operator']);
                } else {
                    $operator = $this->getColumn($columnId)->getDefaultOperator();
                }

                if (!isset($sessionFilter['to']) && isset($sessionFilter['from'])) {
                    $sessionFilter = $sessionFilter['from'];
                }

                $this->sessionFilters[$columnId] = new Filter($operator, $sessionFilter);
            }
        }

        return $this->sessionFilters;
    }

Returns an array of the active filters of the grid stored in session.

@throws \Exception

@return Filter[]

Returns an array of the active filters of the grid stored in session .


public function getFilter($columnId)
    {
        if ($this->hash === null) {
            throw new \Exception(self::GET_FILTERS_NO_REQUEST_HANDLED_EX_MSG);
        }

        $sessionFilters = $this->getFilters();

        return isset($sessionFilters[$columnId]) ? $sessionFilters[$columnId] : null;
    }

public function getFilter ( $ columnId ) { if ( $ this -> hash === null ) { throw new \ Exception ( self :: GET_FILTERS_NO_REQUEST_HANDLED_EX_MSG ) ; } $ sessionFilters = $ this -> getFilters ( ) ; return isset ( $ sessionFilters [ $ columnId ] ) ? $ sessionFilters [ $ columnId ] : null ; }

Returns the filter of a column stored in session.

@param string $columnId
Id of the column

@throws \Exception

@return Filter

Returns the filter of a column stored in session .


public function hasFilter($columnId)
    {
        if ($this->hash === null) {
            throw new \Exception(self::HAS_FILTER_NO_REQUEST_HANDLED_EX_MSG);
        }

        return $this->getFilter($columnId) !== null;
    }

public function hasFilter ( $ columnId ) { if ( $ this -> hash === null ) { throw new \ Exception ( self :: HAS_FILTER_NO_REQUEST_HANDLED_EX_MSG ) ; } return $ this -> getFilter ( $ columnId ) !== null ; }

A filter of the column is stored in session ?

@param string $columnId
Id of the column

@throws \Exception

@return bool


public function initQueryBuilder(QueryBuilder $queryBuilder)
    {
        $this->queryBuilder = clone $queryBuilder;

        //Try to guess the new root alias and apply it to our queries+
        //as the external querybuilder almost certainly is not used our default alias
        $externalTableAliases = $this->queryBuilder->getRootAliases();
        if (count($externalTableAliases)) {
            $this->setTableAlias($externalTableAliases[0]);
        }
    }

Sets the initial QueryBuilder for this DataGrid.

@param QueryBuilder $queryBuilder

Sets the initial QueryBuilder for this DataGrid .


public function renderCell($value, $row, $router)
    {
        if (is_callable($this->callback)) {
            return call_user_func($this->callback, $value, $row, $router);
        }

        $value = is_bool($value) ? (int) $value : $value;
        if (array_key_exists((string) $value, $this->values)) {
            $value = $this->values[$value];
        }

        return $value;
    }

public function renderCell ( $ value , $ row , $ router ) { if ( is_callable ( $ this -> callback ) ) { return call_user_func ( $ this -> callback , $ value , $ row , $ router ) ; } $ value = is_bool ( $ value ) ? ( int ) $ value : $ value ; if ( array_key_exists ( ( string ) $ value , $ this -> values ) ) { $ value = $ this -> values [ $ value ] ; } return $ value ; }

Draw cell.

@param string $value
@param Row    $row
@param $router

@return string


public function isVisible($isExported = false)
    {
        $visible = $isExported && $this->export !== null ? $this->export : $this->visible;

        if ($visible && $this->authorizationChecker !== null && $this->getRole() !== null) {
            return $this->authorizationChecker->isGranted($this->getRole());
        }

        return $visible;
    }

public function isVisible ( $ isExported = false ) { $ visible = $ isExported && $ this -> export !== null ? $ this -> export : $ this -> visible ; if ( $ visible && $ this -> authorizationChecker !== null && $ this -> getRole ( ) !== null ) { return $ this -> authorizationChecker -> isGranted ( $ this -> getRole ( ) ) ; } return $ visible ; }

Return column visibility.

@return bool return true when column is visible


public function setOrder($order)
    {
        if ($order !== null) {
            $this->order = $order;
            $this->isSorted = true;
        }

        return $this;
    }

public function setOrder ( $ order ) { if ( $ order !== null ) { $ this -> order = $ order ; $ this -> isSorted = true ; } return $ this ; }

set column order.

@param string $order asc|desc

@return \APY\DataGridBundle\Grid\Column\Column


public function setSize($size)
    {
        if ($size < -1) {
            throw new \InvalidArgumentException(sprintf('Unsupported column size %s, use positive value or -1 for auto resize', $size));
        }

        $this->size = $size;

        return $this;
    }

Set column width.

@param int $size in pixels

@return \APY\DataGridBundle\Grid\Column\Column


public function setData($data)
    {
        $this->data = ['operator' => $this->getDefaultOperator(), 'from' => static::DEFAULT_VALUE, 'to' => static::DEFAULT_VALUE];

        $hasValue = false;
        if (isset($data['from']) && $this->isQueryValid($data['from'])) {
            $this->data['from'] = $data['from'];
            $hasValue = true;
        }

        if (isset($data['to']) && $this->isQueryValid($data['to'])) {
            $this->data['to'] = $data['to'];
            $hasValue = true;
        }

        $isNullOperator = (isset($data['operator']) && ($data['operator'] === self::OPERATOR_ISNULL || $data['operator'] === self::OPERATOR_ISNOTNULL));
        if (($hasValue || $isNullOperator) && isset($data['operator']) && $this->hasOperator($data['operator'])) {
            $this->data['operator'] = $data['operator'];
        }

        return $this;
    }

public function setData ( $ data ) { $ this -> data = [ 'operator' => $ this -> getDefaultOperator ( ) , 'from' => static :: DEFAULT_VALUE , 'to' => static :: DEFAULT_VALUE ] ; $ hasValue = false ; if ( isset ( $ data [ 'from' ] ) && $ this -> isQueryValid ( $ data [ 'from' ] ) ) { $ this -> data [ 'from' ] = $ data [ 'from' ] ; $ hasValue = true ; } if ( isset ( $ data [ 'to' ] ) && $ this -> isQueryValid ( $ data [ 'to' ] ) ) { $ this -> data [ 'to' ] = $ data [ 'to' ] ; $ hasValue = true ; } $ isNullOperator = ( isset ( $ data [ 'operator' ] ) && ( $ data [ 'operator' ] === self :: OPERATOR_ISNULL || $ data [ 'operator' ] === self :: OPERATOR_ISNOTNULL ) ) ; if ( ( $ hasValue || $ isNullOperator ) && isset ( $ data [ 'operator' ] ) && $ this -> hasOperator ( $ data [ 'operator' ] ) ) { $ this -> data [ 'operator' ] = $ data [ 'operator' ] ; } return $ this ; }

set filter data from session | request.

@param  $data

@return \APY\DataGridBundle\Grid\Column\Column

set filter data from session | request .


public function getData()
    {
        $result = [];

        $hasValue = false;
        if ($this->data['from'] != $this::DEFAULT_VALUE) {
            $result['from'] = $this->data['from'];
            $hasValue = true;
        }

        if ($this->data['to'] != $this::DEFAULT_VALUE) {
            $result['to'] = $this->data['to'];
            $hasValue = true;
        }

        $isNullOperator = (isset($this->data['operator']) && ($this->data['operator'] === self::OPERATOR_ISNULL || $this->data['operator'] === self::OPERATOR_ISNOTNULL));
        if ($hasValue || $isNullOperator) {
            $result['operator'] = $this->data['operator'];
        }

        return $result;
    }

public function getData ( ) { $ result = [ ] ; $ hasValue = false ; if ( $ this -> data [ 'from' ] != $ this :: DEFAULT_VALUE ) { $ result [ 'from' ] = $ this -> data [ 'from' ] ; $ hasValue = true ; } if ( $ this -> data [ 'to' ] != $ this :: DEFAULT_VALUE ) { $ result [ 'to' ] = $ this -> data [ 'to' ] ; $ hasValue = true ; } $ isNullOperator = ( isset ( $ this -> data [ 'operator' ] ) && ( $ this -> data [ 'operator' ] === self :: OPERATOR_ISNULL || $ this -> data [ 'operator' ] === self :: OPERATOR_ISNOTNULL ) ) ; if ( $ hasValue || $ isNullOperator ) { $ result [ 'operator' ] = $ this -> data [ 'operator' ] ; } return $ result ; }

get filter data from session | request.

@return array data

get filter data from session | request .


public function setAlign($align)
    {
        if (!in_array($align, self::$aligns)) {
            throw new \InvalidArgumentException(sprintf('Unsupported align %s, just left, right and center are supported', $align));
        }

        $this->align = $align;

        return $this;
    }

Set column align.

@param string $align left/right/center

@return $this


public function getOperators()
    {
        // Issue with Doctrine
        // -------------------
        // @see http://www.doctrine-project.org/jira/browse/DDC-1857
        // @see http://www.doctrine-project.org/jira/browse/DDC-1858
        if ($this->hasDQLFunction() && version_compare(DoctrineVersion::VERSION, '2.5') < 0) {
            return array_intersect($this->operators, [self::OPERATOR_EQ,
                self::OPERATOR_NEQ,
                self::OPERATOR_LT,
                self::OPERATOR_LTE,
                self::OPERATOR_GT,
                self::OPERATOR_GTE,
                self::OPERATOR_BTW,
                self::OPERATOR_BTWE, ]);
        }

        return $this->operators;
    }

Return column filter operators.

@return array $operators


public function addColumn(Column $column, $position = 0)
    {
        $column->setAuthorizationChecker($this->authorizationChecker);

        if ($position == 0) {
            $this->columns[] = $column;
        } else {
            if ($position > 0) {
                --$position;
            } else {
                $position = max(0, count($this->columns) + $position);
            }

            $head = array_slice($this->columns, 0, $position);
            $tail = array_slice($this->columns, $position);
            $this->columns = array_merge($head, [$column], $tail);
        }

        return $this;
    }

public function addColumn ( Column $ column , $ position = 0 ) { $ column -> setAuthorizationChecker ( $ this -> authorizationChecker ) ; if ( $ position == 0 ) { $ this -> columns [ ] = $ column ; } else { if ( $ position > 0 ) { -- $ position ; } else { $ position = max ( 0 , count ( $ this -> columns ) + $ position ) ; } $ head = array_slice ( $ this -> columns , 0 , $ position ) ; $ tail = array_slice ( $ this -> columns , $ position ) ; $ this -> columns = array_merge ( $ head , [ $ column ] , $ tail ) ; } return $ this ; }

Add column.

@param Column $column
@param int    $position

@return Columns


public function setColumnsOrder(array $columnIds, $keepOtherColumns = true)
    {
        $reorderedColumns = [];
        $columnsIndexedByIds = [];

        foreach ($this->columns as $column) {
            $columnsIndexedByIds[$column->getId()] = $column;
        }

        foreach ($columnIds as $columnId) {
            if (isset($columnsIndexedByIds[$columnId])) {
                $reorderedColumns[] = $columnsIndexedByIds[$columnId];
                unset($columnsIndexedByIds[$columnId]);
            }
        }

        if ($keepOtherColumns) {
            $this->columns = array_merge($reorderedColumns, array_values($columnsIndexedByIds));
        } else {
            $this->columns = $reorderedColumns;
        }

        return $this;
    }

public function setColumnsOrder ( array $ columnIds , $ keepOtherColumns = true ) { $ reorderedColumns = [ ] ; $ columnsIndexedByIds = [ ] ; foreach ( $ this -> columns as $ column ) { $ columnsIndexedByIds [ $ column -> getId ( ) ] = $ column ; } foreach ( $ columnIds as $ columnId ) { if ( isset ( $ columnsIndexedByIds [ $ columnId ] ) ) { $ reorderedColumns [ ] = $ columnsIndexedByIds [ $ columnId ] ; unset ( $ columnsIndexedByIds [ $ columnId ] ) ; } } if ( $ keepOtherColumns ) { $ this -> columns = array_merge ( $ reorderedColumns , array_values ( $ columnsIndexedByIds ) ) ; } else { $ this -> columns = $ reorderedColumns ; } return $ this ; }

Sets order of Columns passing an array of column ids
If the list of ids is uncomplete, the remaining columns will be
placed after if keepOtherColumns is true.

@param array $columnIds
@param bool  $keepOtherColumns

@return Columns

Sets order of Columns passing an array of column ids If the list of ids is uncomplete the remaining columns will be placed after if keepOtherColumns is true .


public function addRouteParameters($routeParameters)
    {
        $routeParameters = (array) $routeParameters;

        foreach ($routeParameters as $key => $routeParameter) {
            if (is_int($key)) {
                $this->routeParameters[] = $routeParameter;
            } else {
                $this->routeParameters[$key] = $routeParameter;
            }
        }

        return $this;
    }

public function addRouteParameters ( $ routeParameters ) { $ routeParameters = ( array ) $ routeParameters ; foreach ( $ routeParameters as $ key => $ routeParameter ) { if ( is_int ( $ key ) ) { $ this -> routeParameters [ ] = $ routeParameter ; } else { $ this -> routeParameters [ $ key ] = $ routeParameter ; } } return $ this ; }

Add route parameter.

@param array|string $routeParameters

@return self


public function getRouteParametersMapping($name)
    {
        return isset($this->routeParametersMapping[$name]) ? $this->routeParametersMapping[$name] : null;
    }

public function getRouteParametersMapping ( $ name ) { return isset ( $ this -> routeParametersMapping [ $ name ] ) ? $ this -> routeParametersMapping [ $ name ] : null ; }

Map the parameter.

@param string $name parameter

@return null|string


public function render($row)
    {
        foreach ($this->callbacks as $callback) {
            if (is_callable($callback)) {
                if (null === call_user_func($callback, $this, $row)) {
                    return;
                }
            }
        }

        return $this;
    }

public function render ( $ row ) { foreach ( $ this -> callbacks as $ callback ) { if ( is_callable ( $ callback ) ) { if ( null === call_user_func ( $ callback , $ this , $ row ) ) { return ; } } } return $ this ; }

Render action for row.

@param Row $row

@return RowAction|null


public function addType(GridTypeInterface $type)
    {
        $name = $type->getName();

        if ($this->hasType($name)) {
            throw new TypeAlreadyExistsException($name);
        }

        $this->types[$name] = $type;

        return $this;
    }

public function addType ( GridTypeInterface $ type ) { $ name = $ type -> getName ( ) ; if ( $ this -> hasType ( $ name ) ) { throw new TypeAlreadyExistsException ( $ name ) ; } $ this -> types [ $ name ] = $ type ; return $ this ; }

Add a grid type.

@param GridTypeInterface $type

@return $this


public function addColumn(Column $column)
    {
        $type = $column->getType();

        if ($this->hasColumn($type)) {
            throw new ColumnAlreadyExistsException($type);
        }

        $this->columns[$type] = $column;

        return $this;
    }

public function addColumn ( Column $ column ) { $ type = $ column -> getType ( ) ; if ( $ this -> hasColumn ( $ type ) ) { throw new ColumnAlreadyExistsException ( $ type ) ; } $ this -> columns [ $ type ] = $ column ; return $ this ; }

Add a column type.

@param Column $column

@return $this


public function setContainer(ContainerInterface $container = null)
    {
        $this->container = $container;

        $this->twig = $this->container->get('twig');

        return $this;
    }

public function setContainer ( ContainerInterface $ container = null ) { $ this -> container = $ container ; $ this -> twig = $ this -> container -> get ( 'twig' ) ; return $ this ; }

Sets the Container associated with this Controller.

@param ContainerInterface $container A ContainerInterface instance

@return \APY\DataGridBundle\Grid\Export\Export

Sets the Container associated with this Controller .


public function getResponse()
    {
        // Response
        $kernelCharset = $this->container->getParameter('kernel.charset');
        if ($this->charset != $kernelCharset && function_exists('mb_strlen')) {
            $this->content = mb_convert_encoding($this->content, $this->charset, $kernelCharset);
            $filesize = mb_strlen($this->content, '8bit');
        } else {
            $filesize = strlen($this->content);
            $this->charset = $kernelCharset;
        }

        $headers = [
            'Content-Description'       => 'File Transfer',
            'Content-Type'              => $this->getMimeType(),
            'Content-Disposition'       => sprintf('attachment; filename="%s"', $this->getBaseName()),
            'Content-Transfer-Encoding' => 'binary',
            'Cache-Control'             => 'must-revalidate',
            'Pragma'                    => 'public',
            'Content-Length'            => $filesize,
        ];

        $response = new Response($this->content, 200, $headers);
        $response->setCharset($this->charset);
        $response->expire();

        return $response;
    }

public
function
getResponse
(
)
{
// Response
$
kernelCharset
=
$
this
->
container
->
getParameter
(
'kernel.charset'
)
;
if
(
$
this
->
charset
!=
$
kernelCharset
&&
function_exists
(
'mb_strlen'
)
)
{
$
this
->
content
=
mb_convert_encoding
(
$
this
->
content
,
$
this
->
charset
,
$
kernelCharset
)
;
$
filesize
=
mb_strlen
(
$
this
->
content
,
'8bit'
)
;
}
else
{
$
filesize
=
strlen
(
$
this
->
content
)
;
$
this
->
charset
=
$
kernelCharset
;
}
$
headers
=
[
'Content-Description'
=>
'File Transfer'
,
'Content-Type'
=>
$
this
->
getMimeType
(
)
,
'Content-Disposition'
=>
sprintf
(
'attachment; filename="%s"'
,
$
this
->
getBaseName
(
)
)
,
'Content-Transfer-Encoding'
=>
'binary'
,
'Cache-Control'
=>
'must-revalidate'
,
'Pragma'
=>
'public'
,
'Content-Length'
=>
$
filesize
,
]
;
$
response
=
new
Response
(
$
this
->
content
,
200
,
$
headers
)
;
$
response
->
setCharset
(
$
this
->
charset
)
;
$
response
->
expire
(
)
;
return
$
response
;
}

gets the export Response.

@return Response


protected function getGridData($grid)
    {
        $result = [];

        $this->grid = $grid;

        if ($this->grid->isTitleSectionVisible()) {
            $result['titles'] = $this->getGridTitles();
        }

        $result['rows'] = $this->getGridRows();

        return $result;
    }

protected function getGridData ( $ grid ) { $ result = [ ] ; $ this -> grid = $ grid ; if ( $ this -> grid -> isTitleSectionVisible ( ) ) { $ result [ 'titles' ] = $ this -> getGridTitles ( ) ; } $ result [ 'rows' ] = $ this -> getGridRows ( ) ; return $ result ; }

Get data form the grid.

@param Grid $grid

@return array

array(
'titles' => array(
'column_id_1' => 'column_title_1',
'column_id_2' => 'column_title_2'
),
'rows' =>array(
array(
'column_id_1' => 'cell_value_1_1',
'column_id_2' => 'cell_value_1_2'
),
array(
'column_id_1' => 'cell_value_2_1',
'column_id_2' => 'cell_value_2_2'
)
)
)


protected function getFlatGridData($grid)
    {
        $data = $this->getGridData($grid);

        $flatData = [];
        if (isset($data['titles'])) {
            $flatData[] = $data['titles'];
        }

        return array_merge($flatData, $data['rows']);
    }

protected function getFlatGridData ( $ grid ) { $ data = $ this -> getGridData ( $ grid ) ; $ flatData = [ ] ; if ( isset ( $ data [ 'titles' ] ) ) { $ flatData [ ] = $ data [ 'titles' ] ; } return array_merge ( $ flatData , $ data [ 'rows' ] ) ; }

Get data form the grid in a flat array.

@param Grid $grid

@return array

array(
'0' => array(
'column_id_1' => 'column_title_1',
'column_id_2' => 'column_title_2'
),
'1' => array(
'column_id_1' => 'cell_value_1_1',
'column_id_2' => 'cell_value_1_2'
),
'2' => array(
'column_id_1' => 'cell_value_2_1',
'column_id_2' => 'cell_value_2_2'
)
)

Get data form the grid in a flat array .


public function setTemplate($template)
    {
        if (is_string($template)) {
            if (substr($template, 0, 8) === '__SELF__') {
                $this->templates = $this->getTemplatesFromString(substr($template, 8));
                $this->templates[] = $this->twig->loadTemplate(static::DEFAULT_TEMPLATE);
            } else {
                $this->templates = $this->getTemplatesFromString($template);
            }
        } elseif ($this->templates === null) {
            $this->templates[] = $this->twig->loadTemplate(static::DEFAULT_TEMPLATE);
        } else {
            throw new \Exception('Unable to load template');
        }

        return $this;
    }

public
function
setTemplate
(
$
template
)
{
if
(
is_string
(
$
template
)
)
{
if
(
substr
(
$
template
,
0
,
8
)
===
'__SELF__'
)
{
$
this
->
templates
=
$
this
->
getTemplatesFromString
(
substr
(
$
template
,
8
)
)
;
$
this
->
templates
[
]
=
$
this
->
twig
->
loadTemplate
(
static
::
DEFAULT_TEMPLATE
)
;
}
else
{
$
this
->
templates
=
$
this
->
getTemplatesFromString
(
$
template
)
;
}
}
elseif
(
$
this
->
templates
===
)
{
$
this
->
templates
[
]
=
$
this
->
twig
->
loadTemplate
(
static
::
DEFAULT_TEMPLATE
)
;
}
else
{
throw
new
\
Exception
(
'Unable to load template'
)
;
}
return
$
this
;
}

set template.

@param \Twig_TemplateInterface|string $template

@throws \Exception

@return \APY\DataGridBundle\Grid\Export\Export


public function getParameter($name)
    {
        if (!$this->hasParameter($name)) {
            throw new \InvalidArgumentException(sprintf('The parameter "%s" must be defined.', $name));
        }

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

public
function
getParameter
(
$
name
)
{
if
(
!
$
this
->
hasParameter
(
$
name
)
)
{
throw
new
\
InvalidArgumentException
(
sprintf
(
'The parameter "%s" must be defined.'
,
$
name
)
)
;
}
return
$
this
->
parameters
[
$
name
]
;
}


public function getActionsToRender($row)
    {
        $list = $this->rowActions;
        foreach ($list as $i => $a) {
            $action = clone $a;
            $list[$i] = $action->render($row);
            if (null === $list[$i]) {
                unset($list[$i]);
            }
        }

        return $list;
    }

public function getActionsToRender ( $ row ) { $ list = $ this -> rowActions ; foreach ( $ list as $ i => $ a ) { $ action = clone $ a ; $ list [ $ i ] = $ action -> render ( $ row ) ; if ( null === $ list [ $ i ] ) { unset ( $ list [ $ i ] ) ; } } return $ list ; }

Get the list of actions to render.

@param $row

@return array


public function clear($save = true): self
    {
        $this->items = [];
        $save && $this->storage->save($this);

        return $this;
    }

public function clear ( $ save = true ) : self { $ this -> items = [ ] ; $ save && $ this -> storage -> save ( $ this ) ; return $ this ; }

Delete all items from the cart

@param bool $save

@return $this


public function add(CartItemInterface $element, $save = true): self
    {
        $this->addItem($element);
        $save && $this->storage->save($this);

        return $this;
    }

public function add ( CartItemInterface $ element , $ save = true ) : self { $ this -> addItem ( $ element ) ; $ save && $ this -> storage -> save ( $ this ) ; return $ this ; }

Add an item to the cart

@param models\CartItemInterface $element
@param bool $save

@return $this


public function remove($uniqueId, $save = true): self
    {
        if (!isset($this->items[$uniqueId])) {
            throw new InvalidParamException('Item not found');
        }

        unset($this->items[$uniqueId]);

        $save && $this->storage->save($this);

        return $this;
    }

public
function
remove
(
$
uniqueId
,
$
save
=
true
)
:
self
{
if
(
!
isset
(
$
this
->
items
[
$
uniqueId
]
)
)
{
throw
new
InvalidParamException
(
'Item not found'
)
;
}
unset
(
$
this
->
items
[
$
uniqueId
]
)
;
$
save
&&
$
this
->
storage
->
save
(
$
this
)
;
return
$
this
;
}

Removes an item from the cart

@param string $uniqueId
@param bool $save

@throws \yii\base\InvalidParamException

@return $this


public function getItems($itemType = null): array
    {
        $items = $this->items;

        if (!is_null($itemType)) {
            $items = array_filter(
                $items,
                function ($item) use ($itemType) {
                    /* @var $item CartItemInterface */
                    return is_a($item, $itemType);
                }
            );
        }

        return $items;
    }

public
function
getItems
(
$
itemType
=
)
:
array
{
$
items
=
$
this
->
items
;
if
(
!
is_null
(
$
itemType
)
)
{
$
items
=
array_filter
(
$
items
,
function
(
$
item
)
use
(
$
itemType
)
{
/* @var $item CartItemInterface */
return
is_a
(
$
item
,
$
itemType
)
;
}
)
;
}
return
$
items
;
}

Returns all items of a given type from the cart

@param string $itemType One of self::ITEM_ constants

@return CartItemInterface[]


public function login($connection = null, $state = null, $additional_params = ['scope' => 'openid profile email'], $response_type = 'code')
    {
        $additional_params['response_type'] = $response_type;
        $this->auth0->login($state, $connection, $additional_params);
    }

public
function
login
(
$
connection
=
,
$
state
=
,
$
additional_params
=
[
'scope'
=>
'openid profile email'
]
,
$
response_type
=
'code'
)
{
$
additional_params
[
'response_type'
]
=
$
response_type
;
$
this
->
auth0
->
login
(
$
state
,
$
connection
,
$
additional_params
)
;
}

Redirects the user to the hosted login page


public function getUser()
    {
        // Get the user info from auth0
        $auth0 = $this->getSDK();
        $user = $auth0->getUser();

        if ($user === null) {
            return;
        }

        return [
            'profile' => $user,
            'accessToken' => $auth0->getAccessToken(),
        ];
    }

public
function
getUser
(
)
{
// Get the user info from auth0
$
auth0
=
$
this
->
getSDK
(
)
;
$
user
=
$
auth0
->
getUser
(
)
;
if
(
$
user
===
)
{
return
;
}
return
[
'profile'
=>
$
user
,
'accessToken'
=>
$
auth0
->
getAccessToken
(
)
,
]
;
}

If the user is logged in, returns the user information.

@return array with the User info as described in https://docs.auth0.com/user-profile and the user access token

If the user is logged in returns the user information .


public function rememberUser($value = null)
    {
        if ($value !== null) {
            $this->rememberUser = $value;
        }

        return $this->rememberUser;
    }

public function rememberUser ( $ value = null ) { if ( $ value !== null ) { $ this -> rememberUser = $ value ; } return $ this -> rememberUser ; }

Use this to either enable or disable the "remember" function for users.

@param null $value

@return bool|null

Use this to either enable or disable the remember function for users .


public function callback()
    {
        // Get a handle of the Auth0 service (we don't know if it has an alias)
        $service = \App::make('auth0');

        // Try to get the user information
        $profile = $service->getUser();

        // Get the user related to the profile
        $auth0User = $this->userRepository->getUserByUserInfo($profile);

        if ($auth0User) {
            // If we have a user, we are going to log them in, but if
            // there is an onLogin defined we need to allow the Laravel developer
            // to implement the user as they want an also let them store it.
            if ($service->hasOnLogin()) {
                $user = $service->callOnLogin($auth0User);
            } else {
                // If not, the user will be fine
                $user = $auth0User;
            }
            \Auth::login($user, $service->rememberUser());
        }

        return \Redirect::intended('/');
    }

Callback action that should be called by auth0, logs the user in.

Callback action that should be called by auth0 logs the user in .


public static function length($string)
    {
        if (function_exists('mb_strlen')) {
            return mb_strlen($string, static::getEncoding());
        }

        if (function_exists('iconv_strlen')) {
            return iconv_strlen($string, static::getEncoding());
        }

        return false;
    }

public static function length ( $ string ) { if ( function_exists ( 'mb_strlen' ) ) { return mb_strlen ( $ string , static :: getEncoding ( ) ) ; } if ( function_exists ( 'iconv_strlen' ) ) { return iconv_strlen ( $ string , static :: getEncoding ( ) ) ; } return false ; }

Calculates count of characters in string.
@param $string
@return bool|int

Calculates count of characters in string .


public static function slice($string, $start, $end = null)
    {
        if ($end !== null) {
            $end -= $start;
        }

        if (function_exists('mb_substr')) {
            return mb_substr($string, $start, $end, static::getEncoding());
        }

        if (function_exists('iconv_substr')) {
            return iconv_substr($string, $start, $end ?: iconv_strlen($string), static::getEncoding());
        }

        return false;
    }

public static function slice ( $ string , $ start , $ end = null ) { if ( $ end !== null ) { $ end -= $ start ; } if ( function_exists ( 'mb_substr' ) ) { return mb_substr ( $ string , $ start , $ end , static :: getEncoding ( ) ) ; } if ( function_exists ( 'iconv_substr' ) ) { return iconv_substr ( $ string , $ start , $ end ? : iconv_strlen ( $ string ) , static :: getEncoding ( ) ) ; } return false ; }

Slices string like python.
@param string $string
@param int $start
@param int|null $end
@return bool|string


public static function lower($string)
    {
        if (function_exists('mb_strtolower')) {
            return mb_strtolower($string, static::getEncoding());
        }

        return static::replaceByMap($string, static::$cyrillicAlphabet[0], static::$cyrillicAlphabet[1]);
    }

public static function lower ( $ string ) { if ( function_exists ( 'mb_strtolower' ) ) { return mb_strtolower ( $ string , static :: getEncoding ( ) ) ; } return static :: replaceByMap ( $ string , static :: $ cyrillicAlphabet [ 0 ] , static :: $ cyrillicAlphabet [ 1 ] ) ; }

Lower case.
@param $string
@return bool|string


public static function upper($string)
    {
        if (function_exists('mb_strtoupper')) {
            return mb_strtoupper($string, static::getEncoding());
        }

        return static::replaceByMap($string, static::$cyrillicAlphabet[1], static::$cyrillicAlphabet[0]);
    }

public static function upper ( $ string ) { if ( function_exists ( 'mb_strtoupper' ) ) { return mb_strtoupper ( $ string , static :: getEncoding ( ) ) ; } return static :: replaceByMap ( $ string , static :: $ cyrillicAlphabet [ 1 ] , static :: $ cyrillicAlphabet [ 0 ] ) ; }

Upper case.
@param $string
@return bool|string


public function getFunctionMock($namespace, $name)
    {
        $delegateBuilder = new MockDelegateFunctionBuilder();
        $delegateBuilder->build($name);

        $mock = $this->getMockBuilder($delegateBuilder->getFullyQualifiedClassName())->getMockForAbstractClass();

        $mock->__phpunit_getInvocationMocker()->addMatcher(new DefaultArgumentRemover());

        $functionMockBuilder = new MockBuilder();
        $functionMockBuilder->setNamespace($namespace)
                            ->setName($name)
                            ->setFunctionProvider($mock);

        $functionMock = $functionMockBuilder->build();
        $functionMock->enable();

        $this->registerForTearDown($functionMock);

        $proxy = new MockObjectProxy($mock);
        return $proxy;
    }

public function getFunctionMock ( $ namespace , $ name ) { $ delegateBuilder = new MockDelegateFunctionBuilder ( ) ; $ delegateBuilder -> build ( $ name ) ; $ mock = $ this -> getMockBuilder ( $ delegateBuilder -> getFullyQualifiedClassName ( ) ) -> getMockForAbstractClass ( ) ; $ mock -> __phpunit_getInvocationMocker ( ) -> addMatcher ( new DefaultArgumentRemover ( ) ) ; $ functionMockBuilder = new MockBuilder ( ) ; $ functionMockBuilder -> setNamespace ( $ namespace ) -> setName ( $ name ) -> setFunctionProvider ( $ mock ) ; $ functionMock = $ functionMockBuilder -> build ( ) ; $ functionMock -> enable ( ) ; $ this -> registerForTearDown ( $ functionMock ) ; $ proxy = new MockObjectProxy ( $ mock ) ; return $ proxy ; }

Returns the enabled function mock.

This mock will be disabled automatically after the test run.

@param string $namespace The function namespace.
@param string $name      The function name.

@return MockObject The PHPUnit mock.


public function registerForTearDown(Deactivatable $deactivatable)
    {
        $result = $this->getTestResultObject();
        $result->addListener(new MockDisabler($deactivatable));
    }

public function registerForTearDown ( Deactivatable $ deactivatable ) { $ result = $ this -> getTestResultObject ( ) ; $ result -> addListener ( new MockDisabler ( $ deactivatable ) ) ; }

Automatically disable function mocks after the test was run.

If you use getFunctionMock() you don't need this method. This method
is meant for a Deactivatable (e.g. a MockEnvironment) which was
directly created with PHPMock's API.

@param Deactivatable $deactivatable The function mocks.

Automatically disable function mocks after the test was run .


public static function defineFunctionMock($namespace, $name)
    {
        $functionMockBuilder = new MockBuilder();
        $functionMockBuilder->setNamespace($namespace)
                            ->setName($name)
                            ->setFunction(function () {
                            })
                            ->build()
                            ->define();
    }

public static function defineFunctionMock ( $ namespace , $ name ) { $ functionMockBuilder = new MockBuilder ( ) ; $ functionMockBuilder -> setNamespace ( $ namespace ) -> setName ( $ name ) -> setFunction ( function ( ) { } ) -> build ( ) -> define ( ) ; }

Defines the mocked function in the given namespace.

In most cases you don't have to call this method. {@link getFunctionMock()}
is doing this for you. But if the mock is defined after the first call in the
tested class, the tested class doesn't resolve to the mock. This is
documented in Bug #68541. You therefore have to define the namespaced
function before the first call (e.g. with the beforeClass annotation).

Defining the function has no side effects. If the function was
already defined this method does nothing.

@see getFunctionMock()
@link https://bugs.php.net/bug.php?id=68541 Bug #68541

@param string $namespace The function namespace.
@param string $name      The function name.

Defines the mocked function in the given namespace .


public static function flag($code = 'default')
    {
        if ($code == 'default') {
            $code = app()->getLocale();
        }

        $name = self::getName($code);
        $code = self::country($code);

        return view('vendor.language.flag', compact('code', 'name'));
    }

public static function flag ( $ code = 'default' ) { if ( $ code == 'default' ) { $ code = app ( ) -> getLocale ( ) ; } $ name = self :: getName ( $ code ) ; $ code = self :: country ( $ code ) ; return view ( 'vendor.language.flag' , compact ( 'code' , 'name' ) ) ; }

Get single flags view.

@param string $code

@return mixed


public static function country($locale = 'default')
    {
        if ($locale == 'default') {
            $locale = app()->getLocale();
        }

        if (config('language.mode.code', 'short') == 'short') {
            $code = strtolower(substr(self::getLongCode($locale), 3));
        } else {
            $code = strtolower(substr($locale, 3));
        }

        return $code;
    }

public static function country ( $ locale = 'default' ) { if ( $ locale == 'default' ) { $ locale = app ( ) -> getLocale ( ) ; } if ( config ( 'language.mode.code' , 'short' ) == 'short' ) { $ code = strtolower ( substr ( self :: getLongCode ( $ locale ) , 3 ) ) ; } else { $ code = strtolower ( substr ( $ locale , 3 ) ) ; } return $ code ; }

Get country code based on locale.

@param string $locale

@return mixed


public static function getCode($name = 'default')
    {
        if ($name == 'default') {
            $name = self::getName();
        }

        return self::codes([$name])[$name];
    }

public static function getCode ( $ name = 'default' ) { if ( $ name == 'default' ) { $ name = self :: getName ( ) ; } return self :: codes ( [ $ name ] ) [ $ name ] ; }

Returns the language code.

@param string $name

@return string


public static function getLongCode($short = 'default')
    {
        if ($short == 'default') {
            $short = app()->getLocale();
        }

        $long = 'en-GB';

        // Get languages from config
        $languages = config('language.all');

        foreach ($languages as $language) {
            if ($language['short'] != $short) {
                continue;
            }

            $long = $language['long'];
        }

        return $long;
    }

public
static
function
getLongCode
(
$
short
=
'default'
)
{
if
(
$
short
==
'default'
)
{
$
short
=
app
(
)
->
getLocale
(
)
;
}
$
long
=
'en-GB'
;
// Get languages from config
$
languages
=
config
(
'language.all'
)
;
foreach
(
$
languages
as
$
language
)
{
if
(
$
language
[
'short'
]
!=
$
short
)
{
continue
;
}
$
long
=
$
language
[
'long'
]
;
}
return
$
long
;
}

Returns the language long code.

@param string $short

@return string


public static function getName($code = 'default')
    {
        if ($code == 'default') {
            $code = app()->getLocale();
        }

        return self::names([$code])[$code];
    }

public static function getName ( $ code = 'default' ) { if ( $ code == 'default' ) { $ code = app ( ) -> getLocale ( ) ; } return self :: names ( [ $ code ] ) [ $ code ] ; }

Returns the language name.

@param string $code

@return string


private function setLocale($locale, $request)
    {
        // Check if is allowed and set default locale if not
        if (!language()->allowed($locale)) {
            $locale = config('app.locale');
        }

        if (Auth::check()) {
            Auth::user()->setAttribute('locale', $locale)->save();
        } else {
            $request->session()->put('locale', $locale);
        }
    }

Set locale if it's allowed.

@param string                   $locale
@param \Illuminate\Http\Request $request


public function home($locale, Request $request)
    {
        $this->setLocale($locale, $request);

        $url = config('language.url') ? url('/' . $locale) : url('/');

        return redirect($url);
    }

public function home ( $ locale , Request $ request ) { $ this -> setLocale ( $ locale , $ request ) ; $ url = config ( 'language.url' ) ? url ( '/' . $ locale ) : url ( '/' ) ; return redirect ( $ url ) ; }

Set locale and return home url.

@param string                   $locale
@param \Illuminate\Http\Request $request

@return string


public function back($locale, Request $request)
    {
        $this->setLocale($locale, $request);

        $session = $request->session();

        if (config('language.url')) {
            $previous_url = substr(str_replace(env('APP_URL'), '', $session->previousUrl()), 7);

            if (strlen($previous_url) == 3) {
                $previous_url = substr($previous_url, 3);
            } else {
                $previous_url = substr($previous_url, strrpos($previous_url, '/') + 1);
            }

            $url = rtrim(env('APP_URL'), '/') . '/' . $locale . '/' . ltrim($previous_url, '/');

            $session->setPreviousUrl($url);
        }

        return redirect($session->previousUrl());
    }

public function back ( $ locale , Request $ request ) { $ this -> setLocale ( $ locale , $ request ) ; $ session = $ request -> session ( ) ; if ( config ( 'language.url' ) ) { $ previous_url = substr ( str_replace ( env ( 'APP_URL' ) , '' , $ session -> previousUrl ( ) ) , 7 ) ; if ( strlen ( $ previous_url ) == 3 ) { $ previous_url = substr ( $ previous_url , 3 ) ; } else { $ previous_url = substr ( $ previous_url , strrpos ( $ previous_url , '/' ) + 1 ) ; } $ url = rtrim ( env ( 'APP_URL' ) , '/' ) . '/' . $ locale . '/' . ltrim ( $ previous_url , '/' ) ; $ session -> setPreviousUrl ( $ url ) ; } return redirect ( $ session -> previousUrl ( ) ) ; }

Set locale and return back.

@param string                   $locale
@param \Illuminate\Http\Request $request

@return string


private function setLocale($locale)
    {
        // Check if is allowed and set default locale if not
        if (!language()->allowed($locale)) {
            $locale = config('app.locale');
        }

        // Set app language
        \App::setLocale($locale);

        // Set carbon language
        if (config('language.carbon')) {
            // Carbon uses only language code
            if (config('language.mode.code') == 'long') {
                $locale = explode('-', $locale)[0];
            }

            \Carbon\Carbon::setLocale($locale);
        }

        // Set date language
        if (config('language.date')) {
            // Date uses only language code
            if (config('language.mode.code') == 'long') {
                $locale = explode('-', $locale)[0];
            }

            \Date::setLocale($locale);
        }
    }

This function checks if language to set is an allowed lang of config.

@param string $locale

This function checks if language to set is an allowed lang of config .


public function indexWhere($callable)
    {
        foreach ($this->elements as $i => $element) {
            if (call_user_func($callable, $element) === true) {
                return $i;
            }
        }

        return -1;
    }

public function indexWhere ( $ callable ) { foreach ( $ this -> elements as $ i => $ element ) { if ( call_user_func ( $ callable , $ element ) === true ) { return $ i ; } } return - 1 ; }

Finds the first index where the given callable returns true.

@param callable $callable

@return integer the index, or -1 if the predicate is not true for any element.

Finds the first index where the given callable returns true .


public function remove($index)
    {
        if ( ! isset($this->elements[$index])) {
            throw new OutOfBoundsException(sprintf('The index "%d" is not in the interval [0, %d).', $index, count($this->elements)));
        }

        $element = $this->elements[$index];
        unset($this->elements[$index]);
        $this->elements = array_values($this->elements);

        return $element;
    }

Removes the element at the given index, and returns it.

@param int $index

@return T

@throws \OutOfBoundsException If there is no element at the given index.

Removes the element at the given index and returns it .


public function takeWhile($callable)
    {
        $newElements = array();

        for ($i=0,$c=count($this->elements); $i<$c; $i++) {
            if (call_user_func($callable, $this->elements[$i]) !== true) {
                break;
            }

            $newElements[] = $this->elements[$i];
        }

        return $this->createNew($newElements);
    }

public function takeWhile ( $ callable ) { $ newElements = array ( ) ; for ( $ i = 0 , $ c = count ( $ this -> elements ) ; $ i < $ c ; $ i ++ ) { if ( call_user_func ( $ callable , $ this -> elements [ $ i ] ) !== true ) { break ; } $ newElements [ ] = $ this -> elements [ $ i ] ; } return $ this -> createNew ( $ newElements ) ; }

Extracts element from the head while the passed callable returns true.

@param callable $callable receives elements of this sequence as first argument, and returns true/false.

@return Sequence

Extracts element from the head while the passed callable returns true .


public function setAuth($username, $password)
    {
        $this->username = $username;
        $this->password = $password;
        $this->logger && $this->logger->debug("Set: the auth login");
        return $this;
    }

public
function
setAuth
(
$
username
,
$
password
)
{
$
this
->
username
=
$
username
;
$
this
->
password
=
$
password
;
$
this
->
logger
&&
$
this
->
logger
->
debug
(
"Set: the auth login"
)
;
return
$
this
;
}

auth login with server
@param string $username
@param string $password
@return $this


public function setOAuth($accessToken)
    {
        $this->oauthToken = $accessToken;
        $this->logger && $this->logger->debug("Set: the auth oauthbearer");
        return $this;
    }

public
function
setOAuth
(
$
accessToken
)
{
$
this
->
oauthToken
=
$
accessToken
;
$
this
->
logger
&&
$
this
->
logger
->
debug
(
"Set: the auth oauthbearer"
)
;
return
$
this
;
}

auth oauthbearer with server
@param string $accessToken
@return $this


public function send(Message $message)
    {
        $this->logger && $this->logger->debug('Set: a message will be sent');
        $this->message = $message;
        $this->connect()
            ->ehlo();

        if ($this->secure === 'tls' || $this->secure === 'tlsv1.0' || $this->secure === 'tlsv1.1' | $this->secure === 'tlsv1.2') {
            $this->starttls()
                ->ehlo();
        }

        if ($this->username !== null || $this->password !== null) {
            $this->authLogin();
        } elseif ($this->oauthToken !== null) {
            $this->authOAuthBearer();
        }
        $this->mailFrom()
            ->rcptTo()
            ->data()
            ->quit();
        return fclose($this->smtp);
    }

public
function
send
(
Message
$
message
)
{
$
this
->
logger
&&
$
this
->
logger
->
debug
(
'Set: a message will be sent'
)
;
$
this
->
message
=
$
message
;
$
this
->
connect
(
)
->
ehlo
(
)
;
if
(
$
this
->
secure
===
'tls'
||
$
this
->
secure
===
'tlsv1.0'
||
$
this
->
secure
===
'tlsv1.1'
|
$
this
->
secure
===
'tlsv1.2'
)
{
$
this
->
starttls
(
)
->
ehlo
(
)
;
}
if
(
$
this
->
username
!==
||
$
this
->
password
!==
)
{
$
this
->
authLogin
(
)
;
}
elseif
(
$
this
->
oauthToken
!==
)
{
$
this
->
authOAuthBearer
(
)
;
}
$
this
->
mailFrom
(
)
->
rcptTo
(
)
->
data
(
)
->
quit
(
)
;
return
fclose
(
$
this
->
smtp
)
;
}

Send the message

@param Message $message
@return bool
@throws CodeException
@throws CryptoException
@throws SMTPException


protected function connect()
    {
        $this->logger && $this->logger->debug("Connecting to {$this->host} at {$this->port}");
        $host = ($this->secure == 'ssl') ? 'ssl://' . $this->host : $this->host;
        $this->smtp = @fsockopen($host, $this->port);
        //set block mode
        //    stream_set_blocking($this->smtp, 1);
        if (!$this->smtp){
            throw new SMTPException("Could not open SMTP Port.");
        }
        $code = $this->getCode();
        if ($code !== '220'){
            throw new CodeException('220', $code, array_pop($this->resultStack));
        }
        return $this;
    }

//    stream_set_blocking($this->smtp, 1);

connect the server
SUCCESS 220
@return $this
@throws CodeException
@throws SMTPException


protected function starttls()
    {
        $in = "STARTTLS" . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '220'){
            throw new CodeException('220', $code, array_pop($this->resultStack));
        }

        if ($this->secure !== 'tls' && version_compare(phpversion(), '5.6.0', '<')) {
            throw new CryptoException('Crypto type expected PHP 5.6 or greater');
        }

        switch ($this->secure) {
            case 'tlsv1.0':
                $crypto_type = STREAM_CRYPTO_METHOD_TLSv1_0_CLIENT;
                break;
            case 'tlsv1.1':
                $crypto_type = STREAM_CRYPTO_METHOD_TLSv1_1_CLIENT;
                break;
            case 'tlsv1.2':
                $crypto_type = STREAM_CRYPTO_METHOD_TLSv1_2_CLIENT;
                break;
            default:
                $crypto_type = STREAM_CRYPTO_METHOD_TLS_CLIENT;
                break;
        }

        if(!\stream_socket_enable_crypto($this->smtp, true, $crypto_type)) {
            throw new CryptoException("Start TLS failed to enable crypto");
        }
        return $this;
    }

SMTP STARTTLS
SUCCESS 220
@return $this
@throws CodeException
@throws CryptoException
@throws SMTPException


protected function authLogin()
    {
        $in = "AUTH LOGIN" . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '334'){
            throw new CodeException('334', $code, array_pop($this->resultStack));
        }
        $in = base64_encode($this->username) . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '334'){
            throw new CodeException('334', $code, array_pop($this->resultStack));
        }
        $in = base64_encode($this->password) . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '235'){
            throw new CodeException('235', $code, array_pop($this->resultStack));
        }
        return $this;
    }

protected
function
authLogin
(
)
{
$
in
=
"AUTH LOGIN"
.
$
this
->
CRLF
;
$
code
=
$
this
->
pushStack
(
$
in
)
;
if
(
$
code
!==
'334'
)
{
throw
new
CodeException
(
'334'
,
$
code
,
array_pop
(
$
this
->
resultStack
)
)
;
}
$
in
=
base64_encode
(
$
this
->
username
)
.
$
this
->
CRLF
;
$
code
=
$
this
->
pushStack
(
$
in
)
;
if
(
$
code
!==
'334'
)
{
throw
new
CodeException
(
'334'
,
$
code
,
array_pop
(
$
this
->
resultStack
)
)
;
}
$
in
=
base64_encode
(
$
this
->
password
)
.
$
this
->
CRLF
;
$
code
=
$
this
->
pushStack
(
$
in
)
;
if
(
$
code
!==
'235'
)
{
throw
new
CodeException
(
'235'
,
$
code
,
array_pop
(
$
this
->
resultStack
)
)
;
}
return
$
this
;
}

SMTP AUTH LOGIN
SUCCESS 334
SUCCESS 334
SUCCESS 235
@return $this
@throws CodeException
@throws SMTPException


protected function authOAuthBearer()
    {
        $authStr = sprintf("n,a=%s,%shost=%s%sport=%s%sauth=Bearer %s%s%s",
            $this->message->getFromEmail(),
            chr(1),
            $this->host,
            chr(1),
            $this->port,
            chr(1),
            $this->oauthToken,
            chr(1),
            chr(1)
        );
        $authStr = base64_encode($authStr);
        $in = "AUTH OAUTHBEARER $authStr" . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '235'){
            throw new CodeException('235', $code, array_pop($this->resultStack));
        }
        return $this;
    }

SMTP AUTH OAUTHBEARER
SUCCESS 235
@return $this
@throws CodeException
@throws SMTPException


protected function authXOAuth2()
    {
        $authStr = sprintf("user=%s%sauth=Bearer %s%s%s",
            $this->message->getFromEmail(),
            chr(1),
            $this->oauthToken,
            chr(1),
            chr(1)
        );
        $authStr = base64_encode($authStr);
        $in = "AUTH XOAUTH2 $authStr" . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '235'){
            throw new CodeException('235', $code, array_pop($this->resultStack));
        }
        return $this;
    }

protected
function
authXOAuth2
(
)
{
$
authStr
=
sprintf
(
"user=%s%sauth=Bearer %s%s%s"
,
$
this
->
message
->
getFromEmail
(
)
,
chr
(
1
)
,
$
this
->
oauthToken
,
chr
(
1
)
,
chr
(
1
)
)
;
$
authStr
=
base64_encode
(
$
authStr
)
;
$
in
=
"AUTH XOAUTH2 $authStr"
.
$
this
->
CRLF
;
$
code
=
$
this
->
pushStack
(
$
in
)
;
if
(
$
code
!==
'235'
)
{
throw
new
CodeException
(
'235'
,
$
code
,
array_pop
(
$
this
->
resultStack
)
)
;
}
return
$
this
;
}

SMTP AUTH XOAUTH2
SUCCESS 235
@return $this
@throws CodeException
@throws SMTPException


protected function rcptTo()
    {
        $to = array_merge(
            $this->message->getTo(),
            $this->message->getCc(),
            $this->message->getBcc()
        );
        foreach ($to as $toEmail=>$_) {
            $in = "RCPT TO:<" . $toEmail . ">" . $this->CRLF;
            $code = $this->pushStack($in);
            if ($code !== '250') {
                throw new CodeException('250', $code, array_pop($this->resultStack));
            }
        }
        return $this;
    }

protected
function
rcptTo
(
)
{
$
to
=
array_merge
(
$
this
->
message
->
getTo
(
)
,
$
this
->
message
->
getCc
(
)
,
$
this
->
message
->
getBcc
(
)
)
;
foreach
(
$
to
as
$
toEmail
=>
$
_
)
{
$
in
=
"RCPT TO:<"
.
$
toEmail
.
">"
.
$
this
->
CRLF
;
$
code
=
$
this
->
pushStack
(
$
in
)
;
if
(
$
code
!==
'250'
)
{
throw
new
CodeException
(
'250'
,
$
code
,
array_pop
(
$
this
->
resultStack
)
)
;
}
}
return
$
this
;
}

SMTP RCPT TO
SUCCESS 250
@return $this
@throws CodeException
@throws SMTPException


protected function data()
    {
        $in = "DATA" . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '354') {
            throw new CodeException('354', $code, array_pop($this->resultStack));
        }
        $in = $this->message->toString();
        $code = $this->pushStack($in);
        if ($code !== '250'){
            throw new CodeException('250', $code, array_pop($this->resultStack));
        }
        return $this;
    }

protected function data ( ) { $ in = "DATA" . $ this -> CRLF ; $ code = $ this -> pushStack ( $ in ) ; if ( $ code !== '354' ) { throw new CodeException ( '354' , $ code , array_pop ( $ this -> resultStack ) ) ; } $ in = $ this -> message -> toString ( ) ; $ code = $ this -> pushStack ( $ in ) ; if ( $ code !== '250' ) { throw new CodeException ( '250' , $ code , array_pop ( $ this -> resultStack ) ) ; } return $ this ; }

SMTP DATA
SUCCESS 354
SUCCESS 250
@return $this
@throws CodeException
@throws SMTPException


protected function quit()
    {
        $in = "QUIT" . $this->CRLF;
        $code = $this->pushStack($in);
        if ($code !== '221'){
            throw new CodeException('221', $code, array_pop($this->resultStack));
        }
        return $this;
    }

protected function quit ( ) { $ in = "QUIT" . $ this -> CRLF ; $ code = $ this -> pushStack ( $ in ) ; if ( $ code !== '221' ) { throw new CodeException ( '221' , $ code , array_pop ( $ this -> resultStack ) ) ; } return $ this ; }

SMTP QUIT
SUCCESS 221
@return $this
@throws CodeException
@throws SMTPException


protected function getCode()
    {
        while ($str = fgets($this->smtp, 515)) {
            $this->logger && $this->logger->debug("Got: ". $str);
            $this->resultStack[] = $str;
            if(substr($str,3,1) == " ") {
                $code = substr($str,0,3);
                return $code;
            }
        }
        throw new SMTPException("SMTP Server did not respond with anything I recognized");
    }

get smtp response code
once time has three digital and a space
@return string
@throws SMTPException


public function setFrom($name, $email)
    {
        $this->fromName = $name;
        $this->fromEmail = $email;
        return $this;
    }

public function setFrom ( $ name , $ email ) { $ this -> fromName = $ name ; $ this -> fromEmail = $ email ; return $ this ; }

set mail from
@param string $name
@param string $email
@return $this


public function setFakeFrom($name, $email)
    {
        $this->fakeFromName = $name;
        $this->fakeFromEmail = $email;
        return $this;
    }

public function setFakeFrom ( $ name , $ email ) { $ this -> fakeFromName = $ name ; $ this -> fakeFromEmail = $ email ; return $ this ; }

set mail fake from
@param string $name
@param string $email
@return $this


public function findFile($class)
    {
        $file = wincache_ucache_get($this->prefix.$class, $success);

        if (!$success) {
            wincache_ucache_set($this->prefix.$class, $file = $this->decorated->findFile($class) ?: null, 0);
        }

        return $file;
    }

public function findFile ( $ class ) { $ file = wincache_ucache_get ( $ this -> prefix . $ class , $ success ) ; if ( ! $ success ) { wincache_ucache_set ( $ this -> prefix . $ class , $ file = $ this -> decorated -> findFile ( $ class ) ? : null , 0 ) ; } return $ file ; }

Finds a file by class name while caching lookups to WinCache.

@param string $class A class name to resolve to file

@return string|null

Finds a file by class name while caching lookups to WinCache .


public function findFile($class)
    {
        $file = apcu_fetch($this->prefix.$class, $success);

        if (!$success) {
            apcu_store($this->prefix.$class, $file = $this->decorated->findFile($class) ?: null);
        }

        return $file;
    }

public function findFile ( $ class ) { $ file = apcu_fetch ( $ this -> prefix . $ class , $ success ) ; if ( ! $ success ) { apcu_store ( $ this -> prefix . $ class , $ file = $ this -> decorated -> findFile ( $ class ) ? : null ) ; } return $ file ; }

Finds a file by class name while caching lookups to APC.

@param string $class A class name to resolve to file

@return string|null

Finds a file by class name while caching lookups to APC .