Filter by.

@param string $filterName
@param string $field
@param array  $values
@param int    $applicationType
@param bool   $aggregate
@param array  $aggregationSort

@return Query
359482
public function filterBy(
        string $filterName,
        string $field,
        array $values,
        int $applicationType = Filter::AT_LEAST_ONE,
        bool $aggregate = true,
        array $aggregationSort = Aggregation::SORT_BY_COUNT_DESC
    ): self {
        $fieldPath = Item::getPathByField($field);
        if (!empty($values)) {
            $this->filters[$filterName] = Filter::create(
                $fieldPath,
                $values,
                $applicationType,
                Filter::TYPE_FIELD
            );
        } else {
            unset($this->filters[$filterName]);
        }

        if ($aggregate) {
            $this->aggregateBy(
                $filterName,
                $field,
                $applicationType,
                $aggregationSort
            );
        }

        return $this;
    }
595640
public function filterBy(array $criteria, array $orderBy = null, $limit = null, $offset = null, CompositeExpression $externalExpression = null)
    {
        $qb = $this->repository->createQueryBuilder('user')->distinct(true)
            ->leftJoin('user.contact', 'contact')
            ->leftJoin('contact.addresses', 'address')
            ->andWhere('address.type = :addressType')
            ->setParameter('addressType', 'main');

        if (array_key_exists('search', $criteria)) {
            $qb->andWhere('user.username like :searchLike or address.firstName like :searchLike or address.lastName like :searchLike or user.id=:search');
            $qb->setParameter('search', $criteria['search']);
            $qb->setParameter('searchLike', '%'.$criteria['search'].'%');
        }

        if (is_array($orderBy)) {
            foreach ($orderBy as $key => $value) {
                if ($key === 'id') {
                    $key = 'user.id';
                }
                $qb->orderBy($key, $value);
            }
        }

        $query = $qb->getQuery();
        $arrayResult = $query->getResult();
        $count = count($arrayResult);

        if ($offset === null) {
            $offset = 0;
        }

        if ($offset || $limit) {
            $arrayResult = array_slice($arrayResult, $offset, $limit);
        }

        $result = new FilterResult($arrayResult);
        $result->setCount($count);

        return $result;
    }
403657
public function distinct($fieldName, $filters = [], $options = [])
    {
        $field = $fieldName;

        $propInfos = $this->classMetadata->getPropertyInfoForField($fieldName);
        if (!$propInfos) {
            $propInfos = $this->classMetadata->getPropertyInfo($fieldName);
        }

        if (isset($propInfos)) {
            $field = $propInfos->getField();

            if ($propInfos->getMetadata()) {
                $field = "metadata." . $field;
            }
        }

        $filters = $this->castQuery($filters);

        $result = $this->collection->distinct($field, $filters, $options);
        return $result;
    }
1066821
public function get($field, $filters = null, $default = null)
    {
        if (!isset($this->_data[$field])) {
            return $default;
        }

        $value = $this->_data[$field];

        if (!$filters) {
            return $value;
        }

        return $this->valueFiltering($value, $filters);
    }
239394
public function filter()
    {
        $condition = func_get_args();
        $cName = Utility::get($condition, 0);
        if (gettype($cName)=="object" && is_callable($cName)) {
            //Able to filter by function
            return $this->filterByFunc($cName);
        }
        $operator = Utility::get($condition, 1);
        $value = Utility::get($condition, 2);
        $optional_value = Utility::get($condition, 3);

        if ($cName===null||$operator===null) {
            throw new \Exception('dataStore->filter() requires condition in array form ($colname,$operator,$value)');
        }

        $result = array();
        $cType = $this->metaData["columns"][$cName]["type"];
        $dtFormat = null;
        if (in_array($cType, array("datetime", "date", "time"))) {
            switch ($cType)
            {
            case "datetime":
                $dtFormat = Utility::get($this->metaData["columns"][$cName], "format", "Y-m-d H:i:s");
                break;
            case "date":
                $dtFormat = Utility::get($this->metaData["columns"][$cName], "format", "Y-m-d");
                break;
            case "time":
                $dtFormat = Utility::get($this->metaData["columns"][$cName], "format", "H:i:s");
                break;
            }
            $value =  \DateTime::createFromFormat($dtFormat, $value);
        }
        
        foreach ($this->rows as $row) {
            $columnValue = $row[$cName]; 
            if ($dtFormat!==null) {
                $columnValue =  \DateTime::createFromFormat($dtFormat, $columnValue);
            }
            switch($operator)
            {
            case "=":
            case "==":
            case "equal":
                if ($columnValue==$value) {
                    array_push($result, $row);
                }
                break;
            case "===":
                if ($columnValue===$value) {
                    array_push($result, $row);
                }
                break;
            case "!=":
            case "notEqual":
                if ($columnValue!=$value) {
                    array_push($result, $row);
                }
                break;
            case "!==":
                if ($columnValue!==$value) {
                    array_push($result, $row);
                }
                break;
            case ">":
            case "gt":
                if ($columnValue>$value) {
                    array_push($result, $row);
                }
                break;
            case ">=":
                if ($columnValue>=$value) {
                    array_push($result, $row);
                }
                break;
            case "<":
            case "lt":
                if ($columnValue<$value) {
                    array_push($result, $row);
                }
                break;
            case "<=":
                if ($columnValue<=$value) {
                    array_push($result, $row);
                }
                break;
            case "contain":
            case "contains":
                if (strpos(strtolower($columnValue), strtolower($value))!==false) {
                    array_push($result, $row);
                }
                break;
            case "notContain":
            case "notContains":
                if (strpos(strtolower($columnValue), strtolower($value))===false) {
                    array_push($result, $row);
                }
                break;
            case "between":
                if ($value<$columnValue && $columnValue<$optional_value) {
                    array_push($result, $row);
                }
                break;
            case "notBetween":
                if (!($value<$columnValue && $columnValue<$optional_value)) {
                    array_push($result, $row);
                }
                break;
            case "in":
                if (!is_array($value)) {
                    $value = array($value);
                }
                if (in_array($columnValue, $value)) {
                    array_push($result, $row);
                }
                break;
            case "notIn":
                if (!is_array($value)) {
                    $value = array($value);
                }
                if (!in_array($columnValue, $value)) {
                    array_push($result, $row);
                }
                break;
            case "startWith":
            case "startsWith":
                if (strpos(strtolower($columnValue), strtolower($value)) === 0) {
                    array_push($result, $row);
                }
                break;
            case "notStartWith":
            case "notStartsWith":
                if (strpos(strtolower($columnValue), strtolower($value)) !== 0) {
                    array_push($result, $row);
                }
                break;
            case "endWith":
            case "endsWith":
                if (strpos(strrev(strtolower($columnValue)), strrev(strtolower($value))) === 0) {
                    array_push($result, $row);
                }
                break;
            case "notEndWith":
            case "notEndsWith":
                if (strpos(strrev(strtolower($columnValue)), strrev(strtolower($value))) !== 0) {
                    array_push($result, $row);
                }
                break;
            default:
                throw new \Exception("Unknown operator [$operator]");
                return $this;
                break;
            }
        }
        return new DataStore($result, $this->metaData);
    }
1218913
private function replaceAggregationFilter($aggregationConfig)
    {
        if (isset($aggregationConfig['filters'])) {
            $filters = [];

            foreach ($aggregationConfig['filters'] as $filterName => $filterClass) {
                // Done in \Smile\ElasticsuiteCore\Search\Request\ContainerConfiguration for query filters.
                $filters[$filterName] = $this->objectManager->get($filterClass)->getFilterQuery();
            }

            $aggregationConfig['filters'] = $filters;
        }

        if (isset($aggregationConfig['childBuckets'])) {
            $childBuckets = [];
            foreach ($aggregationConfig['childBuckets'] as $aggName => $aggConfig) {
                $childBuckets[$aggName] = $this->replaceAggregationFilter($aggConfig);
            }

            $aggregationConfig['childBuckets'] = $childBuckets;
        }

        return $aggregationConfig;
    }
1178579
public function findByWhereFilter($name, $filter, $orderColumn = null, $orderType = NULL) {
        $this->load();
        $mapper = MapperBuilder::buildFromName($this->mapping, $name);

        $query = "SELECT * FROM `" . $mapper->getTable() . "` ";
        $query .= "WHERE 1 ";
        if (!is_null($filter)) {
            $query .= "AND " . $filter;
        }

        if (!is_null($orderColumn)) {
            $query .= "ORDER BY `$orderColumn` ";
            if (!is_null($orderType)) {
                $query .= "$orderType";
            } else {
                $query .= "ASC ";
            }
        }

        $result = $this->getDataSource()->query($query);

        if ($result) {
            $collection = new Collection($mapper->getClass(), $result, $mapper);
        } else {
            $collection = new Collection($mapper->getClass(), array(), $mapper);
        }

        return $collection;
    }
799604
public function getFilteredNamedGroupingPolicy($ptype, $fieldIndex, ...$fieldValues)
    {
        return $this->model->getFilteredPolicy('g', $ptype, $fieldIndex, ...$fieldValues);
    }
88147
public function Applications($Filter = '', $ApplicationName = '', $TransientKey = '') {
      $this->Permission('Garden.Settings.Manage');
      
      // Page setup
      $this->AddJsFile('addons.js');
      $this->AddJsFile('applications.js');
      $this->Title(T('Applications'));
      $this->AddSideMenu('dashboard/settings/applications');
      
      // Validate & set parameters
      $Session = Gdn::Session();
      $ApplicationName = $Session->ValidateTransientKey($TransientKey) ? $ApplicationName : '';
      if (!in_array($Filter, array('enabled', 'disabled')))
         $Filter = 'all';
      $this->Filter = $Filter;
      $AuthenticatedPostBack = $this->Form->AuthenticatedPostBack();      
      
      $ApplicationManager = new Gdn_ApplicationManager();
      $this->AvailableApplications = $ApplicationManager->AvailableVisibleApplications();
      $this->EnabledApplications = $ApplicationManager->EnabledVisibleApplications();
      
      if ($ApplicationName != '') {
         $this->EventArguments['ApplicationName'] = $ApplicationName;
         if (array_key_exists($ApplicationName, $this->EnabledApplications) === TRUE) {
            try {
               $ApplicationManager->DisableApplication($ApplicationName);
               Gdn_LibraryMap::ClearCache();
               $this->FireEvent('AfterDisableApplication');
            } catch (Exception $e) {
               $this->Form->AddError(strip_tags($e->getMessage()));
            }
         } else {
            try {
               $ApplicationManager->CheckRequirements($ApplicationName);
            } catch (Exception $e) {
               $this->Form->AddError(strip_tags($e->getMessage()));
            }
            if ($this->Form->ErrorCount() == 0) {
               $Validation = new Gdn_Validation();
               $ApplicationManager->RegisterPermissions($ApplicationName, $Validation);
               $ApplicationManager->EnableApplication($ApplicationName, $Validation);
               Gdn_LibraryMap::ClearCache();
               $this->Form->SetValidationResults($Validation->Results());
               
               $this->EventArguments['Validation'] = $Validation;
               $this->FireEvent('AfterEnableApplication');
            }
            
         }
         if ($this->Form->ErrorCount() == 0)
            Redirect('settings/applications/'.$this->Filter);
      }
      $this->Render();
   }
1199936
public function findByGenericFilter($name, $filter = null, $page = 1, $orderColumn = null, $orderType = null) {
        $this->load();
        $mapper = MapperBuilder::buildFromName($this->mapping, $name);

        $selectQuery = "";
        $whereQuery = "";
        $orderQuery = "";

        $selectQuery .= "SELECT * FROM `" . $mapper->getTable() . "` ";
        $filterList = array();
        if (!is_null($filter)) {
            $filterList = explode(" ", $filter);
        }

        if (!is_null($filter)) {
            $whereQuery .= " WHERE 1=2 ";
            foreach ($filterList as $searchedWord) {
                foreach ($mapper->getFilter("generic")->getColumns() as $filteredColumn) {
                    $whereQuery .= " OR $filteredColumn LIKE '%" . $searchedWord . "%'";
                }
            }
        } else {
            $whereQuery .= " WHERE 1 ";
        }

        if (!is_null($orderColumn)) {
            $orderQuery .= "ORDER BY $orderColumn ";
            if (!is_null($orderType)) {
                $orderQuery .= "$orderType";
            } else {
                $orderQuery .= "ASC";
            }
        }

        $from = ($page - 1) * $mapper->getFilter("generic")->getItemsPerPage();
        $pageQuery = " LIMIT $from , " . $mapper->getFilter("generic")->getItemsPerPage();

        $query = $selectQuery . $whereQuery . $orderQuery . $pageQuery;
        $result = $this->getDataSource()->query($query);

        if ($result) {
            $collection = new Collection($mapper->getClass(), $result, $mapper);
        } else {
            $collection = new Collection($mapper->getClass(), array(), $mapper);
        }

        $selectCountQuery = "SELECT count(*) as total FROM `" . $mapper->getTable() . "` ";
        $query = $selectCountQuery . $whereQuery;
        $result = $this->getDataSource()->query($query);
        $itemCount = $result[0]["total"];
        $pager = new Pager($collection, $itemCount, $mapper->getFilter("generic")->getItemsPerPage(), $page);

        return $pager;
    }
930807
private function aggregation($field, $isMulti = false, $useMaster = false, $operation = 'COUNT')
    {
        is_string($isMulti) && $this->groupBy($isMulti)->columns($isMulti);
        $count = $this->columns(["{$operation}({$field})" => '__res__'])->select(null, null, $useMaster);
        if ($isMulti) {
            $return = [];
            foreach ($count as $val) {
                $return[$val[$isMulti]] = $operation === 'COUNT' ? intval($val['__res__']) : floatval($val['__res__']);
            }
            return $return;
        } else {
            return $operation === 'COUNT' ? intval($count[0]['__res__']) : floatval($count[0]['__res__']);
        }
    }
1079709
private function filterAndSortByEncryptedField(array $criteria, array $orderBy = null, $limit = null, $offset = null)
    {
        $encryptedSort = $this->orderByHasEncryptedField($orderBy);

        $encryptedFields = $this->getEncryptedFields();
        $notEncryptedCriteria = array_diff_key($criteria, $encryptedFields);
        $notEncryptedOrderBy = !$encryptedSort ? $orderBy : null;

        // Get the result of the filter by not encrypted fields
        $result = $this->wrapped->findBy($notEncryptedCriteria, $notEncryptedOrderBy);

        $encryptedCriteria = array_intersect_key($criteria, $encryptedFields);
        if (!empty($result) && !empty($encryptedCriteria)) {
            $result = $this->filterWithEncryptedCriteria($result, $encryptedCriteria);
        }

        if ($encryptedSort && !empty($orderBy)) {
            $result = $this->sortWithEncryptedOrderBy($result, $orderBy);
        }

        if ($limit) {
            $offset = $offset ? $offset : 0;

            $result = array_slice($result, $offset, $limit);
        }

        return $result;
    }
303741
protected function processOperatorFilter(Criteria $criteria, $field, $value)
    {
        if (is_array($value) && isset($value['operator']) && array_key_exists('value', $value)) {
            $operator = $value['operator'];

            if (!method_exists($criteria->expr(), $operator)) {
                throw RestException::createFilterError(['field' => $field, 'filter' => $value], 'Unknown operator.');
            }

            $criteria->andWhere(
                $criteria->expr()->$operator($field, $value['value'])
            );
        }

        return $this;
    }
733355
private function prepareAggregations(array $searchResponse, AggregationFactory $aggregationFactory)
    {
        $aggregations = [];

        if (isset($searchResponse['aggregations'])) {
            $aggregations = $searchResponse['aggregations'];
        }

        $this->aggregations = $aggregationFactory->create($aggregations);
    }
733474
public function queryFilter(string $filterType, $filterOptions, string $clauseType = 'must'): ElasticSearchQueryBuilder
    {
        $this->request->queryFilter($filterType, $filterOptions, $clauseType);

        return $this;
    }
972324
public function setFilters($filters, QueryBuilder &$query, QueryBuilder &$countQuery, &$selects)
    {
        //then we set the filters
        if ($filters && is_array($filters)) {
            foreach ($filters as $filter) {
                //get the field object
                $fieldObject = $this->fieldFactory->findFilter($filter['field_name']);

                //set the filter on the object
                $fieldObject->setFilter($filter);

                //filter the query objects, only pass in the selects the first time so they aren't added twice
                $fieldObject->filterQuery($query, $selects);
                $fieldObject->filterQuery($countQuery);
            }
        }
    }
1034626
public static function filterEnumByName(
        QueryBuilder $queryBuilder,
        &$criteria,
        $field,
        $enumTypeName,
        $isJoined = false,
        $alias = 'o'
    ) {
        if (isset($criteria[$field])) {
            if (!empty($criteria[$field])) {
                if (!$isJoined) {
                    $queryBuilder->join(sprintf('%s.%s', $alias, $field), 'enum')->join('enum.type', 'enumType');
                }
                $queryBuilder
                    ->andWhere('enumType.name = :enumType')
                    ->andWhere(sprintf('enum.name LIKE :%s', $field))
                    ->setParameter($field, '%'.$criteria[$field].'%')
                    ->setParameter('enumType', $enumTypeName);
            }
            unset($criteria[$field]);
        }

        return $criteria;
    }