Prepare the data models based on the ngrest find query.

{@inheritDoc}

@see \yii\rest\IndexAction::prepareDataProvider()
197851
protected function prepareDataProvider()
    {
        $requestParams = Yii::$app->getRequest()->getBodyParams();
        if (empty($requestParams)) {
            $requestParams = Yii::$app->getRequest()->getQueryParams();
        }
        
        $filter = null;
        if ($this->dataFilter !== null) {
            $this->dataFilter = Yii::createObject($this->dataFilter);
            if ($this->dataFilter->load($requestParams)) {
                $filter = $this->dataFilter->build();
                if ($filter === false) {
                    return $this->dataFilter;
                }
            }
        }
        
        $query = call_user_func($this->prepareActiveDataQuery);
        if (!empty($filter)) {
            $query->andWhere($filter);
        }

        $dataProvider = Yii::createObject([
            'class' => ActiveDataProvider::class,
            'query' => $query,
            'pagination' => $this->controller->pagination,
            'sort' => [
                'attributes' => $this->controller->generateSortAttributes($this->controller->model->getNgRestConfig()),
                'params' => $requestParams,
            ],
        ]);

        if ($this->isCachable() && $this->controller->cacheDependency) {
            Yii::$app->db->cache(function () use ($dataProvider) {
                $dataProvider->prepare();
            }, 0, Yii::createObject($this->controller->cacheDependency));
        }

        return $dataProvider;
    }
66919
public function prepareWizardData()
    {
        $cacheKey = 'property-wizard' . md5(implode(':', $this->handlersList));
        $data = Yii::$app->cache->get($cacheKey);
        if (false === $data) {
            $query = (new Query())->from(PropertyHandlers::tableName())->indexBy('id')->select('class_name');
            if ((count($this->handlersList) != 0)) {
                $query->where(['class_name' => $this->handlersList]);
            }
            $handlers = $query->column();
            $storageToId = (new Query())->from(PropertyStorage::tableName())->indexBy('id')->select('class_name')->column();
            /**
             * @var AbstractPropertyHandler $className
             */
            foreach ($handlers as $id => $className) {
                $data[$id] = [
                    'id' => $id,
                    'allowedTypes' => $className::$allowedTypes,
                    'allowedStorage' => array_keys(array_intersect($storageToId, $className::$allowedStorage)),
                    'allowInSearch' => (bool)$className::$allowInSearch,
                    'multipleMode' => $className::$multipleMode
                ];
            }
            Yii::$app->cache->set(
                $cacheKey,
                $data,
                86400,
                new TagDependency(['tags' => [
                    NamingHelper::getCommonTag(PropertyHandlers::class),
                    NamingHelper::getCommonTag(PropertyStorage::class)
                ]])
            );
        }
        return $data;
    }
1042058
protected function prepareDataProvider($params = []) {
        if (!isset($params['q'])) {
            throw new Exception('Require parameter "q"!');
        }
        $data = [];
        $modelClass = $this->modelClass;
        $listMethod = $this->listMethod;
        if (!is_null($params['q'])) {
            $data['results'] = $modelClass::$listMethod($this->keyAttribute, $this->valueAttribute, "{$this->queryAttribute} like '%{$params['q']}%'", $params);
        } else {
            $data['results'] = $modelClass::$listMethod($this->keyAttribute, $this->valueAttribute, '', $params);
        }
        return $data;
    }
492040
public function prepare() {
        $sql = $this->getSql();
        $params = array_merge($this->whereParams(), $this->having_params);
        return [$sql, $params];
    }
67994
protected function prepare()
    {
        /** @var CollectionView $collection */
        $collection = $this->getComponent('collection_view');
        $collection->setData($this->getDataProvider());
        if ($collection->getDataInjector() === null) {
            $collection->setDataInjector($this->makeDataInjector());
        }
        $this->applyOperations();
        $this->hideSubmitButtonIfNotUsed();
    }
621810
protected function prepareDataProvider($params = []) {
        if (!isset($params['attr']))
            throw new Exception('Require parameter "attr"!');

        $prefix = is_null($this->controller->module) ? $this->controller->module->uniqueId : $this->controller->module->id;
        $prefix.= DIRECTORY_SEPARATOR . $params['attr'];
        $uploadPath = $this->uploadPath . DIRECTORY_SEPARATOR . $prefix;
        $uploadUrl = str_replace('\\', '/', $this->uploadUrl . '/' . $prefix);

        $data = [];
        if (@file_exists($uploadPath)) {
            $whiteExts = array_map(function($value) {
                return "*.{$value}";
            }, $this->whiteExts);
            $files = FileHelper::findFiles($uploadPath, ['only' => $whiteExts]);

            foreach ($files as $file) {
                $fileName = basename($file);
                $data[] = [
                    'title' => $fileName,
                    'thumb' => Url::to($uploadUrl . '/' . $fileName),
                    'image' => Url::to($uploadUrl . '/' . $fileName),
                ];
            }
        }
        return $data;
    }
1199701
public function prepare()
    {
        if ($this->_deleted) {
            throw new DataSift_Exception_InvalidData('Cannot prepare a deleted Historic.');
        }

        if ($this->_playback_id !== false) {
            throw new DataSift_Exception_InvalidData('This historic query has already been prepared.');
        }

        try {
            $res = $this->_user->post(
                'historics/prepare',
                array(
                    'hash' => $this->_hash,
                    'start' => $this->_start,
                    'end' => $this->_end,
                    'name' => $this->_name,
                    'sources' => implode(',', $this->_sources),
                    'sample' => $this->_sample,
                )
            );

            if (isset($res['id'])) {
                $this->_playback_id = $res['id'];
            } else {
                throw new DataSift_Exception_APIError('Prepared successfully but no playback ID in the response');
            }

            if (isset($res['dpus'])) {
                $this->_dpus = $res['dpus'];
            } else {
                throw new DataSift_Exception_APIError('Prepared successfully but no DPU cost in the response');
            }

            if (isset($res['availability'])) {
                $this->_availability = $res['availability'];
            } else {
                throw new DataSift_Exception_APIError('Prepared successfully but no availability in the response');
            }
        } catch (DataSift_Exception_APIError $e) {
            switch ($e->getCode()) {
                case 400:
                    // Missing or invalid parameters
                    throw new DataSift_Exception_InvalidData($e->getMessage());

                default:
                    throw new DataSift_Exception_APIError(
                        'Unexpected APIError code: ' . $e->getCode() . ' [' . $e->getMessage() . ']'
                    );
            }
        }
    }
546861
public function prepareDataSource(array $dataSource)
    {
        if (isset($dataSource['data']['items'])) {
            foreach ($dataSource['data']['items'] as & $item) {
                $name = $this->getData('name');

                if (isset($item['optimizer_id'])) {
                    $item[$name]['edit'] = [
                        'href'  => $this->urlBuilder->getUrl($this->editUrl, ['id' => $item['optimizer_id']]),
                        'label' => __('Edit'),
                    ];

                    $item[$name]['delete'] = [
                        'href'    => $this->urlBuilder->getUrl(self::OPTIMIZER_URL_PATH_DELETE, ['id' => $item['optimizer_id']]),
                        'label'   => __('Delete'),
                        'confirm' => [
                            'title'   => __('Delete ${ $.$data.name }'),
                            'message' => __('Are you sure you want to delete ${ $.$data.name } ?'),
                        ],
                    ];
                }
            }
        }

        return $dataSource;
    }
656064
protected function prepare()
    {
        $this
            ->getSession()
            ->getConnection()
            ->sendPrepareQuery(
                $this->getClientIdentifier(),
                $this->orderParameters($this->sql)
            );
        $this->is_prepared = true;

        return $this;
    }
786469
protected function prepareDataProvider($model)
    {
        $query = $this->getQuery($model);

        if ($model instanceof ActiveSearchInterface) {
            return $model->search($query);
        }

        return new ActiveDataProvider([
            'query' => $query,
            'pagination' => [],
        ]);
    }
1320636
private function _prepareColumns(): void
    {
        if (method_exists($this->_model, 'toFieldsAmiGrid')) {
            $lists = $this->_model->toFieldsAmiGrid();
        } else {
            $lists = \Schema::getColumnListing($this->_model->getTable());
        }
        if ($this->isVisibleColumn()) {
            $lists = array_diff($lists, $this->_model->getHidden());
        }
        foreach ($lists as $key => $list) {
            $this->column($list, $list)
                ->setDateActive(true)
                ->setSort(true);
        }
        $this->columnActions(function ($data) {
            $buttons = [];
            if ($this->_getConfig('routes')) {
                $pathNameForModel = strtolower(\Illuminate\Support\Str::plural(\Illuminate\Support\Str::camel(class_basename($data))));
                $buttons[] = $this->columnAction()
//                    ->setActionDelete('amigrid.delete', [$pathNameForModel, $data->id])
                    ->setUrl('/' . $pathNameForModel . '/delete')
                    ->setLabel('delete');
                $buttons[] = $this->columnAction()
//                    ->setActionShow('amigrid.show', [$pathNameForModel, $data->id])
                    ->setUrl('/' . $pathNameForModel)
                    ->setLabel('show')
//                    ->setHandler(function ($data) {
//                        return $data->id % 2;
//                    })
                ;
                $buttons[] = $this->columnAction()
//                    ->setActionEdit('amigrid.edit', [$pathNameForModel, $data->id])
                    ->setUrl('/' . $pathNameForModel . '/edit')
                    ->setLabel('edit');
            }

            return $buttons;
        });
        if ($this->_getConfig('routes')) {
            $pathNameForModel = strtolower(\Illuminate\Support\Str::plural(\Illuminate\Support\Str::camel(class_basename($this->_model))));
            $this->button()->setButtonCreate('/' . $pathNameForModel . '/create');
        }
    }
1025583
protected static function _prepare()
    {
        if (empty(static::$_module)) {
            $module = Module::getModuleByClassname(Module::className());
            if (!empty($module)) {
                static::$_sysControllerUid = "/sys/main";
                static::$_routeActionView = "/{$module->uniqueId}/main/view";
                static::$_routeActionShow = "/{$module->uniqueId}/main/show";
                static::$_model = $module::model(self::MODEL_ALIAS);
            }
        }
    }
109036
public function prepareListQuery()
    {
        /* @var $modelClass \yii\db\BaseActiveRecord */
        $modelClass = $this->modelClass;

        $find = $modelClass::ngRestFind();

        // check if a pool id is requested:
        $this->appendPoolWhereCondition($find);

        // add tags condition
        $tagIds = Yii::$app->request->get('tags');
        if ($tagIds) {
            $subQuery = clone $find;
            $inQuery = $subQuery->joinWith(['tags tags'])->andWhere(['tags.id' => array_unique(explode(",", $tagIds))])->select(['pk_id']);
            $find->andWhere(['in', $modelClass::primaryKey(), $inQuery]);
        }

        return $find->with($this->getWithRelation('list'));
    }
1098776
public function prepare(){
		$adapter = $this->_dbAdapter ?: Table::getDefaultDbAdapter();
	
		return $adapter->prepare($this->assemble());
	}
1030445
public function actionSearch($query = null)
    {
        $this->checkAccess('search');
        
        if (empty($query)) {
            $query = Yii::$app->request->post('query');
        }
        
        $find = $this->model->ngRestFullQuerySearch($query);
        
        return new ActiveDataProvider([
            'query' => $find->with($this->getWithRelation('search')),
            'pagination' => $this->pagination,
            'sort' => [
                'attributes' => $this->generateSortAttributes($this->model->getNgRestConfig()),
            ]
        ]);
    }
666977
protected function prepareModel()
    {
        if (!$this->model) {
            throw new MissingArgumentException('model property should be filled');
        }

        $this->model = new $this->model();

        $traits = class_uses_recursive(get_class($this->model));

        if (!isset($traits[Searchable::class])) {
            throw new InvalidArgumentException(get_class($this->model).' does not use the searchable trait');
        }
    }
1064282
public function prepare_item_for_database( $request ) {
		$prepared_term = new stdClass;

		$schema = $this->get_item_schema();
		if ( isset( $request['name'] ) && ! empty( $schema['properties']['name'] ) ) {
			$prepared_term->name = $request['name'];
		}

		if ( isset( $request['slug'] ) && ! empty( $schema['properties']['slug'] ) ) {
			$prepared_term->slug = $request['slug'];
		}

		if ( isset( $request['taxonomy'] ) && ! empty( $schema['properties']['taxonomy'] ) ) {
			$prepared_term->taxonomy = $request['taxonomy'];
		}

		if ( isset( $request['description'] ) && ! empty( $schema['properties']['description'] ) ) {
			$prepared_term->description = $request['description'];
		}

		if ( isset( $request['parent'] ) && ! empty( $schema['properties']['parent'] ) ) {
			$parent_term_id = 0;
			$parent_term = get_term( (int) $request['parent'], $this->taxonomy );

			if ( $parent_term ) {
				$parent_term_id = $parent_term->term_id;
			}

			$prepared_term->parent = $parent_term_id;
		}

		/**
		 * Filters term data before inserting term via the REST API.
		 *
		 * @param object          $prepared_term Term object.
		 * @param WP_REST_Request $request       Request object.
		 */
		return apply_filters( "rest_pre_insert_{$this->taxonomy}", $prepared_term, $request );
	}