MergeParamsCommand.php 2.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. declare(strict_types = 1);
  3. namespace Fgm\Drupal\Composer;
  4. use Symfony\Component\Console\Input\InputInterface;
  5. use Symfony\Component\Console\Output\OutputInterface;
  6. use Symfony\Component\Yaml\Yaml;
  7. class MergeParamsCommand extends BaseBuilderCommand
  8. {
  9. const DEFAULT_SITE = '_default';
  10. /**
  11. * @var string
  12. */
  13. protected $eventName;
  14. /**
  15. * {@inheritDoc}
  16. */
  17. public function configure()
  18. {
  19. parent::configure();
  20. $this->eventName = $this->getName();
  21. $this
  22. ->setName('build:merge_params')
  23. ->setDescription('Step 1: merges the params.local.yml with dist.params.local.yml.')
  24. ->setDefinition([])
  25. ->setHelp(
  26. <<<EOT
  27. Step 1 of a build, the build:merge_params command combines shared and per-environment
  28. parameters and generates merged.params.local.yml containing the merged result.
  29. EOT
  30. );
  31. }
  32. protected function merge(array $dist, array $local): array
  33. {
  34. if (empty($local)) {
  35. return $dist;
  36. }
  37. // Merge local into defaults.
  38. $merged = NestedArray::mergeDeepArray([$dist, $local], true);
  39. // Generate per-site data from settings/_default.
  40. $default = $merged['sites'][static::DEFAULT_SITE] ?? [];
  41. $sites = array_diff_key($merged['sites'], [static::DEFAULT_SITE => null]);
  42. $merged['sites'] = [];
  43. foreach ($sites as $name => $params) {
  44. $merged['sites'][$name] = NestedArray::mergeDeep($default, $params);
  45. }
  46. return $merged;
  47. }
  48. /**
  49. * {@inheritDoc}
  50. */
  51. public function execute(InputInterface $input, OutputInterface $output)
  52. {
  53. $settingsPath = $this->getSettingsPath();
  54. $yaml = new Yaml();
  55. // Load defaults.
  56. $defaultsPath = "${settingsPath}/dist.params.local.yml";
  57. $realDefaultsPath = realpath($defaultsPath);
  58. if (empty($realDefaultsPath)) {
  59. $output->writeln("Failed to open $defaultsPath");
  60. return 1;
  61. }
  62. $defaults = $yaml->parseFile($realDefaultsPath);
  63. // Load local.
  64. $localPath = "${settingsPath}/params.local.yml";
  65. $realLocalPath = realpath($localPath);
  66. if (empty($realLocalPath)) {
  67. if ($output->isVerbose()) {
  68. $output->writeln("File $localPath not found, using only defaults");
  69. }
  70. $local = [];
  71. } else {
  72. $local = $yaml->parseFile($realLocalPath);
  73. }
  74. // Merge.
  75. $merged = $this->merge($defaults, $local);
  76. // Write.
  77. $ok = file_put_contents("${settingsPath}/merged.params.local.yml", $yaml->dump($merged, 10, 2));
  78. if (!$ok) {
  79. $output->writeln("Failed to write merged params.");
  80. return 2;
  81. }
  82. }
  83. }