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 TemplateRouter extends Routers\RouteList |
||
| 12 | { |
||
| 13 | /** @var ILatteFactory */ |
||
| 14 | private $latteFactory; |
||
| 15 | |||
| 16 | public function __construct($path, $cachePath, ILatteFactory $latteFactory) |
||
| 17 | { |
||
| 18 | parent::__construct(); |
||
| 19 | $this->latteFactory = $latteFactory; |
||
| 20 | |||
| 21 | if (is_file($cacheFile = $cachePath . '/routes.php')) { |
||
| 22 | $routes = require $cacheFile; |
||
| 23 | } else { |
||
| 24 | $routes = $this->scanRoutes($path); |
||
| 25 | file_put_contents($cacheFile, '<?php return ' . var_export($routes, true) . ';'); |
||
| 26 | } |
||
| 27 | |||
| 28 | foreach ($routes as $mask => $file) { |
||
| 29 | $this[] = new Routers\Route($mask, function ($presenter) use ($file, $cachePath, $latteFactory) { |
||
| 30 | return $presenter->createTemplate(null, [$this, 'createLatte'])->setFile($file); |
||
| 31 | }); |
||
| 32 | } |
||
| 33 | } |
||
| 34 | |||
| 35 | |||
| 36 | public function scanRoutes($path) |
||
| 37 | { |
||
| 38 | $routes = []; |
||
| 39 | |||
| 40 | $latte = $this->createLatte(); |
||
| 41 | $macroSet = new Latte\Macros\MacroSet($latte->getCompiler()); |
||
| 42 | $macroSet->addMacro('url', function ($node) use (&$routes, &$file) { |
||
| 43 | $routes[$node->args] = (string) $file; |
||
| 44 | }, null, null, $macroSet::ALLOWED_IN_HEAD); |
||
| 45 | |||
| 46 | foreach (Nette\Utils\Finder::findFiles('*.latte')->from($path) as $file) { |
||
| 47 | $latte->compile($file); |
||
| 48 | } |
||
| 49 | |||
| 50 | return $routes; |
||
| 51 | } |
||
| 52 | |||
| 53 | public function createLatte() { |
||
| 54 | $latte = $this->latteFactory->create(); |
||
| 55 | $macroSet = new Latte\Macros\MacroSet($latte->getCompiler()); |
||
| 56 | $macroSet->addMacro('url', function () {}, null, null, $macroSet::ALLOWED_IN_HEAD); // ignore |
||
| 57 | return $latte; |
||
| 58 | } |
||
| 59 | } |
||
| 60 |