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