Completed
Push — master ( 38deb0...7544ac )
by Anton
11s
created

DateRule::validate()   B

Complexity

Conditions 5
Paths 5

Size

Total Lines 15
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 10
CRAP Score 5

Importance

Changes 0
Metric Value
cc 5
eloc 10
nc 5
nop 1
dl 0
loc 15
ccs 10
cts 10
cp 1
crap 5
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * Bluz Framework Component
4
 *
5
 * @copyright Bluz PHP Team
6
 * @link      https://github.com/bluzphp/framework
7
 */
8
9
declare(strict_types=1);
10
11
namespace Bluz\Validator\Rule;
12
13
use DateTime;
14
15
/**
16
 * Check for date
17
 *
18
 * @package Bluz\Validator\Rule
19
 */
20
class DateRule extends AbstractRule
21
{
22
    /**
23
     * @var string date format
24
     */
25
    protected $format = null;
26
27
    /**
28
     * Setup validation rule
29
     *
30
     * @param string $format
31
     */
32 8
    public function __construct($format = null)
33
    {
34 8
        $this->format = $format;
35 8
    }
36
37
    /**
38
     * Check input data
39
     *
40
     * @param  mixed $input
41
     *
42
     * @return bool
43
     */
44 8
    public function validate($input): bool
45
    {
46 8
        if ($input instanceof DateTime) {
47 1
            return true;
48 7
        } elseif (!is_string($input)) {
49 1
            return false;
50 6
        } elseif (is_null($this->format)) {
51 2
            return false !== strtotime($input);
52
        }
53
54 4
        $dateFromFormat = DateTime::createFromFormat($this->format, $input);
55
56 4
        return $dateFromFormat
57 4
            && $input === date($this->format, $dateFromFormat->getTimestamp());
58
    }
59
60
    /**
61
     * Get error template
62
     *
63
     * @return string
64
     */
65 6
    public function getDescription() : string
66
    {
67 6
        if ($this->format) {
68 5
            return __('must be a valid date. Sample format: "%s"', $this->format);
69
        }
70 1
        return __('must be a valid date');
71
    }
72
}
73