BaseBuilderCommand.php 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  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, string $buildName): array {
  46. $conf = $this->getComposer()->getPackage()->getExtra()[Builder::NAME] ?? [];
  47. $templateName = $conf['templates'][$buildName] ?? '';
  48. if (empty($templateName)) {
  49. $output->writeln(sprintf(
  50. 'Could not build file %s: no such template in composer.json extra section',
  51. $buildName
  52. ));
  53. return ["", 1];
  54. }
  55. return [$templateName, 0];
  56. }
  57. /**
  58. * Perform template rendering.
  59. *
  60. * @param \Twig\TemplateWrapper $wrapper
  61. * A Twig user-space template wrapper.
  62. * @param array $context
  63. * The data context with which to perform the rendering.
  64. * @param string $destination
  65. * The path where to write the rendering result.
  66. *
  67. * @return array
  68. * - string message
  69. * - int status: 0 on success, other values on errors.
  70. */
  71. protected function render(
  72. TemplateWrapper $wrapper,
  73. array $context,
  74. string $destination
  75. ): array {
  76. if (file_exists($destination)) {
  77. $ok = unlink($destination);
  78. if (!$ok) {
  79. return [sprintf("Could not remove old %s file", $destination), 1];
  80. }
  81. }
  82. $rendered = $wrapper->render($context);
  83. $ok = file_put_contents($destination, $rendered, LOCK_EX);
  84. if (!$ok) {
  85. return [sprintf('Could not write new %s file', $destination), 2];
  86. }
  87. return ["", 0];
  88. }
  89. /**
  90. * Prepare the template and its parameters as obtained from configuration.
  91. *
  92. * @param \Symfony\Component\Console\Input\InputInterface $input
  93. * Command input.
  94. * @param \Symfony\Component\Console\Output\OutputInterface $output
  95. * Command output.
  96. * @param string $buildName
  97. * Machine name of build process.
  98. *
  99. * @return array
  100. * - TemplateWrapper|NULL: Twig template wrapper
  101. * - array: template parameters
  102. * - string: error message
  103. * - int: error, 0 if OK. If non-zero, only the error message is reliable.
  104. *
  105. * @throws \Twig\Error\LoaderError
  106. * @throws \Twig\Error\RuntimeError
  107. * @throws \Twig\Error\SyntaxError
  108. */
  109. protected function prepare(InputInterface $input, OutputInterface $output, string $buildName): array {
  110. [
  111. $templateName,
  112. $err,
  113. ] = $this->validateTemplateName($input, $output, $buildName);
  114. if ($err) {
  115. return [NULL, [], "Could not validate template name", 1];
  116. };
  117. $settingsPath = $this->getSettingsPath();
  118. $templatePath = "${settingsPath}/${templateName}";
  119. $realTemplatePath = realpath($templatePath);
  120. if (empty($realTemplatePath)) {
  121. return [
  122. NULL,
  123. [],
  124. sprintf("Could not load template %s: no such file", $templateName),
  125. 2,
  126. ];
  127. }
  128. [$params, $msg, $err] = $this->getParams();
  129. if ($err) {
  130. return [NULL, [], $msg, $err];
  131. };
  132. $loader = new FilesystemLoader($settingsPath, $settingsPath);
  133. $twig = new Environment($loader, [
  134. 'auto_reload' => TRUE,
  135. 'cache' => FALSE,
  136. 'debug' => TRUE,
  137. 'strict_variables' => TRUE,
  138. ]);
  139. $twig->addExtension(new DebugExtension());
  140. $wrapper = $twig->load($templateName);
  141. return [$wrapper, $params, "", 0];
  142. }
  143. /**
  144. * Get parameters as obtained from configuration.
  145. *
  146. * @return array
  147. * - array: parameters
  148. * - string: error message
  149. * - int: error, 0 if OK. If non-zero, only the error message is reliable.
  150. */
  151. public function getParams() {
  152. $settingsPath = $this->getSettingsPath();
  153. $paramsPath = "${settingsPath}/merged.params.local.yml";
  154. $realParamsPath = realpath($paramsPath);
  155. if (empty($realParamsPath)) {
  156. return [
  157. [],
  158. sprintf("Could not load parameters %s: no such file", $paramsPath),
  159. 3,
  160. ];
  161. }
  162. $yaml = new Yaml();
  163. try {
  164. return [$yaml->parseFile($realParamsPath), '', 0];
  165. }
  166. catch (ParseException $e) {
  167. return [
  168. [],
  169. sprintf("Could not parse %s: %s", $realParamsPath, $e->getMessage()),
  170. 4,
  171. ];
  172. }
  173. }
  174. }