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 | 5 | public function find($ident) |
|
|
|
|||
| 12 | { |
||
| 13 | /** @var AbstractAction $action */ |
||
| 14 | 5 | foreach ($this->actions as $action) { |
|
| 15 | 5 | if ($action->identifier() == $ident) { |
|
| 16 | 5 | return $action; |
|
| 17 | } |
||
| 18 | } |
||
| 19 | return null; |
||
| 20 | } |
||
| 21 | |||
| 22 | View Code Duplication | public function getRowActions(): array |
|
| 34 | |||
| 35 | View Code Duplication | public function remove($ident) |
|
| 47 | |||
| 48 | 17 | public function add($actions) |
|
| 49 | { |
||
| 50 | 17 | $actions = is_array($actions) ? $actions : [$actions]; |
|
| 51 | 17 | foreach ($actions as $action) { |
|
| 52 | 17 | $this->addAction($action); |
|
| 53 | } |
||
| 54 | 17 | } |
|
| 55 | |||
| 56 | 17 | private function addAction(AbstractAction $action) |
|
| 57 | { |
||
| 58 | 17 | $this->actions[] = $action; |
|
| 59 | 17 | } |
|
| 60 | |||
| 61 | 17 | public function set(array $actions = []) |
|
| 62 | { |
||
| 63 | 17 | $this->actions = []; |
|
| 64 | 17 | $this->add($actions); |
|
| 65 | 17 | } |
|
| 66 | |||
| 67 | 5 | public function isAllowed($ident, $model = null): bool |
|
| 68 | { |
||
| 69 | 5 | $action = $this->find($ident); |
|
| 70 | 5 | if (!$action) { |
|
| 71 | return false; |
||
| 72 | } |
||
| 73 | |||
| 74 | 5 | return $action->isAllowed($model); |
|
| 75 | } |
||
| 76 | |||
| 77 | public function shouldRender($ident, $model = null): bool |
||
| 86 | |||
| 87 | View Code Duplication | public function moveAfter($baseActionIdent, $movableActionIdent) |
|
| 104 | |||
| 105 | View Code Duplication | public function moveBefore($baseActionIdent, $movableActionIdent) |
|
| 122 | |||
| 123 | 13 | public function setCrud(CRUD $crud) |
|
| 124 | { |
||
| 125 | /** @var AbstractAction $action */ |
||
| 126 | 13 | foreach ($this->actions as $action) { |
|
| 127 | 13 | $action->setCrud($crud); |
|
| 130 | } |
||
| 131 |
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.