1 | <?php |
||
17 | class VersionServiceConstraint |
||
18 | { |
||
19 | |||
20 | /** DB Field name used for validation and incremental */ |
||
21 | const FIELD_NAME = 'version'; |
||
22 | |||
23 | /** Header name used to inform user */ |
||
24 | const HEADER_NAME = 'X-Current-Version'; |
||
25 | |||
26 | /** @var int */ |
||
27 | private $version; |
||
28 | |||
29 | /** |
||
30 | * @var \Symfony\Component\PropertyAccess\PropertyAccessor |
||
31 | */ |
||
32 | private $accessor; |
||
33 | |||
34 | /** |
||
35 | * ReadOnlyFieldConstraint constructor. |
||
36 | * |
||
37 | * @param ConstraintUtils $utils utils |
||
38 | */ |
||
39 | public function __construct(ConstraintUtils $utils) |
||
44 | |||
45 | /** |
||
46 | * Checks the readOnly fields and sets error in event if needed |
||
47 | * |
||
48 | * @param ConstraintEventSchema $event event class |
||
49 | * |
||
50 | * @return void |
||
51 | */ |
||
52 | public function checkVersionField(ConstraintEventSchema $event) |
||
53 | { |
||
54 | if (!$this->isVersioningService()) { |
||
55 | return; |
||
56 | } |
||
57 | |||
58 | $data = $event->getElement(); |
||
59 | |||
60 | // get the current record |
||
61 | if ($currentRecord = $this->utils->getCurrentEntity()) { |
||
62 | $userVersion = $this->getUserVersion($data); |
||
63 | $storedVersion = $this->getVersionFromObject($currentRecord); |
||
64 | if ($userVersion !== $storedVersion) { |
||
65 | $event->addError( |
||
66 | sprintf( |
||
67 | 'The value you provided does not match current version of the document. '. |
||
68 | 'See the \'%s\' header in this response to determine current version.', |
||
69 | self::HEADER_NAME |
||
70 | ), |
||
71 | self::FIELD_NAME |
||
72 | ); |
||
73 | |||
74 | // store version for response header |
||
75 | $this->version = $storedVersion; |
||
76 | } |
||
77 | } |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * tells whether the current service has versioning activated or not |
||
82 | * |
||
83 | * @return bool true if yes, false otherwise |
||
84 | */ |
||
85 | public function isVersioningService() |
||
93 | |||
94 | /** |
||
95 | * returns the version from a given object |
||
96 | * |
||
97 | * @param object $object object |
||
98 | * |
||
99 | * @return int|null null or the specified version |
||
100 | */ |
||
101 | private function getVersionFromObject($object) |
||
110 | |||
111 | /** |
||
112 | * Gets the user provided version, handling different scenarios |
||
113 | * |
||
114 | * @param object $object object |
||
115 | * |
||
116 | * @return int|null null or the specified version |
||
117 | */ |
||
118 | private function getUserVersion($object) |
||
140 | |||
141 | /** |
||
142 | * Setting if needed the headers to let user know what was the new version. |
||
143 | * |
||
144 | * @param FilterResponseEvent $event SF response event |
||
145 | * @return void |
||
146 | */ |
||
147 | public function setCurrentVersionHeader(FilterResponseEvent $event) |
||
153 | } |
||
154 |