Passed
Push — master ( 163405...503637 )
by George
02:38
created

DatetimeValidator::formatDefault()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 23
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 5.2

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 23
ccs 8
cts 10
cp 0.8
rs 8.5906
cc 5
eloc 10
nc 5
nop 0
crap 5.2
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
     * @access  protected
17
     *
18
     * @return  boolean Whether the input is valid.
19
     */
20 1
    protected function formatDefault()
21
    {
22
        // Check if this is an ISO8601 datetime format (in the UTC timezone).
23 1
        if (true == preg_match('/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/', $this->input)) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing preg_match('/^(\\d{4})-(...{2})Z$/', $this->input) of type integer to the boolean true. If you are specifically checking for non-zero, consider using something more explicit like > 0 or !== 0 instead.
Loading history...
24
            // Check that PHP can build a date object from the input.
25
            return (false !== \DateTime::createFromFormat(DATE_ISO8601, $this->input));
26
        }
27
28 1
        if ($this->formatDate('Y-m-d H:i:s')) {
29 1
            return true;
30
        }
31
32 1
        if ($this->formatDate('Y-m-d')) {
33 1
            return true;
34
        }
35
36 1
        if ($this->formatDate('H:i:s')) {
37 1
            return true;
38
        }
39
40
        // The input didn't match any of the expected formats.
41
        return false;
42
    }
43
44
45
    /**
46
     * Validate that the input is a valid date in the specified format.
47
     *
48
     * @access  protected
49
     *
50
     * @param   string   $format   The date format to validate against.
51
     *
52
     * @return  boolean            Whether the input is valid.
53
     */
54 1
    protected function formatDate($format)
55
    {
56 1
        $date = \DateTime::createFromFormat($format, $this->input);
57
58 1
        return $date && ($date->format($format) === $this->input);
59
    }
60
}
61