PluginViewBuilder.php
69 lines
| 1 | <?php |
| 2 | |
| 3 | namespace FSVendor\WPDesk\View; |
| 4 | |
| 5 | use FSVendor\WPDesk\View\Renderer\SimplePhpRenderer; |
| 6 | use FSVendor\WPDesk\View\Resolver\ChainResolver; |
| 7 | use FSVendor\WPDesk\View\Resolver\DirResolver; |
| 8 | use FSVendor\WPDesk\View\Resolver\WPThemeResolver; |
| 9 | /** |
| 10 | * Facilitates building of the default plugin renderer. |
| 11 | * |
| 12 | * @package WPDesk\View |
| 13 | */ |
| 14 | class PluginViewBuilder |
| 15 | { |
| 16 | /** @var string */ |
| 17 | private $plugin_dir; |
| 18 | /** @var string[] */ |
| 19 | private $template_dirs; |
| 20 | /** |
| 21 | * @param string $plugin_dir Plugin directory path(absolute path) |
| 22 | * @param string|string[] $template_dir Directory or list of directories with templates to render |
| 23 | */ |
| 24 | public function __construct($plugin_dir, $template_dir = 'templates') |
| 25 | { |
| 26 | $this->plugin_dir = $plugin_dir; |
| 27 | if (!is_array($template_dir)) { |
| 28 | $this->template_dirs = [$template_dir]; |
| 29 | } else { |
| 30 | $this->template_dirs = $template_dir; |
| 31 | } |
| 32 | } |
| 33 | /** |
| 34 | * Creates simple renderer that search for the templates in plugin dir and in theme/child dir. |
| 35 | * |
| 36 | * For example if your plugin dir is /plugin, template dir is /templates, theme is /theme, and a child theme is /child |
| 37 | * the templates will be loaded from(order is important): |
| 38 | * - /child/plugin/*.php |
| 39 | * - /theme/plugin/*.php |
| 40 | * - /plugin/templates/*.php |
| 41 | * |
| 42 | * @return SimplePhpRenderer |
| 43 | */ |
| 44 | public function createSimpleRenderer() |
| 45 | { |
| 46 | $resolver = new ChainResolver(); |
| 47 | $resolver->appendResolver(new WPThemeResolver(basename($this->plugin_dir))); |
| 48 | foreach ($this->template_dirs as $dir) { |
| 49 | $dir = trailingslashit($this->plugin_dir) . trailingslashit($dir); |
| 50 | $resolver->appendResolver(new DirResolver($dir)); |
| 51 | } |
| 52 | return new SimplePhpRenderer($resolver); |
| 53 | } |
| 54 | /** |
| 55 | * Load templates using simple renderer. |
| 56 | * |
| 57 | * @param string $name Name of the template |
| 58 | * @param string $path Additional path of the template ie. for path "path" the templates would be loaded from /plugin/templates/path/*.php |
| 59 | * @param array $args Arguments for templates to use |
| 60 | * |
| 61 | * @return string Rendered template. |
| 62 | */ |
| 63 | public function loadTemplate($name, $path = '.', $args = []) |
| 64 | { |
| 65 | $renderer = $this->createSimpleRenderer(); |
| 66 | return $renderer->render(trailingslashit($path) . $name, $args); |
| 67 | } |
| 68 | } |
| 69 |