DateTime::isValid()   B
last analyzed

Complexity

Conditions 8
Paths 7

Size

Total Lines 32
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 8
eloc 18
c 2
b 0
f 0
nc 7
nop 1
dl 0
loc 32
rs 8.4444
1
<?php
2
3
namespace Kontrolio\Rules\Core;
4
5
use DateTime as PhpDateTime;
6
use Kontrolio\Rules\AbstractRule;
7
8
/**
9
 * Date and time validation rule.
10
 *
11
 * @package Kontrolio\Rules\Core
12
 */
13
class DateTime extends AbstractRule
14
{
15
    const PATTERN = '/^(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})$/';
16
    const FORMAT = 'Y-m-d H:i:s';
17
18
    /**
19
     * Validates input.
20
     *
21
     * @param mixed $input
22
     *
23
     * @return bool
24
     */
25
    public function isValid($input = null)
26
    {
27
        if ($input === null || $input === '') {
28
            return false;
29
        }
30
31
        $input = (string) $input;
32
33
        PhpDateTime::createFromFormat(static::FORMAT, $input);
34
        $errors = PhpDateTime::getLastErrors();
35
36
        if ($errors === false) {
37
            return true;
38
        }
39
40
        if ($errors['error_count'] > 0) {
41
            $this->violations[] = 'format';
42
43
            return false;
44
        }
45
46
        foreach ($errors['warnings'] as $warning) {
47
            if ($warning === 'The parsed date was invalid') {
48
                $this->violations[] = 'date';
49
            } elseif ($warning === 'The parsed time was invalid') {
50
                $this->violations[] = 'time';
51
            } else {
52
                $this->violations[] = 'format';
53
            }
54
        }
55
56
        return !$this->hasViolations();
57
    }
58
}
59