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 |
||
14 | class CountryRepository |
||
15 | { |
||
16 | /** |
||
17 | * Database table name that this repository maintains. |
||
18 | * |
||
19 | * @var string |
||
20 | */ |
||
21 | const TABLE = 'countries'; |
||
22 | |||
23 | /** |
||
24 | * @var Connection |
||
25 | */ |
||
26 | private $connection; |
||
27 | |||
28 | /** |
||
29 | * CountryRepository constructor. |
||
30 | * |
||
31 | * @param Connection $connection |
||
32 | */ |
||
33 | public function __construct(Connection $connection) |
||
34 | { |
||
35 | $this->connection = $connection; |
||
36 | } |
||
37 | |||
38 | /** |
||
39 | * Fetches all countries. |
||
40 | * |
||
41 | * @return CountryEntity[] |
||
42 | */ |
||
43 | public function fetchAll() |
||
44 | { |
||
45 | $statement = $this->connection->createQueryBuilder() |
||
46 | ->select('*') |
||
47 | ->from(self::TABLE) |
||
48 | ->execute(); |
||
49 | |||
50 | $result = $statement->fetchAll(); |
||
51 | |||
52 | if ($result === false) { |
||
53 | return []; |
||
54 | } |
||
55 | |||
56 | $countries = []; |
||
57 | |||
58 | foreach ($result as $item) { |
||
59 | $countries[] = (new CountryEntity())->fromDatabaseArray($item); |
||
60 | } |
||
61 | |||
62 | return $countries; |
||
63 | } |
||
64 | |||
65 | /** |
||
66 | * Creates a country in the database. |
||
67 | * |
||
68 | * @param CountryEntity $entity |
||
69 | * |
||
70 | * @return CountryEntity |
||
71 | */ |
||
72 | public function create(CountryEntity $entity) |
||
73 | { |
||
74 | if (!$entity->isNew()) { |
||
75 | throw new InvalidArgumentException('The entity does already exist.'); |
||
76 | } |
||
77 | |||
78 | $this->connection->insert( |
||
79 | self::TABLE, |
||
80 | $entity->toDatabaseArray() |
||
81 | ); |
||
82 | |||
83 | $entity->short = $this->connection->lastInsertId(); |
||
84 | } |
||
85 | |||
86 | /** |
||
87 | * Update a country in the database. |
||
88 | * |
||
89 | * @param CountryEntity $entity |
||
90 | * |
||
91 | * @return CountryEntity |
||
92 | */ |
||
93 | View Code Duplication | public function update(CountryEntity $entity) |
|
109 | |||
110 | /** |
||
111 | * Removes a country from the database. |
||
112 | * |
||
113 | * @param CountryEntity $entity |
||
114 | * |
||
115 | * @return CountryEntity |
||
116 | */ |
||
117 | View Code Duplication | public function remove(CountryEntity $entity) |
|
133 | } |
||
134 |
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.