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

DateRangeCondition::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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