PageRenderTime 29ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/web/vendor/latte/latte/src/Latte/Loaders/FileLoader.php

https://gitlab.com/adam.kvita/MI-VMM-SIFT
PHP | 100 lines | 65 code | 16 blank | 19 comment | 3 complexity | 05990f8fa84d7f9a861fcfa6cac997a7 MD5 | raw file
  1. <?php
  2. /**
  3. * This file is part of the Latte (https://latte.nette.org)
  4. * Copyright (c) 2008 David Grudl (https://davidgrudl.com)
  5. */
  6. namespace Latte\Loaders;
  7. use Latte;
  8. /**
  9. * Template loader.
  10. */
  11. class FileLoader implements Latte\ILoader
  12. {
  13. use Latte\Strict;
  14. /** @var string|NULL */
  15. private $baseDir;
  16. public function __construct($baseDir = NULL)
  17. {
  18. $this->baseDir = $baseDir ? $this->normalizePath("$baseDir/") : NULL;
  19. }
  20. /**
  21. * Returns template source code.
  22. * @return string
  23. */
  24. public function getContent($file)
  25. {
  26. $file = $this->baseDir . $file;
  27. if ($this->baseDir && !Latte\Helpers::startsWith($this->normalizePath($file), $this->baseDir)) {
  28. throw new \RuntimeException("Template '$file' is not within the allowed path '$this->baseDir'.");
  29. } elseif (!is_file($file)) {
  30. throw new \RuntimeException("Missing template file '$file'.");
  31. } elseif ($this->isExpired($file, time())) {
  32. if (@touch($file) === FALSE) {
  33. trigger_error("File's modification time is in the future. Cannot update it: " . error_get_last()['message'], E_USER_WARNING);
  34. }
  35. }
  36. return file_get_contents($file);
  37. }
  38. /**
  39. * @return bool
  40. */
  41. public function isExpired($file, $time)
  42. {
  43. return @filemtime($this->baseDir . $file) > $time; // @ - stat may fail
  44. }
  45. /**
  46. * Returns referred template name.
  47. * @return string
  48. */
  49. public function getReferredName($file, $referringFile)
  50. {
  51. if ($this->baseDir || !preg_match('#/|\\\\|[a-z][a-z0-9+.-]*:#iA', $file)) {
  52. $file = $this->normalizePath($referringFile . '/../' . $file);
  53. }
  54. return $file;
  55. }
  56. /**
  57. * Returns unique identifier for caching.
  58. * @return string
  59. */
  60. public function getUniqueId($file)
  61. {
  62. return $this->baseDir . strtr($file, '/', DIRECTORY_SEPARATOR);
  63. }
  64. /**
  65. * @return string
  66. */
  67. private static function normalizePath($path)
  68. {
  69. $res = [];
  70. foreach (explode('/', strtr($path, '\\', '/')) as $part) {
  71. if ($part === '..' && $res) {
  72. array_pop($res);
  73. } elseif ($part !== '.') {
  74. $res[] = $part;
  75. }
  76. }
  77. return implode(DIRECTORY_SEPARATOR, $res);
  78. }
  79. }