eventName = $this->getName(); $this ->setName('build:merge_params') ->setDescription('Step 1: merges the params.local.yml with dist.params.local.yml.') ->setDefinition([]) ->setHelp( << NULL]); $merged['sites'] = []; foreach ($sites as $name => $params) { $merged['sites'][$name] = static::mergeDeepArray([$default, $params]); } return $merged; } /** * Executes the current command. * * {@inheritDoc} */ public function execute(InputInterface $input, OutputInterface $output) { $settingsPath = $this->getSettingsPath(); $yaml = new Yaml(); // Load defaults. $defaultsPath = "${settingsPath}/dist.params.local.yml"; $realDefaultsPath = realpath($defaultsPath); if (empty($realDefaultsPath)) { $output->writeln("Failed to open $defaultsPath"); return 1; } $defaults = $yaml->parseFile($realDefaultsPath); // Load local. $localPath = "${settingsPath}/params.local.yml"; $realLocalPath = realpath($localPath); if (empty($realLocalPath)) { if ($output->isVerbose()) { $output->writeln("File $localPath not found, using only defaults"); } $local = []; } else { $local = $yaml->parseFile($realLocalPath); } // Merge. $merged = $this->merge($defaults, $local); // Write. $ok = file_put_contents("${settingsPath}/merged.params.local.yml", $yaml->dump($merged, 10, 2)); if (!$ok) { $output->writeln("Failed to write merged params."); return 2; } return 0; } /** * Merges multiple arrays, recursively, and returns the merged array. * * Only keyed arrays are merged recursively, indexed arrays are not merged : * the deepest array replace the less deep array. This is unlike the original * function introduced in Drupal 8.x, from which this derives. * * @param array $arrays * An arrays of arrays to merge. * * @return array * The merged array. * * @see \Fgm\Drupal\Composer\MergeParamsCommandTest::testMergeDeepArray() */ public static function mergeDeepArray(array $arrays) { $result = []; foreach ($arrays as $array) { foreach ($array as $key => $value) { // Remove keys having NULL value to allow deletion of key previously // defined. if ($value === NULL) { unset($result[$key]); continue; } // Renumber integer keys as array_merge_recursive() does. Note that // PHP automatically converts array keys that are integer strings // (e.g., '1') to integers. if (is_int($key)) { // When an indexed array is overrided, the new values replace // all overrided values (no merge). if ($key === 0) { $result = []; } $result[] = $value; } // Recurse when both values are arrays. elseif (isset($result[$key]) && is_array($result[$key]) && is_array($value)) { $result[$key] = static::mergeDeepArray([$result[$key], $value]); } // Otherwise, use the latter value, overriding any previous value. else { $result[$key] = $value; } } } return $result; } }