Passed
Push — master ( 6ec87a...fbe757 )
by George
03:22
created

DatetimeValidator::formatDefault()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 20
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 5.025

Importance

Changes 2
Bugs 1 Features 0
Metric Value
c 2
b 1
f 0
dl 0
loc 20
ccs 9
cts 10
cp 0.9
rs 8.8571
cc 5
eloc 10
nc 5
nop 0
crap 5.025
1
<?php
2
namespace JsonTable\Validate\Format;
3
4
use \JsonTable\Validate\AbstractFormatValidator;
5
6
/**
7
 * Lexical datetime validator.
8
 *
9
 * @package JSON table
10
 */
11
class DatetimeValidator extends AbstractFormatValidator
12
{
13
    /**
14
     * Validate that the input is a valid ISO8601 formatted date.
15
     *
16
     * @return  boolean Whether the input is valid.
17
     */
18 10
    protected function formatDefault()
19
    {
20 10
        if (1 === preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $this->input)) {
21
            return (false !== \DateTime::createFromFormat(DATE_ISO8601, $this->input));
22
        }
23
24 10
        if ($this->formatDate('Y-m-d H:i:s')) {
25 2
            return true;
26
        }
27
28 10
        if ($this->formatDate('Y-m-d')) {
29 3
            return true;
30
        }
31
32 10
        if ($this->formatDate('H:i:s')) {
33 2
            return true;
34
        }
35
36 8
        return false;
37
    }
38
39
40
    /**
41
     * Validate that the input is a valid date in the specified format.
42
     *
43
     * @param   string   $format   The date format to validate against.
44
     *
45
     * @return  boolean            Whether the input is valid.
46
     */
47 10
    protected function formatDate($format)
48
    {
49 10
        $date = \DateTime::createFromFormat($format, $this->input);
50
51 10
        return $date && ($date->format($format) === $this->input);
52
    }
53
}
54