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 |
||
| 5 | trait OldAndAttribute |
||
| 6 | { |
||
| 7 | public function old($name = null) |
||
| 15 | |||
| 16 | public function hasOld($name = null) |
||
| 20 | |||
| 21 | View Code Duplication | public function oldOrDefault($locale = null) |
|
| 22 | { |
||
| 23 | $name = $this->name(); |
||
| 24 | if ($locale) { |
||
| 25 | $name .= '.'. $locale; |
||
| 26 | } |
||
| 27 | |||
| 28 | if ($this->hasOld($name)) { |
||
| 29 | return $this->old($name); |
||
| 30 | } |
||
| 31 | |||
| 32 | return $this->getDefault(); |
||
| 33 | } |
||
| 34 | |||
| 35 | View Code Duplication | public function oldOrAttribute($model, $locale = null) |
|
| 36 | { |
||
| 37 | $name = $this->name(); |
||
| 38 | if ($locale) { |
||
| 39 | $name .= '.'. $locale; |
||
| 40 | } |
||
| 41 | |||
| 42 | if ($this->hasOld($name)) { |
||
| 43 | return $this->old($name); |
||
| 44 | } |
||
| 45 | |||
| 46 | return $this->getAttribute($model, $locale); |
||
| 47 | } |
||
| 48 | |||
| 49 | 1 | public function getAttribute($model, $locale = null) |
|
|
|
|||
| 50 | { |
||
| 51 | 1 | if ($locale && $this->isTranslatable()) { |
|
| 52 | return $model->getTranslation($this->name(), $locale, false); |
||
| 53 | } |
||
| 54 | |||
| 55 | 1 | return $model->{$this->name()}; |
|
| 56 | } |
||
| 57 | |||
| 58 | abstract public function getDefault(); |
||
| 61 | } |
||
| 62 |
Our type inference engine in quite powerful, but sometimes the code does not provide enough clues to go by. In these cases we request you to add a
@returnannotation as described here.