BaseBuilderCommand.php 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. <?php
  2. declare(strict_types = 1);
  3. namespace Fgm\Drupal\Composer;
  4. use Composer\Command\BaseCommand;
  5. use Symfony\Component\Console\Input\InputInterface;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. use Symfony\Component\Yaml\Exception\ParseException;
  8. use Symfony\Component\Yaml\Yaml;
  9. use Twig\Environment;
  10. use Twig\Extension\DebugExtension;
  11. use Twig\Loader\FilesystemLoader;
  12. use Twig\TemplateWrapper;
  13. /**
  14. * Provides command primitives useful for most commands, focused on templating.
  15. *
  16. * @package Fgm\Drupal\Composer
  17. */
  18. abstract class BaseBuilderCommand extends BaseCommand {
  19. /**
  20. * The name of the argument defining the file to generate.
  21. */
  22. const ARG_FILE = 'file';
  23. /**
  24. * Provide the path to the project settings directory.
  25. *
  26. * @return string
  27. * The absolute path to the directory.
  28. */
  29. protected function getSettingsPath(): string {
  30. $settingsPath = getcwd() . "/settings";
  31. return $settingsPath;
  32. }
  33. /**
  34. * Validate template definition for command, returning its name on success.
  35. *
  36. * @param \Symfony\Component\Console\Input\InputInterface $input
  37. * Command input.
  38. * @param \Symfony\Component\Console\Output\OutputInterface $output
  39. * Command output.
  40. *
  41. * @return array
  42. * - string Template name
  43. * - int Error
  44. */
  45. public function validateTemplateName(InputInterface $input, OutputInterface $output): array {
  46. $file = $input->getArgument(static::ARG_FILE);
  47. $conf = $this->getComposer()->getPackage()->getExtra()[Builder::NAME] ?? [];
  48. $templateName = $conf['templates'][$file] ?? '';
  49. if (empty($templateName)) {
  50. $output->writeln(sprintf(
  51. 'Could not build file %s: no such template in composer.json extra section',
  52. $file
  53. ));
  54. return ["", 1];
  55. }
  56. return [$templateName, 0];
  57. }
  58. /**
  59. * Perform template rendering.
  60. *
  61. * @param \Twig\TemplateWrapper $wrapper
  62. * A Twig user-space template wrapper.
  63. * @param array $context
  64. * The data context with which to perform the rendering.
  65. * @param string $destination
  66. * The path where to write the rendering result.
  67. *
  68. * @return array
  69. * - string message
  70. * - int status: 0 on success, other values on errors.
  71. */
  72. protected function render(
  73. TemplateWrapper $wrapper,
  74. array $context,
  75. string $destination
  76. ): array {
  77. if (file_exists($destination)) {
  78. $ok = unlink($destination);
  79. if (!$ok) {
  80. return [sprintf("Could not remove old %s file", $destination), 1];
  81. }
  82. }
  83. $rendered = $wrapper->render($context);
  84. $ok = file_put_contents($destination, $rendered, LOCK_EX);
  85. if (!$ok) {
  86. return [sprintf('Could not write new %s file', $destination), 2];
  87. }
  88. return ["", 0];
  89. }
  90. /**
  91. * Prepare the template and its parameters as obtained from configuration.
  92. *
  93. * @param \Symfony\Component\Console\Input\InputInterface $input
  94. * Command input.
  95. * @param \Symfony\Component\Console\Output\OutputInterface $output
  96. * Command output.
  97. *
  98. * @return array
  99. * - TemplateWrapper|NULL: Twig template wrapper
  100. * - array: template parameters
  101. * - string: error message
  102. * - int: error, 0 if OK. If non-zero, only the error message is reliable.
  103. *
  104. * @throws \Twig\Error\LoaderError
  105. * @throws \Twig\Error\RuntimeError
  106. * @throws \Twig\Error\SyntaxError
  107. */
  108. protected function prepare(InputInterface $input, OutputInterface $output): array {
  109. [$templateName, $err] = $this->validateTemplateName($input, $output);
  110. if ($err) {
  111. return [NULL, [], "Could not validate template name", 1];
  112. };
  113. $settingsPath = $this->getSettingsPath();
  114. $templatePath = "${settingsPath}/${templateName}";
  115. $realTemplatePath = realpath($templatePath);
  116. if (empty($realTemplatePath)) {
  117. return [NULL, [],
  118. sprintf("Could not load template %s: no such file", $templateName),
  119. 2,
  120. ];
  121. }
  122. $paramsPath = "${settingsPath}/merged.params.local.yml";
  123. $realParamsPath = realpath($paramsPath);
  124. if (empty($realParamsPath)) {
  125. return [NULL, [],
  126. sprintf("Could not load parameters %s: no such file", $paramsPath),
  127. 3,
  128. ];
  129. }
  130. $yaml = new Yaml();
  131. try {
  132. $params = $yaml->parseFile($realParamsPath);
  133. }
  134. catch (ParseException $e) {
  135. return [NULL, [],
  136. sprintf("Could not parse %s: %s", $realParamsPath, $e->getMessage()),
  137. 4,
  138. ];
  139. }
  140. $loader = new FilesystemLoader($settingsPath, $settingsPath);
  141. $twig = new Environment($loader, [
  142. 'auto_reload' => TRUE,
  143. 'cache' => FALSE,
  144. 'debug' => TRUE,
  145. 'strict_variables' => TRUE,
  146. ]);
  147. $twig->addExtension(new DebugExtension());
  148. $wrapper = $twig->load($templateName);
  149. return [$wrapper, $params, "", 0];
  150. }
  151. }