MustacheLoader.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. /**
  3. * A Mustache Partial filesystem loader.
  4. *
  5. * @author Justin Hileman {@link http://justinhileman.com}
  6. */
  7. class MustacheLoader implements ArrayAccess {
  8. protected $baseDir;
  9. protected $partialsCache = array();
  10. protected $extension;
  11. /**
  12. * MustacheLoader constructor.
  13. *
  14. * @access public
  15. * @param string $baseDir Base template directory.
  16. * @param string $extension File extension for Mustache files (default: 'mustache')
  17. * @return void
  18. */
  19. public function __construct($baseDir, $extension = 'mustache') {
  20. if (!is_dir($baseDir)) {
  21. throw new InvalidArgumentException('$baseDir must be a valid directory, ' . $baseDir . ' given.');
  22. }
  23. $this->baseDir = $baseDir;
  24. $this->extension = $extension;
  25. }
  26. /**
  27. * @param string $offset Name of partial
  28. * @return boolean
  29. */
  30. public function offsetExists($offset) {
  31. return (isset($this->partialsCache[$offset]) || file_exists($this->pathName($offset)));
  32. }
  33. /**
  34. * @throws InvalidArgumentException if the given partial doesn't exist
  35. * @param string $offset Name of partial
  36. * @return string Partial template contents
  37. */
  38. public function offsetGet($offset) {
  39. if (!$this->offsetExists($offset)) {
  40. throw new InvalidArgumentException('Partial does not exist: ' . $offset);
  41. }
  42. if (!isset($this->partialsCache[$offset])) {
  43. $this->partialsCache[$offset] = file_get_contents($this->pathName($offset));
  44. }
  45. return $this->partialsCache[$offset];
  46. }
  47. /**
  48. * MustacheLoader is an immutable filesystem loader. offsetSet throws a LogicException if called.
  49. *
  50. * @throws LogicException
  51. * @return void
  52. */
  53. public function offsetSet($offset, $value) {
  54. throw new LogicException('Unable to set offset: MustacheLoader is an immutable ArrayAccess object.');
  55. }
  56. /**
  57. * MustacheLoader is an immutable filesystem loader. offsetUnset throws a LogicException if called.
  58. *
  59. * @throws LogicException
  60. * @return void
  61. */
  62. public function offsetUnset($offset) {
  63. throw new LogicException('Unable to unset offset: MustacheLoader is an immutable ArrayAccess object.');
  64. }
  65. /**
  66. * An internal helper for generating path names.
  67. *
  68. * @param string $file Partial name
  69. * @return string File path
  70. */
  71. protected function pathName($file) {
  72. return $this->baseDir . '/' . $file . '.' . $this->extension;
  73. }
  74. }