BaseBuilderCommand.php 5.3 KB

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