DateRule::getDescription()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 6
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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