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 |
||
| 14 | class midgard_object_class |
||
| 15 | { |
||
| 16 | 10 | private static function resolve_classname($guid, $include_deleted = false) |
|
| 17 | { |
||
| 18 | 10 | $qb = connection::get_em()->createQueryBuilder(); |
|
| 19 | 10 | $qb->from('midgard:midgard_repligard', 'r') |
|
| 20 | 10 | ->select('r.typename, r.object_action') |
|
| 21 | 10 | ->where('r.guid = ?1') |
|
| 22 | 10 | ->setParameter(1, $guid); |
|
| 23 | |||
| 24 | try { |
||
| 25 | 10 | $result = $qb->getQuery()->getSingleResult(); |
|
| 26 | 10 | } catch (\Doctrine\ORM\NoResultException $e) { |
|
| 27 | 3 | throw exception::not_exists(); |
|
| 28 | } |
||
| 29 | |||
| 30 | 10 | if ($result["object_action"] == subscriber::ACTION_PURGE) { |
|
| 31 | 2 | throw exception::object_purged(); |
|
| 32 | } |
||
| 33 | 9 | if (!$include_deleted && $result["object_action"] == subscriber::ACTION_DELETE) { |
|
| 34 | 1 | throw exception::object_deleted(); |
|
| 35 | } |
||
| 36 | 8 | if ($include_deleted && !self::has_metadata($result["typename"])) { |
|
| 37 | 1 | throw exception::invalid_property_value(); |
|
| 38 | } |
||
| 39 | |||
| 40 | 7 | return $result["typename"]; |
|
| 41 | } |
||
| 42 | |||
| 43 | 8 | public static function resolve_fqn($classname) |
|
| 48 | |||
| 49 | 5 | public static function factory($classname, $id = null) |
|
| 57 | |||
| 58 | /** |
||
| 59 | * @return boolean |
||
| 60 | */ |
||
| 61 | 4 | public static function undelete($guid) |
|
| 96 | |||
| 97 | 7 | public static function get_object_by_guid($guid) |
|
| 106 | |||
| 107 | 2 | View Code Duplication | public static function get_property_up($classname) |
| 115 | |||
| 116 | 3 | View Code Duplication | public static function get_property_parent($classname) |
| 124 | |||
| 125 | public static function connect_default($classname, $signal, $callback, $userdata = null) // <== check! |
||
| 128 | |||
| 129 | 7 | public static function has_metadata($classname) |
|
| 139 | |||
| 140 | public static function get_schema_value($classname, $node_name) |
||
| 143 | } |
||
| 144 |
Let’s assume that you have a directory layout like this:
. |-- OtherDir | |-- Bar.php | `-- Foo.php `-- SomeDir `-- Foo.phpand let’s assume the following content of
Bar.php:If both files
OtherDir/Foo.phpandSomeDir/Foo.phpare loaded in the same runtime, you will see a PHP error such as the following:PHP Fatal error: Cannot use SomeDir\Foo as Foo because the name is already in use in OtherDir/Foo.phpHowever, as
OtherDir/Foo.phpdoes not necessarily have to be loaded and the error is only triggered if it is loaded beforeOtherDir/Bar.php, this problem might go unnoticed for a while. In order to prevent this error from surfacing, you must import the namespace with a different alias: