Completed
Push — master ( 0c3139...e3501a )
by Antoine
17s
created

src/Bridge/Doctrine/Orm/Filter/DateFilter.php (5 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*
4
 * This file is part of the API Platform project.
5
 *
6
 * (c) Kévin Dunglas <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace ApiPlatform\Core\Bridge\Doctrine\Orm\Filter;
15
16
use ApiPlatform\Core\Bridge\Doctrine\Orm\Util\QueryNameGeneratorInterface;
17
use Doctrine\ORM\QueryBuilder;
18
19
/**
20
 * Filters the collection by date intervals.
21
 *
22
 * @author Kévin Dunglas <[email protected]>
23
 * @author Théo FIDRY <[email protected]>
24
 */
25
class DateFilter extends AbstractFilter
26
{
27
    const PARAMETER_BEFORE = 'before';
28
    const PARAMETER_AFTER = 'after';
29
    const EXCLUDE_NULL = 'exclude_null';
30
    const INCLUDE_NULL_BEFORE = 'include_null_before';
31
    const INCLUDE_NULL_AFTER = 'include_null_after';
32
    const DOCTRINE_DATE_TYPES = [
33
        'date' => true,
34
        'datetime' => true,
35
        'datetimetz' => true,
36
        'time' => true,
37
    ];
38
39
    /**
40
     * {@inheritdoc}
41
     */
42
    public function getDescription(string $resourceClass): array
43
    {
44
        $description = [];
45
46
        $properties = $this->properties;
47
        if (null === $properties) {
48
            $properties = array_fill_keys($this->getClassMetadata($resourceClass)->getFieldNames(), null);
49
        }
50
51
        foreach ($properties as $property => $nullManagement) {
52
            if (!$this->isPropertyMapped($property, $resourceClass) || !$this->isDateField($property, $resourceClass)) {
53
                continue;
54
            }
55
56
            $description += $this->getFilterDescription($property, self::PARAMETER_BEFORE);
57
            $description += $this->getFilterDescription($property, self::PARAMETER_AFTER);
58
        }
59
60
        return $description;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    protected function filterProperty(string $property, $values, QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $resourceClass, string $operationName = null)
67
    {
68
        // Expect $values to be an array having the period as keys and the date value as values
69 View Code Duplication
        if (
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
70
            !is_array($values) ||
71
            !$this->isPropertyEnabled($property, $resourceClass) ||
72
            !$this->isPropertyMapped($property, $resourceClass) ||
73
            !$this->isDateField($property, $resourceClass)
74
        ) {
75
            return;
76
        }
77
78
        $alias = 'o';
79
        $field = $property;
80
81 View Code Duplication
        if ($this->isPropertyNested($property, $resourceClass)) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
82
            list($alias, $field) = $this->addJoinsForNestedProperty($property, $alias, $queryBuilder, $queryNameGenerator, $resourceClass);
83
        }
84
85
        $nullManagement = $this->properties[$property] ?? null;
86
87
        if (self::EXCLUDE_NULL === $nullManagement) {
88
            $queryBuilder->andWhere($queryBuilder->expr()->isNotNull(sprintf('%s.%s', $alias, $field)));
89
        }
90
91 View Code Duplication
        if (isset($values[self::PARAMETER_BEFORE])) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
92
            $this->addWhere(
93
                $queryBuilder,
94
                $queryNameGenerator,
95
                $alias,
96
                $field,
97
                self::PARAMETER_BEFORE,
98
                $values[self::PARAMETER_BEFORE],
99
                $nullManagement
100
            );
101
        }
102
103 View Code Duplication
        if (isset($values[self::PARAMETER_AFTER])) {
0 ignored issues
show
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
            $this->addWhere(
105
                $queryBuilder,
106
                $queryNameGenerator,
107
                $alias,
108
                $field,
109
                self::PARAMETER_AFTER,
110
                $values[self::PARAMETER_AFTER],
111
                $nullManagement
112
            );
113
        }
114
    }
115
116
    /**
117
     * Adds the where clause according to the chosen null management.
118
     *
119
     * @param QueryBuilder                $queryBuilder
120
     * @param QueryNameGeneratorInterface $queryNameGenerator
121
     * @param string                      $alias
122
     * @param string                      $field
123
     * @param string                      $operator
124
     * @param string                      $value
125
     * @param string|null                 $nullManagement
126
     */
127
    protected function addWhere(QueryBuilder $queryBuilder, QueryNameGeneratorInterface $queryNameGenerator, string $alias, string $field, string $operator, string $value, string $nullManagement = null)
128
    {
129
        $valueParameter = $queryNameGenerator->generateParameterName($field);
130
        $baseWhere = sprintf('%s.%s %s :%s', $alias, $field, self::PARAMETER_BEFORE === $operator ? '<=' : '>=', $valueParameter);
131
132
        if (null === $nullManagement || self::EXCLUDE_NULL === $nullManagement) {
133
            $queryBuilder->andWhere($baseWhere);
134
        } elseif (
135
            (self::PARAMETER_BEFORE === $operator && self::INCLUDE_NULL_BEFORE === $nullManagement) ||
136
            (self::PARAMETER_AFTER === $operator && self::INCLUDE_NULL_AFTER === $nullManagement)
137
        ) {
138
            $queryBuilder->andWhere($queryBuilder->expr()->orX(
139
                $baseWhere,
140
                $queryBuilder->expr()->isNull(sprintf('%s.%s', $alias, $field))
141
            ));
142
        } else {
143
            $queryBuilder->andWhere($queryBuilder->expr()->andX(
144
                $baseWhere,
145
                $queryBuilder->expr()->isNotNull(sprintf('%s.%s', $alias, $field))
146
            ));
147
        }
148
149
        $queryBuilder->setParameter($valueParameter, new \DateTime($value));
150
    }
151
152
    /**
153
     * Determines whether the given property refers to a date field.
154
     *
155
     * @param string $property
156
     * @param string $resourceClass
157
     *
158
     * @return bool
159
     */
160 View Code Duplication
    protected function isDateField(string $property, string $resourceClass): bool
0 ignored issues
show
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
161
    {
162
        $propertyParts = $this->splitPropertyParts($property, $resourceClass);
163
        $metadata = $this->getNestedMetadata($resourceClass, $propertyParts['associations']);
164
165
        return isset(self::DOCTRINE_DATE_TYPES[$metadata->getTypeOfField($propertyParts['field'])]);
166
    }
167
168
    /**
169
     * Gets filter description.
170
     *
171
     * @param string $property
172
     * @param string $period
173
     *
174
     * @return array
175
     */
176
    protected function getFilterDescription(string $property, string $period): array
177
    {
178
        return [
179
            sprintf('%s[%s]', $property, $period) => [
180
                'property' => $property,
181
                'type' => \DateTimeInterface::class,
182
                'required' => false,
183
            ],
184
        ];
185
    }
186
}
187