Passed
Push — master ( 3bffb6...f32028 )
by Aleksandr
31:58
created

DateConstraint::validate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 12
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 4
eloc 6
c 1
b 0
f 0
nc 3
nop 1
dl 0
loc 12
rs 10
1
<?php
2
3
namespace Drobotik\Eav\Validation\Constraints;
4
5
use Drobotik\Eav\Interface\ConstraintInterface;
6
7
class DateConstraint implements ConstraintInterface
8
{
9
    private string $format;
10
11
    public function __construct(string $format = 'Y-m-d')
12
    {
13
        $this->format = $format;
14
    }
15
16
    public function validate($value): ?string
17
    {
18
        if (!is_string($value)) {
19
            return "This value must be a string.";
20
        }
21
22
        $dateTime = \DateTime::createFromFormat($this->format, $value);
23
        if (!$dateTime || $dateTime->format($this->format) !== $value) {
0 ignored issues
show
introduced by
$dateTime is of type DateTime, thus it always evaluated to true.
Loading history...
24
            return "This value must be a valid date in '{$this->format}' format.";
25
        }
26
27
        return null;
28
    }
29
}