Blueprints.php 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. /**
  3. * @package Grav\Common\Data
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Data;
  9. use Grav\Common\Grav;
  10. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  11. class Blueprints
  12. {
  13. /** @var array|string */
  14. protected $search;
  15. /** @var array */
  16. protected $types;
  17. /** @var array */
  18. protected $instances = [];
  19. /**
  20. * @param string|array $search Search path.
  21. */
  22. public function __construct($search = 'blueprints://')
  23. {
  24. $this->search = $search;
  25. }
  26. /**
  27. * Get blueprint.
  28. *
  29. * @param string $type Blueprint type.
  30. * @return Blueprint
  31. * @throws \RuntimeException
  32. */
  33. public function get($type)
  34. {
  35. if (!isset($this->instances[$type])) {
  36. $blueprint = $this->loadFile($type);
  37. $this->instances[$type] = $blueprint;
  38. }
  39. return $this->instances[$type];
  40. }
  41. /**
  42. * Get all available blueprint types.
  43. *
  44. * @return array List of type=>name
  45. */
  46. public function types()
  47. {
  48. if ($this->types === null) {
  49. $this->types = [];
  50. $grav = Grav::instance();
  51. /** @var UniformResourceLocator $locator */
  52. $locator = $grav['locator'];
  53. // Get stream / directory iterator.
  54. if ($locator->isStream($this->search)) {
  55. $iterator = $locator->getIterator($this->search);
  56. } else {
  57. $iterator = new \DirectoryIterator($this->search);
  58. }
  59. /** @var \DirectoryIterator $file */
  60. foreach ($iterator as $file) {
  61. if (!$file->isFile() || '.' . $file->getExtension() !== YAML_EXT) {
  62. continue;
  63. }
  64. $name = $file->getBasename(YAML_EXT);
  65. $this->types[$name] = ucfirst(str_replace('_', ' ', $name));
  66. }
  67. }
  68. return $this->types;
  69. }
  70. /**
  71. * Load blueprint file.
  72. *
  73. * @param string $name Name of the blueprint.
  74. * @return Blueprint
  75. */
  76. protected function loadFile($name)
  77. {
  78. $blueprint = new Blueprint($name);
  79. if (\is_array($this->search) || \is_object($this->search)) {
  80. // Page types.
  81. $blueprint->setOverrides($this->search);
  82. $blueprint->setContext('blueprints://pages');
  83. } else {
  84. $blueprint->setContext($this->search);
  85. }
  86. try {
  87. $blueprint->load()->init();
  88. } catch (\RuntimeException $e) {
  89. $log = Grav::instance()['log'];
  90. $log->error(sprintf('Blueprint %s cannot be loaded: %s', $name, $e->getMessage()));
  91. throw $e;
  92. }
  93. return $blueprint;
  94. }
  95. }