Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
3 / 3
CRAP
100.00% covered (success)
100.00%
1 / 1
TemporaAbstract
100.00% covered (success)
100.00%
22 / 22
100.00% covered (success)
100.00%
3 / 3
9
100.00% covered (success)
100.00%
1 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 validate
100.00% covered (success)
100.00%
16 / 16
100.00% covered (success)
100.00%
1 / 1
5
 floatDiff
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 validateDateTime
n/a
0 / 0
n/a
0 / 0
0
1<?php
2
3namespace Verja\Validator;
4
5use Verja\Error;
6use Verja\Validator;
7
8abstract class TemporaAbstract extends Validator
9{
10    /** @var \DateTime */
11    protected $dateTime;
12
13    /** @var string */
14    protected $errorKey;
15
16    /** @var string */
17    protected $errorMessage;
18
19    /**
20     * After constructor.
21     *
22     * @param \DateTime|string $dateTime
23     * @throws \InvalidArgumentException
24     */
25    public function __construct($dateTime)
26    {
27        if (!$dateTime instanceof \DateTime) {
28            if (is_string($dateTime)) {
29                $dateTime = new \DateTime($dateTime);
30            } else {
31                throw new \InvalidArgumentException('$dateTime has to be a DateTime object or time string');
32            }
33        }
34
35        $this->dateTime = $dateTime;
36    }
37
38    /**
39     * Validate $value
40     *
41     * @param mixed $value
42     * @param array $context
43     * @return bool
44     */
45    public function validate($value, array $context = []): bool
46    {
47        if (is_string($value)) {
48            try {
49                $original = $value;
50                $value = new \DateTime($value);
51            } catch (\Exception $e) {
52                // returns in false after next if
53            }
54        }
55
56        if ($value instanceof \DateTime) {
57            if ($this->validateDateTime($value)) {
58                return true;
59            }
60            $this->error = new Error(
61                $this->errorKey,
62                $original ?? $value,
63                sprintf($this->errorMessage, $this->dateTime->format('c')),
64                ['dateTime' => $this->dateTime]
65            );
66            return false;
67        }
68
69        $this->error = new Error('NO_DATE', $value, 'value should be a valid date', ['dateTime' => $this->dateTime]);
70        return false;
71    }
72
73    protected function floatDiff(\DateTime $dt1, \DateTime $dt2)
74    {
75        return (float)$dt1->format('U.u') - (float)$dt2->format('U.u');
76    }
77
78    abstract protected function validateDateTime(\DateTime $value);
79}