Spatie Backtrace

repository·main·Indexed 19 days ago

https://github.com/spatie/backtrace

A PHP package providing a developer-friendly alternative to the native debug_backtrace() function. It allows for the creation of backtraces from the current execution context or Throwables, with features to include function arguments and object contexts, reduce arguments to readable strings via ArgumentReducer, filter frames using offset and limit, and extract code snippets around specific execution lines.

Tokens
3.5K
Snippets
18
Records
19
Agent score
66%

What's inside spatie/backtrace

  1. Reduce arguments to strings

    main

    To make arguments more readable, use reduceArguments(). This converts typical types into string representations. You can also implement a custom ArgumentReducer to define how specific types are handled.

    // Using custom reducers with the default ones
    $backtrace = Spatie\Backtrace\Backtrace::create()->withArguments()->reduceArguments(
        Spatie\Backtrace\Arguments\ArgumentReducers::default([
            new DateTimeWithOtherFormatArgumentReducer()
        ])
    );
    
    // Example of a custom reducer implementation
    class DateTimeWithOtherFormatArgumentReducer implements ArgumentReducer
    {
        public function execute($argument): ReducedArgumentContract
        {
            if (! $argument instanceof DateTimeInterface) {
                return UnReducedArgument::create();
            }
    
            return new ReducedArgument(
                $argument->format('d/m/y H:i'),
                get_class($argument),
            );
        }
    }
  2. Configure application path and trim file paths

    main

    To correctly identify application frames versus vendor frames, use applicationPath(string $path). If you want to clean up the file paths by removing the application base path, also call trimFilePaths().

    // Set application path to identify app frames
    $backtrace = Spatie\Backtrace\Backtrace::create()->applicationPath(base_path());
    
    // Set application path AND trim the file paths for cleaner output
    $backtrace = Spatie\Backtrace\Backtrace::create()->applicationPath(base_path())->trimFilePaths();
  3. Get a backtrace for a Throwable

    main

    To extract a backtrace from an existing exception or error, use Backtrace::createForThrowable($throwable).

    Note: Arguments will only be included if the PHP INI option zend.exception_ignore_args is set to 0 before the exception is thrown. Objects are never included in the backtrace via this method.

    $frames = Spatie\Backtrace\Backtrace::createForThrowable($throwable);
  4. Filter and limit backtrace frames

    main

    You can manipulate the resulting frame list using several methods:

    • startingFromFrame(callable $callback): Returns frames starting from the first frame that satisfies the callback.
    • offset(int $count): Skips the first $count frames.
    • limit(int $count): Limits the total number of frames returned to $count.
    // Start from a specific class
    $frames = Backtrace::create()
        ->startingFromFrame(function (Frame $frame) {
            return $frame->class === MyClass::class;
        })
        ->frames();
    
    // Skip the first 2 frames
    $frames = Backtrace::create()->offset(2)->frames();
    
    // Get only the first 2 frames
    $frames = Backtrace::create()->limit(2)->frames();
  5. Collect arguments and objects in a backtrace

    main

    By default, frames do not include function arguments or the object context for performance reasons. To include them, chain withArguments() and/or withObject() to the creation call.

    $backtrace = Spatie\Backtrace\Backtrace::create()->withArguments()->withObject();
  6. Create a backtrace and get frames

    main

    Use Spatie\Backtrace\Backtrace::create() to initialize a backtrace instance. You can then call frames() to retrieve an array of Spatie\Backtrace\Frame instances.

    $frames = Spatie\Backtrace\Backtrace::create()->frames(); 
    
    $firstFrame = $frames[0];
    $firstFrame->file; // returns the file name
    $firstFrame->lineNumber; // returns the line number
    $firstFrame->class; // returns the class name
  7. Properties of a Spatie\Backtrace\Frame

    main

    Each Spatie\Backtrace\Frame object contains the following properties:

    • file: The name of the file.
    • lineNumber: The line number.
    • arguments: The arguments used for this frame (returns null unless withArguments() was used).
    • class: The class name (returns null if the frame is a function).
    • method: The method used in this frame.
    • object: The object in the current context (returns null unless withObject() was used).
    • applicationFrame: A boolean indicating if the frame belongs to your application (true) or the vendor directory (false).
    • trimmedFilePath: The file path with the application path removed (available if trimFilePaths() is used).
  8. Represent a single backtrace frame with the Frame class

    main

    The Spatie\Backtrace\Frame class represents a single frame in a backtrace. It contains metadata about the execution point, including the file path, line number, method name, class name, and any arguments passed to the function. It also supports retrieving code snippets surrounding the specific line of execution.

    Properties

    • $file: The full path to the file.
    • $trimmedFilePath: An optional trimmed version of the file path.
    • $lineNumber: The line number where the frame occurred.
    • $arguments: An array of arguments passed to the method, or null.
    • $method: The name of the method called, or null.
    • $class: The name of the class, or null.
    • $object: The object instance the method was called on, or null.
    • $applicationFrame: A boolean indicating if this is considered an application frame.

    Snippet Retrieval

    You can retrieve code snippets around the line number using the following methods:

    • getSnippet(int $lineCount): Returns an array of code lines.
    • getSnippetAsString(int $lineCount): Returns the snippet as a single string.
    • getSnippetProperties(int $lineCount): Returns an array of associative arrays, where each entry contains 'line_number' and 'text'.
    use Spatie\Backtrace\Frame;
    
    $frame = new Frame(
        file: '/path/to/file.php',
        lineNumber: 42,
        arguments: ['arg1', 'arg2'],
        method: 'myMethod',
        class: 'MyClass',
        object: $myObject,
        isApplicationFrame: true
    );
    
    // Get code snippets around line 42
    $snippet = $frame->getSnippetAsString(5);
  9. Retrieve code snippets as an array or string

    main

    Once a CodeSnippet is configured, you can extract the code from a SnippetProvider in two formats:

    1. As an associative array: Use get(SnippetProvider $provider) to return an array where the keys are the line numbers and the values are the code strings (truncated to 250 characters).
    2. As a formatted string: Use getAsString(SnippetProvider $provider) to return a single string where each line is prefixed with its line number (e.g., "10 code line content\n").
    // Returns array of [lineNumber => codeLine]
    $codeArray = $snippet->get($provider);
    
    // Returns string with line numbers prefixed
    $codeString = $snippet->getAsString($provider);
  10. Limit and offset backtrace frames

    main

    You can control which part of the backtrace is returned using limit() and offset():

    • limit(int $limit): Limits the number of frames returned.
    • offset(int $offset): Skips a specific number of frames at the beginning of the trace.
    $backtrace = Backtrace::create()
        ->offset(5)
        ->limit(10);
  11. Reduce backtrace arguments

    main

    To prevent large or sensitive data from bloating your backtrace, you can use reduceArguments(). This enables argument reduction, which simplifies complex objects or large arrays into more readable representations.

    You can pass null to use the default reducers, or provide an array of ArgumentReducer instances or class strings.

    $backtrace = Backtrace::create()
        ->withArguments()
        ->reduceArguments(); // Uses default reducers