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 |
||
| 36 | class IdRegistry { |
||
| 37 | |||
| 38 | private static $sInstance; |
||
| 39 | private $mRegistry = array(); |
||
| 40 | |||
| 41 | /** |
||
| 42 | * @return IdRegistry |
||
| 43 | */ |
||
| 44 | public static function getRegistry() { |
||
| 45 | |||
| 46 | if ( self::$sInstance === null ) { |
||
| 47 | self::$sInstance = new IdRegistry(); |
||
| 48 | } |
||
| 49 | |||
| 50 | return self::$sInstance; |
||
| 51 | |||
| 52 | } |
||
| 53 | |||
| 54 | /** |
||
| 55 | * Returns the opening tag of an HTML element in a string. |
||
| 56 | * |
||
| 57 | * The advantage over Html::openElement is that any id attribute is ensured to be unique. |
||
| 58 | * |
||
| 59 | * @param string $tag |
||
| 60 | * @param array $attributes |
||
| 61 | * |
||
| 62 | * @return string |
||
| 63 | */ |
||
| 64 | View Code Duplication | public function openElement( $tag, $attributes = array() ) { |
|
| 65 | |||
| 66 | if ( is_array( $attributes ) && isset( $attributes[ 'id' ] ) ) { |
||
| 67 | $attributes[ 'id' ] = $this->getId( $attributes[ 'id' ] ); |
||
| 68 | } |
||
| 69 | |||
| 70 | return \Html::openElement( $tag, $attributes ); |
||
| 71 | } |
||
| 72 | |||
| 73 | /** |
||
| 74 | * @param null|string $id |
||
| 75 | * @param null|mixed $component |
||
| 76 | * @return string |
||
| 77 | */ |
||
| 78 | public function getId( $id = null, $component = null ) { |
||
| 79 | |||
| 80 | if ( empty( $id ) ) { |
||
| 81 | |||
| 82 | // no specific id requested, just return a unique string |
||
| 83 | return base_convert( uniqid(), 16, 36 ); |
||
| 84 | |||
| 85 | } elseif ( array_key_exists( $id, $this->mRegistry ) ) { |
||
| 86 | |||
| 87 | // specific id requested, but already in use |
||
| 88 | // return a string derived from the id and a unique string |
||
| 89 | $key = "$id-" . base_convert( uniqid(), 16, 36 ); |
||
| 90 | $this->mRegistry[ $id ][ $key ] = $component; |
||
| 91 | return $key; |
||
| 92 | |||
| 93 | } else { |
||
| 94 | |||
| 95 | // specific id requested that is not yet in use |
||
| 96 | // return the id |
||
| 97 | $this->mRegistry[ $id ][ $id ] = $component; |
||
| 98 | return $id; |
||
| 99 | |||
| 100 | } |
||
| 101 | } |
||
| 102 | |||
| 103 | /** |
||
| 104 | * Returns an HTML element in a string. The contents are NOT escaped. |
||
| 105 | * |
||
| 106 | * The advantage over Html::rawElement is that any id attribute is ensured to be unique. |
||
| 107 | * |
||
| 108 | * @param string $tag |
||
| 109 | * @param array $attributes |
||
| 110 | * @param string $contents |
||
| 111 | * |
||
| 112 | * @return string |
||
| 113 | */ |
||
| 114 | View Code Duplication | public function element( $tag, $attributes = array(), $contents = '' ) { |
|
| 122 | } |
||
| 123 |