TraceableCommand.php 10 KB

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