Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / vendor / drush / drush / src / SiteAlias / SiteAliasFileLoader.php
1 <?php
2 namespace Drush\SiteAlias;
3
4 use Consolidation\Config\Loader\ConfigProcessor;
5 use Dflydev\DotAccessData\Util as DotAccessDataUtil;
6 use Drush\Internal\Config\Yaml\Yaml;
7
8 /**
9  * Discover alias files:
10  *
11  * - sitename.site.yml: contains multiple aliases, one for each of the
12  *     environments of 'sitename'.
13  */
14 class SiteAliasFileLoader
15 {
16     /**
17      * @var SiteAliasFileDiscovery
18      */
19     protected $discovery;
20
21     /**
22      * @var array
23      */
24     protected $referenceData;
25
26     /**
27      * SiteAliasFileLoader constructor
28      *
29      * @param SiteAliasFileDiscovery|null $discovery
30      */
31     public function __construct($discovery = null)
32     {
33         $this->discovery = $discovery ?: new SiteAliasFileDiscovery();
34     }
35
36     /**
37      * Allow configuration data to be used in replacements in the alias file.
38      */
39     public function setReferenceData($data)
40     {
41         $this->referenceData = $data;
42     }
43
44     /**
45      * Add a search location to our discovery object.
46      *
47      * @param string $path
48      *
49      * @return $this
50      */
51     public function addSearchLocation($path)
52     {
53         $this->discovery()->addSearchLocation($path);
54         return $this;
55     }
56
57     /**
58      * Return our discovery object.
59      *
60      * @return SiteAliasFileDiscovery
61      */
62     public function discovery()
63     {
64         return $this->discovery;
65     }
66
67     /**
68      * Load the file containing the specified alias name.
69      *
70      * @param SiteAliasName $aliasName
71      *
72      * @return AliasRecord|false
73      */
74     public function load(SiteAliasName $aliasName)
75     {
76         // First attempt to load a sitename.site.yml file for the alias.
77         $aliasRecord = $this->loadSingleAliasFile($aliasName);
78         if ($aliasRecord) {
79             return $aliasRecord;
80         }
81
82         // If aliasname was provides as @site.env and we did not find it,
83         // then we are done.
84         if ($aliasName->hasSitename()) {
85             return false;
86         }
87
88         // If $aliasName was provided as `@foo` and defaulted to `@self.foo`,
89         // then make a new alias name `@foo.default` and see if we can find that.
90         // Note that at the moment, `foo` is stored in $aliasName->env().
91         $sitename = $aliasName->env();
92         return $this->loadDefaultEnvFromSitename($sitename);
93     }
94
95     /**
96      * Given only a site name, load the default environment from it.
97      */
98     protected function loadDefaultEnvFromSitename($sitename)
99     {
100         $path = $this->discovery()->findSingleSiteAliasFile($sitename);
101         if (!$path) {
102             return false;
103         }
104         $data = $this->loadSiteDataFromPath($path);
105         if (!$data) {
106             return false;
107         }
108         $env = $this->getDefaultEnvironmentName($data);
109
110         $aliasName = new SiteAliasName($sitename, $env);
111         $processor = new ConfigProcessor();
112         return $this->fetchAliasRecordFromSiteAliasData($aliasName, $processor, $data);
113     }
114
115     /**
116      * Return a list of all site aliases loadable from any findable path.
117      *
118      * @return AliasRecord[]
119      */
120     public function loadAll()
121     {
122         $result = [];
123         $paths = $this->discovery()->findAllSingleAliasFiles();
124         foreach ($paths as $path) {
125             $aliasRecords = $this->loadSingleSiteAliasFileAtPath($path);
126             foreach ($aliasRecords as $aliasRecord) {
127                 $this->storeAliasRecordInResut($result, $aliasRecord);
128             }
129         }
130         ksort($result);
131         return $result;
132     }
133
134     /**
135      * Return a list of all available alias files. Does not include
136      * legacy files.
137      *
138      * @return string[]
139      */
140     public function listAll()
141     {
142         return $this->discovery()->findAllSingleAliasFiles();
143     }
144
145     /**
146      * Given an alias name that might represent multiple sites,
147      * return a list of all matching alias records. If nothing was found,
148      * or the name represents a single site + env, then we take
149      * no action and return `false`.
150      *
151      * @param string $sitename The site name to return all environments for.
152      * @return AliasRecord[]|false
153      */
154     public function loadMultiple($sitename)
155     {
156         if ($path = $this->discovery()->findSingleSiteAliasFile($sitename)) {
157             if ($siteData = $this->loadSiteDataFromPath($path)) {
158                 // Convert the raw array into a list of alias records.
159                 return $this->createAliasRecordsFromSiteData($sitename, $siteData);
160             }
161         }
162         return false;
163     }
164
165     /**
166      * @param array $siteData list of sites with its respective data
167      *
168      * @param SiteAliasName $aliasName The name of the record being created
169      * @param $siteData An associative array of envrionment => site data
170      * @return AliasRecord[]
171      */
172     protected function createAliasRecordsFromSiteData($sitename, $siteData)
173     {
174         $result = [];
175         if (!is_array($siteData) || empty($siteData)) {
176             return $result;
177         }
178         foreach ($siteData as $envName => $data) {
179             if (is_array($data)) {
180                 $aliasName = new SiteAliasName($sitename, $envName);
181
182                 $processor = new ConfigProcessor();
183                 $oneRecord = $this->fetchAliasRecordFromSiteAliasData($aliasName, $processor, $siteData);
184                 $this->storeAliasRecordInResut($result, $oneRecord);
185             }
186         }
187         return $result;
188     }
189
190     /**
191      * Store an alias record in a list. If the alias record has
192      * a known name, then the key of the list will be the record's name.
193      * Otherwise, append the record to the end of the list with
194      * a numeric index.
195      *
196      * @param &AliasRecord[] $result list of alias records
197      * @param AliasRecord $aliasRecord one more alias to store in the result
198      */
199     protected function storeAliasRecordInResut(&$result, AliasRecord $aliasRecord)
200     {
201         if (!$aliasRecord) {
202             return;
203         }
204         $key = $aliasRecord->name();
205         if (empty($key)) {
206             $result[] = $aliasRecord;
207             return;
208         }
209         $result[$key] = $aliasRecord;
210     }
211
212     /**
213      * If the alias name is '@sitename', or if it is '@sitename.env', then
214      * look for a sitename.site.yml file that contains it.
215      *
216      * @param SiteAliasName $aliasName
217      *
218      * @return AliasRecord|false
219      */
220     protected function loadSingleAliasFile(SiteAliasName $aliasName)
221     {
222         // Check to see if the appropriate sitename.alias.yml file can be
223         // found. Return if it cannot.
224         $path = $this->discovery()->findSingleSiteAliasFile($aliasName->sitename());
225         if (!$path) {
226             return false;
227         }
228         return $this->loadSingleAliasFileWithNameAtPath($aliasName, $path);
229     }
230
231     /**
232      * Given only the path to an alias file `site.alias.yml`, return all
233      * of the alias records for every environment stored in that file.
234      *
235      * @param string $path
236      * @return AliasRecord[]
237      */
238     protected function loadSingleSiteAliasFileAtPath($path)
239     {
240         $sitename = $this->siteNameFromPath($path);
241         $siteData = $this->loadSiteDataFromPath($path);
242         return $this->createAliasRecordsFromSiteData($sitename, $siteData);
243     }
244
245     /**
246      * Given the path to a single site alias file `site.alias.yml`,
247      * return the `site` part.
248      *
249      * @param string $path
250      */
251     protected function siteNameFromPath($path)
252     {
253         return $this->basenameWithoutExtension($path, '.site.yml');
254     }
255
256     /**
257      * Chop off the `aliases.yml` or `alias.yml` part of a path. This works
258      * just like `basename`, except it will throw if the provided path
259      * does not end in the specified extension.
260      *
261      * @param string $path
262      * @param string $extension
263      * @return string
264      * @throws \Exception
265      */
266     protected function basenameWithoutExtension($path, $extension)
267     {
268         $result = basename($path, $extension);
269         // It is an error if $path does not end with site.yml
270         if ($result == basename($path)) {
271             throw new \Exception("$path must end with '$extension'");
272         }
273         return $result;
274     }
275
276     /**
277      * Given an alias name and a path, load the data from the path
278      * and process it as needed to generate the alias record.
279      *
280      * @param SiteAliasName $aliasName
281      * @param string $path
282      * @return AliasRecord|false
283      */
284     protected function loadSingleAliasFileWithNameAtPath(SiteAliasName $aliasName, $path)
285     {
286         $data = $this->loadSiteDataFromPath($path);
287         if (!$data) {
288             return false;
289         }
290         $processor = new ConfigProcessor();
291         return $this->fetchAliasRecordFromSiteAliasData($aliasName, $processor, $data);
292     }
293
294     /**
295      * Load the yml from the given path
296      *
297      * @param string $path
298      * @return array|bool
299      */
300     protected function loadSiteDataFromPath($path)
301     {
302         $data = $this->loadYml($path);
303         if (!$data) {
304             return false;
305         }
306         $selfSiteAliases = $this->findSelfSiteAliases($data);
307         $data = array_merge($data, $selfSiteAliases);
308         return $data;
309     }
310
311     /**
312      * Given an array of site aliases, find the first one that is
313      * local (has no 'host' item) and also contains a 'self.site.yml' file.
314      * @param array $data
315      * @return array
316      */
317     protected function findSelfSiteAliases($site_aliases)
318     {
319         foreach ($site_aliases as $site => $data) {
320             if (!isset($data['host']) && isset($data['root'])) {
321                 foreach (['.', '..'] as $relative_path) {
322                     $candidate = $data['root'] . '/' . $relative_path . '/drush/sites/self.site.yml';
323                     if (file_exists($candidate)) {
324                         return $this->loadYml($candidate);
325                     }
326                 }
327             }
328         }
329         return [];
330     }
331
332     /**
333      * Load the yaml contents of the specified file.
334      *
335      * @param string $path Path to file to load
336      * @return array
337      */
338     protected function loadYml($path)
339     {
340         if (empty($path)) {
341             return [];
342         }
343         // TODO: Perhaps cache these alias files, as they may be read multiple times.
344         // TODO: Maybe use a YamlConfigLoader?
345         return (array) Yaml::parse(file_get_contents($path));
346     }
347
348     /**
349      * Given an array containing site alias data, return an alias record
350      * containing the data for the requested record. If there is a 'common'
351      * section, then merge that in as well.
352      *
353      * @param SiteAliasName $aliasName the alias we are loading
354      * @param array $data
355      *
356      * @return AliasRecord|false
357      */
358     protected function fetchAliasRecordFromSiteAliasData(SiteAliasName $aliasName, ConfigProcessor $processor, array $data)
359     {
360         $data = $this->adjustIfSingleAlias($data);
361         $env = $this->getEnvironmentName($aliasName, $data);
362         if (!$this->siteEnvExists($data, $env)) {
363             return false;
364         }
365
366         // Add the 'common' section if it exists.
367         if (isset($data['common']) && is_array($data['common'])) {
368             $processor->add($data['common']);
369         }
370
371         // Then add the data from the desired environment.
372         $processor->add($data[$env]);
373
374         // Export the combined data and create an AliasRecord object to manage it.
375         return new AliasRecord($processor->export($this->referenceData), '@' . $aliasName->sitename(), $env);
376     }
377
378     /**
379      * Determine whether there is a valid-looking environment '$env' in the
380      * provided site alias data.
381      *
382      * @param array $data
383      * @param string $env
384      * @return bool
385      */
386     protected function siteEnvExists(array $data, $env)
387     {
388         return (
389             is_array($data) &&
390             isset($data[$env]) &&
391             is_array($data[$env])
392         );
393     }
394
395     /**
396      * Adjust the alias data for a single-site alias. Usually, a .yml alias
397      * file will contain multiple entries, one for each of the environments
398      * of an alias. If there are no environments
399      *
400      * @param array $data
401      * @return array
402      */
403     protected function adjustIfSingleAlias($data)
404     {
405         if (!$this->detectSingleAlias($data)) {
406             return $data;
407         }
408
409         $result = [
410             'default' => $data,
411         ];
412
413         return $result;
414     }
415
416     /**
417      * A single-environment alias looks something like this:
418      *
419      *   ---
420      *   root: /path/to/drupal
421      *   uri: https://mysite.org
422      *
423      * A multiple-environment alias looks something like this:
424      *
425      *   ---
426      *   default: dev
427      *   dev:
428      *     root: /path/to/dev
429      *     uri: https://dev.mysite.org
430      *   stage:
431      *     root: /path/to/stage
432      *     uri: https://stage.mysite.org
433      *
434      * The differentiator between these two is that the multi-environment
435      * alias always has top-level elements that are associative arrays, and
436      * the single-environment alias never does.
437      *
438      * @param array $data
439      * @return bool
440      */
441     protected function detectSingleAlias($data)
442     {
443         foreach ($data as $key => $value) {
444             if (is_array($value) && DotAccessDataUtil::isAssoc($value)) {
445                 return false;
446             }
447         }
448         return true;
449     }
450
451     /**
452      * Return the name of the environment requested.
453      *
454      * @param SiteAliasName $aliasName the alias we are loading
455      * @param array $data
456      *
457      * @return string
458      */
459     protected function getEnvironmentName(SiteAliasName $aliasName, array $data)
460     {
461         // If the alias name specifically mentions the environment
462         // to use, then return it.
463         if ($aliasName->hasEnv()) {
464             return $aliasName->env();
465         }
466         return $this->getDefaultEnvironmentName($data);
467     }
468
469     /**
470      * Given a data array containing site alias environments, determine which
471      * envirionmnet should be used as the default environment.
472      *
473      * @param array $data
474      * @return string
475      */
476     protected function getDefaultEnvironmentName(array $data)
477     {
478         // If there is an entry named 'default', it will either contain the
479         // name of the environment to use by default, or it will itself be
480         // the default environment.
481         if (isset($data['default'])) {
482             return is_array($data['default']) ? 'default' : $data['default'];
483         }
484         // If there is an environment named 'dev', it will be our default.
485         if (isset($data['dev'])) {
486             return 'dev';
487         }
488         // If we don't know which environment to use, just take the first one.
489         $keys = array_keys($data);
490         return reset($keys);
491     }
492 }