Completed
Push — feature/EVO-5751-text-index-mo... ( 0ab3ac...8fecb1 )
by
unknown
62:16 queued 57:01
created

checkIncrementalDate()   C

Complexity

Conditions 7
Paths 5

Size

Total Lines 38
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 6
CRAP Score 26.7836

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 38
ccs 6
cts 23
cp 0.2609
rs 6.7272
cc 7
eloc 19
nc 5
nop 1
crap 26.7836
1
<?php
2
/**
3
 * Field constraint that validates if the posted date is greater than the one saved in the database.
4
 */
5
6
namespace Graviton\SchemaBundle\Constraint;
7
8
use Graviton\JsonSchemaBundle\Validator\Constraint\Event\ConstraintEventFormat;
9
use JsonSchema\Rfc3339;
10
use Symfony\Component\PropertyAccess\PropertyAccess;
11
12
/**
13
 * @author   List of contributors <https://github.com/libgraviton/graviton/graphs/contributors>
14
 * @license  http://opensource.org/licenses/gpl-license.php GNU Public License
15
 * @link     http://swisscom.ch
16
 */
17
class IncrementalDateFieldConstraint
18
{
19
    /**
20
     * Constructor
21
     *
22
     * @param ConstraintUtils $utils Utils
23
     */
24 4
    public function __construct(ConstraintUtils $utils)
25
    {
26 4
        $this->utils = $utils;
27 4
    }
28
29
    /**
30
     * Checks the readOnly fields and sets error in event if needed
31
     *
32
     * @param ConstraintEventFormat $event event class
33
     *
34
     * @return void
35
     */
36 4
    public function checkIncrementalDate(ConstraintEventFormat $event)
37
    {
38 4
        $schema = $event->getSchema();
39
40 4
        if (!isset($schema->{'x-constraints'}) ||
41 2
            (is_array($schema->{'x-constraints'}) && !in_array('incrementalDate', $schema->{'x-constraints'}))
42 2
        ) {
43 4
            return;
44
        }
45
46
        // get the current record
47
        $currentRecord = $this->utils->getCurrentEntity();
48
49
        if (is_null($currentRecord)) {
50
            return;
51
        }
52
53
        $data = $event->getElement();
54
        $path = $event->getPath();
55
56
        // get the current value in database
57
        $accessor = PropertyAccess::createPropertyAccessor();
58
59
        if (!$accessor->isReadable($currentRecord, $path)) {
60
            // value is not saved in db..
61
            return;
62
        }
63
64
        $storedValue = $accessor->getValue($currentRecord, $path);
65
        $storedDate = Rfc3339::createFromString($storedValue);
66
        $userDate = Rfc3339::createFromString($data);
67
68
        if ($userDate <= $storedDate) {
69
            $event->addError(
70
                sprintf('The date must be greater than the saved date %s', $storedValue)
71
            );
72
        }
73
    }
74
}
75