|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace Naoray\LaravelGithubMonolog\Issues\Formatters; |
| 4 | + |
| 5 | +use Illuminate\Support\Str; |
| 6 | +use Monolog\LogRecord; |
| 7 | +use Naoray\LaravelGithubMonolog\Issues\InteractsWithLogRecord; |
| 8 | +use Naoray\LaravelGithubMonolog\Issues\StubLoader; |
| 9 | +use Throwable; |
| 10 | + |
| 11 | +class PreviousExceptionFormatter |
| 12 | +{ |
| 13 | + use InteractsWithLogRecord; |
| 14 | + |
| 15 | + private const MAX_PREVIOUS_EXCEPTIONS = 3; |
| 16 | + |
| 17 | + private string $previousExceptionStub; |
| 18 | + |
| 19 | + public function __construct( |
| 20 | + private readonly ExceptionFormatter $exceptionFormatter, |
| 21 | + private readonly StubLoader $stubLoader, |
| 22 | + ) { |
| 23 | + $this->previousExceptionStub = $this->stubLoader->load('previous_exception'); |
| 24 | + } |
| 25 | + |
| 26 | + public function format(LogRecord $record): string |
| 27 | + { |
| 28 | + $exception = $this->getException($record); |
| 29 | + |
| 30 | + if (! $exception instanceof Throwable) { |
| 31 | + return ''; |
| 32 | + } |
| 33 | + |
| 34 | + if (! $previous = $exception->getPrevious()) { |
| 35 | + return ''; |
| 36 | + } |
| 37 | + |
| 38 | + $exceptions = collect() |
| 39 | + ->range(1, self::MAX_PREVIOUS_EXCEPTIONS) |
| 40 | + ->map(function ($count) use (&$previous, $record) { |
| 41 | + if (! $previous) { |
| 42 | + return null; |
| 43 | + } |
| 44 | + |
| 45 | + $current = $previous; |
| 46 | + $previous = $previous->getPrevious(); |
| 47 | + |
| 48 | + $details = $this->exceptionFormatter->format( |
| 49 | + $record->with( |
| 50 | + context: ['exception' => $current], |
| 51 | + extra: [] |
| 52 | + ) |
| 53 | + ); |
| 54 | + |
| 55 | + return Str::of($this->previousExceptionStub) |
| 56 | + ->replace( |
| 57 | + ['{count}', '{message}', '{simplified_stack_trace}', '{full_stack_trace}'], |
| 58 | + [$count, $current->getMessage(), $details['simplified_stack_trace'], str_replace(base_path(), '', $details['full_stack_trace'])] |
| 59 | + ) |
| 60 | + ->toString(); |
| 61 | + }) |
| 62 | + ->filter() |
| 63 | + ->join("\n\n"); |
| 64 | + |
| 65 | + if (empty($exceptions)) { |
| 66 | + return ''; |
| 67 | + } |
| 68 | + |
| 69 | + if ($previous) { |
| 70 | + $exceptions .= "\n\n> Note: Additional previous exceptions were truncated\n"; |
| 71 | + } |
| 72 | + |
| 73 | + return $exceptions; |
| 74 | + } |
| 75 | +} |
0 commit comments