Shell.php 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. * Copyright © Magento, Inc. All rights reserved.
  4. * See COPYING.txt for license details.
  5. */
  6. namespace Magento\Framework\App;
  7. use Magento\Framework\Exception\LocalizedException;
  8. use Magento\Framework\Phrase;
  9. use Magento\Framework\Shell\CommandRendererInterface;
  10. use Magento\Framework\Shell\Driver;
  11. use Magento\Framework\ShellInterface;
  12. use Psr\Log\LoggerInterface;
  13. /**
  14. * Class is separate from \Magento|Framework\Shell because logging behavior is different, and relies on ObjectManager
  15. * being available.
  16. */
  17. class Shell implements ShellInterface
  18. {
  19. /**
  20. * @var \Magento\Framework\Shell\Driver
  21. */
  22. private $driver;
  23. /**
  24. * @var \Psr\Log\LoggerInterface
  25. */
  26. private $logger;
  27. /**
  28. * @param Driver $driver
  29. * @param CommandRendererInterface $commandRenderer
  30. * @param LoggerInterface $logger
  31. */
  32. public function __construct(
  33. Driver $driver,
  34. LoggerInterface $logger
  35. ) {
  36. $this->driver = $driver;
  37. $this->logger = $logger;
  38. }
  39. /**
  40. * Execute a command through the command line, passing properly escaped arguments
  41. *
  42. * @param string $command Command with optional argument markers '%s'
  43. * @param string[] $arguments Argument values to substitute markers with
  44. * @throws \Magento\Framework\Exception\LocalizedException If a command returns non-zero exit code
  45. * @return string
  46. */
  47. public function execute($command, array $arguments = [])
  48. {
  49. try {
  50. $response = $this->driver->execute($command, $arguments);
  51. } catch (LocalizedException $e) {
  52. $this->logger->error($e->getLogMessage());
  53. throw $e;
  54. }
  55. $escapedCommand = $response->getEscapedCommand();
  56. $output = $response->getOutput();
  57. $exitCode = $response->getExitCode();
  58. $logEntry = $escapedCommand . PHP_EOL . $output;
  59. if ($exitCode) {
  60. $this->logger->error($logEntry);
  61. $commandError = new \Exception($output, $exitCode);
  62. throw new LocalizedException(
  63. new Phrase("Command returned non-zero exit code:\n`%1`", [$command]),
  64. $commandError
  65. );
  66. }
  67. $this->logger->info($logEntry);
  68. return $output;
  69. }
  70. }