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 |
||
27 | class Serializer implements SerializerInterface |
||
28 | { |
||
29 | /** |
||
30 | * @var NavigatorInterface |
||
31 | */ |
||
32 | private $navigator; |
||
33 | |||
34 | /** |
||
35 | * @var VisitorRegistryInterface |
||
36 | */ |
||
37 | private $visitorRegistry; |
||
38 | |||
39 | /** |
||
40 | * @var TypeParserInterface |
||
41 | */ |
||
42 | private $typeParser; |
||
43 | |||
44 | /** |
||
45 | * @param NavigatorInterface|null $navigator |
||
46 | * @param VisitorRegistryInterface|null $visitorRegistry |
||
47 | * @param TypeParserInterface|null $typeParser |
||
48 | */ |
||
49 | 1492 | public function __construct( |
|
58 | |||
59 | /** |
||
60 | * {@inheritdoc} |
||
61 | */ |
||
62 | 888 | public function serialize($data, $format, ContextInterface $context = null) |
|
63 | { |
||
64 | 888 | return $this->navigate($data, Direction::SERIALIZATION, $format, $context); |
|
65 | } |
||
66 | |||
67 | /** |
||
68 | * {@inheritdoc} |
||
69 | */ |
||
70 | 606 | public function deserialize($data, $type, $format, ContextInterface $context = null) |
|
71 | { |
||
72 | 606 | if (is_string($type)) { |
|
73 | 590 | $type = $this->typeParser->parse($type); |
|
74 | 296 | } |
|
75 | |||
76 | 606 | View Code Duplication | if (!$type instanceof TypeMetadataInterface) { |
|
|||
77 | 20 | throw new \InvalidArgumentException(sprintf( |
|
78 | 16 | 'The type must be a string or a "%s", got "%s".', |
|
79 | 16 | TypeMetadataInterface::class, |
|
80 | 18 | is_object($type) ? get_class($type) : gettype($type) |
|
81 | 10 | )); |
|
82 | 2 | } |
|
83 | |||
84 | 588 | return $this->navigate($data, Direction::DESERIALIZATION, $format, $context, $type); |
|
85 | } |
||
86 | |||
87 | /** |
||
88 | * @param mixed $data |
||
89 | * @param int $direction |
||
90 | * @param string $format |
||
91 | * @param ContextInterface|null $context |
||
92 | * @param TypeMetadataInterface|null $type |
||
93 | * |
||
94 | * @return mixed |
||
95 | */ |
||
96 | 1476 | private function navigate( |
|
111 | } |
||
112 |
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.