raffaelecarelle / php-error-insight
AI-powered helper for PHP errors, warnings and exceptions: practical, context-aware explanations and suggestions via local or API LLMs.
Installs: 768
Dependents: 2
Suggesters: 0
Security: 0
Stars: 2
Watchers: 1
Forks: 0
Open Issues: 0
pkg:composer/raffaelecarelle/php-error-insight
Requires
- php: >=8.1
- ext-curl: *
- symfony/var-dumper: ^5.0|^6.0|^7.0
Requires (Dev)
- friendsofphp/php-cs-fixer: ^3.86
- phpstan/phpstan: ^1.10
- phpunit/phpunit: ^10.0
- rector/rector: ^1.0
README
A tool that intercepts PHP errors, warnings, and exceptions and provides practical help and advice generated by AI (local models or external APIs). No static text: details and suggestions are created on-the-fly by artificial intelligence based on the error message and context.
Screenshots:
- Supports local AI backends (e.g. Ollama/LocalAI) and APIs (e.g. OpenAI, Anthropic, Google Gemini).
- HTML, text or JSON output.
- Simple configuration via environment variables or by instantiating the Config.
Requirements
- PHP >= 8.1
- Composer
- (Optional) a local AI backend (Ollama/LocalAI) or an API key (OpenAI, etc.)
Installation
composer require raffaelecarelle/php-error-insight
Configuration
You can configure the tool via environment variables or through code.
Supported environment variables:
- PHP_ERROR_INSIGHT_ENABLED: true/false (default: true)
- PHP_ERROR_INSIGHT_BACKEND: none|local|api|openai|anthropic|google|gemini
- PHP_ERROR_INSIGHT_MODEL: model name (e.g. llama3:instruct, gpt-4o-mini, claude-3-5-sonnet-20240620, gemini-1.5-flash)
- PHP_ERROR_INSIGHT_API_KEY: API key (required for api/openai/anthropic/google backends)
- PHP_ERROR_INSIGHT_API_URL: service URL (optional override; e.g. http://localhost:11434 for Ollama, https://api.openai.com/v1/chat/completions for OpenAI, https://api.anthropic.com/v1/messages for Anthropic, https://generativelanguage.googleapis.com/v1/models for Google Gemini)
- PHP_ERROR_INSIGHT_LANG: language for AI prompt (it, en, ...; default: it)
- PHP_ERROR_INSIGHT_OUTPUT: auto|html|text|json (default: auto)
- PHP_ERROR_INSIGHT_VERBOSE: true/false (default: false)
- PHP_ERROR_INSIGHT_TEMPLATE: path to a custom HTML template (optional)
- PHP_ERROR_INSIGHT_ROOT: absolute project root to compute relative file paths in the stack (optional)
- PHP_ERROR_INSIGHT_HOST_ROOT: absolute host project root used to map container paths when opening files via editor links (optional; useful in Docker)
- PHP_ERROR_INSIGHT_EDITOR: editor URL template for clickable file links, using %file and %line placeholders (e.g. "vscode://file/%file:%line" or "phpstorm://open?file=%file&line=%line")
- PHP_ERROR_INSIGHT_CONSOLE_COLORS: JSON object to customize console styles (token colors, severity backgrounds, title/suggestions/stack/location).
Configuration examples:
- Local backend (Ollama):
export PHP_ERROR_INSIGHT_BACKEND=local export PHP_ERROR_INSIGHT_MODEL=llama3:instruct export PHP_ERROR_INSIGHT_API_URL=[http://localhost:11434](http://localhost:11434)
- API backend (OpenAI compatible):
export PHP_ERROR_INSIGHT_BACKEND=api export PHP_ERROR_INSIGHT_MODEL=gpt-4o-mini export PHP_ERROR_INSIGHT_API_KEY=sk-... export PHP_ERROR_INSIGHT_API_URL=https://api.openai.com/v1/chat/completions
- API backend (Anthropic Claude):
export PHP_ERROR_INSIGHT_BACKEND=anthropic export PHP_ERROR_INSIGHT_MODEL=claude-3-5-sonnet-20240620 export PHP_ERROR_INSIGHT_API_KEY=api-key # optional override # export PHP_ERROR_INSIGHT_API_URL=https://api.anthropic.com/v1/messages
- API backend (Google Gemini):
export PHP_ERROR_INSIGHT_BACKEND=google export PHP_ERROR_INSIGHT_MODEL=gemini-1.5-flash export PHP_ERROR_INSIGHT_API_KEY=api-key # optional override # export PHP_ERROR_INSIGHT_API_URL=https://generativelanguage.googleapis.com/v1/models
Editor integration and stack trace copying
When viewing the HTML error page, each stack frame now shows:
- Clickable file path: if PHP_ERROR_INSIGHT_EDITOR (or Config::editorUrl) is set, file paths become links that can open your editor at the exact line.
- Per-row copy button: a small clipboard button copies the project-relative path with line in the format path/to/file.php:LINE.
- Copy title: a button in the header copies the error title (and location) to your clipboard.
- Copy full stack: a button copies all stack lines as plain text.
Configuration options:
- PHP_ERROR_INSIGHT_ROOT: absolute project root used to compute relative paths.
- PHP_ERROR_INSIGHT_EDITOR: URL template with placeholders %file and %line.
- VS Code: vscode://file/%file:%line
- PhpStorm: phpstorm://open?file=%file&line=%line
 
- VS Code: 
Example (VS Code):
export PHP_ERROR_INSIGHT_ROOT=/path/to/your/project export PHP_ERROR_INSIGHT_EDITOR="vscode://file/%file:%line"
Example (PhpStorm):
export PHP_ERROR_INSIGHT_ROOT=/path/to/your/project export PHP_ERROR_INSIGHT_EDITOR="phpstorm://open?file=%file&line=%line"
Docker/containers mapping (open files in host IDE):
When running the app inside a container, set PHP_ERROR_INSIGHT_ROOT to the container project root and PHP_ERROR_INSIGHT_HOST_ROOT to the corresponding host path. Editor links will be generated with the host path so your IDE can open files.
Example (Docker + VS Code):
# inside container, your app root is mounted from /Users/you/project export PHP_ERROR_INSIGHT_ROOT=/var/www/app export PHP_ERROR_INSIGHT_HOST_ROOT=/Users/you/project export PHP_ERROR_INSIGHT_EDITOR="vscode://file/%file:%line"
Example (Docker + PhpStorm):
export PHP_ERROR_INSIGHT_ROOT=/var/www/app export PHP_ERROR_INSIGHT_HOST_ROOT=/Users/you/project export PHP_ERROR_INSIGHT_EDITOR="phpstorm://open?file=%file&line=%line"
Code-based configuration example:
use ErrorExplainer\Config; $config = Config::fromEnvAndArray([ 'projectRoot' => __DIR__, 'editorUrl' => 'vscode://file/%file:%line', ]);
Notes:
- If a file is outside the declared project root, the viewer falls back to trimming from /vendor/when present, or shows a normalized absolute path.
- All clipboard features use a secure helper that falls back to a hidden textarea when the Clipboard API is not available.
Usage (Vanilla PHP)
In your application's bootstrap, register the handler included in the examples, or use the helper provided by the package. A minimal example is available in examples/vanilla/index.php.
Quick example:
use ErrorExplainer\Config; use ErrorExplainer\Register; require **DIR**.'/vendor/autoload.php'; $config = Config::fromEnvAndArray([ 'backend' => 'local', // none | local | api 'model' => 'llama3:instruct', 'language'=> 'en', 'verbose' => true, ]); Register::install($config); // sets up error and exception handlers // Generate an error to see the output strpos();
Output:
- In HTML you'll see the page with stack trace and the "Details/Suggestions" section populated by AI.
- In CLI you'll get text/JSON depending on configuration.
How it works
- The tool intercepts errors/warnings/exceptions.
- Builds a prompt with message, severity and location.
- Sends the prompt to the configured AI backend.
- Shows the AI response as details and practical suggestions.
Note: the tool no longer uses static translated texts for details/suggestions. If the AI backend is not configured or doesn't respond, those sections might remain empty.
Privacy and Data Sanitization
By default, prompts are sanitized before being sent to any AI backend to reduce the risk of leaking sensitive information (emails, tokens, private IPs, cookies, payment-like numbers, etc.). You can control this behavior via environment variables:
- PHP_ERROR_INSIGHT_SANITIZE: 1|0 (default: 1 when unset)
- PHP_ERROR_INSIGHT_SANITIZE_RULES: comma-separated list of rules to enable (secrets, pii, payment, network). Example: secrets,pii,network
- PHP_ERROR_INSIGHT_SANITIZE_MASK: override the default mask string (default: REDACTED)
Technical details:
- Sanitization happens inside Internal/Explainer just after the prompt is built and before any backend/API call.
- The default sanitizer masks Authorization headers, JWT-like tokens, emails, phone numbers, Italian CF/IBAN, payment-like card numbers, private IPs, and Cookie headers.
- You can inject your own AI client (AIClientInterface) if you prefer to handle sanitization externally.
For more details, see docs/sanitizzazione-dati-ai.md.
Console colors customization (CLI)
You can customize the colors used in the CLI output (syntax highlighting, severity header background, title, AI suggestions, stack trace and locations).
Two ways to configure:
- Environment variable PHP_ERROR_INSIGHT_CONSOLE_COLORScontaining a JSON object
- Programmatic via Config::fromEnvAndArray(['consoleColors' => [...]])
Structure of the JSON/object:
{
  "tokens": {
    "default": ["white", null, []],
    "comment": ["white", null, []],
    "string": ["yellow", null, []],
    "keyword": ["magenta", null, ["bold"]],
    "html": ["cyan", null, ["bold"]],
    "variable": ["cyan", null, []],
    "function": ["blue", null, ["bold"]],
    "method": ["green", null, ["underscore"]]
  },
  "severity": {
    "error": "red",
    "warning": "yellow",
    "info": "blue"
  },
  "styles": {
    "title": ["white", null, ["bold"]],
    "suggestion": ["green", null, []],
    "stack": ["yellow", null, []],
    "location": ["blue", null, []],
    "gutter_hl": ["white", "red", ["bold"]],
    "gutter_num": ["gray", null, []],
    "gutter_sep": ["gray", null, []]
  }
}
Notes:
- Each style uses the form [fg, bg, options[]].fgandbgaccept Symfony Console color names (e.g., "white", "yellow", "red", "blue", "cyan", "magenta", "gray"), andoptionscan includebold,underscore,blink,reverse,conceal.
- tokensoverrides the syntax highlighter palette for these categories:- default,- comment,- string,- keyword,- html,- variable,- function,- method.
- severitymaps- error|warning|infoto a background color name for the header badge with the severity label.
- styleslets you tweak semantic tags used by the renderer:- title(error message),- suggestion(AI suggestions label and items),- stack(stack trace lines when rendered in compact mode),- location(file:line),- gutter_hl(current line number in code excerpts),- gutter_num(non-current line numbers), and- gutter_sep(the vertical separator).
- Any key you omit falls back to sensible defaults.
Examples
- Via environment variable:
export PHP_ERROR_INSIGHT_CONSOLE_COLORS='{ "severity": {"error":"magenta","warning":"yellow","info":"cyan"}, "styles": {"title":["white",null,["bold"]],"suggestion":["cyan",null,[]]}, "tokens": {"keyword":["magenta",null,["bold"]],"string":["green",null,[]]} }'
- Via code:
use PhpErrorInsight\Config; $config = Config::fromEnvAndArray([ 'consoleColors' => [ 'severity' => [ 'error' => 'magenta', 'warning' => 'yellow', 'info' => 'blue' ], 'styles' => [ 'title' => ['white', null, ['bold']], 'suggestion' => ['cyan', null, []] ], 'tokens' => [ 'keyword' => ['magenta', null, ['bold']], 'string' => ['green', null, []] ], ], ]);
Development
This project uses several development tools to maintain code quality. Use the following composer scripts for easy access to these tools:
Code Quality Scripts
# Check code style (dry-run) composer cs-check # Fix code style issues composer cs-fix # Check for code improvements with Rector (dry-run) composer rector-check # Apply Rector improvements composer rector-fix # Run static analysis with PHPStan composer phpstan # Run tests composer test # Run tests with coverage report (generates HTML in var/coverage) composer test-coverage
Combined Scripts
# Run all quality checks (cs-check, rector-check, phpstan, test) composer quality # Apply all automatic fixes (cs-fix, rector-fix) composer fix-all
Development Workflow
- Install dependencies: composer install
- Make your changes
- Run quality checks: composer quality
- Fix issues automatically: composer fix-all
- Run tests with coverage: composer test-coverage
The project is configured for PHP 8.1+ and includes:
- PHP CS Fixer for code style enforcement
- Rector for automated code improvements and PHP version upgrades
- PHPStan for static analysis
- PHPUnit for testing
- GitHub Actions with matrix testing for PHP versions 8.1, 8.2, 8.3, 8.4, 8.5
License
GPL-3.0-or-later
This project is licensed under the GNU General Public License v3.0 or later. See the LICENSE file for details.

