Generic DateTime filter

@param QueryBuilder $queryBuilder
@param DateTime $options
@throws InvalidArgumentException if $options is not an instance of DateTime
323625
public function filter(QueryBuilder $queryBuilder, $options = array())
    {
        if ( ! $options instanceof DateTime) {
            throw new InvalidArgumentException(
                '$options is expected to be an instance of DateTime'
            );
        }
        $aliases = $queryBuilder->getRootAliases();
        $queryBuilder->andWhere(sprintf(
            '%s.%s %s :%s',
            $aliases[0],
            $this->getPropertyName(),
            $this->getComparison(),
            $this->getName()
        ));
        $queryBuilder->setParameter(
            $this->getName(),
            $options->format('Y-m-d H:i:s')
        );
    }
1203950
protected function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $alias, string $field, string $operator, string $value, string $nullManagement = null, $type = null)
    {
        $type = (string) $type;
        try {
            $value = false === strpos($type, '_immutable') ? new \DateTime($value) : new \DateTimeImmutable($value);
        } catch (\Exception $e) {
            // Silently ignore this filter if it can not be transformed to a \DateTime
            $this->logger->notice('Invalid filter ignored', [
                'exception' => new InvalidArgumentException(sprintf('The field "%s" has a wrong date format. Use one accepted by the \DateTime constructor', $field)),
            ]);

            return;
        }

        $valueParameter = $queryNameGenerator->generateParameterName($field);
        $operatorValue = [
            self::PARAMETER_BEFORE => '<=',
            self::PARAMETER_STRICTLY_BEFORE => '<',
            self::PARAMETER_AFTER => '>=',
            self::PARAMETER_STRICTLY_AFTER => '>',
        ];
        $baseWhere = sprintf('%s.%s %s :%s', $alias, $field, $operatorValue[$operator], $valueParameter);

        if (null === $nullManagement || self::EXCLUDE_NULL === $nullManagement) {
            $queryBuilder->andWhere($baseWhere);
        } elseif (
            (self::INCLUDE_NULL_BEFORE === $nullManagement && \in_array($operator, [self::PARAMETER_BEFORE, self::PARAMETER_STRICTLY_BEFORE], true)) ||
            (self::INCLUDE_NULL_AFTER === $nullManagement && \in_array($operator, [self::PARAMETER_AFTER, self::PARAMETER_STRICTLY_AFTER], true)) ||
            (self::INCLUDE_NULL_BEFORE_AND_AFTER === $nullManagement && \in_array($operator, [self::PARAMETER_AFTER, self::PARAMETER_STRICTLY_AFTER, self::PARAMETER_BEFORE, self::PARAMETER_STRICTLY_BEFORE], true))
        ) {
            $queryBuilder->andWhere($queryBuilder->expr()->orX(
                $baseWhere,
                $queryBuilder->expr()->isNull(sprintf('%s.%s', $alias, $field))
            ));
        } else {
            $queryBuilder->andWhere($queryBuilder->expr()->andX(
                $baseWhere,
                $queryBuilder->expr()->isNotNull(sprintf('%s.%s', $alias, $field))
            ));
        }

        $queryBuilder->setParameter($valueParameter, $value, $type);
    }
436820
private static function filterInOrNotInList($operation, QueryBuilder $queryBuilder)
    {
        $expressionMethod = lcfirst(preg_replace('/\s+/', '', ucwords(strtolower($operation['operation']))));

        return $queryBuilder
            ->expr()
            ->{$expressionMethod}($operation['property'], $operation['values']);
    }
365707
protected function filterOnlines(QueryBuilder $query_builder = null) {

        if (!$query_builder) {
            $query_builder = $this->getBaseBuilder();
        }

        $query_builder->andWhere("e.status = 1");
        return $query_builder;
    }
1131139
public function filterField($fieldName, array $options = array())
    {
        $filter = '';

        $internalType = $this->_context->type($fieldName);

        if (preg_match('/_id$/', $fieldName))
        {
            $filter .= $this->filterSelect($fieldName, $options);
        }
        else
        {
            switch ($internalType)
            {
                case 'datetime':
                    $filter .= $this->filterDatetime($fieldName, $options);
                    break;

                case 'date':
                    $filter .= $this->filterDate($fieldName, $options);
                    break;

                case 'integer':
                case 'tinyinteger':
                case 'smallinteger':
                case 'biginteger':
                    $filter .= $this->filterInteger($fieldName, $options);
                    break;

                case 'float':
                case 'decimal':
                    $filter .= $this->filterFloat($fieldName, $options);
                    break;

                case 'boolean':
                    $filter .= $this->filterBoolean($fieldName, $options);
                    break;

                default:
                    $filter .= $this->filterText($fieldName, $options);
                    break;
            }
        }

        return $filter;
    }
1073311
public function filterQuery(QueryBuilder &$query, &$selects = null)
    {
        $model = $this->config->getDataModel();

        //try to read the time for the min and max values, and if they check out, set the where
        if ($minValue = $this->getOption('min_value')) {
            $time = new DateTime($minValue);

            if ($time !== false) {
                $query->where($model->getTable().'.'.$this->getOption('field_name'), '>=', $this->getDateString($time));
            }
        }

        if ($maxValue = $this->getOption('max_value')) {
            $time = new DateTime($maxValue);

            if ($time !== false) {
                $query->where($model->getTable().'.'.$this->getOption('field_name'), '<=', $this->getDateString($time));
            }
        }
    }
649055
public function subquery( QueryBuilder $queryBuilder ) {
		$this->subqueries[] = $queryBuilder->getSPARQL( false );
		$this->usageValidator->trackDefinedVariables( implode( ' ', $queryBuilder->getSelects() ) );

		// @todo temp hack to add AS definitions to defined variables
		$regexHelper = new RegexHelper();
		$matches = $regexHelper->getMatches( 'AS \{variable}', implode( ' ', $queryBuilder->getSelects() ) );
		$this->usageValidator->trackDefinedVariables( $matches );

		return $this;
	}
303358
private static function filterAndOr($operation, QueryBuilder $queryBuilder)
    {
        $children = $operation['children'];

        if (empty($children)) {
            return;
        }

        $whereOperation = strtolower($operation['operation']) . 'Where';

        foreach ($children as $child) {
            $queryBuilder->{$whereOperation}(static::calculateSubFilter($child, $queryBuilder));
        }
    }
1312191
protected function filterQueryBuilder(QueryBuilder $queryBuilder, string $field, ListFilter $listFilter)
    {
        $value = $this->filterEasyadminAutocompleteValue($listFilter->getValue());
        // Empty string and numeric keys is considered as "not applied filter"
        if (null === $value || '' === $value || \is_int($field)) {
            return;
        }

        // Add root entity alias if none provided
        $queryField = $listFilter->getProperty();
        if (false === \strpos($queryField, '.')) {
            $queryField = $queryBuilder->getRootAlias().'.'.$queryField;
        }

        // Checks if filter is directly appliable on queryBuilder
        if (!$this->isFilterAppliable($queryBuilder, $queryField)) {
            return;
        }

        $operator = $listFilter->getOperator();
        // Sanitize parameter name
        $parameter = 'form_filter_'.\str_replace('.', '_', $field);

        switch ($operator) {
            case ListFilter::OPERATOR_EQUALS:
                if ('_NULL' === $value) {
                    $queryBuilder->andWhere(\sprintf('%s IS NULL', $queryField));
                } elseif ('_NOT_NULL' === $value) {
                    $queryBuilder->andWhere(\sprintf('%s IS NOT NULL', $queryField));
                } else {
                    $queryBuilder
                        ->andWhere(\sprintf('%s %s :%s', $queryField, '=', $parameter))
                        ->setParameter($parameter, $value)
                    ;
                }
                break;
            case ListFilter::OPERATOR_NOT:
                $queryBuilder
                    ->andWhere(\sprintf('%s %s :%s', $queryField, '!=', $parameter))
                    ->setParameter($parameter, $value)
                ;
                break;
            case ListFilter::OPERATOR_IN:
                // Checks that $value is not an empty Traversable
                if (0 < \count($value)) {
                    $queryBuilder
                        ->andWhere(\sprintf('%s %s (:%s)', $queryField, 'IN', $parameter))
                        ->setParameter($parameter, $value)
                    ;
                }
                break;
            case ListFilter::OPERATOR_NOTIN:
                // Checks that $value is not an empty Traversable
                if (0 < \count($value)) {
                    $queryBuilder
                        ->andWhere(\sprintf('%s %s (:%s)', $queryField, 'NOT IN', $parameter))
                        ->setParameter($parameter, $value)
                    ;
                }
                break;
            case ListFilter::OPERATOR_GT:
                $queryBuilder
                    ->andWhere(\sprintf('%s %s :%s', $queryField, '>', $parameter))
                    ->setParameter($parameter, $value)
                ;
                break;
            case ListFilter::OPERATOR_GTE:
                $queryBuilder
                    ->andWhere(\sprintf('%s %s :%s', $queryField, '>=', $parameter))
                    ->setParameter($parameter, $value)
                ;
                break;
            case ListFilter::OPERATOR_LT:
                $queryBuilder
                    ->andWhere(\sprintf('%s %s :%s', $queryField, '<', $parameter))
                    ->setParameter($parameter, $value)
                ;
                break;
            case ListFilter::OPERATOR_LTE:
                $queryBuilder
                    ->andWhere(\sprintf('%s %s :%s', $queryField, '<=', $parameter))
                    ->setParameter($parameter, $value)
                ;
                break;
            case ListFilter::OPERATOR_LIKE:
                $queryBuilder
                    ->andWhere(\sprintf('%s %s :%s', $queryField, 'LIKE', $parameter))
                    ->setParameter($parameter, '%'.$value.'%')
                ;
                break;
            default:
                throw new \RuntimeException(\sprintf('Operator "%s" is not supported !', $operator));
        }
    }
1031042
private function addPerformanceJoinsToQueryBuilder(QueryBuilder $queryBuilder)
    {
        $queryBuilder
            ->select(['p', 'pa', 'pc', 'rpc', 'i'])
            ->leftJoin('p.principalImage', 'pa')
            ->leftJoin('p.priceCurrency', 'pc')
            ->leftJoin('p.reducedPriceCurrency', 'rpc')
            ->leftJoin('p.images', 'i')
            ->groupBy('p.id');
    }
915634
public function getEventsQuery(\DateTime $begin, \DateTime $end, array $options = array())
    {
        return $this->getEventsQueryBuilder($begin, $end, $options)->getQuery();
    }
54460
public function findFilter(Query $query, array $options)
    {
        foreach ($this->filters()->collection() as $name => $filter) {
            $filter->apply($query, $options);
        }

        return $query;
    }
317697
public function filter($field, $filter, array $options = []) {
        if (!in_array($filter, [self::HTML, self::NEWLINES, self::WHITESPACE, self::XSS])) {
            throw new InvalidArgumentException(sprintf('Filter %s does not exist', $filter));
        }

        $this->_filters[$field][$filter] = $options;

        return $this;
    }
312550
protected function doFiltration(QueryBuilderInterface $queryBuilder)
    {
        $search = $this->getSearchService();

        $filters = $this->map($this->getFilters(), true);
        $query = $search->searchType($queryBuilder, $this->getType(), true);

        foreach ($filters as $filterProp => $filterVal) {
            foreach ($filterVal as $values) {
                if (is_array($values)) {
                    $query->addCriterion($filterProp, SupportedOperatorHelper::IN, $values);
                } elseif (is_string($values)) {
                    $query->addCriterion($filterProp, SupportedOperatorHelper::CONTAIN, $values);
                }
            }
        }

        $queryBuilder->setCriteria($query);
    }
855380
private function getQueryBuilderWithNewAliases(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $originAlias = 'o', string $replacement = 'o_2'): QueryBuilder
    {
        $queryBuilderClone = clone $queryBuilder;

        $joinParts = $queryBuilder->getDQLPart('join');
        $wherePart = $queryBuilder->getDQLPart('where');

        //reset parts
        $queryBuilderClone->resetDQLPart('join');
        $queryBuilderClone->resetDQLPart('where');
        $queryBuilderClone->resetDQLPart('orderBy');
        $queryBuilderClone->resetDQLPart('groupBy');
        $queryBuilderClone->resetDQLPart('having');

        //Change from alias
        $from = $queryBuilderClone->getDQLPart('from')[0];
        $queryBuilderClone->resetDQLPart('from');
        $queryBuilderClone->from($from->getFrom(), $replacement);

        $aliases = ["$originAlias."];
        $replacements = ["$replacement."];

        //Change join aliases
        foreach ($joinParts[$originAlias] as $joinPart) {
            /** @var Join $joinPart */
            $joinString = str_replace($aliases, $replacements, $joinPart->getJoin());
            $pos = strpos($joinString, '.');
            if (false === $pos) {
                if (null !== $joinPart->getCondition() && null !== $this->resourceClassResolver && $this->resourceClassResolver->isResourceClass($joinString)) {
                    $newAlias = $queryNameGenerator->generateJoinAlias($joinPart->getAlias());
                    $aliases[] = "{$joinPart->getAlias()}.";
                    $replacements[] = "$newAlias.";
                    $condition = str_replace($aliases, $replacements, $joinPart->getCondition());
                    $join = new Join($joinPart->getJoinType(), $joinPart->getJoin(), $newAlias, $joinPart->getConditionType(), $condition);
                    $queryBuilderClone->add('join', [$replacement => $join], true);
                }

                continue;
            }
            $alias = substr($joinString, 0, $pos);
            $association = substr($joinString, $pos + 1);
            $condition = str_replace($aliases, $replacements, $joinPart->getCondition());
            $newAlias = QueryBuilderHelper::addJoinOnce($queryBuilderClone, $queryNameGenerator, $alias, $association, $joinPart->getJoinType(), $joinPart->getConditionType(), $condition, $originAlias);
            $aliases[] = "{$joinPart->getAlias()}.";
            $replacements[] = "$newAlias.";
        }

        $queryBuilderClone->add('where', str_replace($aliases, $replacements, (string) $wherePart));

        return $queryBuilderClone;
    }
944907
public function filterByPublishPost(QueryBuilder $query)
    {
        return $query
            ->andWhere('post.publicationDate IS NOT NULL')
            ->andWhere('post.status = :publishedStatus')
            ->andWhere('post.publicationDate <= :currentDate')
            ->setParameter('publishedStatus', Statusable::STATUS_PUBLISHED)
            ->setParameter('currentDate', new \DateTime());
    }
1198445
public function alterBaseQueryBuilder($query, $options = array(), $action = 'list')
    {
        $query = parent::alterBaseQueryBuilder($query, $options, $action);

        $parent_tree = $this->findBaseRootElement();

        if (!is_null($parent_tree)) {
            $query->andWhere(
                $query->getRootAliases()[0] . '.lft <= ' . $this->addNamedParameter('rgt', $parent_tree->getRgt(), $query)
                . ' AND ' . $query->getRootAliases()[0] . '.lft >= ' . $this->addNamedParameter('lft', $parent_tree->getLft(), $query)
            );
        }

        $query->andWhere($query->getRootAliases()[0] . '.parent IS NOT NULL');

        $query->addOrderBy($query->getRootAliases()[0] . '.lft', 'ASC');

        return $query;
    }