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

IncrementalDateFieldConstraint   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 4

Test Coverage

Coverage 34.62%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
wmc 8
c 1
b 0
f 1
lcom 0
cbo 4
dl 0
loc 58
ccs 9
cts 26
cp 0.3462
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
C checkIncrementalDate() 0 38 7
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