Spatie Ignition

repository·main·Indexed 19 days ago

https://github.com/spatie/ignition

A customizable error page for PHP applications that provides a visual way to debug exceptions. It supports framework-agnostic installation via Composer, as well as integrations for Laravel, Symfony, Drupal, and OpenMage. Features include AI-powered solutions via OpenAI, custom solution providers, and exception monitoring integration with Flare.

Tokens
4.8K
Snippets
15
Records
15
Agent score
68%

What's inside spatie/ignition

  1. Add solutions to exceptions

    main

    Ignition can display actionable solutions for errors. There are two ways to implement this:

    1. Implementing ProvidesSolution on an Exception

    Make your custom exception implement the Spatie\Ignition\Contracts\ProvidesSolution interface. You must implement the getSolution() method, which returns an instance of Spatie\Ignition\Contracts\Solution.

    2. Using Solution Providers

    For more complex logic (like looking up solutions on Stack Overflow), implement the Spatie\Ignition\Contracts\HasSolutionsForThrowable interface. This allows you to decide if a provider can solve a specific Throwable via canSolve() and then return the solutions via getSolutions().

    Register providers using addSolutionProviders().

    // Implementing a solution directly in an exception
    use Spatie\Ignition\Contracts\Solution;
    use Spatie\Ignition\Contracts\ProvidesSolution;
    
    class CustomException extends Exception implements ProvidesSolution
    {
        public function getSolution(): Solution
        {
            return new CustomSolution();
        }
    }
    
    class CustomSolution implements Solution
    {
        public function getSolutionTitle(): string
        {
            return 'The solution title goes here';
        }
    
        public function getSolutionDescription(): string
        {
            return 'This is a longer description of the solution that you want to show.';
        }
    
        public function getDocumentationLinks(): array
        {
            return [
                'Your documentation' => 'https://your-project.com/relevant-docs-page',
            ];
        }
    }
    
    // Registering a solution provider
    \Spatie\Ignition\Ignition::make()
        ->addSolutionProviders([
            YourSolutionProvider::class,
        ])
        ->register();
  2. Register Ignition in a PHP application

    main

    To use Ignition in a standard PHP project, you need to include the Composer autoloader and call the register() method on an instance created via Ignition::make().

    Once registered, any unhandled exception thrown during a web request will be rendered using the Ignition error page.

    use Spatie\
    Ignition
    Ignition;
    
    include 'vendor/autoload.php';
    
    Ignition::make()->register();
    
    // Example of triggering the error page
    throw new Exception('Bye world');
  3. Enable AI-powered solutions with OpenAI

    main

    Ignition can use OpenAI to suggest solutions for exceptions.

    1. Install dependency: composer require openai-php/client
    2. Instantiate provider: Create an instance of OpenAiSolutionProvider with your OpenAI API key.
    3. Register provider: Pass the instance to addSolutionProviders().

    Features:

    • Context: It sends the error message, class, stack frame, and surrounding context. It excludes request payloads and environment variables for security.
    • Caching: Use useCache(CacheInterface $cache, int $cacheTtlInSeconds) on the provider to avoid redundant API calls for similar errors.
    • Application Hinting: Use applicationType('Type') (e.g., 'WordPress 6.2') to improve suggestion quality.
    composer require openai-php/client
    use \Spatie\Ignition\Solutions\OpenAi\OpenAiSolutionProvider;
    
    $aiSolutionProvider = new OpenAiSolutionProvider($openAiKey);
    $aiSolutionProvider->applicationType('WordPress 6.2');
    $aiSolutionProvider->useCache($cacheInstance, 3600);
    
    \Spatie\Ignition\Ignition::make()
        ->addSolutionProviders([$aiSolutionProvider])
        ->register();
  4. Install Ignition in a PHP project

    main

    If you are not using a framework-specific integration (like Laravel, Symfony, Drupal, or OpenMage), you can install Ignition directly via Composer.

    For framework-specific implementations, use these packages instead:

    composer require spatie/ignition
  5. Integrate with Flare for exception monitoring

    main

    Ignition can send exceptions to Flare.

    Basic Setup

    Use sendToFlare($apiKey) and runningInProductionEnvironment($boolean) to ensure errors are reported to Flare in production without showing the Ignition UI to users.

    Customizing Flare Data

    Use configureFlare(callable $callback) to access the Spatie\FlareClient\Flare instance for advanced configuration:

    • context($key, $value): Add key-value pairs to every exception.
    • group($key, array $data): Group context items together.
    • anonymizeIp(): Prevent user IP addresses from being sent.
    • censorRequestBodyFields(array $fields): Replace sensitive fields (like password) with <CENSORED>.
    • registerMiddleware(array $middleware): Register classes implementing FlareMiddleware to modify the Report before it is sent.

    Flare Middleware Example

    Implement FlareMiddleware to intercept and modify the Report object.

    use Spatie\FlareClient\Flare;
    use Spatie\FlareClient\FlareMiddleware\FlareMiddleware;
    use Spatie\FlareClient\Report;
    use Closure;
    
    // 1. Define Middleware
    class MyMiddleware implements FlareMiddleware
    {
        public function handle(Report $report, Closure $next)
        {
            $report->message("{$report->getMessage()}, now modified");
            return $next($report);
        }
    }
    
    // 2. Register everything
    \Spatie\Ignition\Ignition::make()
        ->runningInProductionEnvironment(true)
        ->sendToFlare('YOUR_FLARE_API_KEY')
        ->configureFlare(function(Flare $flare) {
            $flare->context('Tenant', 'My-Tenant-Identifier');
            $flare->censorRequestBodyFields(['password']);
            $flare->registerMiddleware([MyMiddleware::class]);
        })
        ->register();
  6. Initialize and register Ignition

    main

    To use Ignition in a framework-agnostic PHP application, use the make() method to instantiate the class and register() to set up the error and exception handlers. Once registered, Ignition will intercept errors and exceptions to display the error page.

    By default, register() uses the current PHP error reporting settings. You can pass a specific integer to register(?int $errorLevels = null) to control which error levels are handled.

    use Spatie\Ignition\Ignition;
    
    $ignition = Ignition::make()->register();
  7. Configure Ignition appearance and environment

    main

    You can customize how Ignition behaves and looks using the following methods:

    • applicationPath($path): Sets the base path of your application. Ignition will trim this value from all displayed paths to make error reports cleaner.
    • setTheme('dark'): Enables dark mode. The default is a white-based theme.
    • shouldDisplayException($boolean): Controls whether the Ignition error page is rendered. Pass false to prevent rendering (e.g., in production).
    • runningInProductionEnvironment($boolean): When used with Flare, if set to true, Ignition will only send exceptions to Flare and will not display the error page locally.
    // Example: Setting path, dark mode, and production safety
    \Spatie\Ignition\Ignition::make()
        ->applicationPath($basePathOfYourApplication)
        ->setTheme('dark')
        ->shouldDisplayException($inLocalEnvironment)
        ->register();
  8. Handle exceptions manually

    main

    While register() automates error handling, you can manually trigger the Ignition lifecycle:

    • handleException(Throwable $throwable): The main entry point for framework-agnostic apps. It creates a report, displays the error page (if not in production), and optionally sends the report to Flare.
    • renderException(Throwable $throwable, ?Report $report = null): Specifically renders the error page UI without necessarily sending the report to Flare (useful for Laravel integrations).
    try {
        // some code
    } catch (Throwable $e) {
        Ignition::make()->handleException($e);
    }
  9. Customize the error page HTML

    main

    If you need to inject custom styles, scripts, or markup into the Ignition error page, use the following methods:

    • addCustomHtmlToHead(string $html): Appends HTML to the <head> section.
    • addCustomHtmlToBody(string $html): Appends HTML to the <body> section.
    $ignition->addCustomHtmlToHead('<style>body { background: red; }</style>');
  10. Configure Ignition appearance and editor

    main

    You can customize the visual presentation of the error page and the preferred editor for solutions using the following methods:

    • setTheme(string $theme): Sets the visual theme (e.g., 'light' or 'dark').
    • setEditor(string $editor): Sets the preferred text editor used when clicking on solutions.

    Note: useDarkMode() and theme() are deprecated in favor of setTheme().

    $ignition = Ignition::make()
        ->setTheme('dark')
        ->setEditor('code');
  11. Register custom solution providers

    main

    Ignition can suggest fixes for common errors using solution providers. You can extend this functionality by registering your own providers that implement Spatie\ErrorSolutions\Contracts\HasSolutionsForThrowable using addSolutionProviders().

    $ignition->addSolutionProviders([
        App\Solutions\MyCustomSolutionProvider::class,
    ]);