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 |
||
| 8 | class Namespace_ extends Node\Stmt |
||
| 9 | { |
||
| 10 | /** @var null|Node\Name Name */ |
||
| 11 | public $name; |
||
| 12 | /** @var Node[] Statements */ |
||
| 13 | public $stmts; |
||
| 14 | |||
| 15 | protected static $specialNames = array( |
||
| 16 | 'self' => true, |
||
| 17 | 'parent' => true, |
||
| 18 | 'static' => true, |
||
| 19 | ); |
||
| 20 | |||
| 21 | /** |
||
| 22 | * Constructs a namespace node. |
||
| 23 | * |
||
| 24 | * @param null|Node\Name $name Name |
||
| 25 | * @param null|Node[] $stmts Statements |
||
| 26 | * @param array $attributes Additional attributes |
||
| 27 | */ |
||
| 28 | public function __construct(Node\Name $name = null, $stmts = array(), array $attributes = array()) { |
||
| 29 | parent::__construct($attributes); |
||
| 30 | $this->name = $name; |
||
| 31 | $this->stmts = $stmts; |
||
|
|
|||
| 32 | |||
| 33 | View Code Duplication | if (isset(self::$specialNames[strtolower($this->name)])) { |
|
| 34 | throw new Error( |
||
| 35 | sprintf('Cannot use \'%s\' as namespace name', $this->name), |
||
| 36 | $this->name->getAttributes() |
||
| 37 | ); |
||
| 38 | } |
||
| 39 | |||
| 40 | if (null !== $this->stmts) { |
||
| 41 | foreach ($this->stmts as $stmt) { |
||
| 42 | if ($stmt instanceof self) { |
||
| 43 | throw new Error('Namespace declarations cannot be nested', $stmt->getAttributes()); |
||
| 44 | } |
||
| 45 | } |
||
| 46 | } |
||
| 47 | } |
||
| 48 | |||
| 49 | public function getSubNodeNames() { |
||
| 52 | } |
||
| 53 |
Our type inference engine has found an assignment of a scalar value (like a string, an integer or null) to a property which is an array.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property.
To type hint that a parameter can be either an array or null, you can set a type hint of array and a default value of null. The PHP interpreter will then accept both an array or null for that parameter.
The function can be called with either null or an array for the parameter
$needlebut will only accept an array as$haystack.