Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / lib / Drupal / Component / Discovery / YamlDiscovery.php
1 <?php
2
3 namespace Drupal\Component\Discovery;
4
5 use Drupal\Component\Serialization\Yaml;
6 use Drupal\Component\FileCache\FileCacheFactory;
7
8 /**
9  * Provides discovery for YAML files within a given set of directories.
10  */
11 class YamlDiscovery implements DiscoverableInterface {
12
13   /**
14    * The base filename to look for in each directory.
15    *
16    * @var string
17    */
18   protected $name;
19
20   /**
21    * An array of directories to scan, keyed by the provider.
22    *
23    * @var array
24    */
25   protected $directories = [];
26
27   /**
28    * Constructs a YamlDiscovery object.
29    *
30    * @param string $name
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.
35    */
36   public function __construct($name, array $directories) {
37     $this->name = $name;
38     $this->directories = $directories;
39   }
40
41   /**
42    * {@inheritdoc}
43    */
44   public function findAll() {
45     $all = [];
46
47     $files = $this->findFiles();
48     $provider_by_files = array_flip($files);
49
50     $file_cache = FileCacheFactory::get('yaml_discovery:' . $this->name);
51
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]);
56     }
57
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]);
66       }
67     }
68
69     return $all;
70   }
71
72   /**
73    * Decode a YAML file.
74    *
75    * @param string $file
76    *   Yaml file path.
77    * @return array
78    */
79   protected function decode($file) {
80     return Yaml::decode(file_get_contents($file)) ?: [];
81   }
82
83   /**
84    * Returns an array of file paths, keyed by provider.
85    *
86    * @return array
87    */
88   protected function findFiles() {
89     $files = [];
90     foreach ($this->directories as $provider => $directory) {
91       $file = $directory . '/' . $provider . '.' . $this->name . '.yml';
92       if (file_exists($file)) {
93         $files[$provider] = $file;
94       }
95     }
96     return $files;
97   }
98
99 }