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 |
||
12 | class JsonInputParam extends InputParam |
||
13 | { |
||
14 | protected $type = self::TYPE_POST_JSON; |
||
15 | |||
16 | private $schema; |
||
17 | |||
18 | 9 | public function __construct(string $key, string $schema) |
|
23 | |||
24 | 3 | public function setMulti(): InputParam |
|
28 | |||
29 | 3 | public function getValue() |
|
34 | |||
35 | 3 | public function validate(): ValidationResultInterface |
|
36 | { |
||
37 | 3 | $schemaValidator = new Validator(); |
|
38 | 3 | $value = $this->getValue(); |
|
39 | 3 | if (json_last_error()) { |
|
40 | 3 | return new ValidationResult(ValidationResult::STATUS_ERROR, [json_last_error_msg()]); |
|
41 | } |
||
42 | |||
43 | 3 | if (!$value && $this->isRequired() === self::OPTIONAL) { |
|
44 | 3 | return new ValidationResult(ValidationResult::STATUS_OK); |
|
45 | } |
||
46 | |||
47 | 3 | $value = json_decode(json_encode($value)); |
|
48 | 3 | $schemaValidator->validate($value, json_decode($this->schema)); |
|
49 | |||
50 | 3 | if ($schemaValidator->isValid()) { |
|
51 | return new ValidationResult(ValidationResult::STATUS_OK); |
||
52 | } |
||
53 | |||
54 | 3 | $errors = []; |
|
55 | 3 | View Code Duplication | foreach ($schemaValidator->getErrors() as $error) { |
|
|||
56 | 3 | $errorMessage = ''; |
|
57 | 3 | if ($error['property']) { |
|
58 | $errorMessage .= '[Property ' . $error['property'] . '] '; |
||
59 | } |
||
60 | 3 | $errorMessage .= $error['message']; |
|
61 | 3 | $errors[] = $errorMessage; |
|
62 | } |
||
63 | 3 | return new ValidationResult(ValidationResult::STATUS_ERROR, $errors); |
|
64 | } |
||
65 | |||
66 | 3 | protected function addFormInput(Form $form, string $key): BaseControl |
|
76 | } |
||
77 |
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.