ListFailedCommand.php 2.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. <?php
  2. namespace Illuminate\Queue\Console;
  3. use Illuminate\Support\Arr;
  4. use Illuminate\Console\Command;
  5. class ListFailedCommand extends Command
  6. {
  7. /**
  8. * The console command name.
  9. *
  10. * @var string
  11. */
  12. protected $name = 'queue:failed';
  13. /**
  14. * The console command description.
  15. *
  16. * @var string
  17. */
  18. protected $description = 'List all of the failed queue jobs';
  19. /**
  20. * The table headers for the command.
  21. *
  22. * @var array
  23. */
  24. protected $headers = ['ID', 'Connection', 'Queue', 'Class', 'Failed At'];
  25. /**
  26. * Execute the console command.
  27. *
  28. * @return void
  29. */
  30. public function handle()
  31. {
  32. if (count($jobs = $this->getFailedJobs()) == 0) {
  33. return $this->info('No failed jobs!');
  34. }
  35. $this->displayFailedJobs($jobs);
  36. }
  37. /**
  38. * Compile the failed jobs into a displayable format.
  39. *
  40. * @return array
  41. */
  42. protected function getFailedJobs()
  43. {
  44. $failed = $this->laravel['queue.failer']->all();
  45. return collect($failed)->map(function ($failed) {
  46. return $this->parseFailedJob((array) $failed);
  47. })->filter()->all();
  48. }
  49. /**
  50. * Parse the failed job row.
  51. *
  52. * @param array $failed
  53. * @return array
  54. */
  55. protected function parseFailedJob(array $failed)
  56. {
  57. $row = array_values(Arr::except($failed, ['payload', 'exception']));
  58. array_splice($row, 3, 0, $this->extractJobName($failed['payload']));
  59. return $row;
  60. }
  61. /**
  62. * Extract the failed job name from payload.
  63. *
  64. * @param string $payload
  65. * @return string|null
  66. */
  67. private function extractJobName($payload)
  68. {
  69. $payload = json_decode($payload, true);
  70. if ($payload && (! isset($payload['data']['command']))) {
  71. return $payload['job'] ?? null;
  72. } elseif ($payload && isset($payload['data']['command'])) {
  73. return $this->matchJobName($payload);
  74. }
  75. }
  76. /**
  77. * Match the job name from the payload.
  78. *
  79. * @param array $payload
  80. * @return string
  81. */
  82. protected function matchJobName($payload)
  83. {
  84. preg_match('/"([^"]+)"/', $payload['data']['command'], $matches);
  85. if (isset($matches[1])) {
  86. return $matches[1];
  87. }
  88. return $payload['job'] ?? null;
  89. }
  90. /**
  91. * Display the failed jobs in the console.
  92. *
  93. * @param array $jobs
  94. * @return void
  95. */
  96. protected function displayFailedJobs(array $jobs)
  97. {
  98. $this->table($this->headers, $jobs);
  99. }
  100. }