Prepare conditions to search in record

@param  string $unparsed
@return array
496776
protected function prepareSearch(array $unparsed, bool $isSearch = false, $hasSubquery = false): array
    {
        $statement = [
            'conditions' => "1 = 1",
            'bind' => [],
        ];

        if ($isSearch) {
            $mapped = $this->parseSearchParameters($unparsed['params']);
            $conditions = '1 = 1';

            $tmpMapped = $mapped;

            foreach ($tmpMapped as $key => $value) {
                if (strpos($value, '~') !== false) {
                    unset($tmpMapped[$key]);
                    $betweenMap[$key] = explode('~', $value);
                }
            }

            $keys = array_keys($tmpMapped);
            $values = array_values($tmpMapped);

            $di = Di::getDefault();

            foreach ($keys as $key => $field) {
                if ($di->get('config')->database->adapter == 'Postgresql') {
	       	           $conditions .= " AND CAST({$field} AS TEXT) LIKE ?{$key}";
    	    	}
    	        else {
    	    	    $conditions .= " AND {$field} LIKE ?{$key}";
    	    	}
            }

            if (isset($betweenMap)) {
                foreach ($betweenMap as $key => $fields) {
                    $binds = count($values);
                    $conditions .= ' AND ' . $key . ' BETWEEN ?' . $binds . ' AND ?' . ($binds + 1);
                    $values = array_merge($values, $fields);
                }
            }

            if ($hasSubquery) {
                $subquery = $this->parseSubquery($unparsed['subquery']);
                $conditions .= ' AND ' . $subquery['firstField'] . ' ' . $subquery['action'] . ' (select ' . $subquery['secondField'] . ' FROM ' . $subquery['model'] . ')';
            }

            $statement = [
                'conditions' => $conditions,
                'bind' => $values,
            ];
        }

        return $statement;
    }
267479
public function load($parse = true)
    {
        $result = trim(shell_exec('cat /proc/loadavg'));
        
        if (!$parse) {
            return $result;
        }
        
        // break into parts
        $parts = explode(' ', $result);
        
        // current/total processes
        $procs = explode('/', isset($parts[3]) ? trim($parts[3]) : '0/0');

        return [
            '1m'        => isset($parts[0]) ? number_format(trim($parts[0]), 2) : '0.00',
            '5m'        => isset($parts[1]) ? number_format(trim($parts[1]), 2) : '0.00',
            '15m'       => isset($parts[2]) ? number_format(trim($parts[2]), 2) : '0.00',
            'curr_proc' => $procs[0],
            'totl_proc' => $procs[1],
            'last_pid'  => isset($parts[4]) ? trim($parts[4]) : 0
        ];
    }
363949
public function search($params)
    {
        $query = Attachment::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'size' => $this->size,
            'created_at' => $this->created_at,
        ]);

        $query->andFilterWhere(['like', 'filename', $this->filename])
            ->andFilterWhere(['like', 'original_name', $this->original_name])
            ->andFilterWhere(['like', 'type', $this->type])
            ->andFilterWhere(['like', 'path', $this->path])
            ->andFilterWhere(['like', 'ip', $this->ip]);

        return $dataProvider;
    }
475292
protected function getAllRecordsMatchingQueryConditions(ReadQuery $query)
    {
        $records = [];
        foreach ($this->getIterator($query->getCollection()) as $record) {
            $records[] = $record;
        }

        if (!$query->getConditions()) {
            return $records;
        }

        foreach ($records as $key => $record) {
            if (!$this->recordMatchesQuery($record, $query)) {
                unset($records[$key]);
            }
        }

        return $records;
    }
1191965
protected function prepareCondition(array $args = []): string
    {
        $condition = array_shift($args);
        foreach ($args as &$value) {
            if (\is_array($value)) {
                $replace = implode(',', array_fill(0, \count($value), ':REPLACE:'));
                $condition = preg_replace('/\?/', $replace, $condition, 1);
                foreach ($value as $part) {
                    $this->setParam(null, $part);
                }
            } else {
                $this->setParam(null, $value);
            }
        }
        unset($value);

        $condition = preg_replace('/(\:REPLACE\:)/', '?', $condition);

        return $condition;
    }
136559
protected function parse(string $urlencoded): array
    {
        $specifics = [];
        foreach (new URLSearchParams($urlencoded) as $name => $value) {
            $specifics[$name][] = $value;
        }
        return $specifics;
    }
23833
public static function preprocess($url_parsed) {
        $url = URL::build($url_parsed);
        if (preg_match('/^[\w\/]*\/index.html$/', $url_parsed['path']) == 1) {
            parse_str($url_parsed['query'], $args);
            if (isset($args['s']) && isset($args['i'])) {
                return array(
                    'url' => $url,
                );
            }
        }
        return FALSE;
    }
122317
public function findAll($conditions = false)
    {
        $this->isColl = true;
        $data = $this->fetchAll($conditions);

        $records = array();
        foreach ($data as $key => $row) {
            /** @var $records Record[] */
            $records[$key] = $this->db->init($this->table, $row, false);
            $records[$key]->triggerCallback('afterFind');
        }

        $this->data = $records;
        return $this;
    }
34078
public function search($params)
    {
        $query = Supplier::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'birth_date' => $this->birth_date,
            'date_join' => $this->date_join,
            'date_left' => $this->date_left,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
            'created_by' => $this->created_by,
            'updated_by' => $this->updated_by,
        ]);

        $query->andFilterWhere(['like', 'avatar', $this->avatar])
            ->andFilterWhere(['like', 'name', $this->name])
            ->andFilterWhere(['like', 'phone', $this->phone])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'website', $this->website])
            ->andFilterWhere(['like', 'gender', $this->gender])
            ->andFilterWhere(['like', 'relationship_status', $this->relationship_status])
            ->andFilterWhere(['like', 'vat_number', $this->vat_number])
            ->andFilterWhere(['like', 'language', $this->language])
            ->andFilterWhere(['like', 'address', $this->address])
            ->andFilterWhere(['like', 'country', $this->country])
            ->andFilterWhere(['like', 'city', $this->city])
            ->andFilterWhere(['like', 'state', $this->state])
            ->andFilterWhere(['like', 'zip_code', $this->zip_code])
            ->andFilterWhere(['like', 'status', $this->status])
            ->andFilterWhere(['like', 'type', $this->type])
            ->andFilterWhere(['like', 'currency', $this->currency]);

        return $dataProvider;
    }
236586
private function prepareCondition($q)
    {
        $condition = [];
        foreach ($this->searchFields as $field) {
            $condition[] = ['like', $field, $q];
        }
        if (count($this->searchFields) > 1) {
            array_unshift($condition, 'or');
        }
        return $condition;
    }
1201522
protected function parseWhere(){
		$conds = $this->stmt->getConditions();

		// Unset glue on last condition
		unset($conds[count($conds)-1]['glue']);

		$conditions = array();
		foreach($conds as $cond){

			// Conditions with modifiers
			if($cond['simple'] === false){
				$values = $this->escapeValue($cond['values'], $cond['types']);
				$s = '(' . $this->applyModifiers($cond['expr'], $cond['modifiers'], $values) . ')';
				if(isset($cond['glue']))
					$s .= ' ' . $cond['glue'];

				$conditions[] = $s;
				continue;
			}

			// Simple conditions
			$field = $this->parseFieldName($cond['field']);
			$operator = '';
			$value = $cond['value'];
			if($value === null){ // field IS NULL
				$value = ' IS NULL';
			} elseif($value === true){	// field
				$value = '';
			} elseif($value === false){ // NOT field
				$value = $field;
				$field = 'NOT ';
			} elseif($value instanceof Result){
				$operator = ' IN ';
				$value = $this->escapeValue($value, Manager::SUBQUERY);
			} elseif(is_array($value) || $value instanceof Traversable){ // field IN (array)
				$value = ' IN ' . $this->escapeValue($value, Manager::ARR);
			} elseif($value instanceof Literal){ // field = SQL literal
				$operator = ' = ';
				$value = $this->escapeValue($value, Manager::LITERAL);
			} elseif($value instanceof DateTime){ // field = DateTime
				$operator = ' = ';
				$value = $this->escapeValue($value, Manager::DATETIME);
			} else{ // field = value
				$operator = ' = ';
				$value = $this->escapeValue($value);
			}
			$s = '(' . $field . $operator . $value . ')';
			if(isset($cond['glue']))
				$s .= ' '.$cond['glue'];

			$conditions[] = $s;

		}

		return "\nWHERE " . implode(' ', $conditions);
	}
581778
public function search($params)
    {
        $query = Category::find()->joinWith('translations')->orderBy(['parent_id' => SORT_ASC, 'position' => SORT_ASC]);

        $this->load($params);

        // grid filtering conditions
        $query->andFilterWhere([
            'shop_category.parent_id' => $this->parent_id,
        ])->andFilterWhere(['like', 'shop_category_translation.title', $this->title
        ])->andFilterWhere(['shop_category.show' => $this->show]);


        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);


        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        return $dataProvider;
    }
503122
public function search($params)
    {
        $query = Banword::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
        ]);
        $query->andFilterWhere(['like', 'word', $this->word]);

        if ($this->created_at) {
            $createdAt = strtotime($this->created_at);
            $createdAtEnd = $createdAt + 24 * 3600;
            $query->andWhere(['between', 'created_at', $createdAt, $createdAtEnd]);
            // $query->andWhere("created_at >= {$createdAt} AND created_at <= {$createdAtEnd}");
        }

        return $dataProvider;
    }
561988
public function search($params)
    {
        $query = Comment::find();

        // add conditions that should always apply here

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'created_at' => SORT_DESC,
                    'id' => SORT_ASC,
                ]
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'model_id' => $this->model_id,
            //'model_class' => $this->model_class,
            'parent' => $this->parent,
            'status' => $this->status,
        ]);

        if ($this->created_at !== null) {
            $date = strtotime($this->created_at);
            $query->andWhere(['between', 'created_at', $date, $date + 3600 * 24]);
        }

        $query->andFilterWhere(['like', 'content', $this->content]);

        return $dataProvider;
    }
1182546
protected function prepareCustomSearch($hasSubquery = false): array
    {
        $metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
        $classReflection = (new \ReflectionClass($this->model));
        $classname = $this->model->getSource();

        $primaryKey = null;

        if ($primaryKey = $metaData->getPrimaryKeyAttributes($this->model)) {
            $primaryKey = $primaryKey[0];
        }

        $customClassname = $classname . '_custom_fields';
        $bindParamsKeys = [];
        $bindParamsValues = [];

        $sql = '';

        if (!empty($this->relationSearchFields)) {
            foreach ($this->relationSearchFields as $model => $searchFields) {
                $modelObject = new $model();
                $model = $modelObject->getSource();

                $relatedKey = $metaData->getPrimaryKeyAttributes($modelObject)[0];
                $relation = $this->model->getModelsManager()->getRelationsBetween(get_class($this->model), get_class($modelObject));

                $relationKey = $primaryKey;
                $referenceKey = $primaryKey;
                
                if (isset($relation) && $relation && count($relation)) {
                    $relationKey =  $relation[0]->getFields();
                    $referenceKey =  $relation[0]->getReferencedFields();
                }

                $sql .= " INNER JOIN {$model} ON {$model}.{$relatedKey} = (";
                $sql .= "SELECT {$model}.{$relatedKey} FROM {$model} WHERE {$model}.{$referenceKey} = {$classname}.{$relationKey}";

                foreach ($searchFields as $fKey => $searchFieldValues) {
                    if (is_array(current($searchFieldValues))) {
                        foreach ($searchFieldValues as $csKey => $chainSearch) {
                            $sql .= !$csKey ? ' (' : '';
                            $sql .= $this->prepareRelatedSql($chainSearch, $model, 'OR', $fKey);
                            $sql .= ($csKey == count($searchFieldValues) - 1) ? ') ' : '';
                        }
                    } else {
                        $sql .= $this->prepareRelatedSql($searchFieldValues, $model, 'AND', $fKey);
                    }
                }

                $sql .= ' LIMIT 1)';
            }

            unset($modelObject);
        }

        // create custom query sql
        if (!empty($this->customSearchFields)) {
            $modules = Modules::findFirstByName($classReflection->getShortName());

            $sql .= ' INNER JOIN ' . $customClassname . ' ON ' . $customClassname . '.id = (';
            $sql .= 'SELECT ' . $customClassname . '.id FROM ' . $customClassname . ' WHERE ' . $customClassname . '.' . $classname . '_id = ' . $classname . '.id';

            foreach ($this->customSearchFields as $fKey => $searchFieldValues) {
                if (is_array(current($searchFieldValues))) {
                    foreach ($searchFieldValues as $csKey => $chainSearch) {
                        $sql .= !$csKey ? ' (' : '';
                        $sql .= $this->prepareCustomSql($chainSearch, $modules, $customClassname, 'OR', $fKey);
                        $sql .= ($csKey == count($searchFieldValues) - 1) ? ') ' : '';
                    }
                } else {
                    $sql .= $this->prepareCustomSql($searchFieldValues, $modules, $customClassname, 'AND', $fKey);
                }
            }

            $sql .= ' LIMIT 1)';
        }

        $sql .= ' WHERE';

        // create normal sql search
        if (!empty($this->normalSearchFields)) {
            foreach ($this->normalSearchFields as $fKey => $searchFieldValues) {
                if (is_array(current($searchFieldValues))) {
                    foreach ($searchFieldValues as $csKey => $chainSearch) {
                        $sql .= !$csKey ? ' (' : '';
                        $sql .= $this->prepareNormalSql($chainSearch, $classname, 'OR', $fKey);
                        $sql .= ($csKey == count($searchFieldValues) - 1) ? ') ' : '';
                    }
                } else {
                    $sql .= $this->prepareNormalSql($searchFieldValues, $classname, 'AND', $fKey);
                }
            }
        }

        // Replace initial `AND ` or `OR ` to avoid SQL errors.
        $sql = str_replace(
            ['WHERE AND', 'WHERE OR', 'WHERE ( OR'],
            ['WHERE', 'WHERE', 'WHERE ('],
            $sql
        );

        // Remove empty where from the end of the string.
        $sql = preg_replace('# WHERE$#', '', $sql);

        //sql string
        $countSql = 'SELECT COUNT(*) total FROM ' . $classname . $sql;
        $resultsSql = "SELECT {$this->columns} FROM {$classname}{$sql}";
        //bind params
        $bindParams = array_combine($this->bindParamsKeys, $this->bindParamsValues);

        return [
            'sql' => $resultsSql,
            'countSql' => $countSql,
            'bind' => $bindParams,
        ];
    }
365488
public function whereIn($expr, $values)
    {
        if ($values instanceof $this) {
            $this->_conditions[] = $expr . ' IN (' . $values->getSql() . ')';
            $this->_bind = array_merge($this->_bind, $values->getBind());
        } elseif ($values) {
            if (strpos($expr, '[') === false && strpos($expr, '(') === false) {
                if (strpos($expr, '.') !== false) {
                    $expr = '[' . str_replace('.', '].[', $expr) . ']';
                } else {
                    $expr = '[' . $expr . ']';
                }
            }

            if (is_int(current($values))) {
                $this->_conditions[] = $expr . ' IN (' . implode(', ', array_map('intval', $values)) . ')';
            } else {
                $bindKeys = [];
                /** @noinspection ForeachSourceInspection */
                foreach ($values as $k => $value) {
                    $key = '_in_' . $this->_hiddenParamNumber . '_' . $k;
                    $bindKeys[] = ":$key";
                    $this->_bind[$key] = $value;
                }

                $this->_conditions[] = $expr . ' IN (' . implode(', ', $bindKeys) . ')';
                $this->_hiddenParamNumber++;
            }
        } else {
            $this->_conditions[] = 'FALSE';
        }

        return $this;
    }
32284
public function getUnindexedFields()
    {
        $unindexedFields = array();
        $fields = $this->getFieldsInQuery();
        foreach ($fields as $field) {
            if ( ! $this->collection->isFieldIndexed($field)) {
                $unindexedFields[] = $field;
            }
        }
        return $unindexedFields;
    }