SproutCMS

This is the code documentation for the SproutCMS project

source of /sprout/Helpers/TwigSkinLoader.php

  1. <?php
  2. /*
  3.  * Copyright (C) 2021 Karmabunny Pty Ltd.
  4.  *
  5.  * This file is a part of SproutCMS.
  6.  *
  7.  * SproutCMS is free software: you can redistribute it and/or modify it under the terms
  8.  * of the GNU General Public License as published by the Free Software Foundation, either
  9.  * version 2 of the License, or (at your option) any later version.
  10.  *
  11.  * For more information, visit <http://getsproutcms.com>.
  12.  */
  13.  
  14. namespace Sprout\Helpers;
  15.  
  16. use Kohana_Exception;
  17. use Exception;
  18. use Sprout\Exceptions\FileMissingException;
  19. use Twig\Error\LoaderError;
  20. use Twig\Loader\LoaderInterface;
  21. use Twig\Source;
  22.  
  23. /**
  24.  * File loader for twig templates.
  25.  *
  26.  * This obeys the same path rules as PHP views:
  27.  * - using the unavailable skin
  28.  * - using module/ sprout/ skin/ prefixes
  29.  *
  30.  * TODO Some actual caching.
  31.  */
  32. class TwigSkinLoader implements LoaderInterface
  33. {
  34.  
  35. /**
  36.   * File path cache.
  37.   *
  38.   * @var string[] [ name => path ]
  39.   */
  40. protected $cache = [];
  41.  
  42.  
  43. /**
  44.   * Template cache.
  45.   *
  46.   * @var string[] [ name => template]
  47.   */
  48. protected $templates = [];
  49.  
  50.  
  51. /**
  52.   * Find a template for the current subsite skin.
  53.   *
  54.   * @param mixed $name
  55.   * @return string
  56.   * @throws Kohana_Exception
  57.   * @throws Exception
  58.   * @throws FileMissingException
  59.   */
  60. protected function findTemplate(string $name)
  61. {
  62. if ($path = $this->cache[$name] ?? null) {
  63. return $path;
  64. }
  65.  
  66. $path = Skin::findTemplate($name, '.twig');
  67. $this->cache[$name] = $path;
  68. return $path;
  69. }
  70.  
  71.  
  72. /** @inheritdoc */
  73. public function getSourceContext(string $name): Source
  74. {
  75. try {
  76. $path = DOCROOT . $this->findTemplate($name);
  77. $template = file_get_contents($path);
  78. return new Source($template, $name);
  79. }
  80. catch (Exception $exception) {
  81. throw new LoaderError($exception->getMessage(), -1, null, $exception);
  82. }
  83. }
  84.  
  85.  
  86. /** @inheritdoc */
  87. public function getCacheKey(string $name): string
  88. {
  89. return $name;
  90. }
  91.  
  92.  
  93. /** @inheritdoc */
  94. public function isFresh(string $name, int $time): bool
  95. {
  96. $this->findTemplate($name);
  97. return true;
  98. }
  99.  
  100.  
  101. /** @inheritdoc */
  102. public function exists(string $name)
  103. {
  104. try {
  105. $this->findTemplate($name);
  106. return true;
  107. }
  108. catch (FileMissingException $e) {
  109. return false;
  110. }
  111. }
  112. }
  113.