BaseBuilderCommand.php 5.4 KB

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