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 |
||
24 | class JsonDecoder |
||
25 | { |
||
26 | /** |
||
27 | * Decode a JSON value as PHP object. |
||
28 | */ |
||
29 | const OBJECT = 0; |
||
30 | |||
31 | /** |
||
32 | * Decode a JSON value as associative array. |
||
33 | */ |
||
34 | const ASSOC_ARRAY = 1; |
||
35 | |||
36 | /** |
||
37 | * Decode a JSON value as float. |
||
38 | */ |
||
39 | const FLOAT = 2; |
||
40 | |||
41 | /** |
||
42 | * Decode a JSON value as string. |
||
43 | */ |
||
44 | const STRING = 3; |
||
45 | |||
46 | /** |
||
47 | * @var JsonValidator |
||
48 | */ |
||
49 | private $validator; |
||
50 | |||
51 | /** |
||
52 | * @var int |
||
53 | */ |
||
54 | private $objectDecoding = self::OBJECT; |
||
55 | |||
56 | /** |
||
57 | * @var int |
||
58 | */ |
||
59 | private $bigIntDecoding = self::FLOAT; |
||
60 | |||
61 | /** |
||
62 | * @var int |
||
63 | */ |
||
64 | private $maxDepth = 512; |
||
65 | |||
66 | /** |
||
67 | * Creates a new decoder. |
||
68 | * |
||
69 | 34 | * @param null|JsonValidator $validator |
|
70 | */ |
||
71 | 34 | public function __construct(JsonValidator $validator = null) |
|
72 | 34 | { |
|
73 | $this->validator = $validator ?: new JsonValidator(); |
||
74 | } |
||
75 | |||
76 | /** |
||
77 | * Decodes and validates a JSON string. |
||
78 | * |
||
79 | * If a schema is passed, the decoded object is validated against that |
||
80 | * schema. The schema may be passed as file path or as object returned from |
||
81 | * `JsonDecoder::decodeFile($schemaFile)`. |
||
82 | * |
||
83 | * You can adjust the decoding with {@link setObjectDecoding()}, |
||
84 | * {@link setBigIntDecoding()} and {@link setMaxDepth()}. |
||
85 | * |
||
86 | * Schema validation is not supported when objects are decoded as |
||
87 | * associative arrays. |
||
88 | * |
||
89 | * @param string $json The JSON string. |
||
90 | * @param string|object $schema The schema file or object. |
||
|
|||
91 | * |
||
92 | * @return mixed The decoded value. |
||
93 | * |
||
94 | * @throws DecodingFailedException If the JSON string could not be decoded. |
||
95 | * @throws ValidationFailedException If the decoded string fails schema |
||
96 | * validation. |
||
97 | 24 | * @throws InvalidSchemaException If the schema is invalid. |
|
98 | */ |
||
99 | 24 | public function decode($json, $schema = null) |
|
100 | 1 | { |
|
101 | if (self::ASSOC_ARRAY === $this->objectDecoding && null !== $schema) { |
||
102 | 1 | throw new \InvalidArgumentException( |
|
103 | 'Schema validation is not supported when objects are decoded '. |
||
104 | 1 | 'as associative arrays. Call '. |
|
105 | 'JsonDecoder::setObjectDecoding(JsonDecoder::JSON_OBJECT) to fix.' |
||
106 | ); |
||
107 | 23 | } |
|
108 | |||
109 | 19 | $decoded = $this->decodeJson($json); |
|
110 | 7 | ||
111 | View Code Duplication | if (null !== $schema) { |
|
112 | 6 | $errors = $this->validator->validate($decoded, $schema); |
|
113 | 4 | ||
114 | if (count($errors) > 0) { |
||
115 | 2 | throw ValidationFailedException::fromErrors($errors); |
|
116 | } |
||
117 | 14 | } |
|
118 | |||
119 | return $decoded; |
||
120 | } |
||
121 | |||
122 | /** |
||
123 | * Decodes and validates a JSON file. |
||
124 | * |
||
125 | * @param string $path The path to the JSON file. |
||
126 | * @param string|object $schema The schema file or object. |
||
127 | * |
||
128 | * @return mixed The decoded file. |
||
129 | * |
||
130 | * @throws FileNotFoundException If the file was not found. |
||
131 | * @throws DecodingFailedException If the file could not be decoded. |
||
132 | * @throws ValidationFailedException If the decoded file fails schema |
||
133 | * validation. |
||
134 | * @throws InvalidSchemaException If the schema is invalid. |
||
135 | * |
||
136 | 7 | * @see decode |
|
137 | */ |
||
138 | 7 | public function decodeFile($path, $schema = null) |
|
139 | 1 | { |
|
140 | 1 | if (!file_exists($path)) { |
|
141 | throw new FileNotFoundException(sprintf( |
||
142 | 1 | 'The file %s does not exist.', |
|
143 | $path |
||
144 | )); |
||
145 | 6 | } |
|
146 | 6 | ||
147 | $errorMessage = null; |
||
148 | 6 | $errorCode = 0; |
|
149 | 1 | ||
150 | 1 | set_error_handler(function ($errno, $errstr) use (&$errorMessage, &$errorCode) { |
|
151 | 6 | $errorMessage = $errstr; |
|
152 | $errorCode = $errno; |
||
153 | 6 | }); |
|
154 | |||
155 | 6 | $content = file_get_contents($path); |
|
156 | |||
157 | 6 | restore_error_handler(); |
|
158 | 1 | ||
159 | View Code Duplication | if (null !== $errorMessage) { |
|
160 | 1 | if (false !== $pos = strpos($errorMessage, '): ')) { |
|
161 | 1 | // cut "file_get_contents(%path%):" to make message more readable |
|
162 | $errorMessage = substr($errorMessage, $pos + 3); |
||
163 | 1 | } |
|
164 | 1 | ||
165 | 1 | throw new IOException(sprintf( |
|
166 | 1 | 'Could not read %s: %s (%s)', |
|
167 | $path, |
||
168 | 1 | $errorMessage, |
|
169 | $errorCode |
||
170 | ), $errorCode); |
||
171 | } |
||
172 | 5 | ||
173 | 4 | try { |
|
174 | return $this->decode($content, $schema); |
||
175 | 1 | } catch (DecodingFailedException $e) { |
|
176 | 1 | // Add the file name to the exception |
|
177 | 1 | throw new DecodingFailedException(sprintf( |
|
178 | 1 | 'An error happened while decoding %s: %s', |
|
179 | 1 | $path, |
|
180 | 3 | $e->getMessage() |
|
181 | ), $e->getCode(), $e); |
||
182 | 2 | } catch (ValidationFailedException $e) { |
|
183 | 2 | // Add the file name to the exception |
|
184 | 2 | throw new ValidationFailedException(sprintf( |
|
185 | 2 | "Validation of %s failed:\n%s", |
|
186 | 2 | $path, |
|
187 | 1 | $e->getErrorsAsString() |
|
188 | ), $e->getErrors(), $e->getCode(), $e); |
||
189 | 1 | } catch (InvalidSchemaException $e) { |
|
190 | 1 | // Add the file name to the exception |
|
191 | 1 | throw new InvalidSchemaException(sprintf( |
|
192 | 1 | 'An error happened while decoding %s: %s', |
|
193 | 1 | $path, |
|
194 | $e->getMessage() |
||
195 | ), $e->getCode(), $e); |
||
196 | } |
||
197 | } |
||
198 | |||
199 | /** |
||
200 | * Returns the maximum recursion depth. |
||
201 | * |
||
202 | * A depth of zero means that objects are not allowed. A depth of one means |
||
203 | * only one level of objects or arrays is allowed. |
||
204 | * |
||
205 | * @return int The maximum recursion depth. |
||
206 | */ |
||
207 | public function getMaxDepth() |
||
208 | { |
||
209 | return $this->maxDepth; |
||
210 | } |
||
211 | |||
212 | /** |
||
213 | * Sets the maximum recursion depth. |
||
214 | * |
||
215 | * If the depth is exceeded during decoding, an {@link DecodingnFailedException} |
||
216 | * will be thrown. |
||
217 | * |
||
218 | * A depth of zero means that objects are not allowed. A depth of one means |
||
219 | * only one level of objects or arrays is allowed. |
||
220 | * |
||
221 | * @param int $maxDepth The maximum recursion depth. |
||
222 | * |
||
223 | * @throws \InvalidArgumentException If the depth is not an integer greater |
||
224 | 6 | * than or equal to zero. |
|
225 | */ |
||
226 | 6 | View Code Duplication | public function setMaxDepth($maxDepth) |
227 | 1 | { |
|
228 | 1 | if (!is_int($maxDepth)) { |
|
229 | 1 | throw new \InvalidArgumentException(sprintf( |
|
230 | 1 | 'The maximum depth should be an integer. Got: %s', |
|
231 | is_object($maxDepth) ? get_class($maxDepth) : gettype($maxDepth) |
||
232 | )); |
||
233 | 5 | } |
|
234 | 1 | ||
235 | 1 | if ($maxDepth < 1) { |
|
236 | throw new \InvalidArgumentException(sprintf( |
||
237 | 1 | 'The maximum depth should 1 or greater. Got: %s', |
|
238 | $maxDepth |
||
239 | )); |
||
240 | 4 | } |
|
241 | 4 | ||
242 | $this->maxDepth = $maxDepth; |
||
243 | } |
||
244 | |||
245 | /** |
||
246 | * Returns the decoding of JSON objects. |
||
247 | * |
||
248 | * @return int One of the constants {@link JSON_OBJECT} and {@link ASSOC_ARRAY}. |
||
249 | */ |
||
250 | public function getObjectDecoding() |
||
251 | { |
||
252 | return $this->objectDecoding; |
||
253 | } |
||
254 | |||
255 | /** |
||
256 | * Sets the decoding of JSON objects. |
||
257 | * |
||
258 | * By default, JSON objects are decoded as instances of {@link \stdClass}. |
||
259 | * |
||
260 | * @param int $decoding One of the constants {@link JSON_OBJECT} and {@link ASSOC_ARRAY}. |
||
261 | * |
||
262 | 6 | * @throws \InvalidArgumentException If the passed decoding is invalid. |
|
263 | */ |
||
264 | 6 | View Code Duplication | public function setObjectDecoding($decoding) |
265 | 3 | { |
|
266 | if (self::OBJECT !== $decoding && self::ASSOC_ARRAY !== $decoding) { |
||
267 | 3 | throw new \InvalidArgumentException(sprintf( |
|
268 | 'Expected JsonDecoder::JSON_OBJECT or JsonDecoder::ASSOC_ARRAY. '. |
||
269 | 3 | 'Got: %s', |
|
270 | $decoding |
||
271 | )); |
||
272 | 3 | } |
|
273 | 3 | ||
274 | $this->objectDecoding = $decoding; |
||
275 | } |
||
276 | |||
277 | /** |
||
278 | * Returns the decoding of big integers. |
||
279 | * |
||
280 | * @return int One of the constants {@link FLOAT} and {@link JSON_STRING}. |
||
281 | */ |
||
282 | public function getBigIntDecoding() |
||
283 | { |
||
284 | return $this->bigIntDecoding; |
||
285 | } |
||
286 | |||
287 | /** |
||
288 | * Sets the decoding of big integers. |
||
289 | * |
||
290 | * By default, big integers are decoded as floats. |
||
291 | * |
||
292 | * @param int $decoding One of the constants {@link FLOAT} and {@link JSON_STRING}. |
||
293 | * |
||
294 | 5 | * @throws \InvalidArgumentException If the passed decoding is invalid. |
|
295 | */ |
||
296 | 5 | View Code Duplication | public function setBigIntDecoding($decoding) |
308 | |||
309 | 23 | private function decodeJson($json) |
|
310 | { |
||
311 | 23 | $assoc = self::ASSOC_ARRAY === $this->objectDecoding; |
|
312 | 23 | ||
313 | if (PHP_VERSION_ID >= 50400 && !defined('JSON_C_VERSION')) { |
||
314 | 23 | $options = self::STRING === $this->bigIntDecoding ? JSON_BIGINT_AS_STRING : 0; |
|
315 | 23 | ||
316 | $decoded = json_decode($json, $assoc, $this->maxDepth, $options); |
||
343 | } |
||
344 |
This check looks for
@param
annotations where the type inferred by our type inference engine differs from the declared type.It makes a suggestion as to what type it considers more descriptive.
Most often this is a case of a parameter that can be null in addition to its declared types.