Completed
Push — master ( f6198e...300d99 )
by Paweł
53:20
created

ContainsValidDateValidator::validate()   A

Complexity

Conditions 4
Paths 3

Size

Total Lines 11
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 11
rs 9.2
c 0
b 0
f 0
cc 4
eloc 7
nc 3
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Superdesk Web Publisher Content List Bundle.
7
 *
8
 * Copyright 2017 Sourcefabric z.ú. and contributors.
9
 *
10
 * For the full copyright and license information, please see the
11
 * AUTHORS and LICENSE files distributed with this source code.
12
 *
13
 * @copyright 2017 Sourcefabric z.ú
14
 * @license http://www.superdesk.org/license
15
 */
16
17
namespace SWP\Bundle\ContentListBundle\Validator\Constraints;
18
19
use Symfony\Component\Validator\Constraint;
20
use Symfony\Component\Validator\ConstraintValidator;
21
22
final class ContainsValidDateValidator extends ConstraintValidator
23
{
24
    /**
25
     * @var array
26
     */
27
    private $dateFilters = ['publishedAt', 'publishedBefore', 'publishedAfter'];
28
29
    /**
30
     * {@inheritdoc}
31
     */
32
    public function validate($value, Constraint $constraint)
33
    {
34
        foreach ($this->dateFilters as $filter) {
35
            if (isset($value[$filter]) && !$this->isValidDate($value[$filter])) {
36
                $this->context->buildViolation($constraint->message)
37
                    ->setParameter('%value%', $filter)
38
                    ->setParameter('%date%', $value[$filter])
39
                    ->addViolation();
40
            }
41
        }
42
    }
43
44
    private function isValidDate(string $date)
45
    {
46
        if (preg_match('/^[0-9]{4}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])$/', $date)) {
47
            $dateTime = \DateTime::createFromFormat('Y-m-d', $date);
48
49
            if ($dateTime && $dateTime->format('Y-m-d') === $date) {
50
                return true;
51
            }
52
        }
53
54
        return false;
55
    }
56
}
57