|
5 | 5 | * @package AI_Logger |
6 | 6 | */ |
7 | 7 |
|
| 8 | +use AI_Logger\Backtrace\Frame; |
8 | 9 | use AI_Logger\Data_Structures; |
9 | 10 |
|
10 | 11 | use function Mantle\Support\Helpers\str; |
@@ -47,12 +48,60 @@ function ai_logger_render_legacy_backtrace( array $backtrace ): void { |
47 | 48 | <?php |
48 | 49 | } |
49 | 50 |
|
| 51 | +/** |
| 52 | + * Collapse do_action/do_action_ref_array/apply_filters/apply_filters_ref_array |
| 53 | + * calls in the backtrace. This is to prevent the backtrace from being |
| 54 | + * cluttered with calls to these internal WordPress functions. |
| 55 | + * |
| 56 | + * @param array<\AI_Logger\Backtrace\Frame> $backtrace Backtrace to collapse. |
| 57 | + * @return array<\AI_Logger\Backtrace\Frame> Collapsed backtrace. |
| 58 | + */ |
| 59 | +function ai_logger_collapse_hook_calls( array $backtrace ): array { |
| 60 | + // Prevent compression if the query parameter is set. |
| 61 | + if ( ! empty( $_GET['ai_logger_dont_compress'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended |
| 62 | + return $backtrace; |
| 63 | + } |
| 64 | + |
| 65 | + for ( $i = 0; $i < count( $backtrace ) - 1; $i++ ) { // phpcs:ignore Generic.CodeAnalysis.ForLoopShouldBeWhileLoop.ForLoop, Squiz.PHP.DisallowSizeFunctionsInLoops.Found, Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed |
| 66 | + $current = $backtrace[ $i ]; |
| 67 | + |
| 68 | + if ( \WP_Hook::class !== $current->class ) { |
| 69 | + continue; |
| 70 | + } |
| 71 | + |
| 72 | + if ( ! in_array( $current->method, Frame::HOOK_METHODS, true ) ) { |
| 73 | + continue; |
| 74 | + } |
| 75 | + |
| 76 | + // Determine where the backtrace exits from WP_Hook. Find all the frames and |
| 77 | + // remove them. This could be in 2 frames or 5. |
| 78 | + for ( $si = $i + 1; $si < count( $backtrace ); $si++ ) { // phpcs:ignore Generic.CodeAnalysis.ForLoopShouldBeWhileLoop.ForLoop, Squiz.PHP.DisallowSizeFunctionsInLoops.Found, Generic.CodeAnalysis.ForLoopWithTestFunctionCall.NotAllowed |
| 79 | + $next = $backtrace[ $si ]; |
| 80 | + |
| 81 | + if ( \WP_Hook::class === $next->class ) { |
| 82 | + continue; |
| 83 | + } |
| 84 | + |
| 85 | + if ( in_array( $next->method, Frame::HOOK_METHODS, true ) ) { |
| 86 | + continue; |
| 87 | + } |
| 88 | + |
| 89 | + array_splice( $backtrace, $i, $si - $i, [] ); |
| 90 | + |
| 91 | + break; |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + return $backtrace; |
| 96 | +} |
| 97 | + |
50 | 98 | /** |
51 | 99 | * Render the backtrace powered by spatie/backtrace. |
52 | 100 | * |
53 | 101 | * @param array<\AI_Logger\Backtrace\Frame> $backtrace Backtrace to render. |
54 | 102 | */ |
55 | 103 | function ai_logger_render_backtrace( array $backtrace ): void { |
| 104 | + $backtrace = ai_logger_collapse_hook_calls( $backtrace ); |
56 | 105 | ?> |
57 | 106 | <div class="ai-log-backtrace"> |
58 | 107 | <?php |
|
0 commit comments