2 namespace Consolidation\SiteAlias;
4 use Consolidation\Config\Loader\ConfigProcessor;
5 use Dflydev\DotAccessData\Util as DotAccessDataUtil;
8 * Discover alias files:
10 * - sitename.site.yml: contains multiple aliases, one for each of the
11 * environments of 'sitename'.
13 class SiteAliasFileLoader
16 * @var SiteAliasFileDiscovery
23 protected $referenceData;
31 * SiteAliasFileLoader constructor
33 * @param SiteAliasFileDiscovery|null $discovery
35 public function __construct($discovery = null)
37 $this->discovery = $discovery ?: new SiteAliasFileDiscovery();
38 $this->referenceData = [];
43 * Allow configuration data to be used in replacements in the alias file.
45 public function setReferenceData($data)
47 $this->referenceData = $data;
51 * Add a search location to our discovery object.
57 public function addSearchLocation($path)
59 $this->discovery()->addSearchLocation($path);
64 * Return our discovery object.
66 * @return SiteAliasFileDiscovery
68 public function discovery()
70 return $this->discovery;
74 * Load the file containing the specified alias name.
76 * @param SiteAliasName $aliasName
78 * @return AliasRecord|false
80 public function load(SiteAliasName $aliasName)
82 // First attempt to load a sitename.site.yml file for the alias.
83 $aliasRecord = $this->loadSingleAliasFile($aliasName);
88 // If aliasname was provides as @site.env and we did not find it,
90 if ($aliasName->hasSitename()) {
94 // If $aliasName was provided as `@foo` (`hasSitename()` returned `false`
95 // above), then this was interpreted as `@self.foo` when we searched
96 // above. If we could not find an alias record for `@self.foo`, then we
97 // will try to search again, this time with the assumption that `@foo`
98 // might be `@foo.<default>`, where `<default>` is the default
99 // environment for the specified site. Note that in this instance, the
100 // sitename will be found in $aliasName->env().
101 $sitename = $aliasName->env();
102 return $this->loadDefaultEnvFromSitename($sitename);
106 * Given only a site name, load the default environment from it.
108 protected function loadDefaultEnvFromSitename($sitename)
110 $path = $this->discovery()->findSingleSiteAliasFile($sitename);
114 $data = $this->loadSiteDataFromPath($path);
118 $env = $this->getDefaultEnvironmentName($data);
120 $aliasName = new SiteAliasName($sitename, $env);
121 $processor = new ConfigProcessor();
122 return $this->fetchAliasRecordFromSiteAliasData($aliasName, $processor, $data);
126 * Return a list of all site aliases loadable from any findable path.
128 * @return AliasRecord[]
130 public function loadAll()
133 $paths = $this->discovery()->findAllSingleAliasFiles();
134 foreach ($paths as $path) {
135 $aliasRecords = $this->loadSingleSiteAliasFileAtPath($path);
137 foreach ($aliasRecords as $aliasRecord) {
138 $this->storeAliasRecordInResut($result, $aliasRecord);
147 * Return a list of all available alias files. Does not include
150 * @param string $location Only consider alias files in the specified location.
153 public function listAll($location = '')
155 return $this->discovery()->filterByLocation($location)->findAllSingleAliasFiles();
159 * Given an alias name that might represent multiple sites,
160 * return a list of all matching alias records. If nothing was found,
161 * or the name represents a single site + env, then we take
162 * no action and return `false`.
164 * @param string $sitename The site name to return all environments for.
165 * @return AliasRecord[]|false
167 public function loadMultiple($sitename, $location = null)
170 foreach ($this->discovery()->filterByLocation($location)->find($sitename) as $path) {
171 if ($siteData = $this->loadSiteDataFromPath($path)) {
172 $location = SiteAliasName::locationFromPath($path);
173 // Convert the raw array into a list of alias records.
174 $result = array_merge(
176 $this->createAliasRecordsFromSiteData($sitename, $siteData, $location)
184 * Given a location, return all alias files located there.
186 * @param string $location The location to filter.
187 * @return AliasRecord[]
189 public function loadLocation($location)
192 foreach ($this->listAll($location) as $path) {
193 if ($siteData = $this->loadSiteDataFromPath($path)) {
194 $location = SiteAliasName::locationFromPath($path);
195 $sitename = $this->siteNameFromPath($path);
196 // Convert the raw array into a list of alias records.
197 $result = array_merge(
199 $this->createAliasRecordsFromSiteData($sitename, $siteData, $location)
207 * @param array $siteData list of sites with its respective data
209 * @param SiteAliasName $aliasName The name of the record being created
210 * @param $siteData An associative array of envrionment => site data
211 * @return AliasRecord[]
213 protected function createAliasRecordsFromSiteData($sitename, $siteData, $location = '')
216 if (!is_array($siteData) || empty($siteData)) {
219 foreach ($siteData as $envName => $data) {
220 if (is_array($data) && $this->isValidEnvName($envName)) {
221 $aliasName = new SiteAliasName($sitename, $envName, $location);
223 $processor = new ConfigProcessor();
224 $oneRecord = $this->fetchAliasRecordFromSiteAliasData($aliasName, $processor, $siteData);
225 $this->storeAliasRecordInResut($result, $oneRecord);
232 * isValidEnvName determines if a given entry should be skipped or not
233 * (e.g. the "common" entry).
235 * @param string $envName The environment name to test
237 protected function isValidEnvName($envName)
239 return $envName != 'common';
243 * Store an alias record in a list. If the alias record has
244 * a known name, then the key of the list will be the record's name.
245 * Otherwise, append the record to the end of the list with
248 * @param &AliasRecord[] $result list of alias records
249 * @param AliasRecord $aliasRecord one more alias to store in the result
251 protected function storeAliasRecordInResut(&$result, AliasRecord $aliasRecord)
256 $key = $aliasRecord->name();
258 $result[] = $aliasRecord;
261 $result[$key] = $aliasRecord;
265 * If the alias name is '@sitename', or if it is '@sitename.env', then
266 * look for a sitename.site.yml file that contains it. We also handle
267 * '@location.sitename.env' here as well.
269 * @param SiteAliasName $aliasName
271 * @return AliasRecord|false
273 protected function loadSingleAliasFile(SiteAliasName $aliasName)
275 // Check to see if the appropriate sitename.alias.yml file can be
276 // found. Return if it cannot.
277 $path = $this->discovery()
278 ->filterByLocation($aliasName->location())
279 ->findSingleSiteAliasFile($aliasName->sitename());
283 return $this->loadSingleAliasFileWithNameAtPath($aliasName, $path);
287 * Given only the path to an alias file `site.alias.yml`, return all
288 * of the alias records for every environment stored in that file.
290 * @param string $path
291 * @return AliasRecord[]
293 protected function loadSingleSiteAliasFileAtPath($path)
295 $sitename = $this->siteNameFromPath($path);
296 $location = SiteAliasName::locationFromPath($path);
297 if ($siteData = $this->loadSiteDataFromPath($path)) {
298 return $this->createAliasRecordsFromSiteData($sitename, $siteData, $location);
304 * Given the path to a single site alias file `site.alias.yml`,
305 * return the `site` part.
307 * @param string $path
309 protected function siteNameFromPath($path)
311 return $this->basenameWithoutExtension($path, '.site.yml');
314 // $filename = basename($path);
315 // return preg_replace('#\..*##', '', $filename);
319 * Chop off the `aliases.yml` or `alias.yml` part of a path. This works
320 * just like `basename`, except it will throw if the provided path
321 * does not end in the specified extension.
323 * @param string $path
324 * @param string $extension
328 protected function basenameWithoutExtension($path, $extension)
330 $result = basename($path, $extension);
331 // It is an error if $path does not end with site.yml
332 if ($result == basename($path)) {
333 throw new \Exception("$path must end with '$extension'");
339 * Given an alias name and a path, load the data from the path
340 * and process it as needed to generate the alias record.
342 * @param SiteAliasName $aliasName
343 * @param string $path
344 * @return AliasRecord|false
346 protected function loadSingleAliasFileWithNameAtPath(SiteAliasName $aliasName, $path)
348 $data = $this->loadSiteDataFromPath($path);
352 $processor = new ConfigProcessor();
353 return $this->fetchAliasRecordFromSiteAliasData($aliasName, $processor, $data);
357 * Load the yml from the given path
359 * @param string $path
362 protected function loadSiteDataFromPath($path)
364 $data = $this->loadData($path);
368 $selfSiteAliases = $this->findSelfSiteAliases($data);
369 $data = array_merge($data, $selfSiteAliases);
374 * Given an array of site aliases, find the first one that is
375 * local (has no 'host' item) and also contains a 'self.site.yml' file.
379 protected function findSelfSiteAliases($site_aliases)
381 foreach ($site_aliases as $site => $data) {
382 if (!isset($data['host']) && isset($data['root'])) {
383 foreach (['.', '..'] as $relative_path) {
384 $candidate = $data['root'] . '/' . $relative_path . '/drush/sites/self.site.yml';
385 if (file_exists($candidate)) {
386 return $this->loadData($candidate);
395 * Load the contents of the specified file.
397 * @param string $path Path to file to load
400 protected function loadData($path)
402 if (empty($path) || !file_exists($path)) {
405 $loader = $this->getLoader(pathinfo($path, PATHINFO_EXTENSION));
409 return $loader->load($path);
413 * @return DataFileLoaderInterface
415 public function getLoader($extension)
417 if (!isset($this->loader[$extension])) {
420 return $this->loader[$extension];
423 public function addLoader($extension, DataFileLoaderInterface $loader)
425 $this->loader[$extension] = $loader;
429 * Given an array containing site alias data, return an alias record
430 * containing the data for the requested record. If there is a 'common'
431 * section, then merge that in as well.
433 * @param SiteAliasName $aliasName the alias we are loading
436 * @return AliasRecord|false
438 protected function fetchAliasRecordFromSiteAliasData(SiteAliasName $aliasName, ConfigProcessor $processor, array $data)
440 $data = $this->adjustIfSingleAlias($data);
441 $env = $this->getEnvironmentName($aliasName, $data);
442 $env_data = $this->getRequestedEnvData($data, $env);
447 // Add the 'common' section if it exists.
448 if ($this->siteEnvExists($data, 'common')) {
449 $processor->add($data['common']);
452 // Then add the data from the desired environment.
453 $processor->add($env_data);
455 // Export the combined data and create an AliasRecord object to manage it.
456 return new AliasRecord($processor->export($this->referenceData + ['env-name' => $env]), '@' . $aliasName->sitenameWithLocation(), $env);
460 * getRequestedEnvData fetches the data for the specified environment
461 * from the provided site record data.
463 * @param array $data The site alias data
464 * @param string $env The name of the environment desired
465 * @return array|false
467 protected function getRequestedEnvData(array $data, $env)
469 // If the requested environment exists, we will use it.
470 if ($this->siteEnvExists($data, $env)) {
474 // If there is a wildcard environment, then return that instead.
475 if ($this->siteEnvExists($data, '*')) {
483 * Determine whether there is a valid-looking environment '$env' in the
484 * provided site alias data.
490 protected function siteEnvExists(array $data, $env)
494 isset($data[$env]) &&
495 is_array($data[$env])
500 * Adjust the alias data for a single-site alias. Usually, a .yml alias
501 * file will contain multiple entries, one for each of the environments
502 * of an alias. If there are no environments
507 protected function adjustIfSingleAlias($data)
509 if (!$this->detectSingleAlias($data)) {
521 * A single-environment alias looks something like this:
524 * root: /path/to/drupal
525 * uri: https://mysite.org
527 * A multiple-environment alias looks something like this:
533 * uri: https://dev.mysite.org
535 * root: /path/to/stage
536 * uri: https://stage.mysite.org
538 * The differentiator between these two is that the multi-environment
539 * alias always has top-level elements that are associative arrays, and
540 * the single-environment alias never does.
545 protected function detectSingleAlias($data)
547 foreach ($data as $key => $value) {
548 if (is_array($value) && DotAccessDataUtil::isAssoc($value)) {
556 * Return the name of the environment requested.
558 * @param SiteAliasName $aliasName the alias we are loading
563 protected function getEnvironmentName(SiteAliasName $aliasName, array $data)
565 // If the alias name specifically mentions the environment
566 // to use, then return it.
567 if ($aliasName->hasEnv()) {
568 return $aliasName->env();
570 return $this->getDefaultEnvironmentName($data);
574 * Given a data array containing site alias environments, determine which
575 * envirionmnet should be used as the default environment.
580 protected function getDefaultEnvironmentName(array $data)
582 // If there is an entry named 'default', it will either contain the
583 // name of the environment to use by default, or it will itself be
584 // the default environment.
585 if (isset($data['default'])) {
586 return is_array($data['default']) ? 'default' : $data['default'];
588 // If there is an environment named 'dev', it will be our default.
589 if (isset($data['dev'])) {
592 // If we don't know which environment to use, just take the first one.
593 $keys = array_keys($data);