Completed
Push — master ( 259f58...54272f )
by Philip
02:08
created

DateTimeComparator::validate()   A

Complexity

Conditions 4
Paths 4

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 1
Metric Value
c 2
b 0
f 1
dl 0
loc 20
rs 9.2
nc 4
cc 4
eloc 12
nop 2
1
<?php
2
3
/*
4
 * This file is part of the Valdi package.
5
 *
6
 * (c) Philip Lehmann-Böhm <[email protected]>
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 Valdi\Validator;
13
14
use Valdi\ValidationException;
15
16
/**
17
 * Abstract validator to compare date times.
18
 * For the format, see:
19
 * http://php.net/manual/en/datetime.createfromformat.php
20
 */
21
abstract class DateTimeComparator extends ParametrizedValidator {
22
23
    /**
24
     * Compares two dates.
25
     *
26
     * @param \DateTime $date
27
     * the first date to compare
28
     * @param \DateTime $compareDate
29
     * the second date to compare
30
     *
31
     * @return boolean
32
     * true if the dates compare
33
     */
34
    abstract protected function compare($date, $compareDate);
35
36
    /**
37
     * Gets a date time format from the parameters if given or a default one.
38
     *
39
     * @param string[] $parameters
40
     * the parameters
41
     *
42
     * @return string
43
     * the date time format
44
     */
45
    protected function getDateTimeFormat($parameters) {
46
        $format = 'Y-m-d H:i:s';
47
        if (count($parameters) > 1) {
48
            $format = $parameters[1];
49
        }
50
        return $format;
51
    }
52
53
    /**
54
     * {@inheritdoc}
55
     */
56
    public function validate($value, array $parameters) {
57
58
        $this->validateMinParameterCount('beforeDateTime', 1, $parameters);
59
60
        $format = $this->getDateTimeFormat($parameters);
61
        $compareDate = \DateTime::createFromFormat($format, $parameters[0]);
62
        if ($compareDate === false) {
63
            throw new ValidationException('"beforeDateTime" expects a date of the format ' . $format . '.');
64
        }
65
66
        if (in_array($value, array('', null), true)) {
67
            return true;
68
        }
69
70
        $date = \DateTime::createFromFormat($format, $value);
71
        if ($date === false) {
72
            return false;
73
        }
74
        return $this->compare($date, $compareDate);
75
    }
76
}
77