Complex classes like Ebi 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 Ebi, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
11 | class Ebi { |
||
12 | /** |
||
13 | * @var string |
||
14 | */ |
||
15 | protected $cachePath; |
||
16 | /** |
||
17 | * @var callable[] |
||
18 | */ |
||
19 | protected $functions; |
||
20 | /** |
||
21 | * @var TemplateLoaderInterface |
||
22 | */ |
||
23 | private $templateLoader; |
||
24 | /** |
||
25 | * @var CompilerInterface |
||
26 | */ |
||
27 | private $compiler; |
||
28 | /** |
||
29 | * @var callable[] |
||
30 | */ |
||
31 | private $components = []; |
||
32 | /** |
||
33 | * @var array |
||
34 | */ |
||
35 | private $meta; |
||
36 | |||
37 | /** |
||
38 | * Ebi constructor. |
||
39 | * |
||
40 | * @param TemplateLoaderInterface $templateLoader Used to load template sources from component names. |
||
41 | * @param string $cachePath The path to cache compiled templates. |
||
42 | * @param CompilerInterface $compiler The compiler used to compile templates. |
||
|
|||
43 | */ |
||
44 | 74 | public function __construct(TemplateLoaderInterface $templateLoader, $cachePath, CompilerInterface $compiler = null) { |
|
45 | 74 | $this->templateLoader = $templateLoader; |
|
46 | 74 | $this->cachePath = $cachePath; |
|
47 | 74 | $this->compiler = $compiler ?: new Compiler(); |
|
48 | |||
49 | 74 | $this->defineFunction('abs'); |
|
50 | 74 | $this->defineFunction('arrayColumn', 'array_column'); |
|
51 | 74 | $this->defineFunction('arrayKeyExists', 'array_key_exists'); |
|
52 | 74 | $this->defineFunction('arrayKeys', 'array_keys'); |
|
53 | 74 | $this->defineFunction('arrayMerge', 'array_merge'); |
|
54 | 74 | $this->defineFunction('arrayMergeRecursive', 'array_merge_recursive'); |
|
55 | 74 | $this->defineFunction('arrayReplace', 'array_replace'); |
|
56 | 74 | $this->defineFunction('arrayReplaceRecursive', 'array_replace_recursive'); |
|
57 | 74 | $this->defineFunction('arrayReverse', 'array_reverse'); |
|
58 | 74 | $this->defineFunction('arrayValues', 'array_values'); |
|
59 | 74 | $this->defineFunction('base64Encode', 'base64_encode'); |
|
60 | 74 | $this->defineFunction('ceil'); |
|
61 | 74 | $this->defineFunction('componentExists', [$this, 'componentExists']); |
|
62 | 74 | $this->defineFunction('count'); |
|
63 | 74 | $this->defineFunction('empty'); |
|
64 | 74 | $this->defineFunction('floor'); |
|
65 | 74 | $this->defineFunction('formatDate', [$this, 'formatDate']); |
|
66 | 74 | $this->defineFunction('formatNumber', 'number_format'); |
|
67 | 74 | $this->defineFunction('htmlEncode', 'htmlspecialchars'); |
|
68 | 74 | $this->defineFunction('isArray', 'is_array'); |
|
69 | 74 | $this->defineFunction('isBool', 'is_bool'); |
|
70 | 74 | $this->defineFunction('isInt', 'is_int'); |
|
71 | 74 | $this->defineFunction('isScalar', 'is_scalar'); |
|
72 | 74 | $this->defineFunction('isString', 'is_string'); |
|
73 | 74 | $this->defineFunction('join'); |
|
74 | 74 | $this->defineFunction('lcase', $this->mb('strtolower')); |
|
75 | 74 | $this->defineFunction('lcfirst'); |
|
76 | 74 | $this->defineFunction('ltrim'); |
|
77 | 74 | $this->defineFunction('max'); |
|
78 | 74 | $this->defineFunction('min'); |
|
79 | 74 | $this->defineFunction('queryEncode', 'http_build_query'); |
|
80 | 74 | $this->defineFunction('round'); |
|
81 | 74 | $this->defineFunction('rtrim'); |
|
82 | 74 | $this->defineFunction('sprintf'); |
|
83 | 74 | $this->defineFunction('strlen', $this->mb('strlen')); |
|
84 | 74 | $this->defineFunction('substr', $this->mb('substr')); |
|
85 | 74 | $this->defineFunction('trim'); |
|
86 | 74 | $this->defineFunction('ucase', $this->mb('strtoupper')); |
|
87 | 74 | $this->defineFunction('ucfirst'); |
|
88 | 74 | $this->defineFunction('ucwords'); |
|
89 | 74 | $this->defineFunction('urlencode', 'rawurlencode'); |
|
90 | |||
91 | 74 | $this->defineFunction('@class', [$this, 'attributeClass']); |
|
92 | |||
93 | // Define a simple component not found component to help troubleshoot. |
||
94 | 74 | $this->defineComponent('@component-not-found', function ($props) { |
|
95 | 1 | echo '<!-- Ebi component "'.htmlspecialchars($props['component']).'" not found. -->'; |
|
96 | 74 | }); |
|
97 | |||
98 | // Define a simple component exception. |
||
99 | 74 | $this->defineComponent('@exception', function ($props) { |
|
100 | 1 | echo "\n<!--\nEbi exception in component \"".htmlspecialchars($props['component'])."\".\n". |
|
101 | 1 | htmlspecialchars($props['message'])."\n-->\n"; |
|
102 | |||
103 | 74 | }); |
|
104 | |||
105 | 74 | $this->defineComponent('@compile-exception', [$this, 'writeCompileException']); |
|
106 | 74 | } |
|
107 | |||
108 | /** |
||
109 | * Register a runtime function. |
||
110 | * |
||
111 | * @param string $name The name of the function. |
||
112 | * @param callable $function The function callback. |
||
113 | */ |
||
114 | 74 | public function defineFunction($name, $function = null) { |
|
115 | 74 | if ($function === null) { |
|
116 | 74 | $function = $name; |
|
117 | } |
||
118 | |||
119 | 74 | $this->functions[strtolower($name)] = $function; |
|
120 | 74 | $this->compiler->defineFunction($name, $function); |
|
121 | 74 | } |
|
122 | |||
123 | 74 | private function mb($func) { |
|
126 | |||
127 | /** |
||
128 | * Write a component to the output buffer. |
||
129 | * |
||
130 | * @param string $component The name of the component. |
||
131 | * @param array ...$args |
||
132 | */ |
||
133 | 22 | public function write($component, ...$args) { |
|
134 | 22 | $component = strtolower($component); |
|
135 | |||
136 | try { |
||
137 | 22 | $callback = $this->lookup($component); |
|
138 | |||
139 | 22 | if (is_callable($callback)) { |
|
140 | 22 | call_user_func($callback, ...$args); |
|
141 | } else { |
||
142 | 22 | $this->write('@component-not-found', ['component' => $component]); |
|
143 | } |
||
144 | 1 | } catch (\Throwable $ex) { |
|
145 | 1 | $this->write('@exception', ['message' => $ex->getMessage(), 'code', $ex->getCode(), 'component' => $component]); |
|
146 | 1 | return; |
|
147 | } catch (\Exception $ex) { |
||
148 | $this->write('@exception', ['message' => $ex->getMessage(), 'code', $ex->getCode(), 'component' => $component]); |
||
149 | return; |
||
150 | } |
||
151 | 22 | } |
|
152 | |||
153 | /** |
||
154 | * Lookup a component with a given name. |
||
155 | * |
||
156 | * @param string $component The component to lookup. |
||
157 | * @return callable|null Returns the component function or **null** if the component is not found. |
||
158 | */ |
||
159 | 69 | public function lookup($component) { |
|
160 | 69 | $component = strtolower($component); |
|
161 | 69 | $key = $this->componentKey($component); |
|
162 | |||
163 | 69 | if (!array_key_exists($key, $this->components)) { |
|
164 | 64 | $this->loadComponent($component); |
|
165 | } |
||
166 | |||
167 | 69 | if (isset($this->components[$key])) { |
|
168 | 68 | return $this->components[$key]; |
|
169 | } else { |
||
170 | // Mark a tombstone to the component array so it doesn't keep getting loaded. |
||
171 | 2 | $this->components[$key] = null; |
|
172 | 2 | return null; |
|
173 | } |
||
174 | } |
||
175 | |||
176 | /** |
||
177 | * Check to see if a component exists. |
||
178 | * |
||
179 | * @param string $component The name of the component. |
||
180 | * @param bool $loader Whether or not to use the component loader or just look in the component cache. |
||
181 | * @return bool Returns **true** if the component exists or **false** otherwise. |
||
182 | */ |
||
183 | 2 | public function componentExists($component, $loader = true) { |
|
192 | |||
193 | /** |
||
194 | * Strip the namespace off a component name to get the component key. |
||
195 | * |
||
196 | * @param string $component The full name of the component with a possible namespace. |
||
197 | * @return string Returns the component key. |
||
198 | */ |
||
199 | 71 | protected function componentKey($component) { |
|
200 | 71 | if (false !== $pos = strpos($component, ':')) { |
|
201 | 1 | $component = substr($component, $pos + 1); |
|
202 | } |
||
203 | 71 | return strtolower($component); |
|
204 | } |
||
205 | |||
206 | /** |
||
207 | * Load a component. |
||
208 | * |
||
209 | * @param string $component The name of the component to load. |
||
210 | * @return callable|null Returns the component or **null** if the component isn't found. |
||
211 | */ |
||
212 | 64 | protected function loadComponent($component) { |
|
236 | |||
237 | 8 | protected function writeCompileException($props) { |
|
238 | 8 | echo "\n<section class=\"ebi-ex\">\n", |
|
239 | 8 | '<h2>Error compiling '.htmlspecialchars($props['path'])." near line {$props['line']}.</h2>\n"; |
|
240 | |||
241 | 8 | echo '<p class="ebi-ex-message">'.htmlspecialchars($props['message'])."</p>\n"; |
|
242 | |||
243 | 8 | if (!empty($props['source'])) { |
|
244 | 6 | $source = $props['source']; |
|
245 | 6 | if (isset($props['sourcePosition'])) { |
|
246 | 3 | $pos = $props['sourcePosition']; |
|
247 | 3 | $len = isset($props['sourceLength']) ? $props['sourceLength'] : 1; |
|
248 | |||
249 | 3 | if ($len === 1) { |
|
250 | // Small kludge to select a viewable character. |
||
251 | 3 | for (; $pos >= 0 && isset($source[$pos]) && in_array($source[$pos], [' ', "\n"], true); $pos--, $len++) { |
|
252 | // It's all in the loop. |
||
253 | } |
||
254 | } |
||
255 | |||
256 | 3 | $source = htmlspecialchars(substr($source, 0, $pos)). |
|
257 | 3 | '<mark class="ebi-ex-highlight">'.htmlspecialchars(substr($source, $pos, $len)).'</mark>'. |
|
258 | 3 | htmlspecialchars(substr($source, $pos + $len)); |
|
259 | } else { |
||
260 | 3 | $source = htmlspecialchars($source); |
|
261 | } |
||
262 | |||
263 | 6 | echo '<pre class="ebi-ex-source ebi-ex-context"><code>', |
|
264 | 6 | $source, |
|
265 | 6 | "</code></pre>\n"; |
|
266 | } |
||
267 | |||
268 | 8 | if (!empty($props['lines'])) { |
|
269 | 8 | echo '<pre class="ebi-ex-source ebi-ex-lines">'; |
|
270 | |||
271 | 8 | foreach ($props['lines'] as $i => $line) { |
|
272 | 8 | echo '<code class="ebi-ex-line">'; |
|
273 | |||
274 | 8 | $str = sprintf("%3d. %s", $i, htmlspecialchars($line)); |
|
275 | 8 | if ($i === $props['line']) { |
|
276 | 8 | echo "<mark class=\"ebi-ex-highlight\">$str</mark>"; |
|
277 | } else { |
||
278 | 6 | echo $str; |
|
279 | } |
||
280 | |||
281 | 8 | echo "</code>\n"; |
|
282 | } |
||
283 | |||
284 | 8 | echo "</pre>\n"; |
|
285 | } |
||
286 | |||
287 | 8 | echo "</section>\n"; |
|
288 | 8 | } |
|
289 | |||
290 | /** |
||
291 | * Check to see if a specific cache key exists in the cache. |
||
292 | * |
||
293 | * @param string $cacheKey The cache key to check. |
||
294 | * @return bool Returns **true** if there is a cache key at the file or **false** otherwise. |
||
295 | */ |
||
296 | 1 | public function cacheKeyExists($cacheKey) { |
|
300 | |||
301 | /** |
||
302 | * Compile a component from source, cache it and include it. |
||
303 | * |
||
304 | * @param string $component The name of the component. |
||
305 | * @param string $src The component source. |
||
306 | * @param string $cacheKey The cache key of the component. |
||
307 | * @return callable|null Returns the compiled component closure. |
||
308 | */ |
||
309 | 66 | public function compile($component, $src, $cacheKey) { |
|
320 | |||
321 | /** |
||
322 | * Include a cached component. |
||
323 | * |
||
324 | * @param string $component The component key. |
||
325 | * @param string $cachePath The path to the component. |
||
326 | * @return callable|null Returns the component function or **null** if the component wasn't properly defined. |
||
327 | */ |
||
328 | 58 | private function includeComponent($component, $cachePath) { |
|
342 | |||
343 | /** |
||
344 | * A safe version of {@link file_put_contents()} that also clears op caches. |
||
345 | * |
||
346 | * @param string $path The path to save to. |
||
347 | * @param string $contents The contents of the file. |
||
348 | * @return bool Returns **true** on success or **false** on failure. |
||
349 | */ |
||
350 | 58 | private function filePutContents($path, $contents) { |
|
351 | 58 | if (!file_exists(dirname($path))) { |
|
352 | 4 | mkdir(dirname($path), 0777, true); |
|
353 | } |
||
354 | 58 | $tmpPath = tempnam(dirname($path), 'ebi-'); |
|
355 | 58 | $r = false; |
|
356 | 58 | if (file_put_contents($tmpPath, $contents) !== false) { |
|
357 | 58 | chmod($tmpPath, 0664); |
|
358 | 58 | $r = rename($tmpPath, $path); |
|
359 | } |
||
360 | |||
361 | 58 | if (function_exists('apc_delete_file')) { |
|
362 | // This fixes a bug with some configurations of apc. |
||
363 | @apc_delete_file($path); |
||
364 | 58 | } elseif (function_exists('opcache_invalidate')) { |
|
365 | 58 | @opcache_invalidate($path); |
|
366 | } |
||
367 | |||
368 | 58 | return $r; |
|
369 | } |
||
370 | |||
371 | /** |
||
372 | * Include a file. |
||
373 | * |
||
374 | * This is method is useful for including a file bound to this object instance. |
||
375 | * |
||
376 | * @param string $path The path to the file to include. |
||
377 | * @return mixed Returns the result of the include. |
||
378 | */ |
||
379 | 58 | public function requireFile($path) { |
|
382 | |||
383 | /** |
||
384 | * Register a component. |
||
385 | * |
||
386 | * @param string $name The name of the component to register. |
||
387 | * @param callable $component The component function. |
||
388 | */ |
||
389 | 74 | public function defineComponent($name, callable $component) { |
|
392 | |||
393 | /** |
||
394 | * Render a component to a string. |
||
395 | * |
||
396 | * @param string $component The name of the component to render. |
||
397 | * @param array ...$args Arguments to pass to the component. |
||
398 | * @return string|null Returns the rendered component or **null** if the component was not found. |
||
399 | */ |
||
400 | 65 | public function render($component, ...$args) { |
|
413 | |||
414 | /** |
||
415 | * Set the error reporting appropriate for template rendering. |
||
416 | * |
||
417 | * @return int Returns the previous error level. |
||
418 | */ |
||
419 | public function setErrorReporting() { |
||
423 | |||
424 | /** |
||
425 | * Call a function registered with **defineFunction()**. |
||
426 | * |
||
427 | * If a static or global function is registered then it's simply rendered in the compiled template. |
||
428 | * This method is for closures or callbacks. |
||
429 | * |
||
430 | * @param string $name The name of the registered function. |
||
431 | * @param array ...$args The function's argument. |
||
432 | * @return mixed Returns the result of the function |
||
433 | * @throws RuntimeException Throws an exception when the function isn't found. |
||
434 | */ |
||
435 | 4 | public function call($name, ...$args) { |
|
442 | |||
443 | /** |
||
444 | * Render a variable appropriately for CSS. |
||
445 | * |
||
446 | * This is a convenience runtime function. |
||
447 | * |
||
448 | * @param string|array $expr A CSS class, an array of CSS classes, or an associative array where the keys are class |
||
449 | * names and the values are truthy conditions to include the class (or not). |
||
450 | * @return string Returns a space-delimited CSS class string. |
||
451 | */ |
||
452 | 7 | public function attributeClass($expr) { |
|
453 | 7 | if (is_array($expr)) { |
|
454 | 4 | $classes = []; |
|
455 | 4 | foreach ($expr as $i => $val) { |
|
456 | 4 | if (is_array($val)) { |
|
457 | 1 | $classes[] = $this->attributeClass($val); |
|
458 | 4 | } elseif (is_int($i)) { |
|
459 | 1 | $classes[] = $val; |
|
460 | 3 | } elseif (!empty($val)) { |
|
461 | 4 | $classes[] = $i; |
|
462 | } |
||
463 | } |
||
464 | 4 | return implode(' ', $classes); |
|
465 | } else { |
||
466 | 3 | return (string)$expr; |
|
467 | } |
||
468 | } |
||
469 | |||
470 | /** |
||
471 | * Format a data. |
||
472 | * |
||
473 | * @param mixed $date The date to format. This can be a string data, a timestamp or an instance of **DateTimeInterface**. |
||
474 | * @param string $format The format of the date. |
||
475 | * @return string Returns the formatted data. |
||
476 | * @see date_format() |
||
477 | */ |
||
478 | 1 | public function formatDate($date, $format = 'c') { |
|
479 | 1 | if (is_string($date)) { |
|
480 | try { |
||
481 | 1 | $date = new \DateTimeImmutable($date); |
|
482 | } catch (\Exception $ex) { |
||
483 | 1 | return '#error#'; |
|
484 | } |
||
485 | } elseif (empty($date)) { |
||
486 | return ''; |
||
487 | } elseif (is_int($date)) { |
||
488 | try { |
||
489 | $date = new \DateTimeImmutable('@'.$date); |
||
490 | } catch (\Exception $ex) { |
||
491 | return '#error#'; |
||
492 | } |
||
493 | } elseif (!$date instanceof \DateTimeInterface) { |
||
494 | return '#error#'; |
||
495 | } |
||
496 | |||
497 | 1 | return $date->format($format); |
|
498 | } |
||
499 | |||
500 | /** |
||
501 | * Get a single item from the meta array. |
||
502 | * |
||
503 | * @param string $name The key to get from. |
||
504 | * @param mixed $default The default value if no item at the key exists. |
||
505 | * @return mixed Returns the meta value. |
||
506 | */ |
||
507 | public function getMeta($name, $default = null) { |
||
510 | |||
511 | /** |
||
512 | * Set a single item to the meta array. |
||
513 | * |
||
514 | * @param string $name The key to set. |
||
515 | * @param mixed $value The new value. |
||
516 | * @return $this |
||
517 | */ |
||
518 | 1 | public function setMeta($name, $value) { |
|
522 | |||
523 | /** |
||
524 | * Get the template loader. |
||
525 | * |
||
526 | * The template loader translates component names into template contents. |
||
527 | * |
||
528 | * @return TemplateLoaderInterface Returns the template loader. |
||
529 | */ |
||
530 | 1 | public function getTemplateLoader() { |
|
533 | |||
534 | /** |
||
535 | * Set the template loader. |
||
536 | * |
||
537 | * The template loader translates component names into template contents. |
||
538 | * |
||
539 | * @param TemplateLoaderInterface $templateLoader The new template loader. |
||
540 | * @return $this |
||
541 | */ |
||
542 | public function setTemplateLoader($templateLoader) { |
||
546 | |||
547 | /** |
||
548 | * Get the entire meta array. |
||
549 | * |
||
550 | * @return array Returns the meta. |
||
551 | */ |
||
552 | public function getMetaArray() { |
||
555 | |||
556 | /** |
||
557 | * Set the entire meta array. |
||
558 | * |
||
559 | * @param array $meta The new meta array. |
||
560 | * @return $this |
||
561 | */ |
||
562 | public function setMetaArray(array $meta) { |
||
566 | |||
567 | /** |
||
568 | * Return a dynamic attribute. |
||
569 | * |
||
570 | * The attribute renders differently depending on the value. |
||
571 | * |
||
572 | * - If the value is **true** then it will render as an HTML5 boolean attribute. |
||
573 | * - If the value is **false** or **null** then the attribute will not render. |
||
574 | * - Other values render as attribute values. |
||
575 | * - Attributes that start with **aria-** render **true** and **false** as values. |
||
576 | * |
||
577 | * @param string $name The name of the attribute. |
||
578 | * @param mixed $value The value of the attribute. |
||
579 | * @return string Returns the attribute definition or an empty string. |
||
580 | */ |
||
581 | 16 | public function attribute($name, $value) { |
|
582 | 16 | if (substr($name, 0, 5) === 'aria-' && is_bool($value)) { |
|
583 | 2 | $value = $value ? 'true' : 'false'; |
|
584 | } |
||
585 | |||
586 | 16 | if ($value === true) { |
|
587 | 1 | return ' '.$name; |
|
588 | 15 | } elseif (!in_array($value, [null, false], true)) { |
|
589 | 12 | return " $name=\"".htmlspecialchars($value).'"'; |
|
590 | } |
||
591 | 4 | return ''; |
|
592 | } |
||
593 | |||
594 | /** |
||
595 | * Escape a value for echoing to HTML with a bit of non-scalar checking. |
||
596 | * |
||
597 | * @param mixed $val The value to escape. |
||
598 | * @return string The escaped value. |
||
599 | */ |
||
600 | 27 | public function escape($val = null) { |
|
611 | |||
612 | /** |
||
613 | * Write children blocks. |
||
614 | * |
||
615 | * @param array|callable|null $children The children blocks to write. |
||
616 | */ |
||
617 | 4 | public function writeChildren($children) { |
|
618 | 4 | if (empty($children)) { |
|
619 | return; |
||
620 | 4 | } elseif (is_array($children)) { |
|
621 | 1 | array_map([$this, 'writeChildren'], $children); |
|
626 | } |
||
627 |
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.