Completed
Push — master ( 635f40...1b3e69 )
by Philip
02:15
created

DateTimeComparator   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 31
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 1

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 5
c 1
b 0
f 1
lcom 0
cbo 1
dl 0
loc 31
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
compare() 0 1 ?
B validate() 0 23 5
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
/**
15
 * Abstract validator to compare date times.
16
 * For the format, see:
17
 * http://php.net/manual/en/datetime.createfromformat.php
18
 */
19
abstract class DateTimeComparator extends ParametrizedValidator {
20
21
    abstract protected function compare($date, $compareDate);
22
23
    /**
24
     * {@inheritdoc}
25
     */
26
    public function validate($value, array $parameters) {
27
28
        $this->validateMinParameterCount('beforeDateTime', 1, $parameters);
29
30
        $format = 'Y-m-d H:i:s';
31
        if (count($parameters) > 1) {
32
            $format = $parameters[1];
33
        }
34
        $compareDate = \DateTime::createFromFormat($format, $parameters[0]);
35
        if ($compareDate === false) {
36
            throw new ValidationException('"beforeDateTime" expects a date of the format ' . $format . '.');
37
        }
38
39
        if (in_array($value, array('', null), true)) {
40
            return true;
41
        }
42
43
        $date = \DateTime::createFromFormat($format, $value);
44
        if ($date === false) {
45
            return false;
46
        }
47
        return $this->compare($date, $compareDate);
48
    }
49
}
50