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 |
||
11 | class CEscaper |
||
12 | { |
||
13 | private $CHARSET; |
||
14 | |||
15 | 9 | public function __construct($encoding = 'UTF-8') { |
|
22 | |||
23 | /** Sets the used charset for the esacpeHTML and escapeXML function. |
||
24 | * |
||
25 | * @param $value, the string/value to escape. |
||
26 | * |
||
27 | */ |
||
28 | 1 | public function setEncoding($value) { |
|
32 | |||
33 | /** Returns the used charset for the esacpeHTML and escapeXML function. |
||
34 | * |
||
35 | * @return the current charset as a string. |
||
36 | */ |
||
37 | 2 | public function getEncoding() { |
|
40 | |||
41 | /** Escapes HTML string using htmlspecialchars(). |
||
42 | * |
||
43 | * @param $string, the untrusted string to escape. |
||
44 | * |
||
45 | * @return $result, escaped string. |
||
46 | */ |
||
47 | 2 | public function escapeHTML($value) { |
|
53 | |||
54 | /** Escapes non-alphanumeric characters in an untrusted string for HTML attribute values. |
||
55 | * |
||
56 | * @param $string, the untrusted string to escape. |
||
57 | * |
||
58 | * @return $result, escaped string. |
||
59 | */ |
||
60 | 2 | View Code Duplication | public function escapeHTMLattr($value) { |
67 | |||
68 | /** Escapes non-alphanumeric characters in an untrusted string for JS input values. |
||
69 | * |
||
70 | * @param $string, the untrusted string to escape. |
||
71 | * |
||
72 | * @return $result, escaped string. |
||
73 | */ |
||
74 | 1 | View Code Duplication | public function escapeJs($value) { |
82 | |||
83 | /** Escapes non-alphanumeric characters in an untrusted string for CSS input values. |
||
84 | * |
||
85 | * @param $string, the untrusted string to escape. |
||
86 | * |
||
87 | * @return $result, escaped string. |
||
88 | */ |
||
89 | View Code Duplication | public function escapeCSS($value) { |
|
97 | |||
98 | /** Escapes data that is to be inserted in a URL not the whole URL itself. |
||
99 | * |
||
100 | * @param $string, the untrusted string to escape. |
||
101 | * |
||
102 | * @return, escaped string. |
||
103 | */ |
||
104 | 1 | public function escapeUrl($value) { |
|
107 | |||
108 | /** |
||
109 | * Aliases to HTML functions for semantic value. |
||
110 | * XML escaping is identical to HTML escaping. |
||
111 | */ |
||
112 | 1 | public function escapeXml($value) { |
|
115 | |||
116 | 1 | public function escapeXmlAttr($value) { |
|
119 | } |
||
120 |
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: