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 Container |
||
| 8 | extends ContainerBase |
||
|
|
|||
| 9 | { |
||
| 10 | private $resources; |
||
| 11 | |||
| 12 | private $allowed = [ |
||
| 13 | 'allowed', |
||
| 14 | 'allowedRanges', |
||
| 15 | 'allowedValues', |
||
| 16 | 'defaults', |
||
| 17 | 'mandatory', |
||
| 18 | 'rules', |
||
| 19 | ]; |
||
| 20 | |||
| 21 | public function __construct(array $resources) |
||
| 22 | { |
||
| 23 | if (!isset($resources['resources'])) { |
||
| 24 | throw new RuntimeException( |
||
| 25 | 'resources element is not defined' |
||
| 26 | ); |
||
| 27 | } |
||
| 28 | |||
| 29 | $this->rewrites = []; |
||
| 30 | $this->globals = []; |
||
| 31 | |||
| 32 | $this->ensureValidConstraints($resources); |
||
| 33 | |||
| 34 | foreach ($resources['resources'] as $item) { |
||
| 35 | if (isset($item['rewrite'])) { |
||
| 36 | foreach ($item['rewrite'] as $field => $rewriteRule) { |
||
| 37 | $this->rewrites[$field] = $rewriteRule; |
||
| 38 | } |
||
| 39 | } |
||
| 40 | } |
||
| 41 | |||
| 42 | if (isset($resources['globals'])) { |
||
| 43 | $this->globals = $resources['globals']; |
||
| 44 | } |
||
| 45 | |||
| 46 | $this->resources = $resources; |
||
| 47 | } |
||
| 48 | |||
| 49 | private function ensureValidConstraints($resources) |
||
| 50 | { |
||
| 51 | foreach ($resources['resources'] as $item) { |
||
| 52 | if (isset($item['constraints'])) { |
||
| 53 | foreach ($item['constraints'] as $name => $value) { |
||
| 54 | if (!in_array($name, $this->allowed)) { |
||
| 55 | throw new RuntimeException( |
||
| 56 | 'Invalid constraint: ' |
||
| 57 | . 'name ' . $name |
||
| 58 | . '; value ' . $value |
||
| 59 | ); |
||
| 60 | } |
||
| 61 | } |
||
| 62 | } |
||
| 63 | } |
||
| 64 | } |
||
| 65 | |||
| 66 | public function countResources() |
||
| 72 | |||
| 73 | public function create($resource, array $constraints) |
||
| 89 | |||
| 90 | public function allowed($resource) |
||
| 105 | |||
| 106 | public function getConstraints( |
||
| 116 | |||
| 117 | public function rewrites() |
||
| 121 | |||
| 122 | public function globals() |
||
| 126 | } |
||
| 127 |