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 |
||
| 10 | trait ItFetchesSites |
||
| 11 | { |
||
| 12 | /** |
||
| 13 | * Fetch sites |
||
| 14 | */ |
||
| 15 | protected function fetchSites($server_id) |
||
| 16 | { |
||
| 17 | $url = config('forge-publish.url') . config('forge-publish.user_sites_uri') . '/' . $server_id; |
||
| 18 | try { |
||
| 19 | $response = $this->http->get($url, [ |
||
|
|
|||
| 20 | 'headers' => [ |
||
| 21 | 'X-Requested-With' => 'XMLHttpRequest', |
||
| 22 | 'Authorization' => 'Bearer ' . fp_env('ACACHA_FORGE_ACCESS_TOKEN') |
||
| 23 | ] |
||
| 24 | ]); |
||
| 25 | } catch (\Exception $e) { |
||
| 26 | $this->error('And error occurs connecting to the api url: ' . $url); |
||
| 27 | $this->error('Status code: ' . $e->getResponse()->getStatusCode() . ' | Reason : ' . $e->getResponse()->getReasonPhrase()); |
||
| 28 | return []; |
||
| 29 | } |
||
| 30 | return json_decode((string) $response->getBody()); |
||
| 31 | } |
||
| 32 | |||
| 33 | /** |
||
| 34 | * Get forge site from sites by name. |
||
| 35 | * |
||
| 36 | * @param $sites |
||
| 37 | * @param $site_id |
||
| 38 | * @return mixed |
||
| 39 | */ |
||
| 40 | View Code Duplication | protected function getSiteByName($sites, $site_name) |
|
| 51 | |||
| 52 | /** |
||
| 53 | * Get forge site from sites. |
||
| 54 | * |
||
| 55 | * @param $sites |
||
| 56 | * @param $site_id |
||
| 57 | * @return mixed |
||
| 58 | */ |
||
| 59 | View Code Duplication | protected function getSite($sites, $site_id) |
|
| 70 | |||
| 71 | /** |
||
| 72 | * Get forge site name from site id. |
||
| 73 | * |
||
| 74 | * @param $sites |
||
| 75 | * @param $site_id |
||
| 76 | * @return mixed |
||
| 77 | */ |
||
| 78 | protected function getSiteName($sites, $site_id) |
||
| 85 | |||
| 86 | /** |
||
| 87 | * Get forge site id from site name. |
||
| 88 | * |
||
| 89 | * @param $sites |
||
| 90 | * @param $site_name |
||
| 91 | * @return mixed |
||
| 92 | */ |
||
| 93 | protected function getSiteId($sites, $site_name) |
||
| 100 | } |
||
| 101 |
In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:
Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion: