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 | 87 | public function old($name = null) |
|
| 8 | { |
||
| 9 | 87 | if (is_null($name)) { |
|
| 10 | 19 | $name = $this->name(); |
|
| 11 | 19 | if ($this->belongsToArray()) { |
|
| 12 | 3 | $name = $this->getDotPatternName(); |
|
| 13 | } |
||
| 14 | } |
||
| 15 | |||
| 16 | 87 | return old($name); |
|
| 17 | } |
||
| 18 | |||
| 19 | 70 | public function hasOld($name = null) |
|
| 20 | { |
||
| 21 | 70 | return !is_null($this->old($name)); |
|
| 22 | } |
||
| 23 | |||
| 24 | 17 | View Code Duplication | public function oldOrDefault($locale = null) |
| 25 | { |
||
| 26 | 17 | $name = $this->name(); |
|
| 27 | 17 | if ($locale) { |
|
| 28 | $name .= '.'. $locale; |
||
| 29 | } |
||
| 30 | |||
| 31 | 17 | if ($this->belongsToArray()) { |
|
| 32 | 1 | $name = $this->getDotPatternName(); |
|
| 33 | } |
||
| 34 | |||
| 35 | 17 | if ($this->hasOld($name)) { |
|
| 36 | 17 | return $this->old($name); |
|
| 37 | } |
||
| 38 | |||
| 39 | 17 | return $this->getDefault(); |
|
| 40 | } |
||
| 41 | |||
| 42 | 19 | View Code Duplication | public function oldOrAttribute($model, $locale = null) |
| 43 | { |
||
| 44 | 19 | $name = $this->name(); |
|
| 45 | 19 | if ($locale) { |
|
| 46 | $name .= '.'. $locale; |
||
| 47 | } |
||
| 48 | |||
| 49 | 19 | if ($this->belongsToArray()) { |
|
| 50 | 2 | $name = $this->getDotPatternName(); |
|
| 51 | } |
||
| 52 | |||
| 53 | 19 | if ($this->hasOld($name)) { |
|
| 54 | 17 | return $this->old($name); |
|
| 55 | } |
||
| 56 | |||
| 57 | 2 | return $this->getAttribute($model, $locale); |
|
| 58 | } |
||
| 59 | |||
| 60 | 35 | public function getAttribute($model, $locale = null) |
|
|
|
|||
| 61 | { |
||
| 62 | 35 | if ($locale && $this->isTranslatable()) { |
|
| 63 | return $model->getTranslation($this->name(), $locale, false); |
||
| 64 | } |
||
| 65 | |||
| 66 | 35 | if ($this->belongsToArray()) { |
|
| 67 | 2 | $values = $model->{$this->getAncestorName()}; |
|
| 68 | 2 | return $values[$this->getDescendantName()] ?? null; |
|
| 69 | } |
||
| 70 | |||
| 71 | 33 | return $model->{$this->name()}; |
|
| 72 | } |
||
| 73 | |||
| 74 | abstract public function getDefault(); |
||
| 81 | } |
||
| 82 |
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.