YamlDiscovery.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace Drupal\Component\Discovery;
  3. use Drupal\Component\Serialization\Yaml;
  4. use Drupal\Component\FileCache\FileCacheFactory;
  5. /**
  6. * Provides discovery for YAML files within a given set of directories.
  7. */
  8. class YamlDiscovery implements DiscoverableInterface {
  9. /**
  10. * The base filename to look for in each directory.
  11. *
  12. * @var string
  13. */
  14. protected $name;
  15. /**
  16. * An array of directories to scan, keyed by the provider.
  17. *
  18. * @var array
  19. */
  20. protected $directories = [];
  21. /**
  22. * Constructs a YamlDiscovery object.
  23. *
  24. * @param string $name
  25. * The base filename to look for in each directory. The format will be
  26. * $provider.$name.yml.
  27. * @param array $directories
  28. * An array of directories to scan, keyed by the provider.
  29. */
  30. public function __construct($name, array $directories) {
  31. $this->name = $name;
  32. $this->directories = $directories;
  33. }
  34. /**
  35. * {@inheritdoc}
  36. */
  37. public function findAll() {
  38. $all = [];
  39. $files = $this->findFiles();
  40. $provider_by_files = array_flip($files);
  41. $file_cache = FileCacheFactory::get('yaml_discovery:' . $this->name);
  42. // Try to load from the file cache first.
  43. foreach ($file_cache->getMultiple($files) as $file => $data) {
  44. $all[$provider_by_files[$file]] = $data;
  45. unset($provider_by_files[$file]);
  46. }
  47. // If there are files left that were not returned from the cache, load and
  48. // parse them now. This list was flipped above and is keyed by filename.
  49. if ($provider_by_files) {
  50. foreach ($provider_by_files as $file => $provider) {
  51. // If a file is empty or its contents are commented out, return an empty
  52. // array instead of NULL for type consistency.
  53. $all[$provider] = $this->decode($file);
  54. $file_cache->set($file, $all[$provider]);
  55. }
  56. }
  57. return $all;
  58. }
  59. /**
  60. * Decode a YAML file.
  61. *
  62. * @param string $file
  63. * Yaml file path.
  64. * @return array
  65. */
  66. protected function decode($file) {
  67. return Yaml::decode(file_get_contents($file)) ?: [];
  68. }
  69. /**
  70. * Returns an array of file paths, keyed by provider.
  71. *
  72. * @return array
  73. */
  74. protected function findFiles() {
  75. $files = [];
  76. foreach ($this->directories as $provider => $directory) {
  77. $file = $directory . '/' . $provider . '.' . $this->name . '.yml';
  78. if (file_exists($file)) {
  79. $files[$provider] = $file;
  80. }
  81. }
  82. return $files;
  83. }
  84. }