TraceableCommand.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Console\Command;
  11. use Symfony\Component\Console\Application;
  12. use Symfony\Component\Console\Completion\CompletionInput;
  13. use Symfony\Component\Console\Completion\CompletionSuggestions;
  14. use Symfony\Component\Console\Helper\HelperInterface;
  15. use Symfony\Component\Console\Helper\HelperSet;
  16. use Symfony\Component\Console\Input\InputDefinition;
  17. use Symfony\Component\Console\Input\InputInterface;
  18. use Symfony\Component\Console\Output\ConsoleOutputInterface;
  19. use Symfony\Component\Console\Output\OutputInterface;
  20. use Symfony\Component\Stopwatch\Stopwatch;
  21. /**
  22. * @internal
  23. *
  24. * @author Jules Pietri <jules@heahprod.com>
  25. */
  26. final class TraceableCommand extends Command
  27. {
  28. public readonly Command $command;
  29. public int $exitCode;
  30. public ?int $interruptedBySignal = null;
  31. public bool $ignoreValidation;
  32. public bool $isInteractive = false;
  33. public string $duration = 'n/a';
  34. public string $maxMemoryUsage = 'n/a';
  35. public InputInterface $input;
  36. public OutputInterface $output;
  37. /** @var array<string, mixed> */
  38. public array $arguments;
  39. /** @var array<string, mixed> */
  40. public array $options;
  41. /** @var array<string, mixed> */
  42. public array $interactiveInputs = [];
  43. public array $handledSignals = [];
  44. public ?array $invokableCommandInfo = null;
  45. public function __construct(
  46. Command $command,
  47. private readonly Stopwatch $stopwatch,
  48. ) {
  49. if ($command instanceof LazyCommand) {
  50. $command = $command->getCommand();
  51. }
  52. $this->command = $command;
  53. // prevent call to self::getDefaultDescription()
  54. $this->setDescription($command->getDescription());
  55. parent::__construct($command->getName());
  56. // init below enables calling {@see parent::run()}
  57. [$code, $processTitle, $ignoreValidationErrors] = \Closure::bind(fn () => [$this->code, $this->processTitle, $this->ignoreValidationErrors], $command, Command::class)();
  58. if (\is_callable($code)) {
  59. $this->setCode($code);
  60. }
  61. if ($processTitle) {
  62. parent::setProcessTitle($processTitle);
  63. }
  64. if ($ignoreValidationErrors) {
  65. parent::ignoreValidationErrors();
  66. }
  67. $this->ignoreValidation = $ignoreValidationErrors;
  68. }
  69. public function __call(string $name, array $arguments): mixed
  70. {
  71. return $this->command->{$name}(...$arguments);
  72. }
  73. public function getSubscribedSignals(): array
  74. {
  75. return $this->command->getSubscribedSignals();
  76. }
  77. public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
  78. {
  79. $event = $this->stopwatch->start($this->getName().'.handle_signal');
  80. $exit = $this->command->handleSignal($signal, $previousExitCode);
  81. $event->stop();
  82. if (!isset($this->handledSignals[$signal])) {
  83. $this->handledSignals[$signal] = [
  84. 'handled' => 0,
  85. 'duration' => 0,
  86. 'memory' => 0,
  87. ];
  88. }
  89. ++$this->handledSignals[$signal]['handled'];
  90. $this->handledSignals[$signal]['duration'] += $event->getDuration();
  91. $this->handledSignals[$signal]['memory'] = max(
  92. $this->handledSignals[$signal]['memory'],
  93. $event->getMemory() >> 20
  94. );
  95. return $exit;
  96. }
  97. /**
  98. * {@inheritdoc}
  99. *
  100. * Calling parent method is required to be used in {@see parent::run()}.
  101. */
  102. public function ignoreValidationErrors(): void
  103. {
  104. $this->ignoreValidation = true;
  105. $this->command->ignoreValidationErrors();
  106. parent::ignoreValidationErrors();
  107. }
  108. public function setApplication(?Application $application = null): void
  109. {
  110. $this->command->setApplication($application);
  111. }
  112. public function getApplication(): ?Application
  113. {
  114. return $this->command->getApplication();
  115. }
  116. public function setHelperSet(HelperSet $helperSet): void
  117. {
  118. $this->command->setHelperSet($helperSet);
  119. }
  120. public function getHelperSet(): ?HelperSet
  121. {
  122. return $this->command->getHelperSet();
  123. }
  124. public function isEnabled(): bool
  125. {
  126. return $this->command->isEnabled();
  127. }
  128. public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
  129. {
  130. $this->command->complete($input, $suggestions);
  131. }
  132. /**
  133. * {@inheritdoc}
  134. *
  135. * Calling parent method is required to be used in {@see parent::run()}.
  136. */
  137. public function setCode(callable $code): static
  138. {
  139. if ($code instanceof InvokableCommand) {
  140. $r = \Closure::bind(fn () => $this->invokable, $code, InvokableCommand::class)();
  141. $this->invokableCommandInfo = [
  142. 'class' => $r->getClosureScopeClass()->name,
  143. 'file' => $r->getFileName(),
  144. 'line' => $r->getStartLine(),
  145. ];
  146. // Pass the original callable to avoid double-wrapping in Command::setCode()
  147. $this->command->setCode($code->getCode());
  148. } else {
  149. $this->command->setCode($code);
  150. }
  151. return parent::setCode(function (InputInterface $input, OutputInterface $output) use ($code): int {
  152. $event = $this->stopwatch->start($this->getName().'.code');
  153. $this->exitCode = $code($input, $output);
  154. $event->stop();
  155. return $this->exitCode;
  156. });
  157. }
  158. /**
  159. * @internal
  160. */
  161. public function mergeApplicationDefinition(bool $mergeArgs = true): void
  162. {
  163. $this->command->mergeApplicationDefinition($mergeArgs);
  164. }
  165. public function setDefinition(array|InputDefinition $definition): static
  166. {
  167. $this->command->setDefinition($definition);
  168. return $this;
  169. }
  170. public function getDefinition(): InputDefinition
  171. {
  172. return $this->command->getDefinition();
  173. }
  174. public function getNativeDefinition(): InputDefinition
  175. {
  176. return $this->command->getNativeDefinition();
  177. }
  178. public function addArgument(string $name, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static
  179. {
  180. $this->command->addArgument($name, $mode, $description, $default, $suggestedValues);
  181. return $this;
  182. }
  183. public function addOption(string $name, string|array|null $shortcut = null, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static
  184. {
  185. $this->command->addOption($name, $shortcut, $mode, $description, $default, $suggestedValues);
  186. return $this;
  187. }
  188. /**
  189. * {@inheritdoc}
  190. *
  191. * Calling parent method is required to be used in {@see parent::run()}.
  192. */
  193. public function setProcessTitle(string $title): static
  194. {
  195. $this->command->setProcessTitle($title);
  196. return parent::setProcessTitle($title);
  197. }
  198. public function setHelp(string $help): static
  199. {
  200. $this->command->setHelp($help);
  201. return $this;
  202. }
  203. public function getHelp(): string
  204. {
  205. return $this->command->getHelp();
  206. }
  207. public function getProcessedHelp(): string
  208. {
  209. return $this->command->getProcessedHelp();
  210. }
  211. public function getSynopsis(bool $short = false): string
  212. {
  213. return $this->command->getSynopsis($short);
  214. }
  215. public function addUsage(string $usage): static
  216. {
  217. $this->command->addUsage($usage);
  218. return $this;
  219. }
  220. public function getUsages(): array
  221. {
  222. return $this->command->getUsages();
  223. }
  224. public function getHelper(string $name): HelperInterface
  225. {
  226. return $this->command->getHelper($name);
  227. }
  228. public function run(InputInterface $input, OutputInterface $output): int
  229. {
  230. $this->input = $input;
  231. $this->output = $output;
  232. $initialArguments = $input->getArguments();
  233. $initialOptions = $input->getOptions();
  234. $event = $this->stopwatch->start($this->getName(), 'command');
  235. try {
  236. $this->exitCode = $this->command->run($input, $output);
  237. } finally {
  238. $event->stop();
  239. if ($output instanceof ConsoleOutputInterface && $output->isDebug()) {
  240. $output->getErrorOutput()->writeln((string) $event);
  241. }
  242. $this->duration = $event->getDuration().' ms';
  243. $this->maxMemoryUsage = ($event->getMemory() >> 20).' MiB';
  244. $this->arguments = $input->getArguments();
  245. $this->options = $input->getOptions();
  246. $this->extractInteractiveInputs($initialArguments, $initialOptions);
  247. $this->isInteractive = $this->isInteractive || $this->interactiveInputs;
  248. }
  249. return $this->exitCode;
  250. }
  251. protected function initialize(InputInterface $input, OutputInterface $output): void
  252. {
  253. $event = $this->stopwatch->start($this->getName().'.init', 'command');
  254. $this->command->initialize($input, $output);
  255. $event->stop();
  256. }
  257. protected function interact(InputInterface $input, OutputInterface $output): void
  258. {
  259. if (!$this->isInteractive = Command::class !== (new \ReflectionMethod($this->command, 'interact'))->getDeclaringClass()->getName()) {
  260. return;
  261. }
  262. $event = $this->stopwatch->start($this->getName().'.interact', 'command');
  263. $this->command->interact($input, $output);
  264. $event->stop();
  265. }
  266. protected function execute(InputInterface $input, OutputInterface $output): int
  267. {
  268. $event = $this->stopwatch->start($this->getName().'.execute', 'command');
  269. $exitCode = $this->command->execute($input, $output);
  270. $event->stop();
  271. return $exitCode;
  272. }
  273. private function extractInteractiveInputs(array $initialArguments, array $initialOptions): void
  274. {
  275. $nativeDefinition = $this->command->getNativeDefinition();
  276. foreach ($nativeDefinition->getArguments() as $argName => $argument) {
  277. if (\array_key_exists($argName, $initialArguments) && $initialArguments[$argName] === $this->arguments[$argName]) {
  278. continue;
  279. }
  280. $this->interactiveInputs[$argName] = $this->arguments[$argName];
  281. }
  282. foreach ($nativeDefinition->getOptions() as $optName => $option) {
  283. if (\array_key_exists($optName, $initialOptions) && $initialOptions[$optName] === $this->options[$optName]) {
  284. continue;
  285. }
  286. $this->interactiveInputs['--'.$optName] = $this->options[$optName];
  287. }
  288. }
  289. }