Completed
Push — master ( e436fa...d7d537 )
by Philip
02:17
created

DateTimeComparator::validate()   B

Complexity

Conditions 5
Paths 7

Size

Total Lines 26
Code Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 4
Bugs 0 Features 3
Metric Value
c 4
b 0
f 3
dl 0
loc 26
rs 8.439
cc 5
eloc 15
nc 7
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
     * Holds the amount of parameters.
25
     */
26
    protected $amountOfParameters = 1;
27
28
    /**
29
     * Holds the type of the validator.
30
     */
31
    protected $type;
32
33
    /**
34
     * Compares two dates.
35
     *
36
     * @param \DateTime $date
37
     * the first date to compare
38
     * @param \DateTime[] $compareDates
39
     * the second date to compare
40
     *
41
     * @return boolean
42
     * true if the dates compare
43
     */
44
    abstract protected function compare($date, array $compareDates);
45
46
    /**
47
     * Gets a date time format from the parameters if given or a default one.
48
     *
49
     * @param string[] $parameters
50
     * the parameters
51
     *
52
     * @return string
53
     * the date time format
54
     */
55
    protected function getDateTimeFormat($parameters) {
56
        $format = 'Y-m-d H:i:s';
57
        if (count($parameters) > $this->amountOfParameters) {
58
            $format = $parameters[$this->amountOfParameters];
59
        }
60
        return $format;
61
    }
62
63
    /**
64
     * {@inheritdoc}
65
     */
66
    public function validate($value, array $parameters) {
67
68
        $this->validateMinParameterCount($this->type, $this->amountOfParameters, $parameters);
69
70
        $format = $this->getDateTimeFormat($parameters);
71
72
        $compareDates = array();
73
        for ($i = 0; $i < $this->amountOfParameters; ++$i) {
74
            $compareDate = \DateTime::createFromFormat($format, $parameters[0]);
75
            if ($compareDate === false) {
76
                throw new ValidationException('"' . $this->type . '" expects a date of the format "' . $format . '".');
77
            }
78
            $compareDates[] = $compareDate;
79
        }
80
81
82
        if (in_array($value, array('', null), true)) {
83
            return true;
84
        }
85
86
        $date = \DateTime::createFromFormat($format, $value);
87
        if ($date === false) {
88
            return false;
89
        }
90
        return $this->compare($date, $compareDates);
91
    }
92
}
93