|
| 1 | +<?php |
| 2 | + |
| 3 | +/** |
| 4 | + * This file is part of the Nette Framework (https://nette.org) |
| 5 | + * Copyright (c) 2004 David Grudl (https://davidgrudl.com) |
| 6 | + */ |
| 7 | + |
| 8 | +declare(strict_types=1); |
| 9 | + |
| 10 | +namespace Nette\Bridges\ApplicationLatte; |
| 11 | + |
| 12 | +use Latte; |
| 13 | +use Latte\Runtime\TemplatePrinter as Helpers; |
| 14 | +use Nette\Application\UI\Presenter; |
| 15 | + |
| 16 | + |
| 17 | +/** |
| 18 | + * Generates blueprint of template class. |
| 19 | + */ |
| 20 | +final class TemplatePrinter |
| 21 | +{ |
| 22 | + use Nette\SmartObject; |
| 23 | + |
| 24 | + public function print(Latte\Runtime\Template $template, string $class = null): string |
| 25 | + { |
| 26 | + $types = array_map([Helpers::class, 'getType'], $template->getParameters()); |
| 27 | + if ($template->getParameter('control') instanceof Presenter) { |
| 28 | + unset($types['control']); |
| 29 | + $subject = $template->getParameter('presenter'); |
| 30 | + $class = $class ?: preg_replace('#Presenter$#', '', get_class($subject)) . ucfirst($subject->getView()) . 'Template'; |
| 31 | + } else { |
| 32 | + unset($types['presenter']); |
| 33 | + $subject = $template->getParameter('control'); |
| 34 | + $class = $class ?: preg_replace('#Control$#', '', get_class($subject)) . 'Template'; |
| 35 | + } |
| 36 | + unset($types['user'], $types['baseUrl'], $types['basePath'], $types['flashes']); |
| 37 | + |
| 38 | + $funcs = []; |
| 39 | + foreach ($template->global as $name => $val) { |
| 40 | + if (substr($name, 0, 3) === '_fn') { |
| 41 | + $name = substr($name, 3); |
| 42 | + $funcs[$name] = Helpers::printFunction($name, $val, true); |
| 43 | + } |
| 44 | + } |
| 45 | + unset($funcs['islinkcurrent'], $funcs['ismodulecurrent']); |
| 46 | + |
| 47 | + $parts = explode('\\', $class); |
| 48 | + $name = array_pop($parts); |
| 49 | + $namespace = implode('\\', $parts); |
| 50 | + $parent = Template::class; |
| 51 | + $subject = explode('\\', get_class($subject)); |
| 52 | + $subject = end($subject); |
| 53 | + return |
| 54 | + ($namespace ? "namespace $namespace;\n\n" : '') |
| 55 | + . "class $name extends $parent\n" |
| 56 | + . "{\n" . Helpers::printProperties($types, true) . "\n}\n" |
| 57 | + . "\n\n" |
| 58 | + . "/**\n" . Helpers::printProperties($types, false) . "\n" |
| 59 | + . implode("\n", $funcs) . "\n */\n" |
| 60 | + . "class $name extends $parent\n" |
| 61 | + . "{\n}\n" |
| 62 | + . "\n\n" |
| 63 | + . "/**\n * @property $name \$template\n */\n" |
| 64 | + . "class $subject\n" |
| 65 | + . "{\n}\n"; |
| 66 | + } |
| 67 | +} |
0 commit comments