TraceableCommand.php 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  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 implements SignalableCommandInterface
  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 function __construct(
  45. Command $command,
  46. private readonly Stopwatch $stopwatch,
  47. ) {
  48. if ($command instanceof LazyCommand) {
  49. $command = $command->getCommand();
  50. }
  51. $this->command = $command;
  52. // prevent call to self::getDefaultDescription()
  53. $this->setDescription($command->getDescription());
  54. parent::__construct($command->getName());
  55. // init below enables calling {@see parent::run()}
  56. [$code, $processTitle, $ignoreValidationErrors] = \Closure::bind(function () {
  57. return [$this->code, $this->processTitle, $this->ignoreValidationErrors];
  58. }, $command, Command::class)();
  59. if (\is_callable($code)) {
  60. $this->setCode($code);
  61. }
  62. if ($processTitle) {
  63. parent::setProcessTitle($processTitle);
  64. }
  65. if ($ignoreValidationErrors) {
  66. parent::ignoreValidationErrors();
  67. }
  68. $this->ignoreValidation = $ignoreValidationErrors;
  69. }
  70. public function __call(string $name, array $arguments): mixed
  71. {
  72. return $this->command->{$name}(...$arguments);
  73. }
  74. public function getSubscribedSignals(): array
  75. {
  76. return $this->command instanceof SignalableCommandInterface ? $this->command->getSubscribedSignals() : [];
  77. }
  78. public function handleSignal(int $signal, int|false $previousExitCode = 0): int|false
  79. {
  80. if (!$this->command instanceof SignalableCommandInterface) {
  81. return false;
  82. }
  83. $event = $this->stopwatch->start($this->getName().'.handle_signal');
  84. $exit = $this->command->handleSignal($signal, $previousExitCode);
  85. $event->stop();
  86. if (!isset($this->handledSignals[$signal])) {
  87. $this->handledSignals[$signal] = [
  88. 'handled' => 0,
  89. 'duration' => 0,
  90. 'memory' => 0,
  91. ];
  92. }
  93. ++$this->handledSignals[$signal]['handled'];
  94. $this->handledSignals[$signal]['duration'] += $event->getDuration();
  95. $this->handledSignals[$signal]['memory'] = max(
  96. $this->handledSignals[$signal]['memory'],
  97. $event->getMemory() >> 20
  98. );
  99. return $exit;
  100. }
  101. /**
  102. * {@inheritdoc}
  103. *
  104. * Calling parent method is required to be used in {@see parent::run()}.
  105. */
  106. public function ignoreValidationErrors(): void
  107. {
  108. $this->ignoreValidation = true;
  109. $this->command->ignoreValidationErrors();
  110. parent::ignoreValidationErrors();
  111. }
  112. public function setApplication(?Application $application = null): void
  113. {
  114. $this->command->setApplication($application);
  115. }
  116. public function getApplication(): ?Application
  117. {
  118. return $this->command->getApplication();
  119. }
  120. public function setHelperSet(HelperSet $helperSet): void
  121. {
  122. $this->command->setHelperSet($helperSet);
  123. }
  124. public function getHelperSet(): ?HelperSet
  125. {
  126. return $this->command->getHelperSet();
  127. }
  128. public function isEnabled(): bool
  129. {
  130. return $this->command->isEnabled();
  131. }
  132. public function complete(CompletionInput $input, CompletionSuggestions $suggestions): void
  133. {
  134. $this->command->complete($input, $suggestions);
  135. }
  136. /**
  137. * {@inheritdoc}
  138. *
  139. * Calling parent method is required to be used in {@see parent::run()}.
  140. */
  141. public function setCode(callable $code): static
  142. {
  143. $this->command->setCode($code);
  144. return parent::setCode(function (InputInterface $input, OutputInterface $output) use ($code): int {
  145. $event = $this->stopwatch->start($this->getName().'.code');
  146. $this->exitCode = $code($input, $output);
  147. $event->stop();
  148. return $this->exitCode;
  149. });
  150. }
  151. /**
  152. * @internal
  153. */
  154. public function mergeApplicationDefinition(bool $mergeArgs = true): void
  155. {
  156. $this->command->mergeApplicationDefinition($mergeArgs);
  157. }
  158. public function setDefinition(array|InputDefinition $definition): static
  159. {
  160. $this->command->setDefinition($definition);
  161. return $this;
  162. }
  163. public function getDefinition(): InputDefinition
  164. {
  165. return $this->command->getDefinition();
  166. }
  167. public function getNativeDefinition(): InputDefinition
  168. {
  169. return $this->command->getNativeDefinition();
  170. }
  171. public function addArgument(string $name, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static
  172. {
  173. $this->command->addArgument($name, $mode, $description, $default, $suggestedValues);
  174. return $this;
  175. }
  176. public function addOption(string $name, string|array|null $shortcut = null, ?int $mode = null, string $description = '', mixed $default = null, array|\Closure $suggestedValues = []): static
  177. {
  178. $this->command->addOption($name, $shortcut, $mode, $description, $default, $suggestedValues);
  179. return $this;
  180. }
  181. /**
  182. * {@inheritdoc}
  183. *
  184. * Calling parent method is required to be used in {@see parent::run()}.
  185. */
  186. public function setProcessTitle(string $title): static
  187. {
  188. $this->command->setProcessTitle($title);
  189. return parent::setProcessTitle($title);
  190. }
  191. public function setHelp(string $help): static
  192. {
  193. $this->command->setHelp($help);
  194. return $this;
  195. }
  196. public function getHelp(): string
  197. {
  198. return $this->command->getHelp();
  199. }
  200. public function getProcessedHelp(): string
  201. {
  202. return $this->command->getProcessedHelp();
  203. }
  204. public function getSynopsis(bool $short = false): string
  205. {
  206. return $this->command->getSynopsis($short);
  207. }
  208. public function addUsage(string $usage): static
  209. {
  210. $this->command->addUsage($usage);
  211. return $this;
  212. }
  213. public function getUsages(): array
  214. {
  215. return $this->command->getUsages();
  216. }
  217. public function getHelper(string $name): HelperInterface
  218. {
  219. return $this->command->getHelper($name);
  220. }
  221. public function run(InputInterface $input, OutputInterface $output): int
  222. {
  223. $this->input = $input;
  224. $this->output = $output;
  225. $this->arguments = $input->getArguments();
  226. $this->options = $input->getOptions();
  227. $event = $this->stopwatch->start($this->getName(), 'command');
  228. try {
  229. $this->exitCode = parent::run($input, $output);
  230. } finally {
  231. $event->stop();
  232. if ($output instanceof ConsoleOutputInterface && $output->isDebug()) {
  233. $output->getErrorOutput()->writeln((string) $event);
  234. }
  235. $this->duration = $event->getDuration().' ms';
  236. $this->maxMemoryUsage = ($event->getMemory() >> 20).' MiB';
  237. if ($this->isInteractive) {
  238. $this->extractInteractiveInputs($input->getArguments(), $input->getOptions());
  239. }
  240. }
  241. return $this->exitCode;
  242. }
  243. protected function initialize(InputInterface $input, OutputInterface $output): void
  244. {
  245. $event = $this->stopwatch->start($this->getName().'.init', 'command');
  246. $this->command->initialize($input, $output);
  247. $event->stop();
  248. }
  249. protected function interact(InputInterface $input, OutputInterface $output): void
  250. {
  251. if (!$this->isInteractive = Command::class !== (new \ReflectionMethod($this->command, 'interact'))->getDeclaringClass()->getName()) {
  252. return;
  253. }
  254. $event = $this->stopwatch->start($this->getName().'.interact', 'command');
  255. $this->command->interact($input, $output);
  256. $event->stop();
  257. }
  258. protected function execute(InputInterface $input, OutputInterface $output): int
  259. {
  260. $event = $this->stopwatch->start($this->getName().'.execute', 'command');
  261. $exitCode = $this->command->execute($input, $output);
  262. $event->stop();
  263. return $exitCode;
  264. }
  265. private function extractInteractiveInputs(array $arguments, array $options): void
  266. {
  267. foreach ($arguments as $argName => $argValue) {
  268. if (\array_key_exists($argName, $this->arguments) && $this->arguments[$argName] === $argValue) {
  269. continue;
  270. }
  271. $this->interactiveInputs[$argName] = $argValue;
  272. }
  273. foreach ($options as $optName => $optValue) {
  274. if (\array_key_exists($optName, $this->options) && $this->options[$optName] === $optValue) {
  275. continue;
  276. }
  277. $this->interactiveInputs['--'.$optName] = $optValue;
  278. }
  279. }
  280. }