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:
Complex classes like Renderer often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use Renderer, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
28 | class Renderer |
||
29 | { |
||
30 | |||
31 | /** |
||
32 | * No indention |
||
33 | * |
||
34 | * @var integer |
||
35 | */ |
||
36 | const INDENT_NO_INDENT = 0; |
||
37 | |||
38 | /** |
||
39 | * One indention |
||
40 | * |
||
41 | * @var integer |
||
42 | */ |
||
43 | const INDENT_4_SPACES = 4; |
||
44 | |||
45 | /** |
||
46 | * Two indentions |
||
47 | * |
||
48 | * @var integer |
||
49 | */ |
||
50 | const INDENT_8_SPACES = 8; |
||
51 | |||
52 | /** |
||
53 | * @var string |
||
54 | */ |
||
55 | const JMS_ANNOTATION_NAMESPACE = "@\\JMS\\Serializer\\Annotation"; |
||
56 | |||
57 | /** |
||
58 | * @var TemplateManager |
||
59 | */ |
||
60 | private $templateManager; |
||
61 | |||
62 | /** |
||
63 | * CONSTR |
||
64 | */ |
||
65 | public function __construct(TemplateManager $templateManager) |
||
69 | |||
70 | /** |
||
71 | * @return TemplateManager |
||
72 | */ |
||
73 | public function getTemplateManager() |
||
77 | |||
78 | /** |
||
79 | * Render renderable item |
||
80 | * |
||
81 | * @param RenderableInterface $item |
||
82 | * @return string |
||
83 | * @throws RendererException |
||
84 | * @throws UnrecognizedItemToRenderException |
||
85 | */ |
||
86 | public function render(RenderableInterface $item) |
||
87 | { |
||
88 | $this->getTemplateManager()->loadAndSetTemplateOnItem($item); |
||
89 | switch (true) { |
||
90 | case $item instanceof ClassManager: |
||
91 | return $this->renderClass($item); |
||
92 | case $item instanceof ClassConstructorManager: |
||
93 | return $this->renderClassConstructor($item); |
||
94 | case $item instanceof InitPropertyManager: |
||
95 | return $this->renderInitProperty($item); |
||
96 | case $item instanceof InterfaceManager: |
||
97 | return $this->renderInterface($item); |
||
98 | case $item instanceof PropertyManager: |
||
99 | return $this->renderProperty($item); |
||
100 | case $item instanceof MethodManager: |
||
101 | return $this->renderMethod($item); |
||
102 | case $item instanceof TestClassManager: |
||
103 | return $this->renderTestClass($item); |
||
104 | case $item instanceof TestMethodManager: |
||
105 | return $this->renderTestMethod($item); |
||
106 | default: |
||
107 | throw $this->getExceptionUnrecognizedItem($item); |
||
108 | } |
||
109 | } |
||
110 | |||
111 | /** |
||
112 | * @param string $content |
||
113 | * @param ClassConstructorManager $constructor |
||
114 | * @param int $position |
||
115 | * @return string |
||
116 | */ |
||
117 | public function renderAndPutConstructorBodyToContent($content, ClassConstructorManager $constructor, $position = 0) |
||
118 | { |
||
119 | $source = Tools::explodeTemplateStringToArray($content); |
||
120 | foreach ($constructor->getInitProperties() as $initProperty) { |
||
121 | $this->putElementIntoSource($source, $position, $this->addIndentation($this->render($initProperty), self::INDENT_8_SPACES)); |
||
122 | } |
||
123 | |||
124 | return Tools::implodeArrayToTemplate($source); |
||
125 | } |
||
126 | |||
127 | /** |
||
128 | * @param string $content |
||
129 | * @param ArrayCollection $itemsToRender |
||
130 | * @param int $position |
||
131 | * @return string |
||
132 | */ |
||
133 | public function renderAndPutItemsToContent($content, ArrayCollection $itemsToRender, $position = 0) |
||
134 | { |
||
135 | $itemsRendered = []; |
||
136 | foreach ($itemsToRender as $itemToRender) { |
||
137 | $itemsRendered[] = $this->render($itemToRender); |
||
138 | } |
||
139 | |||
140 | return $this->updateSourceWithElements($content, $position, $itemsRendered); |
||
141 | } |
||
142 | |||
143 | /** |
||
144 | * @param InitPropertyManager $initProperty |
||
145 | * @return string |
||
146 | * @throws RendererException |
||
147 | */ |
||
148 | protected function renderInitProperty(InitPropertyManager $initProperty) |
||
149 | { |
||
150 | $template = $initProperty->getTemplate(); |
||
151 | $tags = $initProperty->getTemplateTags(); |
||
152 | |||
153 | $args[RenderableInterface::TAG_PROPERTY_NAME] = $initProperty->getProperty()->getPreparedName(); |
||
|
|||
154 | $args[RenderableInterface::TAG_PROPERTY_TYPE] = sprintf('\%s', $initProperty->getProperty()->getTypeName()); |
||
155 | return $this->replace($tags, $args, $template); |
||
156 | } |
||
157 | |||
158 | /** |
||
159 | * @param ClassConstructorManager $classConstructor |
||
160 | * @return string |
||
161 | * @throws RendererException |
||
162 | */ |
||
163 | protected function renderClassConstructor(ClassConstructorManager $classConstructor) |
||
164 | { |
||
165 | $template = $classConstructor->getTemplate(); |
||
166 | $tags = $classConstructor->getTemplateTags(); |
||
167 | |||
168 | $initProperties = []; |
||
169 | foreach ($classConstructor->getInitProperties() as $initProperty) { |
||
170 | $initProperties[] = $this->render($initProperty); |
||
171 | } |
||
172 | |||
173 | $initPropertiesRendered = empty($initProperties) ? "" : Tools::implodeArrayToTemplate($initProperties); |
||
174 | $args[RenderableInterface::TAG_INIT_PROPERTIES] = $initPropertiesRendered; |
||
175 | |||
176 | return $this->addNewLineAfter($this->addIndentation($this->replace($tags, $args, $template), self::INDENT_4_SPACES)); |
||
177 | } |
||
178 | |||
179 | /** |
||
180 | * @param MethodManager $method |
||
181 | * @return string |
||
182 | * @throws RendererException |
||
183 | * @throws UnrecognizedItemToRenderException |
||
184 | */ |
||
185 | protected function renderMethod(MethodManager $method) |
||
186 | { |
||
187 | $template = $method->getTemplate(); |
||
188 | $tags = $method->getTemplateTags(); |
||
189 | |||
190 | $property = $method->getProperty(); |
||
191 | $propertyName = $property->getPreparedName(); |
||
192 | $methodName = $method->getPreparedName(); |
||
193 | $comment = sprintf('For property "%s"', $propertyName); |
||
194 | |||
195 | $args = []; |
||
196 | switch (true) { |
||
197 | View Code Duplication | case $method instanceof MethodGetterManager: |
|
198 | $args[RenderableInterface::TAG_COMMENT] = $comment; |
||
199 | $args[RenderableInterface::TAG_PROPERTY_TYPE] = $this->getScalarTypeOrAbsoluteObjectTypeFromProperty($property); |
||
200 | $args[RenderableInterface::TAG_METHOD_NAME] = $methodName; |
||
201 | $args[RenderableInterface::TAG_PROPERTY_NAME] = $propertyName; |
||
202 | break; |
||
203 | case $method instanceof MethodGetterInterfaceManager: |
||
204 | $args[RenderableInterface::TAG_COMMENT] = $comment; |
||
205 | $args[RenderableInterface::TAG_PROPERTY_TYPE] = $this->getScalarTypeOrAbsoluteObjectTypeFromProperty($property); |
||
206 | $args[RenderableInterface::TAG_METHOD_NAME] = $methodName; |
||
207 | break; |
||
208 | View Code Duplication | case $method instanceof MethodGetterBooleanManager: |
|
209 | $args[RenderableInterface::TAG_COMMENT] = $comment; |
||
210 | $args[RenderableInterface::TAG_PROPERTY_TYPE] = $this->getScalarTypeOrAbsoluteObjectTypeFromProperty($property); |
||
211 | $args[RenderableInterface::TAG_METHOD_NAME] = $methodName; |
||
212 | $args[RenderableInterface::TAG_PROPERTY_NAME] = $propertyName; |
||
213 | break; |
||
214 | case $method instanceof MethodGetterBooleanInterfaceManager: |
||
215 | $args[RenderableInterface::TAG_COMMENT] = $comment; |
||
216 | $args[RenderableInterface::TAG_PROPERTY_TYPE] = $this->getScalarTypeOrAbsoluteObjectTypeFromProperty($property); |
||
217 | $args[RenderableInterface::TAG_METHOD_NAME] = $methodName; |
||
218 | break; |
||
219 | case $method instanceof SetterMethodInterface: |
||
220 | $typeHintitngPart = ''; |
||
221 | if ($method->canAddTypeHinting()) { |
||
222 | $typeHintitngPart = sprintf('%s ', $property->getTypeNameAbsoluteIfIsObjectTypeOrThrowException()); |
||
223 | } |
||
224 | |||
225 | $optionalPart = ''; |
||
226 | if ($property->isOptional()) { |
||
227 | $optionalPart = ' = null'; |
||
228 | } |
||
229 | |||
230 | $args[RenderableInterface::TAG_COMMENT] = $comment; |
||
231 | $args[RenderableInterface::TAG_PROPERTY_TYPE] = $this->getScalarTypeOrAbsoluteObjectTypeFromProperty($property); |
||
232 | $args[RenderableInterface::TAG_TYPE_HINTING] = $typeHintitngPart; |
||
233 | $args[RenderableInterface::TAG_METHOD_NAME] = $methodName; |
||
234 | $args[RenderableInterface::TAG_PROPERTY_NAME] = $propertyName; |
||
235 | $args[RenderableInterface::TAG_OPTIONAL_PART] = $optionalPart; |
||
236 | break; |
||
237 | default: |
||
238 | throw $this->getExceptionUnrecognizedItem($method); |
||
239 | } |
||
240 | |||
241 | return $this->addNewLineAfter($this->addIndentation($this->replace($tags, $args, $template), self::INDENT_4_SPACES)); |
||
242 | } |
||
243 | |||
244 | /** |
||
245 | * @param ClassManager $class |
||
246 | * @return string |
||
247 | * @throws RendererException |
||
248 | */ |
||
249 | protected function renderClass(ClassManager $class) |
||
250 | { |
||
251 | $template = $class->getTemplate(); |
||
252 | $tags = $class->getTemplateTags(); |
||
253 | |||
254 | $properties = []; |
||
255 | $methods = []; |
||
256 | $interfacePart = ''; |
||
257 | $extendsPart = ''; |
||
258 | foreach ($class->getProperties() as $property) { |
||
259 | $properties[] = $this->render($property); |
||
260 | } |
||
261 | foreach ($class->getMethods() as $method) { |
||
262 | $methods[] = $this->render($method); |
||
263 | } |
||
264 | if ($class->hasExtends()) { |
||
265 | $extendsPart = sprintf(" extends %s", $class->getExtends()); |
||
266 | } |
||
267 | if ($class->hasInterface()) { |
||
268 | $interfacePart = sprintf(" implements %s", $class->getInterface()->getNamespace()); |
||
269 | } |
||
270 | |||
271 | $args[RenderableInterface::TAG_NAMESPACE] = $class->getNamespaceWithoutNameAndBackslashPrefix(); |
||
272 | $args[RenderableInterface::TAG_COMMENT] = empty($class->getComment()) ? "" : $class->getComment(); |
||
273 | $args[RenderableInterface::TAG_NAME] = $class->getName(); |
||
274 | $args[RenderableInterface::TAG_EXTENDS] = $extendsPart; |
||
275 | $args[RenderableInterface::TAG_INTERFACE] = $interfacePart; |
||
276 | $args[RenderableInterface::TAG_CONSTRUCTOR] = $this->addNewLineBefore($this->render($class->getConstructor())); |
||
277 | $args[RenderableInterface::TAG_PROPERTIES] = $this->addNewLineBefore(Tools::implodeArrayToTemplate($properties)); |
||
278 | $args[RenderableInterface::TAG_METHODS] = $this->addNewLineBefore(Tools::implodeArrayToTemplate($methods)); |
||
279 | $args[RenderableInterface::TAG_MULTILINE_COMMENT] = $this->prepareMultilineCommentForCollection($class->getMultilineComment()); |
||
280 | |||
281 | return $this->addNewLineAfter($this->replace($tags, $args, $template)); |
||
282 | } |
||
283 | |||
284 | /** |
||
285 | * @param InterfaceManager $interface |
||
286 | * @return string |
||
287 | * @throws RendererException |
||
288 | */ |
||
289 | protected function renderInterface(InterfaceManager $interface) |
||
290 | { |
||
291 | $template = $interface->getTemplate(); |
||
292 | $tags = $interface->getTemplateTags(); |
||
293 | |||
294 | $methods = []; |
||
295 | foreach ($interface->getMethods() as $method) { |
||
296 | $methods[] = $this->render($method); |
||
297 | } |
||
298 | |||
299 | $args[RenderableInterface::TAG_NAMESPACE] = $interface->getNamespaceWithoutNameAndBackslashPrefix(); |
||
300 | $args[RenderableInterface::TAG_COMMENT] = $interface->getComment(); |
||
301 | $args[RenderableInterface::TAG_NAME] = $interface->getName(); |
||
302 | $args[RenderableInterface::TAG_METHODS] = $this->addNewLineBefore(Tools::implodeArrayToTemplate($methods)); |
||
303 | |||
304 | return $this->addNewLineAfter($this->replace($tags, $args, $template)); |
||
305 | } |
||
306 | |||
307 | /** |
||
308 | * @param PropertyManager $property |
||
309 | * @return string |
||
310 | * @throws RendererException |
||
311 | */ |
||
312 | protected function renderProperty(PropertyManager $property) |
||
313 | { |
||
314 | $template = $property->getTemplate(); |
||
315 | $tags = $property->getTemplateTags(); |
||
316 | |||
317 | $comment = $property->getComment(); |
||
318 | if (empty($comment)) { |
||
319 | $comment = sprintf("'%s' property", $property->getName()); |
||
320 | } |
||
321 | |||
322 | $jmsCollection = new ArrayCollection(); |
||
323 | $jmsCollection->add(sprintf("%s\Type(\"%s\")", self::JMS_ANNOTATION_NAMESPACE, $property->getType())); |
||
324 | if ($property->hasSerializedName()) { |
||
325 | $jmsCollection->add(sprintf("%s\SerializedName(\"%s\")", self::JMS_ANNOTATION_NAMESPACE, $property->getSerializedName())); |
||
326 | } else { |
||
327 | $jmsCollection->add(sprintf("%s\SerializedName(\"%s\")", self::JMS_ANNOTATION_NAMESPACE, $property->getName())); |
||
328 | } |
||
329 | |||
330 | $args[RenderableInterface::TAG_COMMENT] = $comment; |
||
331 | $args[RenderableInterface::TAG_CONSTRAINTS] = $this->prepareMultilineCommentForCollection($property->getConstraintAnnotationCollection()); |
||
332 | $args[RenderableInterface::TAG_JMS_PART] = $this->prepareMultilineCommentForCollection($jmsCollection); |
||
333 | $args[RenderableInterface::TAG_TYPE] = $this->getScalarTypeOrAbsoluteObjectTypeFromProperty($property); |
||
334 | $args[RenderableInterface::TAG_NAME] = $property->getPreparedName(); |
||
335 | $args[RenderableInterface::TAG_MULTILINE_COMMENT] = $this->prepareMultilineCommentForCollection($property->getMultilineComment()); |
||
336 | |||
337 | return $this->addNewLineAfter($this->addIndentation($this->replace($tags, $args, $template), self::INDENT_4_SPACES)); |
||
338 | } |
||
339 | |||
340 | /** |
||
341 | * @param TestClassManager $testClass |
||
342 | * @return string |
||
343 | * @throws RendererException |
||
344 | */ |
||
345 | protected function renderTestClass(TestClassManager $testClass) |
||
346 | { |
||
347 | $template = $testClass->getTemplate(); |
||
348 | $tags = $testClass->getTemplateTags(); |
||
349 | |||
350 | $constructTestMethodBody = []; |
||
351 | $methods = []; |
||
352 | foreach ($testClass->getMethods() as $method) { |
||
353 | $methods[] = $this->render($method); |
||
354 | } |
||
355 | |||
356 | $class = $testClass->getClassManager(); |
||
357 | |||
358 | $constructTestMethodBody[] = "\$this->assertNotNull(\$this->object);"; |
||
359 | if ($testClass->getClassManager()->hasInterface()) { |
||
360 | $interfaceTestAssert = sprintf("\$this->assertInstanceof('%s', \$this->object);", $testClass->getClassManager()->getInterface()->getNamespace()); |
||
361 | $constructTestMethodBody[] = $this->addIndentation($interfaceTestAssert, self::INDENT_8_SPACES); |
||
362 | } |
||
363 | |||
364 | $classTestAssert = sprintf("\$this->assertInstanceof('%s', \$this->object);", $class->getNamespace()); |
||
365 | $constructTestMethodBody[] = $this->addIndentation($classTestAssert, self::INDENT_8_SPACES); |
||
366 | |||
367 | if ($testClass->getClassManager()->hasExtends()) { |
||
368 | $extendsTestAssert = sprintf("\$this->assertInstanceof('%s', \$this->object);", $testClass->getClassManager()->getExtends()); |
||
369 | $constructTestMethodBody[] = $this->addIndentation($extendsTestAssert, self::INDENT_8_SPACES); |
||
370 | } |
||
371 | |||
372 | $testObjectType = $class->getNamespace(); |
||
373 | if ($class->hasInterface()) { |
||
374 | $testObjectType = $class->getInterface()->getNamespace(); |
||
375 | } |
||
376 | |||
377 | $args[RenderableInterface::TAG_NAMESPACE] = $testClass->getNamespaceWithoutNameAndBackslashPrefix(); |
||
378 | $args[RenderableInterface::TAG_COMMENT] = $testClass->getComment(); |
||
379 | $args[RenderableInterface::TAG_NAME] = $testClass->getName(); |
||
380 | $args[RenderableInterface::TAG_CLASS] = $class->getNamespace(); |
||
381 | $args[RenderableInterface::TAG_METHODS] = $this->addNewLineBefore(Tools::implodeArrayToTemplate($methods)); |
||
382 | $args[RenderableInterface::TAG_TEST_OBJECT_TYPE] = $testObjectType; |
||
383 | $args[RenderableInterface::TAG_METHOD_BODY] = Tools::implodeArrayToTemplate($constructTestMethodBody); |
||
384 | |||
385 | return $this->addNewLineAfter($this->replace($tags, $args, $template)); |
||
386 | } |
||
387 | |||
388 | /** |
||
389 | * @param TestMethodManager $testMethod |
||
390 | * @return string |
||
391 | * @throws RendererException |
||
392 | */ |
||
393 | protected function renderTestMethod(TestMethodManager $testMethod) |
||
394 | { |
||
395 | $template = $testMethod->getTemplate(); |
||
396 | $tags = $testMethod->getTemplateTags(); |
||
397 | |||
398 | $args[RenderableInterface::TAG_CLASS] = $testMethod->getMethod()->getClassManager()->getNamespace(); |
||
399 | $args[RenderableInterface::TAG_METHOD_NAME] = $testMethod->getMethod()->getPreparedName(); |
||
400 | $args[RenderableInterface::TAG_TEST_METHOD_NAME] = $testMethod->getPreparedName(); |
||
401 | |||
402 | return $this->addNewLineAfter($this->addIndentation($this->replace($tags, $args, $template), self::INDENT_4_SPACES)); |
||
403 | } |
||
404 | |||
405 | /** |
||
406 | * Replace tags in template witch arguments |
||
407 | * |
||
408 | * @param array $tags |
||
409 | * @param array $args |
||
410 | * @param string $template |
||
411 | * @return string |
||
412 | * @throws RendererException |
||
413 | */ |
||
414 | protected function replace($tags, $args, $template) |
||
415 | { |
||
416 | if ($tags !== array_keys($args)) { |
||
417 | throw new RendererException("Tags and keys are not identical!"); |
||
418 | } |
||
419 | |||
420 | return str_replace($tags, array_values($args), $template); |
||
421 | } |
||
422 | |||
423 | /** |
||
424 | * Add Indentation to template |
||
425 | * |
||
426 | * @param string $template |
||
427 | * @param integer $spaces |
||
428 | */ |
||
429 | protected function addIndentation($template, $spaces = self::INDENT_NO_INDENT) |
||
430 | { |
||
431 | $parts = Tools::explodeTemplateStringToArray($template); |
||
432 | array_walk( |
||
433 | $parts, function (&$value) use ($spaces) { |
||
434 | $value = str_pad($value, strlen($value) + (int) $spaces, " ", STR_PAD_LEFT); |
||
435 | } |
||
436 | ); |
||
437 | |||
438 | return Tools::implodeArrayToTemplate($parts); |
||
439 | } |
||
440 | |||
441 | /** |
||
442 | * @param mixed $item |
||
443 | * @return UnrecognizedItemToRenderException |
||
444 | */ |
||
445 | protected function getExceptionUnrecognizedItem($item) |
||
446 | { |
||
447 | return new UnrecognizedItemToRenderException(sprintf("Unrecognized item: %s", get_class($item))); |
||
448 | } |
||
449 | |||
450 | /** |
||
451 | * Update source file with rendered elements |
||
452 | * |
||
453 | * @param string $content |
||
454 | * @param integer $startPosition |
||
455 | * @param array $renderedElements |
||
456 | * @return string |
||
457 | */ |
||
458 | protected function updateSourceWithElements($content, $startPosition = 0, array $renderedElements = []) |
||
459 | { |
||
460 | $source = Tools::explodeTemplateStringToArray($content); |
||
461 | foreach ($renderedElements as $renderedElement) { |
||
462 | $this->putElementIntoSource($source, $startPosition, $renderedElement); |
||
463 | } |
||
464 | |||
465 | return Tools::implodeArrayToTemplate($source); |
||
466 | } |
||
467 | |||
468 | /** |
||
469 | * @param array $source |
||
470 | * @param integer $offset |
||
471 | * @param string $element |
||
472 | */ |
||
473 | protected function putElementIntoSource(&$source, $offset, $element) |
||
474 | { |
||
475 | array_splice($source, $offset, 0, [$element]); |
||
476 | } |
||
477 | |||
478 | /** |
||
479 | * Put new line to the end of conent |
||
480 | * |
||
481 | * @param string $content |
||
482 | * @return string |
||
483 | * @throws RendererException |
||
484 | */ |
||
485 | View Code Duplication | protected function addNewLineAfter($content) |
|
486 | { |
||
487 | if (false === is_string($content)) { |
||
488 | throw new RendererException("Invalid string!"); |
||
489 | } |
||
490 | |||
491 | return sprintf("%s\n", $content); |
||
492 | } |
||
493 | |||
494 | /** |
||
495 | * Put new line before conent |
||
496 | * |
||
497 | * @param string $content |
||
498 | * @return string |
||
499 | * @throws RendererException |
||
500 | */ |
||
501 | View Code Duplication | protected function addNewLineBefore($content) |
|
509 | |||
510 | /** |
||
511 | * @param \ArrayCollection $collection |
||
512 | * @return string |
||
513 | */ |
||
514 | protected function prepareMultilineCommentForCollection(ArrayCollection $collection) |
||
533 | |||
534 | /** |
||
535 | * @param PropertyManager $property |
||
536 | * @return string |
||
537 | * @throws \Exception |
||
538 | */ |
||
539 | protected function getScalarTypeOrAbsoluteObjectTypeFromProperty(PropertyManager $property) |
||
547 | } |
||
548 |
Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.
Let’s take a look at an example:
As you can see in this example, the array
$myArray
is initialized the first time when the foreach loop is entered. You can also see that the value of thebar
key is only written conditionally; thus, its value might result from a previous iteration.This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.