BuildServicesCommand.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. <?php
  2. namespace Fgm\Drupal\Composer;
  3. use Symfony\Component\Console\Input\InputArgument;
  4. use Symfony\Component\Console\Input\InputDefinition;
  5. use Symfony\Component\Console\Input\InputInterface;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. use Symfony\Component\Yaml\Yaml;
  8. /**
  9. * Build the services.yml file for all sites in the multisite.
  10. *
  11. * @package Fgm\Drupal\Composer
  12. */
  13. class BuildServicesCommand extends BaseBuilderCommand {
  14. /**
  15. * Machine name of current building process.
  16. *
  17. * Used as file name if none provided.
  18. */
  19. const BUILD_NAME = 'services';
  20. /**
  21. * The event triggering this command.
  22. *
  23. * @var string
  24. */
  25. protected $eventName;
  26. /**
  27. * Configures the current command.
  28. */
  29. public function configure() {
  30. parent::configure();
  31. $this->eventName = $this->getName();
  32. $this
  33. ->setName('build:services')
  34. ->setDescription('Step 5: build the services.yml file.')
  35. ->setDefinition(
  36. new InputDefinition([
  37. new InputArgument(static::ARG_FILE, InputArgument::OPTIONAL, '', static::BUILD_NAME),
  38. ])
  39. )
  40. ->setHelp(
  41. <<<EOT
  42. The build:services command combines shared and per-environment parameters and passes
  43. them to the services.local.yml.twig template to build the settings/services.yml file.
  44. EOT
  45. );
  46. }
  47. /**
  48. * Executes the current command.
  49. *
  50. * {@inheritDoc}
  51. */
  52. public function execute(InputInterface $input, OutputInterface $output): int {
  53. [
  54. $params,
  55. $msg,
  56. $err,
  57. ] = $this->getParams();
  58. if ($err != 0) {
  59. $output->writeln($msg);
  60. return $err;
  61. }
  62. foreach ($params['sites'] as $name => $siteParams) {
  63. $services = [];
  64. if (!empty($siteParams['parameters'])) {
  65. $services['parameters'] = $siteParams['parameters'];
  66. }
  67. if (!empty($siteParams['services'])) {
  68. $services['services'] = $siteParams['services'];
  69. }
  70. if (!$services) {
  71. return 0;
  72. }
  73. $fileName = $input->getArgument(static::ARG_FILE);
  74. $destination = "web/sites/$name/$fileName.yml";
  75. if (file_exists($destination)) {
  76. $ok = unlink($destination);
  77. if (!$ok) {
  78. return 1;
  79. }
  80. }
  81. // Convert PHP array to Yaml.
  82. $yamlServices = Yaml::dump($services, 4, 2);
  83. $ok = file_put_contents($destination, $yamlServices, LOCK_EX);
  84. if (!$ok) {
  85. return 2;
  86. }
  87. }
  88. return 0;
  89. }
  90. }