RoundDateTime::modify()   A
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 15
rs 9.4555
c 0
b 0
f 0
cc 5
nc 3
nop 1
1
<?php
2
3
/**
4
 * This file is part of the Happyr Doctrine Specification package.
5
 *
6
 * (c) Tobias Nyholm <[email protected]>
7
 *     Kacper Gunia <[email protected]>
8
 *     Peter Gribanov <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Happyr\DoctrineSpecification\Result;
15
16
use Doctrine\ORM\AbstractQuery;
17
use Doctrine\ORM\Query\Parameter;
18
19
/**
20
 * Round a \DateTime to enable caching.
21
 */
22
class RoundDateTime implements ResultModifier
23
{
24
    /**
25
     * @var int How may seconds to round time
26
     */
27
    private $roundSeconds;
28
29
    /**
30
     * @param int $roundSeconds How may seconds to round time
31
     */
32
    public function __construct($roundSeconds)
33
    {
34
        $this->roundSeconds = $roundSeconds;
35
    }
36
37
    /**
38
     * @param AbstractQuery $query
39
     */
40
    public function modify(AbstractQuery $query)
41
    {
42
        foreach ($query->getParameters() as $parameter) {
43
            if ($parameter instanceof Parameter &&
44
                ($value = $parameter->getValue()) &&
45
                $value instanceof \DateTimeInterface
46
            ) {
47
                // round down so that the results do not include data that should not be there.
48
                $uts = (int) (floor($value->getTimestamp() / $this->roundSeconds) * $this->roundSeconds);
49
                $date = (new \DateTimeImmutable('now', $value->getTimezone()))->setTimestamp($uts);
50
51
                $query->setParameter($parameter->getName(), $date, $parameter->getType());
52
            }
53
        }
54
    }
55
}
56