Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
1 | <?php |
||
17 | class VersionFieldConstraint |
||
18 | { |
||
19 | /** DB Field name used for validation and incremental */ |
||
20 | const FIELD_NAME = 'version'; |
||
21 | |||
22 | /** Header name used to inform user */ |
||
23 | const HEADER_NAME = 'X-Current-Version'; |
||
24 | |||
25 | /** @var ConstraintUtils */ |
||
26 | private $utils; |
||
27 | |||
28 | /** @var Integer */ |
||
29 | private $version; |
||
30 | |||
31 | /** |
||
32 | * Constructor |
||
33 | * |
||
34 | * @param ConstraintUtils $utils Utils |
||
35 | */ |
||
36 | public function __construct(ConstraintUtils $utils) |
||
40 | |||
41 | /** |
||
42 | * Check if the version is correct: versioning |
||
43 | * -> Post, even if posted it should be version 1 |
||
44 | * -> Put, should be the same value. Reject if not. |
||
45 | * -> Patch, no check, only increment |
||
46 | * |
||
47 | * Default, if object have version as integer , increment 1. |
||
48 | * |
||
49 | * @param ConstraintEventFormat $event event class |
||
50 | * |
||
51 | * @return void |
||
52 | */ |
||
53 | public function validate(ConstraintEventFormat $event) |
||
54 | { |
||
55 | $schema = $event->getSchema(); |
||
56 | |||
57 | View Code Duplication | if (!isset($schema->{'x-constraints'}) || |
|
|
|||
58 | (is_array($schema->{'x-constraints'}) && !in_array('versioning', $schema->{'x-constraints'})) |
||
59 | ) { |
||
60 | return; |
||
61 | } |
||
62 | |||
63 | // get the current recor |
||
64 | if ($currentRecord = $this->utils->getCurrentEntity()) { |
||
65 | $formVersion = $event->getElement(); |
||
66 | /** @var \JsonSchema\Entity\JsonPointer $pointer */ |
||
67 | $pointer = $event->getPath(); |
||
68 | $accessor = PropertyAccess::createPropertyAccessor(); |
||
69 | $path = $this->utils->getNormalizedPathFromPointer($pointer); |
||
70 | $storedVersion = $accessor->getValue($currentRecord, $path); |
||
71 | if ($storedVersion !== $formVersion) { |
||
72 | $this->version = $storedVersion; |
||
73 | $event->addError('The version does not match, please update your data.'); |
||
74 | return; |
||
75 | } |
||
76 | } |
||
77 | return; |
||
78 | } |
||
79 | |||
80 | /** |
||
81 | * Setting if needed the headers to let user know what was the new version. |
||
82 | * |
||
83 | * @param FilterResponseEvent $event SF response event |
||
84 | * @return void |
||
85 | */ |
||
86 | public function setCurrentVersionHeader(FilterResponseEvent $event) |
||
92 | } |
||
93 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.