Passed
Pull Request — 3.x (#201)
by Giso
02:52
created

DateRangeCondition::apply()   A

Complexity

Conditions 6
Paths 5

Size

Total Lines 17
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 10
c 1
b 0
f 0
nc 5
nop 1
dl 0
loc 17
rs 9.2222
1
<?php
2
3
4
namespace DH\DoctrineAuditBundle\Reader;
5
6
7
use Doctrine\DBAL\Query\QueryBuilder;
8
9
class DateRangeCondition implements ConditionInterface
10
{
11
    /**
12
     * @var \DateTime|null
13
     */
14
    private $startDate;
15
16
    /**
17
     * @var \DateTime|null
18
     */
19
    private $endDate;
20
21
    /**
22
     * Apply date filtering.
23
     *
24
     * @param \DateTime|null $startDate
25
     * @param \DateTime|null $endDate
26
     */
27
    public function __construct(?\DateTime $startDate, ?\DateTime $endDate)
28
    {
29
        $this->startDate = $startDate;
30
        $this->endDate   = $endDate;
31
    }
32
33
    public function apply(QueryBuilder $queryBuilder)
34
    {
35
        if (null !== $this->startDate && null !== $this->endDate && $this->endDate < $this->startDate) {
36
            throw new \InvalidArgumentException('End date must be greater than start date.');
37
        }
38
39
        if (null !== $this->startDate) {
40
            $queryBuilder
41
                ->andWhere('created_at >= :start_date')
42
                ->setParameter('start_date', $this->startDate->format('Y-m-d H:i:s'))
43
            ;
44
        }
45
46
        if (null !== $this->endDate) {
47
            $queryBuilder
48
                ->andWhere('created_at <= :end_date')
49
                ->setParameter('end_date', $this->endDate->format('Y-m-d H:i:s'))
50
            ;
51
        }
52
    }
53
}
54