Completed
Push — master ( 52c6c6...d7d00c )
by Łukasz
09:42
created

DateFilter::apply()   C

Complexity

Conditions 7
Paths 36

Size

Total Lines 26
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 26
rs 6.7272
c 0
b 0
f 0
cc 7
eloc 17
nc 36
nop 4
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
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
namespace Sylius\Component\Grid\Filter;
13
14
use Sylius\Component\Grid\Data\DataSourceInterface;
15
use Sylius\Component\Grid\Filtering\FilterInterface;
16
17
/**
18
 * @author Grzegorz Sadowski <[email protected]>
19
 */
20
final class DateFilter implements FilterInterface
21
{
22
    const NAME = 'date';
23
    const DEFAULT_INCLUSIVE_FROM = true;
24
    const DEFAULT_INCLUSIVE_TO = false;
25
26
    /**
27
     * {@inheritdoc}
28
     */
29
    public function apply(DataSourceInterface $dataSource, $name, $data, array $options)
30
    {
31
        $expressionBuilder = $dataSource->getExpressionBuilder();
32
33
        $field = $this->getOption($options, 'field', $name);
34
35
        $from = isset($data['from']) ? $this->getDateTime($data['from']) : null;
36
        if (null !== $from) {
37
            $inclusive = (bool)$this->getOption($options, 'inclusive_from', self::DEFAULT_INCLUSIVE_FROM);
38
            if (true === $inclusive) {
39
                $expressionBuilder->greaterThanOrEqual($field, $from);
40
            } else {
41
                $expressionBuilder->greaterThan($field, $from);
42
            }
43
        }
44
45
        $to = isset($data['to']) ? $this->getDateTime($data['to']) : null;
46
        if (null !== $to) {
47
            $inclusive = (bool)$this->getOption($options, 'inclusive_to', self::DEFAULT_INCLUSIVE_TO);
48
            if (true === $inclusive) {
49
                $expressionBuilder->lessThanOrEqual($field, $to);
50
            } else {
51
                $expressionBuilder->lessThan($field, $to);
52
            }
53
        }
54
    }
55
56
57
    /**
58
     * @param array $options
59
     * @param string $name
60
     * @param null|mixed $default
61
     *
62
     * @return null|mixed
63
     */
64
    private function getOption(array $options, $name, $default = null)
65
    {
66
        return isset($options[$name]) ? $options[$name] : $default;
67
    }
68
69
    /**
70
     * @param string[] $data
71
     *
72
     * @return null|string
73
     */
74
    private function getDateTime(array $data)
75
    {
76
        if (empty($data['date'])) {
77
            return null;
78
        }
79
80
        if (empty($data['time'])) {
81
            return $data['date'];
82
        }
83
84
        return $data['date'].' '.$data['time'];
85
    }
86
}
87