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 | 86 | public function old($name = null) |
|
| 8 | { |
||
| 9 | 86 | if (is_null($name)) { |
|
| 10 | 17 | $name = $this->name(); |
|
| 11 | } |
||
| 12 | |||
| 13 | 86 | return old($name); |
|
| 14 | } |
||
| 15 | |||
| 16 | 69 | public function hasOld($name = null) |
|
| 17 | { |
||
| 18 | 69 | return !is_null($this->old($name)); |
|
| 19 | } |
||
| 20 | |||
| 21 | 17 | View Code Duplication | public function oldOrDefault($locale = null) |
| 22 | { |
||
| 23 | 17 | $name = $this->name(); |
|
| 24 | 17 | if ($locale) { |
|
| 25 | $name .= '.'. $locale; |
||
| 26 | } |
||
| 27 | |||
| 28 | 17 | if ($this->hasOld($name)) { |
|
| 29 | 17 | return $this->old($name); |
|
| 30 | } |
||
| 31 | |||
| 32 | 17 | return $this->getDefault(); |
|
| 33 | } |
||
| 34 | |||
| 35 | 18 | View Code Duplication | public function oldOrAttribute($model, $locale = null) |
| 36 | { |
||
| 37 | 18 | $name = $this->name(); |
|
| 38 | 18 | if ($locale) { |
|
| 39 | $name .= '.'. $locale; |
||
| 40 | } |
||
| 41 | |||
| 42 | 18 | if ($this->hasOld($name)) { |
|
| 43 | 17 | return $this->old($name); |
|
| 44 | } |
||
| 45 | |||
| 46 | 1 | return $this->getAttribute($model, $locale); |
|
| 47 | } |
||
| 48 | |||
| 49 | 35 | public function getAttribute($model, $locale = null) |
|
|
|
|||
| 50 | { |
||
| 51 | 35 | if ($locale && $this->isTranslatable()) { |
|
| 52 | return $model->getTranslation($this->name(), $locale, false); |
||
| 53 | } |
||
| 54 | |||
| 55 | 35 | 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.