3 namespace Drupal\Component\Discovery;
5 use Drupal\Component\Serialization\Yaml;
6 use Drupal\Component\FileCache\FileCacheFactory;
9 * Provides discovery for YAML files within a given set of directories.
11 class YamlDiscovery implements DiscoverableInterface {
14 * The base filename to look for in each directory.
21 * An array of directories to scan, keyed by the provider.
25 protected $directories = [];
28 * Constructs a YamlDiscovery object.
31 * The base filename to look for in each directory. The format will be
32 * $provider.$name.yml.
33 * @param array $directories
34 * An array of directories to scan, keyed by the provider.
36 public function __construct($name, array $directories) {
38 $this->directories = $directories;
44 public function findAll() {
47 $files = $this->findFiles();
48 $provider_by_files = array_flip($files);
50 $file_cache = FileCacheFactory::get('yaml_discovery:' . $this->name);
52 // Try to load from the file cache first.
53 foreach ($file_cache->getMultiple($files) as $file => $data) {
54 $all[$provider_by_files[$file]] = $data;
55 unset($provider_by_files[$file]);
58 // If there are files left that were not returned from the cache, load and
59 // parse them now. This list was flipped above and is keyed by filename.
60 if ($provider_by_files) {
61 foreach ($provider_by_files as $file => $provider) {
62 // If a file is empty or its contents are commented out, return an empty
63 // array instead of NULL for type consistency.
64 $all[$provider] = $this->decode($file);
65 $file_cache->set($file, $all[$provider]);
79 protected function decode($file) {
80 return Yaml::decode(file_get_contents($file)) ?: [];
84 * Returns an array of file paths, keyed by provider.
88 protected function findFiles() {
90 foreach ($this->directories as $provider => $directory) {
91 $file = $directory . '/' . $provider . '.' . $this->name . '.yml';
92 if (file_exists($file)) {
93 $files[$provider] = $file;