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 |
||
| 5 | class Writer { |
||
| 6 | |||
| 7 | public $indent = false; |
||
| 8 | |||
| 9 | 2 | View Code Duplication | public function __construct( $options = array()) |
|
|
|||
| 10 | { |
||
| 11 | 2 | $optionList = array( 'indent' ); |
|
| 12 | 2 | foreach( $options as $option => $optionValue) { |
|
| 13 | if (in_array( $option, $optionList )) { |
||
| 14 | $this->{$option} = $optionValue; |
||
| 15 | } |
||
| 16 | } |
||
| 17 | 2 | } |
|
| 18 | |||
| 19 | 1 | public function __call( $name, $args) |
|
| 23 | |||
| 24 | 1 | public static function name( $name) |
|
| 25 | { |
||
| 26 | 1 | return preg_replace( '/^[^:a-z_]*/isU', '', |
|
| 27 | 1 | preg_replace( '/[^-.0-9:a-z_]/isU', '', $name |
|
| 28 | ) ); |
||
| 29 | } |
||
| 30 | |||
| 31 | 2 | public static function value( $value) |
|
| 32 | { |
||
| 33 | 2 | if (is_array( $value )) { |
|
| 34 | $content = array_reduce( $value, function( $result, $value) |
||
| 35 | { |
||
| 36 | return $result . ' ' . self::value( $value ); |
||
| 37 | } ); |
||
| 38 | 2 | } else if (is_bool( $value )) { |
|
| 39 | $content = $value ? 'true' : 'false'; |
||
| 40 | } else { |
||
| 41 | 2 | $value = (string) $value; |
|
| 42 | 2 | if (preg_match( '/^\s*<!\[CDATA\[/', $value )) { |
|
| 43 | $content = $value; |
||
| 44 | } else { |
||
| 45 | 2 | $content = htmlspecialchars( $value, ENT_QUOTES, 'UTF-8' ); |
|
| 46 | } |
||
| 47 | } |
||
| 48 | 2 | return $content; |
|
| 49 | } |
||
| 50 | |||
| 51 | public static function attribute( $name, $value) |
||
| 61 | |||
| 62 | 1 | public static function comment( $content) |
|
| 66 | |||
| 67 | 1 | public static function cdata( $content) |
|
| 71 | |||
| 72 | 1 | public static function preamble( $version = '1.0', $encoding = null, $standalone = null) |
|
| 73 | { |
||
| 74 | 1 | if (isset($standalone)) { |
|
| 91 | } |
||
| 92 |
Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.
You can also find more detailed suggestions in the “Code” section of your repository.