Prepares builder object before calling get method on it

@throws CollectionException
173858
private function _prepareBuilder()
    {
        $builder = $this->_builder;
        $params = Input::get();

        /*
         * START filters
         */
        if ($this->renderFilterForm()) {
            foreach ($this->_columns as $columnData) {
                $column = new Column($columnData);
                if (!$column->searchable()) {
                    // Not a searchable column - skip it
                    continue;
                }

                if (!isset($params['resource_table_'.$column->index()])) {
                    // Searched string not found in GET query
                    continue;
                }

                $value = $params['resource_table_'.$column->index()];
                if (!$value || !is_string($value)) {
                    // Skip empty values
                    continue;
                }

                $value = $this->_prepareFilterValue($columnData, $value);
                switch ($column->searchType()) {

                    // Use simple WHERE = 'value' for selects
                    case 'select':
                        if (ResourceTable::ALL_SELECT_VALUES_KEY == $value) {
                            // Any value in select - skip it
                            continue;
                        }
                        $builder = $this->_addQueryCondition($builder, $column->queryConditionType(), $column->getDatabaseName(), '=', $value);
                        break;

                    // Use LIKE '%value%' for strings
                    case 'string':
                    default:
                        $builder = $this->_addQueryCondition($builder, $column->queryConditionType(), $column->getDatabaseName(), 'LIKE', '%'.$value.'%');
                        break;
                }
            }
        }
        /*
         * END filters
         */

        /*
         * START pagination
         */
        if ($this->_paginate) {
            if (isset($params['per_page']) && is_numeric($params['per_page']) && $params['per_page'] > 0) {
                // Get per_page from GET
                $this->_perPage = (int)$params['per_page'];
            }

            if (isset($params['page']) && is_numeric($params['page']) && $params['page'] > 1) {
                // Get page from GET
                $this->_page = (int)$params['page'];
            }
            $toSkip = ($this->_page * $this->_perPage) - $this->_perPage;

            // A the end set pagination
            $this->_totalItems = $this->_getCountForPagination($builder);
            $builder = $builder->skip($toSkip)->take($this->_perPage);
        }
        /*
         * END pagination
         */

        /*
         * START sort
         */
        if ($this->_validSort($params)) {
            // If sort configuration is valid then set it
            $this->sort($params['order_by'], strtoupper($params['order_dir']));
        }

        // Set sort configuration
        $sort = $this->getSort();
        if ($sort['index'] && $sort['dir']) {
            $builder = $builder->orderBy($sort['index'], $sort['dir']);
        }
        /*
         * END sort
         */

        $this->_builder = $builder;
    }
1193376
public function beforeCompile()
	{
		$builder = $this->getContainerBuilder();

		if (!$builder->getByType(Application::class)) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', Application::class));
		}

		if (!$builder->getByType(EventDispatcher::class)) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', EventDispatcher::class));
		}

		$application = $builder->getDefinition($builder->getByType(Application::class));
		$dispatcher = $builder->getDefinition($builder->getByType(EventDispatcher::class));

		$application->addSetup('?->onStartup[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_STARTUP,
			new PhpLiteral(StartupEvent::class),
		]);
		$application->addSetup('?->onError[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_ERROR,
			new PhpLiteral(ErrorEvent::class),
		]);
		$application->addSetup('?->onPresenter[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER,
			new PhpLiteral(PresenterEvent::class),
		]);
		$application->addSetup('?->onRequest[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_REQUEST,
			new PhpLiteral(RequestEvent::class),
		]);
		$application->addSetup('?->onResponse[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_RESPONSE,
			new PhpLiteral(ResponseEvent::class),
		]);
		$application->addSetup('?->onShutdown[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_SHUTDOWN,
			new PhpLiteral(ShutdownEvent::class),
		]);
	}
346589
protected function prepareData()
    {
        if ($this->prepared) {
            return;
        }

        $this->presences         = new Collection;
        $this->modulePresences   = new Collection;
        $this->permissions       = [];
        $this->modulePermissions = [];

        $this->loadAclModules()
             ->collapsePermissions();

        $this->prepared = true;
    }
1246468
public ClassFileBuilder prepare() throws SupportException {
        if (mPrimaryKey == null) {
            throw new IllegalStateException("Primary key not defined");
        }

        // Clear the cached result, if any
        mStorableClass = null;

        mClassFileGenerator = new StorableClassFileBuilder(
             mClassNameProvider,
             mLoader,
             SyntheticStorableBuilder.class,
             mEvolvable);
        ClassFile cf = mClassFileGenerator.getClassFile();

        for (SyntheticProperty prop : mPropertyList) {
            definePropertyBeanMethods(cf, prop);
        }

        definePrimaryKey(cf);
        defineAlternateKeys(cf);
        defineIndexes(cf);

        return mClassFileGenerator;
    }
510670
public function initialize()
    {
        if (!$this->isInitialized()) {
            $this->getOriginalNodeNames();
            $fetchDepth = $this->fetchDepth > 0 ? $this->fetchDepth + 1 : -1;
            $childNodes = $this->getNode($fetchDepth)->getNodes($this->filter);
            $this->collection = new ArrayCollection($this->getChildren($childNodes));
            $this->initialized = self::INITIALIZED_FROM_PHPCR;
        }
    }
7359
protected function collectionLoader()
    {
        if ($this->collectionLoader === null) {
            throw new RuntimeException(sprintf(
                'Collection Loader is not defined for "%s"',
                get_class($this)
            ));
        }

        return $this->collectionLoader;
    }
1236033
public function make()
    {
        if (empty($this->_columns)) {
            throw new CollectionException('At least one column is required to generate a resource table.');
        }

        // Prepare builder object before calling Table
        $this->_prepareBuilder();

        // Finally execute prepared query builder
        $items = $this->_builder->get();

        return with(new Table($items, [
            'collection_generator' => $this,
            'columns'              => $this->_columns,
            'per_page'             => $this->_perPage,
            'paginate'             => $this->_paginate,
            'paginator_presenter'  => $this->_getPaginatorPresenter($items),
            'view_name'            => $this->_viewName,
            'filter'               => $this->_filter,
            'extra'                => $this->_extraViewData,
        ]))->make();
    }
1029847
protected function updateCollection(){
        $responseBody = $this->Response->getBody();
        if (is_array($responseBody)){
            if (isset($this->model)){
                $modelIdKey = $this->buildModel()->modelIdKey();
                foreach($responseBody as $key => $model){
                    if (isset($model[$modelIdKey])){
                        $this->collection[$model[$modelIdKey]] = $model;
                    } else {
                        $this->collection[] = $model;
                    }
                }
            } else {
                $this->collection = $responseBody;
            }
        }
    }
1182251
protected function _prepareCollection()
    {
        parent::_prepareCollection();
        $collection = $this->getCollection();
        $turpentineEnabled = false;
        $fullPageEnabled = false;
        foreach ($collection as $key=>$item) {
            if ($item->getStatus() == 1 && ($item->getId() == 'turpentine_pages' || $item->getId() == 'turpentine_esi_blocks')) {
                $turpentineEnabled = true;
            }
            if ($item->getStatus() == 1 && $item->getId() == 'full_page') {
                $fullPageEnabled = true;
            }
        }
        if ($turpentineEnabled  && !$fullPageEnabled) {
            $collection->removeItemByKey('full_page');
        }
        if ($fullPageEnabled && !$turpentineEnabled) {
            $collection->removeItemByKey('turpentine_pages');
            $collection->removeItemByKey('turpentine_esi_blocks');
        }
        $this->setCollection($collection);
        return $this;
    }
614250
public function collectionLoaderFactory()
    {
        if (!isset($this->collectionLoaderFactory)) {
            throw new RuntimeException(sprintf(
                'Collection Loader Factory is not defined for [%s]',
                get_class($this)
            ));
        }

        return $this->collectionLoaderFactory;
    }
944558
public function beforeCompile(): void
	{
		$builder = $this->getContainerBuilder();

		if ($builder->getByType(Application::class) === null) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', Application::class));
		}

		if ($builder->getByType(EventDispatcherInterface::class) === null) {
			throw new LogicException(sprintf('Service of type "%s" is needed. Please register it.', EventDispatcherInterface::class));
		}

		$dispatcher = $builder->getDefinition($builder->getByType(EventDispatcherInterface::class));

		$application = $builder->getDefinition($builder->getByType(Application::class));

		$application->addSetup('?->onStartup[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_STARTUP,
			new PhpLiteral(StartupEvent::class),
		]);

		$application->addSetup('?->onError[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_ERROR,
			new PhpLiteral(ErrorEvent::class),
		]);

		$application->addSetup('?->onPresenter[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER,
			new PhpLiteral(PresenterEvent::class),
		]);

		$application->addSetup('?->onPresenter[] = function($application, $presenter) {if(!property_exists($presenter, "onStartup")){return;} $presenter->onStartup[] = function() {?->dispatch(?, new ?(...func_get_args()));};}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER_STARTUP,
			new PhpLiteral(PresenterStartupEvent::class),
		]);

		$application->addSetup('?->onPresenter[] = function($application, $presenter) {if(!property_exists($presenter, "onShutdown")){return;} $presenter->onShutdown[] = function() {?->dispatch(?, new ?(...func_get_args()));};}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_PRESENTER_SHUTDOWN,
			new PhpLiteral(PresenterShutdownEvent::class),
		]);

		$application->addSetup('?->onRequest[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_REQUEST,
			new PhpLiteral(RequestEvent::class),
		]);

		$application->addSetup('?->onResponse[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_RESPONSE,
			new PhpLiteral(ResponseEvent::class),
		]);

		$application->addSetup('?->onShutdown[] = function() {?->dispatch(?, new ?(...func_get_args()));}', [
			'@self',
			$dispatcher,
			ApplicationEvents::ON_SHUTDOWN,
			new PhpLiteral(ShutdownEvent::class),
		]);
	}
309702
protected function prepareCollectionItem(array &$collection_item)
    {
        $item = $this->collection_item->getItem(array(
            'collection_item_id' => $collection_item['collection_item_id']));

        $collection_item['title'] = isset($item['title']) ? $item['title'] : '';
    }
308893
public function prepareQuery()
    {
        $query = $this->model->newQuery();
        $primaryTable = $this->model->getTable();
        $selects = [$primaryTable.'.*'];
        $joins = [];
        $withs = [];

        /**
         * @event backend.list.extendQueryBefore
         * Provides an opportunity to modify the `$query` object before the List widget applies its scopes to it.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQueryBefore', function($listWidget, $query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQueryBefore', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        $this->fireSystemEvent('backend.list.extendQueryBefore', [$query]);

        /*
         * Prepare searchable column names
         */
        $primarySearchable = [];
        $relationSearchable = [];

        $columnsToSearch = [];
        if (!empty($this->searchTerm) && ($searchableColumns = $this->getSearchableColumns())) {
            foreach ($searchableColumns as $column) {
                /*
                 * Related
                 */
                if ($this->isColumnRelated($column)) {
                    $table = $this->model->makeRelation($column->relation)->getTable();
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $table))
                        : $table . '.' . $column->valueFrom;

                    $relationSearchable[$column->relation][] = $columnName;
                }
                /*
                 * Primary
                 */
                else {
                    $columnName = isset($column->sqlSelect)
                        ? DbDongle::raw($this->parseTableName($column->sqlSelect, $primaryTable))
                        : DbDongle::cast(Db::getTablePrefix() . $primaryTable . '.' . $column->columnName, 'TEXT');

                    $primarySearchable[] = $columnName;
                }
            }
        }

        /*
         * Prepare related eager loads (withs) and custom selects (joins)
         */
        foreach ($this->getVisibleColumns() as $column) {

            // If useRelationCount is enabled, eager load the count of the relation into $relation_count
            if ($column->relation && @$column->config['useRelationCount']) {
                $query->withCount($column->relation);
            }

            if (!$this->isColumnRelated($column) || (!isset($column->sqlSelect) && !isset($column->valueFrom))) {
                continue;
            }

            if (isset($column->valueFrom)) {
                $withs[] = $column->relation;
            }

            $joins[] = $column->relation;
        }

        /*
         * Add eager loads to the query
         */
        if ($withs) {
            $query->with(array_unique($withs));
        }

        /*
         * Apply search term
         */
        $query->where(function ($innerQuery) use ($primarySearchable, $relationSearchable, $joins) {

            /*
             * Search primary columns
             */
            if (count($primarySearchable) > 0) {
                $this->applySearchToQuery($innerQuery, $primarySearchable, 'or');
            }

            /*
             * Search relation columns
             */
            if ($joins) {
                foreach (array_unique($joins) as $join) {
                    /*
                     * Apply a supplied search term for relation columns and
                     * constrain the query only if there is something to search for
                     */
                    $columnsToSearch = array_get($relationSearchable, $join, []);

                    if (count($columnsToSearch) > 0) {
                        $innerQuery->orWhereHas($join, function ($_query) use ($columnsToSearch) {
                            $this->applySearchToQuery($_query, $columnsToSearch);
                        });
                    }
                }
            }

        });

        /*
         * Custom select queries
         */
        foreach ($this->getVisibleColumns() as $column) {
            if (!isset($column->sqlSelect)) {
                continue;
            }

            $alias = $query->getQuery()->getGrammar()->wrap($column->columnName);

            /*
             * Relation column
             */
            if (isset($column->relation)) {

                // @todo Find a way...
                $relationType = $this->model->getRelationType($column->relation);
                if ($relationType == 'morphTo') {
                    throw new ApplicationException('The relationship morphTo is not supported for list columns.');
                }

                $table =  $this->model->makeRelation($column->relation)->getTable();
                $sqlSelect = $this->parseTableName($column->sqlSelect, $table);

                /*
                 * Manipulate a count query for the sub query
                 */
                $relationObj = $this->model->{$column->relation}();
                $countQuery = $relationObj->getRelationExistenceQuery($relationObj->getRelated()->newQueryWithoutScopes(), $query);

                $joinSql = $this->isColumnRelated($column, true)
                    ? DbDongle::raw("group_concat(" . $sqlSelect . " separator ', ')")
                    : DbDongle::raw($sqlSelect);

                $joinSql = $countQuery->select($joinSql)->toSql();

                $selects[] = Db::raw("(".$joinSql.") as ".$alias);
            }
            /*
             * Primary column
             */
            else {
                $sqlSelect = $this->parseTableName($column->sqlSelect, $primaryTable);
                $selects[] = DbDongle::raw($sqlSelect . ' as '. $alias);
            }
        }

        /*
         * Apply sorting
         */
        if (($sortColumn = $this->getSortColumn()) && !$this->showTree) {
            if (($column = array_get($this->allColumns, $sortColumn)) && $column->valueFrom) {
                $sortColumn = $this->isColumnPivot($column)
                    ? 'pivot_' . $column->valueFrom
                    : $column->valueFrom;
            }

            // Set the sorting column to $relation_count if useRelationCount enabled
            if (isset($column->relation) && @$column->config['useRelationCount']) {
                $sortColumn = $column->relation . '_count';
            }

            $query->orderBy($sortColumn, $this->sortDirection);
        }

        /*
         * Apply filters
         */
        foreach ($this->filterCallbacks as $callback) {
            $callback($query);
        }

        /*
         * Add custom selects
         */
        $query->addSelect($selects);

        /**
         * @event backend.list.extendQuery
         * Provides an opportunity to modify and / or return the `$query` object after the List widget has applied its scopes to it and before it's used to get the records.
         *
         * Example usage:
         *
         *     Event::listen('backend.list.extendQuery', function($listWidget, $query) {
         *         $newQuery = MyModel::newQuery();
         *         return $newQuery;
         *     });
         *
         * Or
         *
         *     $listWidget->bindEvent('list.extendQuery', function ($query) {
         *         $query->whereNull('deleted_at');
         *     });
         *
         */
        if ($event = $this->fireSystemEvent('backend.list.extendQuery', [$query])) {
            return $event;
        }

        return $query;
    }
1033620
public function build(): GetHeapObjectIdRequest
	{
		$instance = new GetHeapObjectIdRequest();
		if ($this->objectId === null) {
			throw new BuilderException('Property [objectId] is required.');
		}
		$instance->objectId = $this->objectId;
		return $instance;
	}
834832
protected function _prepareCollection()
    {

        /** @var Adyen_Payment_Model_Resource_Billing_Agreement_Collection $collection */
        $collection = Mage::getResourceModel('adyen/billing_agreement_collection')
            ->addCustomerDetails();
        $collection->addNameToSelect();
        $this->setCollection($collection);

        call_user_func(array(get_parent_class(get_parent_class($this)), __FUNCTION__));
        return $this;
    }
770474
protected function prepare()
        {
            if (!Core::getDBlink() instanceof \PDO) {
                throw new Exception('Connection not up, can\'t prepare the statement');
            }

            $this->statement = Core::getDBlink()->prepare($this->query->getSql());
        }
923926
public function initializeObject()
    {
        /** @var $querySettings \TYPO3\CMS\Extbase\Persistence\Generic\Typo3QuerySettings */
        $querySettings = $this->objectManager->get('TYPO3\\CMS\\Extbase\\Persistence\\Generic\\Typo3QuerySettings');
        $querySettings->setRespectStoragePage(false);
        $this->setDefaultQuerySettings($querySettings);
        $this->backendLayoutView = GeneralUtility::makeInstance(\MASK\Mask\Backend\BackendLayoutView::class);
    }