Blueprints.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. $this->instances[$type] = $this->loadFile($type);
  37. }
  38. return $this->instances[$type];
  39. }
  40. /**
  41. * Get all available blueprint types.
  42. *
  43. * @return array List of type=>name
  44. */
  45. public function types()
  46. {
  47. if ($this->types === null) {
  48. $this->types = [];
  49. $grav = Grav::instance();
  50. /** @var UniformResourceLocator $locator */
  51. $locator = $grav['locator'];
  52. // Get stream / directory iterator.
  53. if ($locator->isStream($this->search)) {
  54. $iterator = $locator->getIterator($this->search);
  55. } else {
  56. $iterator = new \DirectoryIterator($this->search);
  57. }
  58. /** @var \DirectoryIterator $file */
  59. foreach ($iterator as $file) {
  60. if (!$file->isFile() || '.' . $file->getExtension() !== YAML_EXT) {
  61. continue;
  62. }
  63. $name = $file->getBasename(YAML_EXT);
  64. $this->types[$name] = ucfirst(str_replace('_', ' ', $name));
  65. }
  66. }
  67. return $this->types;
  68. }
  69. /**
  70. * Load blueprint file.
  71. *
  72. * @param string $name Name of the blueprint.
  73. * @return Blueprint
  74. */
  75. protected function loadFile($name)
  76. {
  77. $blueprint = new Blueprint($name);
  78. if (\is_array($this->search) || \is_object($this->search)) {
  79. // Page types.
  80. $blueprint->setOverrides($this->search);
  81. $blueprint->setContext('blueprints://pages');
  82. } else {
  83. $blueprint->setContext($this->search);
  84. }
  85. return $blueprint->load()->init();
  86. }
  87. }