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 InputParam implements ParamInterface |
||
| 8 | { |
||
| 9 | const TYPE_POST = 'POST'; |
||
| 10 | const TYPE_GET = 'GET'; |
||
| 11 | const TYPE_FILE = 'FILE'; |
||
| 12 | |||
| 13 | const OPTIONAL = false; |
||
| 14 | const REQUIRED = true; |
||
| 15 | |||
| 16 | /** |
||
| 17 | * @var string |
||
| 18 | */ |
||
| 19 | private $type; |
||
| 20 | |||
| 21 | /** |
||
| 22 | * @var string |
||
| 23 | */ |
||
| 24 | private $key; |
||
| 25 | |||
| 26 | /** |
||
| 27 | * @var bool |
||
| 28 | */ |
||
| 29 | private $required; |
||
| 30 | |||
| 31 | /** |
||
| 32 | * @var array|null |
||
| 33 | */ |
||
| 34 | private $availableValues; |
||
| 35 | |||
| 36 | /** |
||
| 37 | * @var bool |
||
| 38 | */ |
||
| 39 | private $multi; |
||
| 40 | |||
| 41 | 33 | public function __construct($type, $key, $required = self::OPTIONAL, $availableValues = null, $multi = false) |
|
| 42 | { |
||
| 43 | 33 | $this->type = $type; |
|
| 44 | 33 | $this->key = $key; |
|
| 45 | 33 | $this->required = $required; |
|
| 46 | 33 | $this->availableValues = $availableValues; |
|
| 47 | 33 | $this->multi = $multi; |
|
| 48 | 33 | } |
|
| 49 | |||
| 50 | /** |
||
| 51 | * @return string |
||
| 52 | */ |
||
| 53 | 9 | public function getType() |
|
| 57 | |||
| 58 | /** |
||
| 59 | * @return string |
||
| 60 | */ |
||
| 61 | 18 | public function getKey() |
|
| 65 | |||
| 66 | /** |
||
| 67 | * @return boolean |
||
| 68 | */ |
||
| 69 | 6 | public function isRequired() |
|
| 73 | |||
| 74 | 6 | public function getAvailableValues() |
|
| 78 | |||
| 79 | /** |
||
| 80 | * @return bool |
||
| 81 | */ |
||
| 82 | 12 | public function isMulti() |
|
| 86 | |||
| 87 | /** |
||
| 88 | * Check if actual value from environment is valid |
||
| 89 | * |
||
| 90 | * @return bool |
||
| 91 | * |
||
| 92 | * @throws Exception if actual InputParam has unsupported type |
||
| 93 | */ |
||
| 94 | 12 | public function isValid() |
|
| 113 | |||
| 114 | /** |
||
| 115 | * Process environment variables like POST|GET|etc.. and return actual value |
||
| 116 | * |
||
| 117 | * @return mixed |
||
| 118 | * |
||
| 119 | * @throws Exception if actual InputParam has unsupported type |
||
| 120 | */ |
||
| 121 | 24 | public function getValue() |
|
| 149 | } |
||
| 150 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: