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 |
||
| 7 | class ActionsContainer |
||
| 8 | { |
||
| 9 | private $actions = []; |
||
| 10 | |||
| 11 | 27 | public function find($ident) |
|
|
|
|||
| 12 | { |
||
| 13 | /** @var AbstractAction $action */ |
||
| 14 | 27 | foreach ($this->actions as $action) { |
|
| 15 | 27 | if ($action->identifier() == $ident) { |
|
| 16 | 27 | return $action; |
|
| 17 | } |
||
| 18 | } |
||
| 19 | 10 | return null; |
|
| 20 | } |
||
| 21 | |||
| 22 | 2 | public function getRowActions(): array |
|
| 23 | { |
||
| 24 | 2 | $actions = []; |
|
| 25 | /** @var AbstractAction $action */ |
||
| 26 | 2 | foreach ($this->actions as $action) { |
|
| 27 | 2 | if ($action->identifier() != 'create') { |
|
| 28 | 2 | $actions[] = $action; |
|
| 29 | } |
||
| 30 | } |
||
| 31 | |||
| 32 | 2 | return $actions; |
|
| 33 | } |
||
| 34 | |||
| 35 | 1 | public function remove($ident) |
|
| 36 | { |
||
| 37 | 1 | $actions = []; |
|
| 38 | /** @var AbstractAction $action */ |
||
| 39 | 1 | foreach ($this->actions as $action) { |
|
| 40 | 1 | if ($action->identifier() != $ident) { |
|
| 41 | 1 | $actions[] = $action; |
|
| 42 | } |
||
| 43 | } |
||
| 44 | |||
| 45 | 1 | $this->actions = $actions; |
|
| 46 | 1 | } |
|
| 47 | |||
| 48 | 54 | public function add($actions) |
|
| 55 | |||
| 56 | 54 | private function addAction(AbstractAction $action) |
|
| 60 | |||
| 61 | 54 | public function set(array $actions = []) |
|
| 66 | |||
| 67 | 16 | public function isAllowed($ident, $model = null): bool |
|
| 68 | { |
||
| 69 | 16 | $action = $this->find($ident); |
|
| 76 | |||
| 77 | 1 | public function shouldRender($ident, $model = null): bool |
|
| 86 | |||
| 87 | 4 | View Code Duplication | public function moveAfter($baseActionIdent, $movableActionIdent) |
| 110 | |||
| 111 | 4 | View Code Duplication | public function moveBefore($baseActionIdent, $movableActionIdent) |
| 134 | |||
| 135 | 34 | public function setCrud(CRUD $crud) |
|
| 142 | } |
||
| 143 |
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.