first commit

This commit is contained in:
Sampanna Rimal
2024-08-27 17:48:06 +05:45
commit 53c0140f58
10839 changed files with 1125847 additions and 0 deletions

21
vendor/spatie/backtrace/LICENSE.md vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Spatie bvba <info@spatie.be>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

198
vendor/spatie/backtrace/README.md vendored Normal file
View File

@@ -0,0 +1,198 @@
# A better PHP backtrace
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/backtrace.svg?style=flat-square)](https://packagist.org/packages/spatie/backtrace)
![Tests](https://github.com/spatie/backtrace/workflows/Tests/badge.svg)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/backtrace.svg?style=flat-square)](https://packagist.org/packages/spatie/backtrace)
To get the backtrace in PHP you can use the `debug_backtrace` function. By default, it can be hard to work with. The
reported function name for a frame is skewed: it belongs to the previous frame. Also, options need to be passed using a bitmask.
This package provides a better way than `debug_backtrace` to work with a back trace. Here's an example:
```php
// returns an array with `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
```
## Support us
[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/backtrace.jpg?t=1" width="419px" />](https://spatie.be/github-ad-click/backtrace)
We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can
support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards
on [our virtual postcard wall](https://spatie.be/open-source/postcards).
## Installation
You can install the package via composer:
```bash
composer require spatie/backtrace
```
## Usage
This is how you can create a backtrace instance:
```php
$backtrace = Spatie\Backtrace\Backtrace::create();
```
### Getting the frames
To get all the frames you can call `frames`.
```php
$frames = $backtrace->frames(); // contains an array with `Spatie\Backtrace\Frame` instances
```
A `Spatie\Backtrace\Frame` has these properties:
- `file`: the name of the file
- `lineNumber`: the line number
- `arguments`: the arguments used for this frame. Will be `null` if `withArguments` was not used.
- `class`: the class name for this frame. Will be `null` if the frame concerns a function.
- `method`: the method used in this frame
- `applicationFrame`: contains `true` is this frame belongs to your application, and `false` if it belongs to a file in
the vendor directory
### Collecting arguments
For performance reasons, the frames of the back trace will not contain the arguments of the called functions. If you
want to add those use the `withArguments` method.
```php
$backtrace = Spatie\Backtrace\Backtrace::create()->withArguments();
```
#### Reducing arguments
For viewing purposes, arguments can be reduced to a string:
```php
$backtrace = Spatie\Backtrace\Backtrace::create()->withArguments()->reduceArguments();
```
By default, some typical types will be reduced to a string. You can define your own reduction algorithm per type by implementing an `ArgumentReducer`:
```php
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),
);
}
}
```
This is a copy of the built-in argument reducer for `DateTimeInterface` where we've updated the format. An `UnReducedArgument` object is returned when the argument is not of the expected type. A `ReducedArgument` object is returned with the reduced value of the argument and the original type of the argument.
The reducer can be used as such:
```php
$backtrace = Spatie\Backtrace\Backtrace::create()->withArguments()->reduceArguments(
Spatie\Backtrace\Arguments\ArgumentReducers::default([
new DateTimeWithOtherFormatArgumentReducer()
])
);
```
Which will first execute the new reducer and then the default ones.
### Setting the application path
You can use the `applicationPath` to pass the base path of your app. This value will be used to determine whether a
frame is an application frame, or a vendor frame. Here's an example using a Laravel specific function.
```php
$backtrace = Spatie\Backtrace\Backtrace::create()->applicationPath(base_path());
```
### Getting a certain part of a trace
If you only want to have the frames starting from a particular frame in the backtrace you can use
the `startingFromFrame` method:
```php
use Spatie\Backtrace\Backtrace;
use Spatie\Backtrace\Frame;
$frames = Backtrace::create()
->startingFromFrame(function (Frame $frame) {
return $frame->class === MyClass::class;
})
->frames();
```
With this code, all frames before the frame that concerns `MyClass` will have been filtered out.
Alternatively, you can use the `offset` method, which will skip the given number of frames. In this example the first 2 frames will not end up in `$frames`.
```php
$frames = Spatie\Backtrace\Backtrace::create()
->offset(2)
->frames();
```
### Limiting the number of frames
To only get a specific number of frames use the `limit` function. In this example, we'll only get the first two frames.
```php
$frames = Spatie\Backtrace\Backtrace::create()
->limit(2)
->frames();
```
### Getting a backtrace for a throwable
Here's how you can get a backtrace for a throwable.
```php
$frames = Spatie\Backtrace\Backtrace::createForThrowable($throwable)
```
Because we will use the backtrace that is already available the throwable, the frames will always contain the arguments used.
## Testing
``` bash
composer test
```
## Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Contributing
Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.
## Security Vulnerabilities
Please review [our security policy](../../security/policy) on how to report security vulnerabilities.
## Credits
- [Freek Van de Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

58
vendor/spatie/backtrace/composer.json vendored Normal file
View File

@@ -0,0 +1,58 @@
{
"name": "spatie/backtrace",
"description": "A better backtrace",
"keywords": [
"spatie",
"backtrace"
],
"homepage": "https://github.com/spatie/backtrace",
"license": "MIT",
"authors": [
{
"name": "Freek Van de Herten",
"email": "freek@spatie.be",
"homepage": "https://spatie.be",
"role": "Developer"
}
],
"require": {
"php": "^7.3|^8.0"
},
"require-dev": {
"ext-json": "*",
"phpunit/phpunit": "^9.3",
"spatie/phpunit-snapshot-assertions": "^4.2",
"symfony/var-dumper": "^5.1"
},
"autoload": {
"psr-4": {
"Spatie\\Backtrace\\": "src"
}
},
"autoload-dev": {
"psr-4": {
"Spatie\\Backtrace\\Tests\\": "tests"
}
},
"scripts": {
"psalm": "vendor/bin/psalm",
"test": "vendor/bin/phpunit",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage",
"format": "vendor/bin/php-cs-fixer fix --allow-risky=yes"
},
"config": {
"sort-packages": true
},
"minimum-stability": "dev",
"prefer-stable": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/spatie"
},
{
"type": "other",
"url": "https://spatie.be/open-source/support-us"
}
]
}

View File

@@ -0,0 +1,81 @@
<?php
namespace Spatie\Backtrace\Arguments;
use Spatie\Backtrace\Arguments\Reducers\ArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\ArrayArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\BaseTypeArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\ClosureArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\DateTimeArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\DateTimeZoneArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\EnumArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\MinimalArrayArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\SensitiveParameterArrayReducer;
use Spatie\Backtrace\Arguments\Reducers\StdClassArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\StringableArgumentReducer;
use Spatie\Backtrace\Arguments\Reducers\SymphonyRequestArgumentReducer;
class ArgumentReducers
{
/** @var array<int, ArgumentReducer> */
public $argumentReducers = [];
/**
* @param array<ArgumentReducer|class-string<ArgumentReducer>> $argumentReducers
*/
public static function create(array $argumentReducers): self
{
return new self(array_map(
function ($argumentReducer) {
/** @var $argumentReducer ArgumentReducer|class-string<ArgumentReducer> */
return $argumentReducer instanceof ArgumentReducer ? $argumentReducer : new $argumentReducer();
},
$argumentReducers
));
}
public static function default(array $extra = []): self
{
return new self(static::defaultReducers($extra));
}
public static function minimal(array $extra = []): self
{
return new self(static::minimalReducers($extra));
}
/**
* @param array<int, ArgumentReducer> $argumentReducers
*/
protected function __construct(array $argumentReducers)
{
$this->argumentReducers = $argumentReducers;
}
protected static function defaultReducers(array $extra = []): array
{
return array_merge($extra, [
new BaseTypeArgumentReducer(),
new ArrayArgumentReducer(),
new StdClassArgumentReducer(),
new EnumArgumentReducer(),
new ClosureArgumentReducer(),
new SensitiveParameterArrayReducer(),
new DateTimeArgumentReducer(),
new DateTimeZoneArgumentReducer(),
new SymphonyRequestArgumentReducer(),
new StringableArgumentReducer(),
]);
}
protected static function minimalReducers(array $extra = []): array
{
return array_merge($extra, [
new BaseTypeArgumentReducer(),
new MinimalArrayArgumentReducer(),
new EnumArgumentReducer(),
new ClosureArgumentReducer(),
new SensitiveParameterArrayReducer(),
]);
}
}

View File

@@ -0,0 +1,118 @@
<?php
namespace Spatie\Backtrace\Arguments;
use ReflectionParameter;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\TruncatedReducedArgument;
class ProvidedArgument
{
/** @var string */
public $name;
/** @var bool */
public $passedByReference = false;
/** @var bool */
public $isVariadic = false;
/** @var bool */
public $hasDefaultValue = false;
/** @var mixed */
public $defaultValue = null;
/** @var bool */
public $defaultValueUsed = false;
/** @var bool */
public $truncated = false;
/** @var mixed */
public $reducedValue = null;
/** @var string|null */
public $originalType = null;
public static function fromReflectionParameter(ReflectionParameter $parameter): self
{
return new self(
$parameter->getName(),
$parameter->isPassedByReference(),
$parameter->isVariadic(),
$parameter->isDefaultValueAvailable(),
$parameter->isDefaultValueAvailable() ? $parameter->getDefaultValue() : null,
);
}
public static function fromNonReflectableParameter(
int $index
): self {
return new self(
"arg{$index}",
false,
);
}
public function __construct(
string $name,
bool $passedByReference = false,
bool $isVariadic = false,
bool $hasDefaultValue = false,
$defaultValue = null,
bool $defaultValueUsed = false,
bool $truncated = false,
$reducedValue = null,
?string $originalType = null
) {
$this->originalType = $originalType;
$this->reducedValue = $reducedValue;
$this->truncated = $truncated;
$this->defaultValueUsed = $defaultValueUsed;
$this->defaultValue = $defaultValue;
$this->hasDefaultValue = $hasDefaultValue;
$this->isVariadic = $isVariadic;
$this->passedByReference = $passedByReference;
$this->name = $name;
if ($this->isVariadic) {
$this->defaultValue = [];
}
}
public function setReducedArgument(
ReducedArgument $reducedArgument
): self {
$this->reducedValue = $reducedArgument->value;
$this->originalType = $reducedArgument->originalType;
if ($reducedArgument instanceof TruncatedReducedArgument) {
$this->truncated = true;
}
return $this;
}
public function defaultValueUsed(): self
{
$this->defaultValueUsed = true;
$this->originalType = get_debug_type($this->defaultValue);
return $this;
}
public function toArray(): array
{
return [
'name' => $this->name,
'value' => $this->defaultValueUsed
? $this->defaultValue
: $this->reducedValue,
'original_type' => $this->originalType,
'passed_by_reference' => $this->passedByReference,
'is_variadic' => $this->isVariadic,
'truncated' => $this->truncated,
];
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace Spatie\Backtrace\Arguments;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
class ReduceArgumentPayloadAction
{
/** @var \Spatie\Backtrace\Arguments\ArgumentReducers */
protected $argumentReducers;
public function __construct(
ArgumentReducers $argumentReducers
) {
$this->argumentReducers = $argumentReducers;
}
public function reduce($argument, bool $includeObjectType = false): ReducedArgument
{
foreach ($this->argumentReducers->argumentReducers as $reducer) {
$reduced = $reducer->execute($argument);
if ($reduced instanceof ReducedArgument) {
return $reduced;
}
}
if (gettype($argument) === 'object' && $includeObjectType) {
return new ReducedArgument(
'object ('.get_class($argument).')',
get_debug_type($argument),
);
}
if (gettype($argument) === 'object') {
return new ReducedArgument('object', get_debug_type($argument), );
}
return new ReducedArgument(
$argument,
get_debug_type($argument),
);
}
}

View File

@@ -0,0 +1,117 @@
<?php
namespace Spatie\Backtrace\Arguments;
use ReflectionException;
use ReflectionFunction;
use ReflectionMethod;
use ReflectionParameter;
use Spatie\Backtrace\Arguments\ReducedArgument\VariadicReducedArgument;
use Throwable;
class ReduceArgumentsAction
{
/** @var ArgumentReducers */
protected $argumentReducers;
/** @var ReduceArgumentPayloadAction */
protected $reduceArgumentPayloadAction;
public function __construct(
ArgumentReducers $argumentReducers
) {
$this->argumentReducers = $argumentReducers;
$this->reduceArgumentPayloadAction = new ReduceArgumentPayloadAction($argumentReducers);
}
public function execute(
?string $class,
?string $method,
?array $frameArguments
): ?array {
try {
if ($frameArguments === null) {
return null;
}
$parameters = $this->getParameters($class, $method);
if ($parameters === null) {
$arguments = [];
foreach ($frameArguments as $index => $argument) {
$arguments[$index] = ProvidedArgument::fromNonReflectableParameter($index)
->setReducedArgument($this->reduceArgumentPayloadAction->reduce($argument))
->toArray();
}
return $arguments;
}
$arguments = array_map(
function ($argument) {
return $this->reduceArgumentPayloadAction->reduce($argument);
},
$frameArguments,
);
$argumentsCount = count($arguments);
$hasVariadicParameter = false;
foreach ($parameters as $index => $parameter) {
if ($index + 1 > $argumentsCount) {
$parameter->defaultValueUsed();
} elseif ($parameter->isVariadic) {
$parameter->setReducedArgument(new VariadicReducedArgument(array_slice($arguments, $index)));
$hasVariadicParameter = true;
} else {
$parameter->setReducedArgument($arguments[$index]);
}
$parameters[$index] = $parameter->toArray();
}
if ($this->moreArgumentsProvidedThanParameters($arguments, $parameters, $hasVariadicParameter)) {
for ($i = count($parameters); $i < count($arguments); $i++) {
$parameters[$i] = ProvidedArgument::fromNonReflectableParameter(count($parameters))
->setReducedArgument($arguments[$i])
->toArray();
}
}
return $parameters;
} catch (Throwable $e) {
return null;
}
}
/** @return null|Array<\Spatie\Backtrace\Arguments\ProvidedArgument> */
protected function getParameters(
?string $class,
?string $method
): ?array {
try {
$reflection = $class !== null
? new ReflectionMethod($class, $method)
: new ReflectionFunction($method);
} catch (ReflectionException $e) {
return null;
}
return array_map(
function (ReflectionParameter $reflectionParameter) {
return ProvidedArgument::fromReflectionParameter($reflectionParameter);
},
$reflection->getParameters(),
);
}
protected function moreArgumentsProvidedThanParameters(
array $arguments,
array $parameters,
bool $hasVariadicParameter
): bool {
return count($arguments) > count($parameters) && ! $hasVariadicParameter;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\Backtrace\Arguments\ReducedArgument;
class ReducedArgument implements ReducedArgumentContract
{
/** @var mixed */
public $value;
/** @var string */
public $originalType;
/**
* @param mixed $value
*/
public function __construct(
$value,
string $originalType
) {
$this->originalType = $originalType;
$this->value = $value;
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Spatie\Backtrace\Arguments\ReducedArgument;
interface ReducedArgumentContract
{
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Spatie\Backtrace\Arguments\ReducedArgument;
class TruncatedReducedArgument extends ReducedArgument
{
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Spatie\Backtrace\Arguments\ReducedArgument;
class UnReducedArgument implements ReducedArgumentContract
{
/** @var self|null */
private static $instance = null;
private function __construct()
{
}
public static function create(): self
{
if (self::$instance !== null) {
return self::$instance;
}
return self::$instance = new self();
}
}

View File

@@ -0,0 +1,21 @@
<?php
namespace Spatie\Backtrace\Arguments\ReducedArgument;
use Exception;
class VariadicReducedArgument extends ReducedArgument
{
public function __construct(array $value)
{
foreach ($value as $key => $item) {
if (! $item instanceof ReducedArgument) {
throw new Exception('VariadicReducedArgument must be an array of ReducedArgument');
}
$value[$key] = $item->value;
}
parent::__construct($value, 'array');
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
interface ArgumentReducer
{
/**
* @param mixed $argument
*/
public function execute($argument): ReducedArgumentContract;
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ArgumentReducers;
use Spatie\Backtrace\Arguments\ReduceArgumentPayloadAction;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\TruncatedReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
class ArrayArgumentReducer implements ReducedArgumentContract
{
/** @var int */
protected $maxArraySize = 25;
/** @var \Spatie\Backtrace\Arguments\ReduceArgumentPayloadAction */
protected $reduceArgumentPayloadAction;
public function __construct()
{
$this->reduceArgumentPayloadAction = new ReduceArgumentPayloadAction(ArgumentReducers::minimal());
}
public function execute($argument): ReducedArgumentContract
{
if (! is_array($argument)) {
return UnReducedArgument::create();
}
return $this->reduceArgument($argument, 'array');
}
protected function reduceArgument(array $argument, string $originalType): ReducedArgumentContract
{
foreach ($argument as $key => $value) {
$argument[$key] = $this->reduceArgumentPayloadAction->reduce(
$value,
true
)->value;
}
if (count($argument) > $this->maxArraySize) {
return new TruncatedReducedArgument(
array_slice($argument, 0, $this->maxArraySize),
'array'
);
}
return new ReducedArgument($argument, $originalType);
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
class BaseTypeArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (is_int($argument)
|| is_float($argument)
|| is_bool($argument)
|| is_string($argument)
|| $argument === null
) {
return new ReducedArgument($argument, get_debug_type($argument));
}
return UnReducedArgument::create();
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Closure;
use ReflectionFunction;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
class ClosureArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (! $argument instanceof Closure) {
return UnReducedArgument::create();
}
$reflection = new ReflectionFunction($argument);
if ($reflection->getFileName() && $reflection->getStartLine() && $reflection->getEndLine()) {
return new ReducedArgument(
"{$reflection->getFileName()}:{$reflection->getStartLine()}-{$reflection->getEndLine()}",
'Closure'
);
}
return new ReducedArgument("{$reflection->getFileName()}", 'Closure');
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use DateTimeInterface;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
class DateTimeArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (! $argument instanceof DateTimeInterface) {
return UnReducedArgument::create();
}
return new ReducedArgument(
$argument->format('d M Y H:i:s e'),
get_class($argument),
);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use DateTimeZone;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
class DateTimeZoneArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (! $argument instanceof DateTimeZone) {
return UnReducedArgument::create();
}
return new ReducedArgument(
$argument->getName(),
get_class($argument),
);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
use UnitEnum;
class EnumArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (! $argument instanceof UnitEnum) {
return UnReducedArgument::create();
}
return new ReducedArgument(
get_class($argument).'::'.$argument->name,
get_class($argument),
);
}
}

View File

@@ -0,0 +1,22 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
class MinimalArrayArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if(! is_array($argument)) {
return UnReducedArgument::create();
}
return new ReducedArgument(
'array (size='.count($argument).')',
'array'
);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use SensitiveParameterValue;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
class SensitiveParameterArrayReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (! $argument instanceof SensitiveParameterValue) {
return UnReducedArgument::create();
}
return new ReducedArgument(
'SensitiveParameterValue('.get_debug_type($argument->getValue()).')',
get_class($argument)
);
}
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
use stdClass;
class StdClassArgumentReducer extends ArrayArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (! $argument instanceof stdClass) {
return UnReducedArgument::create();
}
return parent::reduceArgument((array) $argument, stdClass::class);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
use Stringable;
class StringableArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if (! $argument instanceof Stringable) {
return UnReducedArgument::create();
}
return new ReducedArgument(
(string) $argument,
get_class($argument),
);
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\Backtrace\Arguments\Reducers;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgument;
use Spatie\Backtrace\Arguments\ReducedArgument\ReducedArgumentContract;
use Spatie\Backtrace\Arguments\ReducedArgument\UnReducedArgument;
use Symfony\Component\HttpFoundation\Request;
class SymphonyRequestArgumentReducer implements ArgumentReducer
{
public function execute($argument): ReducedArgumentContract
{
if(! $argument instanceof Request) {
return UnReducedArgument::create();
}
return new ReducedArgument(
"{$argument->getMethod()} {$argument->getUri()}",
get_class($argument),
);
}
}

View File

@@ -0,0 +1,271 @@
<?php
namespace Spatie\Backtrace;
use Closure;
use Spatie\Backtrace\Arguments\ArgumentReducers;
use Spatie\Backtrace\Arguments\ReduceArgumentsAction;
use Spatie\Backtrace\Arguments\Reducers\ArgumentReducer;
use Throwable;
class Backtrace
{
/** @var bool */
protected $withArguments = false;
/** @var bool */
protected $reduceArguments = false;
/** @var array<class-string<ArgumentReducer>|ArgumentReducer>|ArgumentReducers|null */
protected $argumentReducers = null;
/** @var bool */
protected $withObject = false;
/** @var string|null */
protected $applicationPath;
/** @var int */
protected $offset = 0;
/** @var int */
protected $limit = 0;
/** @var \Closure|null */
protected $startingFromFrameClosure = null;
/** @var \Throwable|null */
protected $throwable = null;
public static function create(): self
{
return new static();
}
public static function createForThrowable(Throwable $throwable): self
{
return (new static())->forThrowable($throwable);
}
protected function forThrowable(Throwable $throwable): self
{
$this->throwable = $throwable;
return $this;
}
public function withArguments(
bool $withArguments = true
): self {
$this->withArguments = $withArguments;
return $this;
}
/**
* @param array<class-string<ArgumentReducer>|ArgumentReducer>|ArgumentReducers|null $argumentReducers
*
* @return $this
*/
public function reduceArguments(
$argumentReducers = null
): self {
$this->reduceArguments = true;
$this->argumentReducers = $argumentReducers;
return $this;
}
public function withObject(): self
{
$this->withObject = true;
return $this;
}
public function applicationPath(string $applicationPath): self
{
$this->applicationPath = rtrim($applicationPath, '/');
return $this;
}
public function offset(int $offset): self
{
$this->offset = $offset;
return $this;
}
public function limit(int $limit): self
{
$this->limit = $limit;
return $this;
}
public function startingFromFrame(Closure $startingFromFrameClosure)
{
$this->startingFromFrameClosure = $startingFromFrameClosure;
return $this;
}
/**
* @return \Spatie\Backtrace\Frame[]
*/
public function frames(): array
{
$rawFrames = $this->getRawFrames();
return $this->toFrameObjects($rawFrames);
}
public function firstApplicationFrameIndex(): ?int
{
foreach ($this->frames() as $index => $frame) {
if ($frame->applicationFrame) {
return $index;
}
}
return null;
}
protected function getRawFrames(): array
{
if ($this->throwable) {
return $this->throwable->getTrace();
}
$options = null;
if (! $this->withArguments) {
$options = $options | DEBUG_BACKTRACE_IGNORE_ARGS;
}
if ($this->withObject()) {
$options = $options | DEBUG_BACKTRACE_PROVIDE_OBJECT;
}
$limit = $this->limit;
if ($limit !== 0) {
$limit += 3;
}
return debug_backtrace($options, $limit);
}
/**
* @return \Spatie\Backtrace\Frame[]
*/
protected function toFrameObjects(array $rawFrames): array
{
$currentFile = $this->throwable ? $this->throwable->getFile() : '';
$currentLine = $this->throwable ? $this->throwable->getLine() : 0;
$arguments = $this->withArguments ? [] : null;
$frames = [];
$reduceArgumentsAction = new ReduceArgumentsAction($this->resolveArgumentReducers());
foreach ($rawFrames as $rawFrame) {
$frames[] = new Frame(
$currentFile,
$currentLine,
$arguments,
$rawFrame['function'] ?? null,
$rawFrame['class'] ?? null,
$this->isApplicationFrame($currentFile)
);
$arguments = $this->withArguments
? $rawFrame['args'] ?? null
: null;
if ($this->reduceArguments) {
$arguments = $reduceArgumentsAction->execute(
$rawFrame['class'] ?? null,
$rawFrame['function'] ?? null,
$arguments
);
}
$currentFile = $rawFrame['file'] ?? 'unknown';
$currentLine = $rawFrame['line'] ?? 0;
}
$frames[] = new Frame(
$currentFile,
$currentLine,
[],
'[top]'
);
$frames = $this->removeBacktracePackageFrames($frames);
if ($closure = $this->startingFromFrameClosure) {
$frames = $this->startAtFrameFromClosure($frames, $closure);
}
$frames = array_slice($frames, $this->offset, $this->limit === 0 ? PHP_INT_MAX : $this->limit);
return array_values($frames);
}
protected function isApplicationFrame(string $frameFilename): bool
{
$relativeFile = str_replace('\\', DIRECTORY_SEPARATOR, $frameFilename);
if (! empty($this->applicationPath)) {
$relativeFile = array_reverse(explode($this->applicationPath ?? '', $frameFilename, 2))[0];
}
if (strpos($relativeFile, DIRECTORY_SEPARATOR.'vendor') === 0) {
return false;
}
return true;
}
protected function removeBacktracePackageFrames(array $frames): array
{
return $this->startAtFrameFromClosure($frames, function (Frame $frame) {
return $frame->class !== static::class;
});
}
/**
* @param \Spatie\Backtrace\Frame[] $frames
* @param \Closure $closure
*
* @return array
*/
protected function startAtFrameFromClosure(array $frames, Closure $closure): array
{
foreach ($frames as $i => $frame) {
$foundStartingFrame = $closure($frame);
if ($foundStartingFrame) {
return $frames;
}
unset($frames[$i]);
}
return $frames;
}
protected function resolveArgumentReducers(): ArgumentReducers
{
if ($this->argumentReducers === null) {
return ArgumentReducers::default();
}
if ($this->argumentReducers instanceof ArgumentReducers) {
return $this->argumentReducers;
}
return ArgumentReducers::create($this->argumentReducers);
}
}

View File

@@ -0,0 +1,83 @@
<?php
namespace Spatie\Backtrace;
use RuntimeException;
class CodeSnippet
{
/** @var int */
protected $surroundingLine = 1;
/** @var int */
protected $snippetLineCount = 9;
public function surroundingLine(int $surroundingLine): self
{
$this->surroundingLine = $surroundingLine;
return $this;
}
public function snippetLineCount(int $snippetLineCount): self
{
$this->snippetLineCount = $snippetLineCount;
return $this;
}
public function get(string $fileName): array
{
if (! file_exists($fileName)) {
return [];
}
try {
$file = new File($fileName);
[$startLineNumber, $endLineNumber] = $this->getBounds($file->numberOfLines());
$code = [];
$line = $file->getLine($startLineNumber);
$currentLineNumber = $startLineNumber;
while ($currentLineNumber <= $endLineNumber) {
$code[$currentLineNumber] = rtrim(substr($line, 0, 250));
$line = $file->getNextLine();
$currentLineNumber++;
}
return $code;
} catch (RuntimeException $exception) {
return [];
}
}
public function getAsString(string $fileName): string
{
$snippet = $this->get($fileName);
$snippetStrings = array_map(function (string $line, string $number) {
return "{$number} {$line}";
}, $snippet, array_keys($snippet));
return implode(PHP_EOL, $snippetStrings);
}
protected function getBounds(int $totalNumberOfLineInFile): array
{
$startLine = max($this->surroundingLine - floor($this->snippetLineCount / 2), 1);
$endLine = $startLine + ($this->snippetLineCount - 1);
if ($endLine > $totalNumberOfLineInFile) {
$endLine = $totalNumberOfLineInFile;
$startLine = max($endLine - ($this->snippetLineCount - 1), 1);
}
return [$startLine, $endLine];
}
}

41
vendor/spatie/backtrace/src/File.php vendored Normal file
View File

@@ -0,0 +1,41 @@
<?php
namespace Spatie\Backtrace;
use SplFileObject;
class File
{
/** @var \SplFileObject */
protected $file;
public function __construct(string $path)
{
$this->file = new SplFileObject($path);
}
public function numberOfLines(): int
{
$this->file->seek(PHP_INT_MAX);
return $this->file->key() + 1;
}
public function getLine(int $lineNumber = null): string
{
if (is_null($lineNumber)) {
return $this->getNextLine();
}
$this->file->seek($lineNumber - 1);
return $this->file->current();
}
public function getNextLine(): string
{
$this->file->next();
return $this->file->current();
}
}

73
vendor/spatie/backtrace/src/Frame.php vendored Normal file
View File

@@ -0,0 +1,73 @@
<?php
namespace Spatie\Backtrace;
class Frame
{
/** @var string */
public $file;
/** @var int */
public $lineNumber;
/** @var array|null */
public $arguments = null;
/** @var bool */
public $applicationFrame;
/** @var string|null */
public $method;
/** @var string|null */
public $class;
public function __construct(
string $file,
int $lineNumber,
?array $arguments,
string $method = null,
string $class = null,
bool $isApplicationFrame = false
) {
$this->file = $file;
$this->lineNumber = $lineNumber;
$this->arguments = $arguments;
$this->method = $method;
$this->class = $class;
$this->applicationFrame = $isApplicationFrame;
}
public function getSnippet(int $lineCount): array
{
return (new CodeSnippet())
->surroundingLine($this->lineNumber)
->snippetLineCount($lineCount)
->get($this->file);
}
public function getSnippetAsString(int $lineCount): string
{
return (new CodeSnippet())
->surroundingLine($this->lineNumber)
->snippetLineCount($lineCount)
->getAsString($this->file);
}
public function getSnippetProperties(int $lineCount): array
{
$snippet = $this->getSnippet($lineCount);
return array_map(function (int $lineNumber) use ($snippet) {
return [
'line_number' => $lineNumber,
'text' => $snippet[$lineNumber],
];
}, array_keys($snippet));
}
}

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Facade <info@facade.company>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,39 @@
# Send PHP errors to Flare
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/flare-client-php.svg?style=flat-square)](https://packagist.org/packages/spatie/flare-client-php)
[![Run tests](https://github.com/spatie/flare-client-php/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/flare-client-php/actions/workflows/run-tests.yml)
[![PHPStan](https://github.com/spatie/flare-client-php/actions/workflows/phpstan.yml/badge.svg)](https://github.com/spatie/flare-client-php/actions/workflows/phpstan.yml)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/flare-client-php.svg?style=flat-square)](https://packagist.org/packages/spatie/flare-client-php)
This repository contains the PHP client to send errors and exceptions to [Flare](https://flareapp.io). The client can be installed using composer and works for PHP 8.0 and above.
Using Laravel? You probably want to use [Ignition for Laravel](https://github.com/spatie/laravel-ignition). It comes with a beautiful error page and has the Flare client built in.
![Screenshot of error in Flare](https://facade.github.io/flare-client-php/screenshot.png)
## Documentation
You can find the documentation of this package at [the docs of Flare](https://flareapp.io/docs/flare/general/welcome-to-flare).
## Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information on what has changed recently.
## Testing
``` bash
composer test
```
## Contributing
Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.
## Security
If you discover any security related issues, please email support@flareapp.io instead of using the issue tracker.
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

View File

@@ -0,0 +1,63 @@
{
"name": "spatie/flare-client-php",
"description": "Send PHP errors to Flare",
"keywords": [
"spatie",
"flare",
"exception",
"reporting"
],
"homepage": "https://github.com/spatie/flare-client-php",
"license": "MIT",
"require": {
"php": "^8.0",
"illuminate/pipeline": "^8.0|^9.0|^10.0|^11.0",
"spatie/backtrace": "^1.5.2",
"symfony/http-foundation": "^5.2|^6.0|^7.0",
"symfony/mime": "^5.2|^6.0|^7.0",
"symfony/process": "^5.2|^6.0|^7.0",
"symfony/var-dumper": "^5.2|^6.0|^7.0"
},
"require-dev": {
"dms/phpunit-arraysubset-asserts": "^0.5.0",
"phpstan/extension-installer": "^1.1",
"phpstan/phpstan-deprecation-rules": "^1.0",
"phpstan/phpstan-phpunit": "^1.0",
"spatie/phpunit-snapshot-assertions": "^4.0|^5.0",
"pestphp/pest": "^1.20|^2.0"
},
"autoload": {
"psr-4": {
"Spatie\\FlareClient\\": "src"
},
"files": [
"src/helpers.php"
]
},
"autoload-dev": {
"psr-4": {
"Spatie\\FlareClient\\Tests\\": "tests"
}
},
"scripts": {
"analyse": "vendor/bin/phpstan analyse",
"baseline": "vendor/bin/phpstan analyse --generate-baseline",
"format": "vendor/bin/php-cs-fixer fix --allow-risky=yes",
"test": "vendor/bin/pest",
"test-coverage": "vendor/bin/phpunit --coverage-html coverage"
},
"config": {
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"phpstan/extension-installer": true
}
},
"prefer-stable": true,
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-main": "1.3.x-dev"
}
}
}

View File

@@ -0,0 +1,86 @@
<?php
namespace Spatie\FlareClient;
use Exception;
use Spatie\FlareClient\Http\Client;
use Spatie\FlareClient\Truncation\ReportTrimmer;
class Api
{
protected Client $client;
protected bool $sendReportsImmediately = false;
/** @var array<int, Report> */
protected array $queue = [];
public function __construct(Client $client)
{
$this->client = $client;
register_shutdown_function([$this, 'sendQueuedReports']);
}
public function sendReportsImmediately(): self
{
$this->sendReportsImmediately = true;
return $this;
}
public function report(Report $report): void
{
try {
$this->sendReportsImmediately
? $this->sendReportToApi($report)
: $this->addReportToQueue($report);
} catch (Exception $e) {
//
}
}
public function sendTestReport(Report $report): self
{
$this->sendReportToApi($report);
return $this;
}
protected function addReportToQueue(Report $report): self
{
$this->queue[] = $report;
return $this;
}
public function sendQueuedReports(): void
{
try {
foreach ($this->queue as $report) {
$this->sendReportToApi($report);
}
} catch (Exception $e) {
//
} finally {
$this->queue = [];
}
}
protected function sendReportToApi(Report $report): void
{
$payload = $this->truncateReport($report->toArray());
$this->client->post('reports', $payload);
}
/**
* @param array<int|string, mixed> $payload
*
* @return array<int|string, mixed>
*/
protected function truncateReport(array $payload): array
{
return (new ReportTrimmer())->trim($payload);
}
}

View File

@@ -0,0 +1,63 @@
<?php
namespace Spatie\FlareClient\Concerns;
trait HasContext
{
protected ?string $messageLevel = null;
protected ?string $stage = null;
/**
* @var array<string, mixed>
*/
protected array $userProvidedContext = [];
public function stage(?string $stage): self
{
$this->stage = $stage;
return $this;
}
public function messageLevel(?string $messageLevel): self
{
$this->messageLevel = $messageLevel;
return $this;
}
/**
* @param string $groupName
* @param mixed $default
*
* @return array<int, mixed>
*/
public function getGroup(string $groupName = 'context', $default = []): array
{
return $this->userProvidedContext[$groupName] ?? $default;
}
public function context(string $key, mixed $value): self
{
return $this->group('context', [$key => $value]);
}
/**
* @param string $groupName
* @param array<string, mixed> $properties
*
* @return $this
*/
public function group(string $groupName, array $properties): self
{
$group = $this->userProvidedContext[$groupName] ?? [];
$this->userProvidedContext[$groupName] = array_merge_recursive_distinct(
$group,
$properties
);
return $this;
}
}

View File

@@ -0,0 +1,23 @@
<?php
namespace Spatie\FlareClient\Concerns;
use Spatie\FlareClient\Time\SystemTime;
use Spatie\FlareClient\Time\Time;
trait UsesTime
{
public static Time $time;
public static function useTime(Time $time): void
{
self::$time = $time;
}
public function getCurrentTime(): int
{
$time = self::$time ?? new SystemTime();
return $time->getCurrentTime();
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Spatie\FlareClient\Context;
class BaseContextProviderDetector implements ContextProviderDetector
{
public function detectCurrentContext(): ContextProvider
{
if ($this->runningInConsole()) {
return new ConsoleContextProvider($_SERVER['argv'] ?? []);
}
return new RequestContextProvider();
}
protected function runningInConsole(): bool
{
if (isset($_ENV['APP_RUNNING_IN_CONSOLE'])) {
return $_ENV['APP_RUNNING_IN_CONSOLE'] === 'true';
}
if (isset($_ENV['FLARE_FAKE_WEB_REQUEST'])) {
return false;
}
return in_array(php_sapi_name(), ['cli', 'phpdb']);
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Spatie\FlareClient\Context;
class ConsoleContextProvider implements ContextProvider
{
/**
* @var array<string, mixed>
*/
protected array $arguments = [];
/**
* @param array<string, mixed> $arguments
*/
public function __construct(array $arguments = [])
{
$this->arguments = $arguments;
}
/**
* @return array<int|string, mixed>
*/
public function toArray(): array
{
return [
'arguments' => $this->arguments,
];
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace Spatie\FlareClient\Context;
interface ContextProvider
{
/**
* @return array<int, string|mixed>
*/
public function toArray(): array;
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Spatie\FlareClient\Context;
interface ContextProviderDetector
{
public function detectCurrentContext(): ContextProvider;
}

View File

@@ -0,0 +1,157 @@
<?php
namespace Spatie\FlareClient\Context;
use RuntimeException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Mime\Exception\InvalidArgumentException;
use Throwable;
class RequestContextProvider implements ContextProvider
{
protected ?Request $request;
public function __construct(Request $request = null)
{
$this->request = $request ?? Request::createFromGlobals();
}
/**
* @return array<string, mixed>
*/
public function getRequest(): array
{
return [
'url' => $this->request->getUri(),
'ip' => $this->request->getClientIp(),
'method' => $this->request->getMethod(),
'useragent' => $this->request->headers->get('User-Agent'),
];
}
/**
* @return array<int, mixed>
*/
protected function getFiles(): array
{
if (is_null($this->request->files)) {
return [];
}
return $this->mapFiles($this->request->files->all());
}
/**
* @param array<int, mixed> $files
*
* @return array<string, string>
*/
protected function mapFiles(array $files): array
{
return array_map(function ($file) {
if (is_array($file)) {
return $this->mapFiles($file);
}
if (! $file instanceof UploadedFile) {
return;
}
try {
$fileSize = $file->getSize();
} catch (RuntimeException $e) {
$fileSize = 0;
}
try {
$mimeType = $file->getMimeType();
} catch (InvalidArgumentException $e) {
$mimeType = 'undefined';
}
return [
'pathname' => $file->getPathname(),
'size' => $fileSize,
'mimeType' => $mimeType,
];
}, $files);
}
/**
* @return array<string, mixed>
*/
public function getSession(): array
{
try {
$session = $this->request->getSession();
} catch (Throwable $exception) {
$session = [];
}
return $session ? $this->getValidSessionData($session) : [];
}
protected function getValidSessionData($session): array
{
if (! method_exists($session, 'all')) {
return [];
}
try {
json_encode($session->all());
} catch (Throwable $e) {
return [];
}
return $session->all();
}
/**
* @return array<int|string, mixed
*/
public function getCookies(): array
{
return $this->request->cookies->all();
}
/**
* @return array<string, mixed>
*/
public function getHeaders(): array
{
/** @var array<string, list<string|null>> $headers */
$headers = $this->request->headers->all();
return array_filter(
array_map(
fn (array $header) => $header[0],
$headers
)
);
}
/**
* @return array<string, mixed>
*/
public function getRequestData(): array
{
return [
'queryString' => $this->request->query->all(),
'body' => $this->request->request->all(),
'files' => $this->getFiles(),
];
}
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'request' => $this->getRequest(),
'request_data' => $this->getRequestData(),
'headers' => $this->getHeaders(),
'cookies' => $this->getCookies(),
'session' => $this->getSession(),
];
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace Spatie\FlareClient\Contracts;
interface ProvidesFlareContext
{
/**
* @return array<int|string, mixed>
*/
public function context(): array;
}

View File

@@ -0,0 +1,12 @@
<?php
namespace Spatie\FlareClient\Enums;
class MessageLevels
{
const INFO = 'info';
const DEBUG = 'debug';
const WARNING = 'warning';
const ERROR = 'error';
const CRITICAL = 'critical';
}

View File

@@ -0,0 +1,459 @@
<?php
namespace Spatie\FlareClient;
use Error;
use ErrorException;
use Exception;
use Illuminate\Contracts\Container\Container;
use Illuminate\Pipeline\Pipeline;
use Spatie\Backtrace\Arguments\ArgumentReducers;
use Spatie\Backtrace\Arguments\Reducers\ArgumentReducer;
use Spatie\FlareClient\Concerns\HasContext;
use Spatie\FlareClient\Context\BaseContextProviderDetector;
use Spatie\FlareClient\Context\ContextProviderDetector;
use Spatie\FlareClient\Enums\MessageLevels;
use Spatie\FlareClient\FlareMiddleware\AddEnvironmentInformation;
use Spatie\FlareClient\FlareMiddleware\AddGlows;
use Spatie\FlareClient\FlareMiddleware\CensorRequestBodyFields;
use Spatie\FlareClient\FlareMiddleware\FlareMiddleware;
use Spatie\FlareClient\FlareMiddleware\RemoveRequestIp;
use Spatie\FlareClient\Glows\Glow;
use Spatie\FlareClient\Glows\GlowRecorder;
use Spatie\FlareClient\Http\Client;
use Throwable;
class Flare
{
use HasContext;
protected Client $client;
protected Api $api;
/** @var array<int, FlareMiddleware|class-string<FlareMiddleware>> */
protected array $middleware = [];
protected GlowRecorder $recorder;
protected ?string $applicationPath = null;
protected ContextProviderDetector $contextDetector;
protected $previousExceptionHandler = null;
/** @var null|callable */
protected $previousErrorHandler = null;
/** @var null|callable */
protected $determineVersionCallable = null;
protected ?int $reportErrorLevels = null;
/** @var null|callable */
protected $filterExceptionsCallable = null;
/** @var null|callable */
protected $filterReportsCallable = null;
protected ?string $stage = null;
protected ?string $requestId = null;
protected ?Container $container = null;
/** @var array<class-string<ArgumentReducer>|ArgumentReducer>|ArgumentReducers|null */
protected null|array|ArgumentReducers $argumentReducers = null;
protected bool $withStackFrameArguments = true;
public static function make(
string $apiKey = null,
ContextProviderDetector $contextDetector = null
): self {
$client = new Client($apiKey);
return new self($client, $contextDetector);
}
public function setApiToken(string $apiToken): self
{
$this->client->setApiToken($apiToken);
return $this;
}
public function apiTokenSet(): bool
{
return $this->client->apiTokenSet();
}
public function setBaseUrl(string $baseUrl): self
{
$this->client->setBaseUrl($baseUrl);
return $this;
}
public function setStage(?string $stage): self
{
$this->stage = $stage;
return $this;
}
public function sendReportsImmediately(): self
{
$this->api->sendReportsImmediately();
return $this;
}
public function determineVersionUsing(callable $determineVersionCallable): self
{
$this->determineVersionCallable = $determineVersionCallable;
return $this;
}
public function reportErrorLevels(int $reportErrorLevels): self
{
$this->reportErrorLevels = $reportErrorLevels;
return $this;
}
public function filterExceptionsUsing(callable $filterExceptionsCallable): self
{
$this->filterExceptionsCallable = $filterExceptionsCallable;
return $this;
}
public function filterReportsUsing(callable $filterReportsCallable): self
{
$this->filterReportsCallable = $filterReportsCallable;
return $this;
}
/** @param array<class-string<ArgumentReducer>|ArgumentReducer>|ArgumentReducers|null $argumentReducers */
public function argumentReducers(null|array|ArgumentReducers $argumentReducers): self
{
$this->argumentReducers = $argumentReducers;
return $this;
}
public function withStackFrameArguments(bool $withStackFrameArguments = true): self
{
$this->withStackFrameArguments = $withStackFrameArguments;
return $this;
}
public function version(): ?string
{
if (! $this->determineVersionCallable) {
return null;
}
return ($this->determineVersionCallable)();
}
/**
* @param \Spatie\FlareClient\Http\Client $client
* @param \Spatie\FlareClient\Context\ContextProviderDetector|null $contextDetector
* @param array<int, FlareMiddleware> $middleware
*/
public function __construct(
Client $client,
ContextProviderDetector $contextDetector = null,
array $middleware = [],
) {
$this->client = $client;
$this->recorder = new GlowRecorder();
$this->contextDetector = $contextDetector ?? new BaseContextProviderDetector();
$this->middleware = $middleware;
$this->api = new Api($this->client);
$this->registerDefaultMiddleware();
}
/** @return array<int, FlareMiddleware|class-string<FlareMiddleware>> */
public function getMiddleware(): array
{
return $this->middleware;
}
public function setContextProviderDetector(ContextProviderDetector $contextDetector): self
{
$this->contextDetector = $contextDetector;
return $this;
}
public function setContainer(Container $container): self
{
$this->container = $container;
return $this;
}
public function registerFlareHandlers(): self
{
$this->registerExceptionHandler();
$this->registerErrorHandler();
return $this;
}
public function registerExceptionHandler(): self
{
/** @phpstan-ignore-next-line */
$this->previousExceptionHandler = set_exception_handler([$this, 'handleException']);
return $this;
}
public function registerErrorHandler(): self
{
$this->previousErrorHandler = set_error_handler([$this, 'handleError']);
return $this;
}
protected function registerDefaultMiddleware(): self
{
return $this->registerMiddleware([
new AddGlows($this->recorder),
new AddEnvironmentInformation(),
]);
}
/**
* @param FlareMiddleware|array<FlareMiddleware>|class-string<FlareMiddleware>|callable $middleware
*
* @return $this
*/
public function registerMiddleware($middleware): self
{
if (! is_array($middleware)) {
$middleware = [$middleware];
}
$this->middleware = array_merge($this->middleware, $middleware);
return $this;
}
/**
* @return array<int,FlareMiddleware|class-string<FlareMiddleware>>
*/
public function getMiddlewares(): array
{
return $this->middleware;
}
/**
* @param string $name
* @param string $messageLevel
* @param array<int, mixed> $metaData
*
* @return $this
*/
public function glow(
string $name,
string $messageLevel = MessageLevels::INFO,
array $metaData = []
): self {
$this->recorder->record(new Glow($name, $messageLevel, $metaData));
return $this;
}
public function handleException(Throwable $throwable): void
{
$this->report($throwable);
if ($this->previousExceptionHandler && is_callable($this->previousExceptionHandler)) {
call_user_func($this->previousExceptionHandler, $throwable);
}
}
/**
* @return mixed
*/
public function handleError(mixed $code, string $message, string $file = '', int $line = 0)
{
$exception = new ErrorException($message, 0, $code, $file, $line);
$this->report($exception);
if ($this->previousErrorHandler) {
return call_user_func(
$this->previousErrorHandler,
$message,
$code,
$file,
$line
);
}
}
public function applicationPath(string $applicationPath): self
{
$this->applicationPath = $applicationPath;
return $this;
}
public function report(Throwable $throwable, callable $callback = null, Report $report = null): ?Report
{
if (! $this->shouldSendReport($throwable)) {
return null;
}
$report ??= $this->createReport($throwable);
if (! is_null($callback)) {
call_user_func($callback, $report);
}
$this->recorder->reset();
$this->sendReportToApi($report);
return $report;
}
protected function shouldSendReport(Throwable $throwable): bool
{
if (isset($this->reportErrorLevels) && $throwable instanceof Error) {
return (bool) ($this->reportErrorLevels & $throwable->getCode());
}
if (isset($this->reportErrorLevels) && $throwable instanceof ErrorException) {
return (bool) ($this->reportErrorLevels & $throwable->getSeverity());
}
if ($this->filterExceptionsCallable && $throwable instanceof Exception) {
return (bool) (call_user_func($this->filterExceptionsCallable, $throwable));
}
return true;
}
public function reportMessage(string $message, string $logLevel, callable $callback = null): void
{
$report = $this->createReportFromMessage($message, $logLevel);
if (! is_null($callback)) {
call_user_func($callback, $report);
}
$this->sendReportToApi($report);
}
public function sendTestReport(Throwable $throwable): void
{
$this->api->sendTestReport($this->createReport($throwable));
}
protected function sendReportToApi(Report $report): void
{
if ($this->filterReportsCallable) {
if (! call_user_func($this->filterReportsCallable, $report)) {
return;
}
}
try {
$this->api->report($report);
} catch (Exception $exception) {
}
}
public function reset(): void
{
$this->api->sendQueuedReports();
$this->userProvidedContext = [];
$this->recorder->reset();
}
protected function applyAdditionalParameters(Report $report): void
{
$report
->stage($this->stage)
->messageLevel($this->messageLevel)
->setApplicationPath($this->applicationPath)
->userProvidedContext($this->userProvidedContext);
}
public function anonymizeIp(): self
{
$this->registerMiddleware(new RemoveRequestIp());
return $this;
}
/**
* @param array<int, string> $fieldNames
*
* @return $this
*/
public function censorRequestBodyFields(array $fieldNames): self
{
$this->registerMiddleware(new CensorRequestBodyFields($fieldNames));
return $this;
}
public function createReport(Throwable $throwable): Report
{
$report = Report::createForThrowable(
$throwable,
$this->contextDetector->detectCurrentContext(),
$this->applicationPath,
$this->version(),
$this->argumentReducers,
$this->withStackFrameArguments
);
return $this->applyMiddlewareToReport($report);
}
public function createReportFromMessage(string $message, string $logLevel): Report
{
$report = Report::createForMessage(
$message,
$logLevel,
$this->contextDetector->detectCurrentContext(),
$this->applicationPath,
$this->argumentReducers,
$this->withStackFrameArguments
);
return $this->applyMiddlewareToReport($report);
}
protected function applyMiddlewareToReport(Report $report): Report
{
$this->applyAdditionalParameters($report);
$middleware = array_map(function ($singleMiddleware) {
return is_string($singleMiddleware)
? new $singleMiddleware
: $singleMiddleware;
}, $this->middleware);
$report = (new Pipeline())
->send($report)
->through($middleware)
->then(fn ($report) => $report);
return $report;
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use ArrayObject;
use Closure;
use Spatie\FlareClient\Report;
class AddDocumentationLinks implements FlareMiddleware
{
protected ArrayObject $documentationLinkResolvers;
public function __construct(ArrayObject $documentationLinkResolvers)
{
$this->documentationLinkResolvers = $documentationLinkResolvers;
}
public function handle(Report $report, Closure $next)
{
if (! $throwable = $report->getThrowable()) {
return $next($report);
}
$links = $this->getLinks($throwable);
if (count($links)) {
$report->addDocumentationLinks($links);
}
return $next($report);
}
/** @return array<int, string> */
protected function getLinks(\Throwable $throwable): array
{
$allLinks = [];
foreach ($this->documentationLinkResolvers as $resolver) {
$resolvedLinks = $resolver($throwable);
if (is_null($resolvedLinks)) {
continue;
}
if (is_string($resolvedLinks)) {
$resolvedLinks = [$resolvedLinks];
}
foreach ($resolvedLinks as $link) {
$allLinks[] = $link;
}
}
return array_values(array_unique($allLinks));
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Closure;
use Spatie\FlareClient\Report;
class AddEnvironmentInformation implements FlareMiddleware
{
public function handle(Report $report, Closure $next)
{
$report->group('env', [
'php_version' => phpversion(),
]);
return $next($report);
}
}

View File

@@ -0,0 +1,89 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Closure;
use Spatie\FlareClient\Report;
use Symfony\Component\Process\Process;
use Throwable;
class AddGitInformation
{
protected ?string $baseDir = null;
public function handle(Report $report, Closure $next)
{
try {
$this->baseDir = $this->getGitBaseDirectory();
if (! $this->baseDir) {
return $next($report);
}
$report->group('git', [
'hash' => $this->hash(),
'message' => $this->message(),
'tag' => $this->tag(),
'remote' => $this->remote(),
'isDirty' => ! $this->isClean(),
]);
} catch (Throwable) {
}
return $next($report);
}
protected function hash(): ?string
{
return $this->command("git log --pretty=format:'%H' -n 1") ?: null;
}
protected function message(): ?string
{
return $this->command("git log --pretty=format:'%s' -n 1") ?: null;
}
protected function tag(): ?string
{
return $this->command('git describe --tags --abbrev=0') ?: null;
}
protected function remote(): ?string
{
return $this->command('git config --get remote.origin.url') ?: null;
}
protected function isClean(): bool
{
return empty($this->command('git status -s'));
}
protected function getGitBaseDirectory(): ?string
{
/** @var Process $process */
$process = Process::fromShellCommandline("echo $(git rev-parse --show-toplevel)")->setTimeout(1);
$process->run();
if (! $process->isSuccessful()) {
return null;
}
$directory = trim($process->getOutput());
if (! file_exists($directory)) {
return null;
}
return $directory;
}
protected function command($command)
{
$process = Process::fromShellCommandline($command, $this->baseDir)->setTimeout(1);
$process->run();
return trim($process->getOutput());
}
}

View File

@@ -0,0 +1,28 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
namespace Spatie\FlareClient\FlareMiddleware;
use Closure;
use Spatie\FlareClient\Glows\GlowRecorder;
use Spatie\FlareClient\Report;
class AddGlows implements FlareMiddleware
{
protected GlowRecorder $recorder;
public function __construct(GlowRecorder $recorder)
{
$this->recorder = $recorder;
}
public function handle(Report $report, Closure $next)
{
foreach ($this->recorder->glows() as $glow) {
$report->addGlow($glow);
}
return $next($report);
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Spatie\FlareClient\Report;
class AddNotifierName implements FlareMiddleware
{
public const NOTIFIER_NAME = 'Flare Client';
public function handle(Report $report, $next)
{
$report->notifierName(static::NOTIFIER_NAME);
return $next($report);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Closure;
use Spatie\FlareClient\Report;
use Spatie\Ignition\Contracts\SolutionProviderRepository;
class AddSolutions implements FlareMiddleware
{
protected SolutionProviderRepository $solutionProviderRepository;
public function __construct(SolutionProviderRepository $solutionProviderRepository)
{
$this->solutionProviderRepository = $solutionProviderRepository;
}
public function handle(Report $report, Closure $next)
{
if ($throwable = $report->getThrowable()) {
$solutions = $this->solutionProviderRepository->getSolutionsForThrowable($throwable);
foreach ($solutions as $solution) {
$report->addSolution($solution);
}
}
return $next($report);
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Spatie\FlareClient\Report;
class CensorRequestBodyFields implements FlareMiddleware
{
protected array $fieldNames = [];
public function __construct(array $fieldNames)
{
$this->fieldNames = $fieldNames;
}
public function handle(Report $report, $next)
{
$context = $report->allContext();
foreach ($this->fieldNames as $fieldName) {
if (isset($context['request_data']['body'][$fieldName])) {
$context['request_data']['body'][$fieldName] = '<CENSORED>';
}
}
$report->userProvidedContext($context);
return $next($report);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Spatie\FlareClient\Report;
class CensorRequestHeaders implements FlareMiddleware
{
protected array $headers = [];
public function __construct(array $headers)
{
$this->headers = $headers;
}
public function handle(Report $report, $next)
{
$context = $report->allContext();
foreach ($this->headers as $header) {
$header = strtolower($header);
if (isset($context['headers'][$header])) {
$context['headers'][$header] = '<CENSORED>';
}
}
$report->userProvidedContext($context);
return $next($report);
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Closure;
use Spatie\FlareClient\Report;
interface FlareMiddleware
{
public function handle(Report $report, Closure $next);
}

View File

@@ -0,0 +1,19 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Spatie\FlareClient\Report;
class RemoveRequestIp implements FlareMiddleware
{
public function handle(Report $report, $next)
{
$context = $report->allContext();
$context['request']['ip'] = null;
$report->userProvidedContext($context);
return $next($report);
}
}

View File

@@ -0,0 +1,32 @@
<?php
namespace Spatie\FlareClient;
use Spatie\Backtrace\Frame as SpatieFrame;
class Frame
{
public static function fromSpatieFrame(
SpatieFrame $frame,
): self {
return new self($frame);
}
public function __construct(
protected SpatieFrame $frame,
) {
}
public function toArray(): array
{
return [
'file' => $this->frame->file,
'line_number' => $this->frame->lineNumber,
'method' => $this->frame->method,
'class' => $this->frame->class,
'code_snippet' => $this->frame->getSnippet(30),
'arguments' => $this->frame->arguments,
'application_frame' => $this->frame->applicationFrame,
];
}
}

View File

@@ -0,0 +1,52 @@
<?php
namespace Spatie\FlareClient\Glows;
use Spatie\FlareClient\Concerns\UsesTime;
use Spatie\FlareClient\Enums\MessageLevels;
class Glow
{
use UsesTime;
protected string $name;
/** @var array<int, mixed> */
protected array $metaData = [];
protected string $messageLevel;
protected float $microtime;
/**
* @param string $name
* @param string $messageLevel
* @param array<int, mixed> $metaData
* @param float|null $microtime
*/
public function __construct(
string $name,
string $messageLevel = MessageLevels::INFO,
array $metaData = [],
?float $microtime = null
) {
$this->name = $name;
$this->messageLevel = $messageLevel;
$this->metaData = $metaData;
$this->microtime = $microtime ?? microtime(true);
}
/**
* @return array{time: int, name: string, message_level: string, meta_data: array, microtime: float}
*/
public function toArray(): array
{
return [
'time' => $this->getCurrentTime(),
'name' => $this->name,
'message_level' => $this->messageLevel,
'meta_data' => $this->metaData,
'microtime' => $this->microtime,
];
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Spatie\FlareClient\Glows;
class GlowRecorder
{
const GLOW_LIMIT = 30;
/** @var array<int, Glow> */
protected array $glows = [];
public function record(Glow $glow): void
{
$this->glows[] = $glow;
$this->glows = array_slice($this->glows, static::GLOW_LIMIT * -1, static::GLOW_LIMIT);
}
/** @return array<int, Glow> */
public function glows(): array
{
return $this->glows;
}
public function reset(): void
{
$this->glows = [];
}
}

View File

@@ -0,0 +1,228 @@
<?php
namespace Spatie\FlareClient\Http;
use Spatie\FlareClient\Http\Exceptions\BadResponseCode;
use Spatie\FlareClient\Http\Exceptions\InvalidData;
use Spatie\FlareClient\Http\Exceptions\MissingParameter;
use Spatie\FlareClient\Http\Exceptions\NotFound;
class Client
{
protected ?string $apiToken;
protected ?string $baseUrl;
protected int $timeout;
protected $lastRequest = null;
public function __construct(
?string $apiToken = null,
string $baseUrl = 'https://reporting.flareapp.io/api',
int $timeout = 10
) {
$this->apiToken = $apiToken;
if (! $baseUrl) {
throw MissingParameter::create('baseUrl');
}
$this->baseUrl = $baseUrl;
if (! $timeout) {
throw MissingParameter::create('timeout');
}
$this->timeout = $timeout;
}
public function setApiToken(string $apiToken): self
{
$this->apiToken = $apiToken;
return $this;
}
public function apiTokenSet(): bool
{
return ! empty($this->apiToken);
}
public function setBaseUrl(string $baseUrl): self
{
$this->baseUrl = $baseUrl;
return $this;
}
/**
* @param string $url
* @param array $arguments
*
* @return array|false
*/
public function get(string $url, array $arguments = [])
{
return $this->makeRequest('get', $url, $arguments);
}
/**
* @param string $url
* @param array $arguments
*
* @return array|false
*/
public function post(string $url, array $arguments = [])
{
return $this->makeRequest('post', $url, $arguments);
}
/**
* @param string $url
* @param array $arguments
*
* @return array|false
*/
public function patch(string $url, array $arguments = [])
{
return $this->makeRequest('patch', $url, $arguments);
}
/**
* @param string $url
* @param array $arguments
*
* @return array|false
*/
public function put(string $url, array $arguments = [])
{
return $this->makeRequest('put', $url, $arguments);
}
/**
* @param string $method
* @param array $arguments
*
* @return array|false
*/
public function delete(string $method, array $arguments = [])
{
return $this->makeRequest('delete', $method, $arguments);
}
/**
* @param string $httpVerb
* @param string $url
* @param array $arguments
*
* @return array
*/
protected function makeRequest(string $httpVerb, string $url, array $arguments = [])
{
$queryString = http_build_query([
'key' => $this->apiToken,
]);
$fullUrl = "{$this->baseUrl}/{$url}?{$queryString}";
$headers = [
'x-api-token: '.$this->apiToken,
];
$response = $this->makeCurlRequest($httpVerb, $fullUrl, $headers, $arguments);
if ($response->getHttpResponseCode() === 422) {
throw InvalidData::createForResponse($response);
}
if ($response->getHttpResponseCode() === 404) {
throw NotFound::createForResponse($response);
}
if ($response->getHttpResponseCode() !== 200 && $response->getHttpResponseCode() !== 204) {
throw BadResponseCode::createForResponse($response);
}
return $response->getBody();
}
public function makeCurlRequest(string $httpVerb, string $fullUrl, array $headers = [], array $arguments = []): Response
{
$curlHandle = $this->getCurlHandle($fullUrl, $headers);
switch ($httpVerb) {
case 'post':
curl_setopt($curlHandle, CURLOPT_POST, true);
$this->attachRequestPayload($curlHandle, $arguments);
break;
case 'get':
curl_setopt($curlHandle, CURLOPT_URL, $fullUrl.'&'.http_build_query($arguments));
break;
case 'delete':
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'DELETE');
break;
case 'patch':
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'PATCH');
$this->attachRequestPayload($curlHandle, $arguments);
break;
case 'put':
curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, 'PUT');
$this->attachRequestPayload($curlHandle, $arguments);
break;
}
$body = json_decode(curl_exec($curlHandle), true);
$headers = curl_getinfo($curlHandle);
$error = curl_error($curlHandle);
return new Response($headers, $body, $error);
}
protected function attachRequestPayload(&$curlHandle, array $data)
{
$encoded = json_encode($data);
$this->lastRequest['body'] = $encoded;
curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $encoded);
}
/**
* @param string $fullUrl
* @param array $headers
*
* @return resource
*/
protected function getCurlHandle(string $fullUrl, array $headers = [])
{
$curlHandle = curl_init();
curl_setopt($curlHandle, CURLOPT_URL, $fullUrl);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, array_merge([
'Accept: application/json',
'Content-Type: application/json',
], $headers));
curl_setopt($curlHandle, CURLOPT_USERAGENT, 'Laravel/Flare API 1.0');
curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curlHandle, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($curlHandle, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
curl_setopt($curlHandle, CURLOPT_ENCODING, '');
curl_setopt($curlHandle, CURLINFO_HEADER_OUT, true);
curl_setopt($curlHandle, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curlHandle, CURLOPT_MAXREDIRS, 1);
return $curlHandle;
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace Spatie\FlareClient\Http\Exceptions;
use Exception;
use Spatie\FlareClient\Http\Response;
class BadResponse extends Exception
{
public Response $response;
public static function createForResponse(Response $response): self
{
$exception = new self("Could not perform request because: {$response->getError()}");
$exception->response = $response;
return $exception;
}
}

View File

@@ -0,0 +1,34 @@
<?php
namespace Spatie\FlareClient\Http\Exceptions;
use Exception;
use Spatie\FlareClient\Http\Response;
class BadResponseCode extends Exception
{
public Response $response;
/**
* @var array<int, mixed>
*/
public array $errors = [];
public static function createForResponse(Response $response): self
{
$exception = new self(static::getMessageForResponse($response));
$exception->response = $response;
$bodyErrors = isset($response->getBody()['errors']) ? $response->getBody()['errors'] : [];
$exception->errors = $bodyErrors;
return $exception;
}
public static function getMessageForResponse(Response $response): string
{
return "Response code {$response->getHttpResponseCode()} returned";
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\FlareClient\Http\Exceptions;
use Spatie\FlareClient\Http\Response;
class InvalidData extends BadResponseCode
{
public static function getMessageForResponse(Response $response): string
{
return 'Invalid data found';
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\FlareClient\Http\Exceptions;
use Exception;
class MissingParameter extends Exception
{
public static function create(string $parameterName): self
{
return new self("`$parameterName` is a required parameter");
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\FlareClient\Http\Exceptions;
use Spatie\FlareClient\Http\Response;
class NotFound extends BadResponseCode
{
public static function getMessageForResponse(Response $response): string
{
return 'Not found';
}
}

View File

@@ -0,0 +1,50 @@
<?php
namespace Spatie\FlareClient\Http;
class Response
{
protected mixed $headers;
protected mixed $body;
protected mixed $error;
public function __construct(mixed $headers, mixed $body, mixed $error)
{
$this->headers = $headers;
$this->body = $body;
$this->error = $error;
}
public function getHeaders(): mixed
{
return $this->headers;
}
public function getBody(): mixed
{
return $this->body;
}
public function hasBody(): bool
{
return $this->body != false;
}
public function getError(): mixed
{
return $this->error;
}
public function getHttpResponseCode(): ?int
{
if (! isset($this->headers['http_code'])) {
return null;
}
return (int) $this->headers['http_code'];
}
}

View File

@@ -0,0 +1,398 @@
<?php
namespace Spatie\FlareClient;
use ErrorException;
use Spatie\Backtrace\Arguments\ArgumentReducers;
use Spatie\Backtrace\Arguments\Reducers\ArgumentReducer;
use Spatie\Backtrace\Backtrace;
use Spatie\Backtrace\Frame as SpatieFrame;
use Spatie\FlareClient\Concerns\HasContext;
use Spatie\FlareClient\Concerns\UsesTime;
use Spatie\FlareClient\Context\ContextProvider;
use Spatie\FlareClient\Contracts\ProvidesFlareContext;
use Spatie\FlareClient\Glows\Glow;
use Spatie\FlareClient\Solutions\ReportSolution;
use Spatie\Ignition\Contracts\Solution;
use Spatie\LaravelIgnition\Exceptions\ViewException;
use Throwable;
class Report
{
use UsesTime;
use HasContext;
protected Backtrace $stacktrace;
protected string $exceptionClass = '';
protected string $message = '';
/** @var array<int, array{time: int, name: string, message_level: string, meta_data: array, microtime: float}> */
protected array $glows = [];
/** @var array<int, array<int|string, mixed>> */
protected array $solutions = [];
/** @var array<int, string> */
public array $documentationLinks = [];
protected ContextProvider $context;
protected ?string $applicationPath = null;
protected ?string $applicationVersion = null;
/** @var array<int|string, mixed> */
protected array $userProvidedContext = [];
/** @var array<int|string, mixed> */
protected array $exceptionContext = [];
protected ?Throwable $throwable = null;
protected string $notifierName = 'Flare Client';
protected ?string $languageVersion = null;
protected ?string $frameworkVersion = null;
protected ?int $openFrameIndex = null;
protected string $trackingUuid;
protected ?View $view;
public static ?string $fakeTrackingUuid = null;
/** @param array<class-string<ArgumentReducer>|ArgumentReducer>|ArgumentReducers|null $argumentReducers */
public static function createForThrowable(
Throwable $throwable,
ContextProvider $context,
?string $applicationPath = null,
?string $version = null,
null|array|ArgumentReducers $argumentReducers = null,
bool $withStackTraceArguments = true,
): self {
$stacktrace = Backtrace::createForThrowable($throwable)
->withArguments($withStackTraceArguments)
->reduceArguments($argumentReducers)
->applicationPath($applicationPath ?? '');
return (new self())
->setApplicationPath($applicationPath)
->throwable($throwable)
->useContext($context)
->exceptionClass(self::getClassForThrowable($throwable))
->message($throwable->getMessage())
->stackTrace($stacktrace)
->exceptionContext($throwable)
->setApplicationVersion($version);
}
protected static function getClassForThrowable(Throwable $throwable): string
{
/** @phpstan-ignore-next-line */
if ($throwable::class === ViewException::class) {
/** @phpstan-ignore-next-line */
if ($previous = $throwable->getPrevious()) {
return get_class($previous);
}
}
return get_class($throwable);
}
/** @param array<class-string<ArgumentReducer>|ArgumentReducer>|ArgumentReducers|null $argumentReducers */
public static function createForMessage(
string $message,
string $logLevel,
ContextProvider $context,
?string $applicationPath = null,
null|array|ArgumentReducers $argumentReducers = null,
bool $withStackTraceArguments = true,
): self {
$stacktrace = Backtrace::create()
->withArguments($withStackTraceArguments)
->reduceArguments($argumentReducers)
->applicationPath($applicationPath ?? '');
return (new self())
->setApplicationPath($applicationPath)
->message($message)
->useContext($context)
->exceptionClass($logLevel)
->stacktrace($stacktrace)
->openFrameIndex($stacktrace->firstApplicationFrameIndex());
}
public function __construct()
{
$this->trackingUuid = self::$fakeTrackingUuid ?? $this->generateUuid();
}
public function trackingUuid(): string
{
return $this->trackingUuid;
}
public function exceptionClass(string $exceptionClass): self
{
$this->exceptionClass = $exceptionClass;
return $this;
}
public function getExceptionClass(): string
{
return $this->exceptionClass;
}
public function throwable(Throwable $throwable): self
{
$this->throwable = $throwable;
return $this;
}
public function getThrowable(): ?Throwable
{
return $this->throwable;
}
public function message(string $message): self
{
$this->message = $message;
return $this;
}
public function getMessage(): string
{
return $this->message;
}
public function stacktrace(Backtrace $stacktrace): self
{
$this->stacktrace = $stacktrace;
return $this;
}
public function getStacktrace(): Backtrace
{
return $this->stacktrace;
}
public function notifierName(string $notifierName): self
{
$this->notifierName = $notifierName;
return $this;
}
public function languageVersion(string $languageVersion): self
{
$this->languageVersion = $languageVersion;
return $this;
}
public function frameworkVersion(string $frameworkVersion): self
{
$this->frameworkVersion = $frameworkVersion;
return $this;
}
public function useContext(ContextProvider $request): self
{
$this->context = $request;
return $this;
}
public function openFrameIndex(?int $index): self
{
$this->openFrameIndex = $index;
return $this;
}
public function setApplicationPath(?string $applicationPath): self
{
$this->applicationPath = $applicationPath;
return $this;
}
public function getApplicationPath(): ?string
{
return $this->applicationPath;
}
public function setApplicationVersion(?string $applicationVersion): self
{
$this->applicationVersion = $applicationVersion;
return $this;
}
public function getApplicationVersion(): ?string
{
return $this->applicationVersion;
}
public function view(?View $view): self
{
$this->view = $view;
return $this;
}
public function addGlow(Glow $glow): self
{
$this->glows[] = $glow->toArray();
return $this;
}
public function addSolution(Solution $solution): self
{
$this->solutions[] = ReportSolution::fromSolution($solution)->toArray();
return $this;
}
/**
* @param array<int, string> $documentationLinks
*
* @return $this
*/
public function addDocumentationLinks(array $documentationLinks): self
{
$this->documentationLinks = $documentationLinks;
return $this;
}
/**
* @param array<int|string, mixed> $userProvidedContext
*
* @return $this
*/
public function userProvidedContext(array $userProvidedContext): self
{
$this->userProvidedContext = $userProvidedContext;
return $this;
}
/**
* @return array<int|string, mixed>
*/
public function allContext(): array
{
$context = $this->context->toArray();
$context = array_merge_recursive_distinct($context, $this->exceptionContext);
return array_merge_recursive_distinct($context, $this->userProvidedContext);
}
protected function exceptionContext(Throwable $throwable): self
{
if ($throwable instanceof ProvidesFlareContext) {
$this->exceptionContext = $throwable->context();
}
return $this;
}
/**
* @return array<int|string, mixed>
*/
protected function stracktraceAsArray(): array
{
return array_map(
fn (SpatieFrame $frame) => Frame::fromSpatieFrame($frame)->toArray(),
$this->cleanupStackTraceForError($this->stacktrace->frames()),
);
}
/**
* @param array<SpatieFrame> $frames
*
* @return array<SpatieFrame>
*/
protected function cleanupStackTraceForError(array $frames): array
{
if ($this->throwable === null || get_class($this->throwable) !== ErrorException::class) {
return $frames;
}
$firstErrorFrameIndex = null;
$restructuredFrames = array_values(array_slice($frames, 1)); // remove the first frame where error was created
foreach ($restructuredFrames as $index => $frame) {
if ($frame->file === $this->throwable->getFile()) {
$firstErrorFrameIndex = $index;
break;
}
}
if ($firstErrorFrameIndex === null) {
return $frames;
}
$restructuredFrames[$firstErrorFrameIndex]->arguments = null; // Remove error arguments
return array_values(array_slice($restructuredFrames, $firstErrorFrameIndex));
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
return [
'notifier' => $this->notifierName ?? 'Flare Client',
'language' => 'PHP',
'framework_version' => $this->frameworkVersion,
'language_version' => $this->languageVersion ?? phpversion(),
'exception_class' => $this->exceptionClass,
'seen_at' => $this->getCurrentTime(),
'message' => $this->message,
'glows' => $this->glows,
'solutions' => $this->solutions,
'documentation_links' => $this->documentationLinks,
'stacktrace' => $this->stracktraceAsArray(),
'context' => $this->allContext(),
'stage' => $this->stage,
'message_level' => $this->messageLevel,
'open_frame_index' => $this->openFrameIndex,
'application_path' => $this->applicationPath,
'application_version' => $this->applicationVersion,
'tracking_uuid' => $this->trackingUuid,
];
}
/*
* Found on https://stackoverflow.com/questions/2040240/php-function-to-generate-v4-uuid/15875555#15875555
*/
protected function generateUuid(): string
{
// Generate 16 bytes (128 bits) of random data or use the data passed into the function.
$data = random_bytes(16);
// Set version to 0100
$data[6] = chr(ord($data[6]) & 0x0f | 0x40);
// Set bits 6-7 to 10
$data[8] = chr(ord($data[8]) & 0x3f | 0x80);
// Output the 36 character UUID.
return vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4));
}
}

View File

@@ -0,0 +1,40 @@
<?php
namespace Spatie\FlareClient\Solutions;
use Spatie\Ignition\Contracts\RunnableSolution;
use Spatie\Ignition\Contracts\Solution as SolutionContract;
class ReportSolution
{
protected SolutionContract $solution;
public function __construct(SolutionContract $solution)
{
$this->solution = $solution;
}
public static function fromSolution(SolutionContract $solution): self
{
return new self($solution);
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
$isRunnable = ($this->solution instanceof RunnableSolution);
return [
'class' => get_class($this->solution),
'title' => $this->solution->getSolutionTitle(),
'description' => $this->solution->getSolutionDescription(),
'links' => $this->solution->getDocumentationLinks(),
/** @phpstan-ignore-next-line */
'action_description' => $isRunnable ? $this->solution->getSolutionActionDescription() : null,
'is_runnable' => $isRunnable,
'ai_generated' => $this->solution->aiGenerated ?? false,
];
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\FlareClient\Time;
use DateTimeImmutable;
class SystemTime implements Time
{
public function getCurrentTime(): int
{
return (new DateTimeImmutable())->getTimestamp();
}
}

View File

@@ -0,0 +1,8 @@
<?php
namespace Spatie\FlareClient\Time;
interface Time
{
public function getCurrentTime(): int;
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\FlareClient\Truncation;
abstract class AbstractTruncationStrategy implements TruncationStrategy
{
protected ReportTrimmer $reportTrimmer;
public function __construct(ReportTrimmer $reportTrimmer)
{
$this->reportTrimmer = $reportTrimmer;
}
}

View File

@@ -0,0 +1,53 @@
<?php
namespace Spatie\FlareClient\Truncation;
class ReportTrimmer
{
protected static int $maxPayloadSize = 524288;
/** @var array<int, class-string<\Spatie\FlareClient\Truncation\TruncationStrategy>> */
protected array $strategies = [
TrimStringsStrategy::class,
TrimStackFrameArgumentsStrategy::class,
TrimContextItemsStrategy::class,
];
/**
* @param array<int|string, mixed> $payload
*
* @return array<int|string, mixed>
*/
public function trim(array $payload): array
{
foreach ($this->strategies as $strategy) {
if (! $this->needsToBeTrimmed($payload)) {
break;
}
$payload = (new $strategy($this))->execute($payload);
}
return $payload;
}
/**
* @param array<int|string, mixed> $payload
*
* @return bool
*/
public function needsToBeTrimmed(array $payload): bool
{
return strlen((string)json_encode($payload)) > self::getMaxPayloadSize();
}
public static function getMaxPayloadSize(): int
{
return self::$maxPayloadSize;
}
public static function setMaxPayloadSize(int $maxPayloadSize): void
{
self::$maxPayloadSize = $maxPayloadSize;
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Spatie\FlareClient\Truncation;
class TrimContextItemsStrategy extends AbstractTruncationStrategy
{
/**
* @return array<int, int>
*/
public static function thresholds(): array
{
return [100, 50, 25, 10];
}
/**
* @param array<int|string, mixed> $payload
*
* @return array<int|string, mixed>
*/
public function execute(array $payload): array
{
foreach (static::thresholds() as $threshold) {
if (! $this->reportTrimmer->needsToBeTrimmed($payload)) {
break;
}
$payload['context'] = $this->iterateContextItems($payload['context'], $threshold);
}
return $payload;
}
/**
* @param array<int|string, mixed> $contextItems
* @param int $threshold
*
* @return array<int|string, mixed>
*/
protected function iterateContextItems(array $contextItems, int $threshold): array
{
array_walk($contextItems, [$this, 'trimContextItems'], $threshold);
return $contextItems;
}
protected function trimContextItems(mixed &$value, mixed $key, int $threshold): mixed
{
if (is_array($value)) {
if (count($value) > $threshold) {
$value = array_slice($value, $threshold * -1, $threshold);
}
array_walk($value, [$this, 'trimContextItems'], $threshold);
}
return $value;
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Spatie\FlareClient\Truncation;
class TrimStackFrameArgumentsStrategy implements TruncationStrategy
{
public function execute(array $payload): array
{
for ($i = 0; $i < count($payload['stacktrace']); $i++) {
$payload['stacktrace'][$i]['arguments'] = null;
}
return $payload;
}
}

View File

@@ -0,0 +1,49 @@
<?php
namespace Spatie\FlareClient\Truncation;
class TrimStringsStrategy extends AbstractTruncationStrategy
{
/**
* @return array<int, int>
*/
public static function thresholds(): array
{
return [1024, 512, 256];
}
/**
* @param array<int|string, mixed> $payload
*
* @return array<int|string, mixed>
*/
public function execute(array $payload): array
{
foreach (static::thresholds() as $threshold) {
if (! $this->reportTrimmer->needsToBeTrimmed($payload)) {
break;
}
$payload = $this->trimPayloadString($payload, $threshold);
}
return $payload;
}
/**
* @param array<int|string, mixed> $payload
* @param int $threshold
*
* @return array<int|string, mixed>
*/
protected function trimPayloadString(array $payload, int $threshold): array
{
array_walk_recursive($payload, function (&$value) use ($threshold) {
if (is_string($value) && strlen($value) > $threshold) {
$value = substr($value, 0, $threshold);
}
});
return $payload;
}
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\FlareClient\Truncation;
interface TruncationStrategy
{
/**
* @param array<int|string, mixed> $payload
*
* @return array<int|string, mixed>
*/
public function execute(array $payload): array;
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Spatie\FlareClient;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\HtmlDumper;
class View
{
protected string $file;
/** @var array<string, mixed> */
protected array $data = [];
/**
* @param string $file
* @param array<string, mixed> $data
*/
public function __construct(string $file, array $data = [])
{
$this->file = $file;
$this->data = $data;
}
/**
* @param string $file
* @param array<string, mixed> $data
*
* @return self
*/
public static function create(string $file, array $data = []): self
{
return new self($file, $data);
}
protected function dumpViewData(mixed $variable): string
{
$cloner = new VarCloner();
$dumper = new HtmlDumper();
$dumper->setDumpHeader('');
$output = fopen('php://memory', 'r+b');
if (! $output) {
return '';
}
$dumper->dump($cloner->cloneVar($variable)->withMaxDepth(1), $output, [
'maxDepth' => 1,
'maxStringLength' => 160,
]);
return (string)stream_get_contents($output, -1, 0);
}
/** @return array<string, mixed> */
public function toArray(): array
{
return [
'file' => $this->file,
'data' => array_map([$this, 'dumpViewData'], $this->data),
];
}
}

View File

@@ -0,0 +1,23 @@
<?php
if (! function_exists('array_merge_recursive_distinct')) {
/**
* @param array<int|string, mixed> $array1
* @param array<int|string, mixed> $array2
*
* @return array<int|string, mixed>
*/
function array_merge_recursive_distinct(array &$array1, array &$array2): array
{
$merged = $array1;
foreach ($array2 as $key => &$value) {
if (is_array($value) && isset($merged[$key]) && is_array($merged[$key])) {
$merged[$key] = array_merge_recursive_distinct($merged[$key], $value);
} else {
$merged[$key] = $value;
}
}
return $merged;
}
}

21
vendor/spatie/ignition/LICENSE.md vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Spatie <info@spatie.be>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

435
vendor/spatie/ignition/README.md vendored Normal file
View File

@@ -0,0 +1,435 @@
# Ignition: a beautiful error page for PHP apps
[![Latest Version on Packagist](https://img.shields.io/packagist/v/spatie/ignition.svg?style=flat-square)](https://packagist.org/packages/spatie/ignition)
[![Run tests](https://github.com/spatie/ignition/actions/workflows/run-tests.yml/badge.svg)](https://github.com/spatie/ignition/actions/workflows/run-tests.yml)
[![Total Downloads](https://img.shields.io/packagist/dt/spatie/ignition.svg?style=flat-square)](https://packagist.org/packages/spatie/ignition)
[Ignition](https://flareapp.io/docs/ignition-for-laravel/introduction) is a beautiful and customizable error page for
PHP applications
Here's a minimal example on how to register ignition.
```php
use Spatie\Ignition\Ignition;
include 'vendor/autoload.php';
Ignition::make()->register();
```
Let's now throw an exception during a web request.
```php
throw new Exception('Bye world');
```
This is what you'll see in the browser.
![Screenshot of ignition](https://spatie.github.io/ignition/ignition.png)
There's also a beautiful dark mode.
![Screenshot of ignition in dark mode](https://spatie.github.io/ignition/ignition-dark.png)
## Are you a visual learner?
In [this video on YouTube](https://youtu.be/LEY0N0Bteew?t=739), you'll see a demo of all of the features.
Do know more about the design decisions we made, read [this blog post](https://freek.dev/2168-ignition-the-most-beautiful-error-page-for-laravel-and-php-got-a-major-redesign).
## Support us
[<img src="https://github-ads.s3.eu-central-1.amazonaws.com/ignition.jpg?t=1" width="419px" />](https://spatie.be/github-ad-click/ignition)
We invest a lot of resources into creating [best in class open source packages](https://spatie.be/open-source). You can
support us by [buying one of our paid products](https://spatie.be/open-source/support-us).
We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.
You'll find our address on [our contact page](https://spatie.be/about-us). We publish all received postcards
on [our virtual postcard wall](https://spatie.be/open-source/postcards).
## Installation
For Laravel apps, head over to [laravel-ignition](https://github.com/spatie/laravel-ignition).
For Symfony apps, go to [symfony-ignition-bundle](https://github.com/spatie/symfony-ignition-bundle).
For Drupal 10+ websites, use the [Ignition module](https://www.drupal.org/project/ignition).
For all other PHP projects, install the package via composer:
```bash
composer require spatie/ignition
```
## Usage
In order to display the Ignition error page when an error occurs in your project, you must add this code. Typically, this would be done in the bootstrap part of your application.
```php
\Spatie\Ignition\Ignition::make()->register();
```
### Setting the application path
When setting the application path, Ignition will trim the given value from all paths. This will make the error page look
more cleaner.
```php
\Spatie\Ignition\Ignition::make()
->applicationPath($basePathOfYourApplication)
->register();
```
### Using dark mode
By default, Ignition uses a nice white based theme. If this is too bright for your eyes, you can use dark mode.
```php
\Spatie\Ignition\Ignition::make()
->useDarkMode()
->register();
```
### Avoid rendering Ignition in a production environment
You don't want to render the Ignition error page in a production environment, as it potentially can display sensitive
information.
To avoid rendering Ignition, you can call `shouldDisplayException` and pass it a falsy value.
```php
\Spatie\Ignition\Ignition::make()
->shouldDisplayException($inLocalEnvironment)
->register();
```
### Displaying solutions
In addition to displaying an exception, Ignition can display a solution as well.
Out of the box, Ignition will display solutions for common errors such as bad methods calls, or using undefined properties.
#### Adding a solution directly to an exception
To add a solution text to your exception, let the exception implement the `Spatie\Ignition\Contracts\ProvidesSolution`
interface.
This interface requires you to implement one method, which is going to return the `Solution` that users will see when
the exception gets thrown.
```php
use Spatie\Ignition\Contracts\Solution;
use Spatie\Ignition\Contracts\ProvidesSolution;
class CustomException extends Exception implements ProvidesSolution
{
public function getSolution(): Solution
{
return new CustomSolution();
}
}
```
```php
use Spatie\Ignition\Contracts\Solution;
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',
];
}
}
```
This is how the exception would be displayed if you were to throw it.
![Screenshot of solution](https://spatie.github.io/ignition/solution.png)
#### Using solution providers
Instead of adding solutions to exceptions directly, you can also create a solution provider. While exceptions that
return a solution, provide the solution directly to Ignition, a solution provider allows you to figure out if an
exception can be solved.
For example, you could create a custom "Stack Overflow solution provider", that will look up if a solution can be found
for a given throwable.
Solution providers can be added by third party packages or within your own application.
A solution provider is any class that implements the \Spatie\Ignition\Contracts\HasSolutionsForThrowable interface.
This is how the interface looks like:
```php
interface HasSolutionsForThrowable
{
public function canSolve(Throwable $throwable): bool;
/** @return \Spatie\Ignition\Contracts\Solution[] */
public function getSolutions(Throwable $throwable): array;
}
```
When an error occurs in your app, the class will receive the `Throwable` in the `canSolve` method. In that method you
can decide if your solution provider is applicable to the `Throwable` passed. If you return `true`, `getSolutions` will
get called.
To register a solution provider to Ignition you must call the `addSolutionProviders` method.
```php
\Spatie\Ignition\Ignition::make()
->addSolutionProviders([
YourSolutionProvider::class,
AnotherSolutionProvider::class,
])
->register();
```
### AI powered solutions
Ignition can send your exception to Open AI that will attempt to automatically suggest a solution. In many cases, the suggested solutions is quite useful, but keep in mind that the solution may not be 100% correct for your context.
To generate AI powered solutions, you must first install this optional dependency.
```bash
composer require openai-php/client
```
To start sending your errors to OpenAI, you must instanciate the `OpenAiSolutionProvider`. The constructor expects a OpenAI API key to be passed, you should generate this key [at OpenAI](https://platform.openai.com).
```php
use \Spatie\Ignition\Solutions\OpenAi\OpenAiSolutionProvider;
$aiSolutionProvider = new OpenAiSolutionProvider($openAiKey);
```
To use the solution provider, you should pass it to `addSolutionProviders` when registering Ignition.
```php
\Spatie\Ignition\Ignition::make()
->addSolutionProviders([
$aiSolutionProvider,
// other solution providers...
])
->register();
```
By default, the solution provider will send these bits of info to Open AI:
- the error message
- the error class
- the stack frame
- other small bits of info of context surrounding your error
It will not send the request payload or any environment variables to avoid sending sensitive data to OpenAI.
#### Caching requests to AI
By default, all errors will be sent to OpenAI. Optionally, you can add caching so similar errors will only get sent to OpenAI once. To cache errors, you can call `useCache` on `$aiSolutionProvider`. You should pass [a simple-cache-implementation](https://packagist.org/providers/psr/simple-cache-implementation). Here's the signature of the `useCache` method.
```php
public function useCache(CacheInterface $cache, int $cacheTtlInSeconds = 60 * 60)
```
#### Hinting the application type
To increase the quality of the suggested solutions, you can send along the application type (Symfony, Drupal, WordPress, ...) to the AI.
To send the application type call `applicationType` on the solution provider.
```php
$aiSolutionProvider->applicationType('WordPress 6.2')
```
### Sending exceptions to Flare
Ignition comes with the ability to send exceptions to [Flare](https://flareapp.io), an exception monitoring service. Flare
can notify you when new exceptions are occurring in your production environment.
To send exceptions to Flare, simply call the `sendToFlareMethod` and pass it the API key you got when creating a project
on Flare.
You probably want to combine this with calling `runningInProductionEnvironment`. That method will, when passed a truthy
value, not display the Ignition error page, but only send the exception to Flare.
```php
\Spatie\Ignition\Ignition::make()
->runningInProductionEnvironment($boolean)
->sendToFlare($yourApiKey)
->register();
```
When you pass a falsy value to `runningInProductionEnvironment`, the Ignition error page will get shown, but no
exceptions will be sent to Flare.
### Sending custom context to Flare
When you send an error to Flare, you can add custom information that will be sent along with every exception that
happens in your application. This can be very useful if you want to provide key-value related information that
furthermore helps you to debug a possible exception.
```php
use Spatie\FlareClient\Flare;
\Spatie\Ignition\Ignition::make()
->runningInProductionEnvironment($boolean)
->sendToFlare($yourApiKey)
->configureFlare(function(Flare $flare) {
$flare->context('Tenant', 'My-Tenant-Identifier');
})
->register();
```
Sometimes you may want to group your context items by a key that you provide to have an easier visual differentiation
when you look at your custom context items.
The Flare client allows you to also provide your own custom context groups like this:
```php
use Spatie\FlareClient\Flare;
\Spatie\Ignition\Ignition::make()
->runningInProductionEnvironment($boolean)
->sendToFlare($yourApiKey)
->configureFlare(function(Flare $flare) {
$flare->group('Custom information', [
'key' => 'value',
'another key' => 'another value',
]);
})
->register();
```
### Anonymize request to Flare
By default, the Ignition collects information about the IP address of your application users. If you don't want to send this information to Flare, call `anonymizeIp()`.
```php
use Spatie\FlareClient\Flare;
\Spatie\Ignition\Ignition::make()
->runningInProductionEnvironment($boolean)
->sendToFlare($yourApiKey)
->configureFlare(function(Flare $flare) {
$flare->anonymizeIp();
})
->register();
```
### Censoring request body fields
When an exception occurs in a web request, the Flare client will pass on any request fields that are present in the body.
In some cases, such as a login page, these request fields may contain a password that you don't want to send to Flare.
To censor out values of certain fields, you can use `censorRequestBodyFields`. You should pass it the names of the fields you wish to censor.
```php
use Spatie\FlareClient\Flare;
\Spatie\Ignition\Ignition::make()
->runningInProductionEnvironment($boolean)
->sendToFlare($yourApiKey)
->configureFlare(function(Flare $flare) {
$flare->censorRequestBodyFields(['password']);
})
->register();
```
This will replace the value of any sent fields named "password" with the value "<CENSORED>".
### Using middleware to modify data sent to Flare
Before Flare receives the data that was collected from your local exception, we give you the ability to call custom middleware methods. These methods retrieve the report that should be sent to Flare and allow you to add custom information to that report.
A valid middleware is any class that implements `FlareMiddleware`.
```php
use Spatie\FlareClient\Report;
use Spatie\FlareClient\FlareMiddleware\FlareMiddleware;
class MyMiddleware implements FlareMiddleware
{
public function handle(Report $report, Closure $next)
{
$report->message("{$report->getMessage()}, now modified");
return $next($report);
}
}
```
```php
use Spatie\FlareClient\Flare;
\Spatie\Ignition\Ignition::make()
->runningInProductionEnvironment($boolean)
->sendToFlare($yourApiKey)
->configureFlare(function(Flare $flare) {
$flare->registerMiddleware([
MyMiddleware::class,
])
})
->register();
```
### Changelog
Please see [CHANGELOG](CHANGELOG.md) for more information about what has changed recently.
## Contributing
Please see [CONTRIBUTING](https://github.com/spatie/.github/blob/main/CONTRIBUTING.md) for details.
## Dev setup
Here are the steps you'll need to perform if you want to work on the UI of Ignition.
- clone (or move) `spatie/ignition`, `spatie/ignition-ui`, `spatie/laravel-ignition`, `spatie/flare-client-php` and `spatie/ignition-test` into the same directory (e.g. `~/code/flare`)
- create a new `package.json` file in `~/code/flare` directory:
```json
{
"private": true,
"workspaces": [
"ignition-ui",
"ignition"
]
}
```
- run `yarn install` in the `~/code/flare` directory
- in the `~/code/flare/ignition-test` directory
- run `composer update`
- run `cp .env.example .env`
- run `php artisan key:generate`
- run `yarn dev` in both the `ignition` and `ignition-ui` project
- http://ignition-test.test/ should now work (= show the new UI). If you use valet, you might want to run `valet park` inside the `~/code/flare` directory.
- http://ignition-test.test/ has a bit of everything
- http://ignition-test.test/sql-error has a solution and SQL exception
## Security Vulnerabilities
Please review [our security policy](../../security/policy) on how to report security vulnerabilities.
## Credits
- [Spatie](https://spatie.be)
- [All Contributors](../../contributors)
## License
The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

82
vendor/spatie/ignition/composer.json vendored Normal file
View File

@@ -0,0 +1,82 @@
{
"name" : "spatie/ignition",
"description" : "A beautiful error page for PHP applications.",
"keywords" : [
"error",
"page",
"laravel",
"flare"
],
"authors" : [
{
"name" : "Spatie",
"email" : "info@spatie.be",
"role" : "Developer"
}
],
"homepage": "https://flareapp.io/ignition",
"license": "MIT",
"require": {
"php": "^8.0",
"ext-json": "*",
"ext-mbstring": "*",
"spatie/backtrace": "^1.5.3",
"spatie/flare-client-php": "^1.4.0",
"symfony/console": "^5.4|^6.0|^7.0",
"symfony/var-dumper": "^5.4|^6.0|^7.0"
},
"require-dev" : {
"illuminate/cache" : "^9.52|^10.0|^11.0",
"mockery/mockery" : "^1.4",
"pestphp/pest" : "^1.20|^2.0",
"phpstan/extension-installer" : "^1.1",
"phpstan/phpstan-deprecation-rules" : "^1.0",
"phpstan/phpstan-phpunit" : "^1.0",
"psr/simple-cache-implementation" : "*",
"symfony/cache" : "^5.4|^6.0|^7.0",
"symfony/process" : "^5.4|^6.0|^7.0",
"vlucas/phpdotenv" : "^5.5"
},
"suggest" : {
"openai-php/client" : "Require get solutions from OpenAI",
"simple-cache-implementation" : "To cache solutions from OpenAI"
},
"config" : {
"sort-packages" : true,
"allow-plugins" : {
"phpstan/extension-installer": true,
"pestphp/pest-plugin": true,
"php-http/discovery": false
}
},
"autoload" : {
"psr-4" : {
"Spatie\\Ignition\\" : "src"
}
},
"autoload-dev" : {
"psr-4" : {
"Spatie\\Ignition\\Tests\\" : "tests"
}
},
"minimum-stability" : "dev",
"prefer-stable" : true,
"scripts" : {
"analyse" : "vendor/bin/phpstan analyse",
"baseline" : "vendor/bin/phpstan analyse --generate-baseline",
"format" : "vendor/bin/php-cs-fixer fix --allow-risky=yes",
"test" : "vendor/bin/pest",
"test-coverage" : "vendor/bin/phpunit --coverage-html coverage"
},
"support" : {
"issues" : "https://github.com/spatie/ignition/issues",
"forum" : "https://twitter.com/flareappio",
"source" : "https://github.com/spatie/ignition",
"docs" : "https://flareapp.io/docs/ignition-for-laravel/introduction"
},
"extra" : {
"branch-alias" : {
"dev-main" : "1.5.x-dev"
}
}
}

View File

@@ -0,0 +1,4 @@
*
!.gitignore
!ignition.css
!ignition.js

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,36 @@
<?php /** @var \Spatie\Ignition\Solutions\OpenAi\OpenAiPromptViewModel $viewModel */ ?>
You are a very skilled PHP programmer.
<?php if($viewModel->applicationType()) { ?>
You are working on a <?php echo $viewModel->applicationType() ?> application.
<?php } ?>
Use the following context to find a possible fix for the exception message at the end. Limit your answer to 4 or 5 sentences. Also include a few links to documentation that might help.
Use this format in your answer, make sure links are json:
FIX
insert the possible fix here
ENDFIX
LINKS
{"title": "Title link 1", "url": "URL link 1"}
{"title": "Title link 2", "url": "URL link 2"}
ENDLINKS
---
Here comes the context and the exception message:
Line: <?php echo $viewModel->line() ?>
File:
<?php echo $viewModel->file() ?>
Snippet including line numbers:
<?php echo $viewModel->snippet() ?>
Exception class:
<?php echo $viewModel->exceptionClass() ?>
Exception message:
<?php echo $viewModel->exceptionMessage() ?>

View File

@@ -0,0 +1,75 @@
<!DOCTYPE html>
<?php /** @var \Spatie\Ignition\ErrorPage\ErrorPageViewModel $viewModel */ ?>
<html lang="en" class="<?= $viewModel->theme() ?>">
<!--
<?= $viewModel->throwableString() ?>
-->
<head>
<!-- Hide dumps asap -->
<style>
pre.sf-dump {
display: none !important;
}
</style>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta name="robots" content="noindex, nofollow">
<title><?= $viewModel->title() ?></title>
<script>
// Livewire modals remove CSS classes on the `html` element so we re-add
// the theme class again using JavaScript.
document.documentElement.classList.add('<?= $viewModel->theme() ?>');
// Process `auto` theme as soon as possible to avoid flashing of white background.
if (document.documentElement.classList.contains('auto') && window.matchMedia('(prefers-color-scheme: dark)').matches) {
document.documentElement.classList.add('dark');
}
</script>
<style><?= $viewModel->getAssetContents('ignition.css') ?></style>
<?= $viewModel->customHtmlHead() ?>
</head>
<body class="scrollbar-lg antialiased bg-center bg-dots-darker dark:bg-dots-lighter">
<script>
window.data = <?=
$viewModel->jsonEncode([
'report' => $viewModel->report(),
'shareableReport' => $viewModel->shareableReport(),
'config' => $viewModel->config(),
'solutions' => $viewModel->solutions(),
'updateConfigEndpoint' => $viewModel->updateConfigEndpoint(),
])
?>;
</script>
<!-- The noscript representation is for HTTP client like Postman that have JS disabled. -->
<noscript>
<pre><?= $viewModel->throwableString() ?></pre>
</noscript>
<div id="app"></div>
<script>
<!--
<?= $viewModel->getAssetContents('ignition.js') ?>
-->
</script>
<script>
window.ignite(window.data);
</script>
<?= $viewModel->customHtmlBody() ?>
<!--
<?= $viewModel->throwableString() ?>
-->
</body>
</html>

View File

@@ -0,0 +1,158 @@
<?php
namespace Spatie\Ignition\Config;
use Spatie\Ignition\Contracts\ConfigManager;
use Throwable;
class FileConfigManager implements ConfigManager
{
private const SETTINGS_FILE_NAME = '.ignition.json';
private string $path;
private string $file;
public function __construct(string $path = '')
{
$this->path = $this->initPath($path);
$this->file = $this->initFile();
}
protected function initPath(string $path): string
{
$path = $this->retrievePath($path);
if (! $this->isValidWritablePath($path)) {
return '';
}
return $this->preparePath($path);
}
protected function retrievePath(string $path): string
{
if ($path !== '') {
return $path;
}
return $this->initPathFromEnvironment();
}
protected function isValidWritablePath(string $path): bool
{
return @file_exists($path) && @is_writable($path);
}
protected function preparePath(string $path): string
{
return rtrim($path, DIRECTORY_SEPARATOR);
}
protected function initPathFromEnvironment(): string
{
if (! empty($_SERVER['HOMEDRIVE']) && ! empty($_SERVER['HOMEPATH'])) {
return $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
}
if (! empty(getenv('HOME'))) {
return getenv('HOME');
}
return '';
}
protected function initFile(): string
{
return $this->path . DIRECTORY_SEPARATOR . self::SETTINGS_FILE_NAME;
}
/** {@inheritDoc} */
public function load(): array
{
return $this->readFromFile();
}
/** @return array<string, mixed> */
protected function readFromFile(): array
{
if (! $this->isValidFile()) {
return [];
}
$content = (string)file_get_contents($this->file);
$settings = json_decode($content, true) ?? [];
return $settings;
}
protected function isValidFile(): bool
{
return $this->isValidPath() &&
@file_exists($this->file) &&
@is_writable($this->file);
}
protected function isValidPath(): bool
{
return trim($this->path) !== '';
}
/** {@inheritDoc} */
public function save(array $options): bool
{
if (! $this->createFile()) {
return false;
}
return $this->saveToFile($options);
}
protected function createFile(): bool
{
if (! $this->isValidPath()) {
return false;
}
if (@file_exists($this->file)) {
return true;
}
return (file_put_contents($this->file, '') !== false);
}
/**
* @param array<string, mixed> $options
*
* @return bool
*/
protected function saveToFile(array $options): bool
{
try {
$content = json_encode($options, JSON_THROW_ON_ERROR);
} catch (Throwable) {
return false;
}
return $this->writeToFile($content);
}
protected function writeToFile(string $content): bool
{
if (! $this->isValidFile()) {
return false;
}
return (file_put_contents($this->file, $content) !== false);
}
/** {@inheritDoc} */
public function getPersistentInfo(): array
{
return [
'name' => self::SETTINGS_FILE_NAME,
'path' => $this->path,
'file' => $this->file,
];
}
}

View File

@@ -0,0 +1,225 @@
<?php
namespace Spatie\Ignition\Config;
use Illuminate\Contracts\Support\Arrayable;
use Spatie\Ignition\Contracts\ConfigManager;
use Throwable;
/** @implements Arrayable<string, string|null|bool|array<string, mixed>> */
class IgnitionConfig implements Arrayable
{
private ConfigManager $manager;
public static function loadFromConfigFile(): self
{
return (new self())->loadConfigFile();
}
/**
* @param array<string, mixed> $options
*/
public function __construct(protected array $options = [])
{
$defaultOptions = $this->getDefaultOptions();
$this->options = array_merge($defaultOptions, $options);
$this->manager = $this->initConfigManager();
}
public function setOption(string $name, string $value): self
{
$this->options[$name] = $value;
return $this;
}
private function initConfigManager(): ConfigManager
{
try {
/** @phpstan-ignore-next-line */
return app(ConfigManager::class);
} catch (Throwable) {
return new FileConfigManager();
}
}
/** @param array<string, string> $options */
public function merge(array $options): self
{
$this->options = array_merge($this->options, $options);
return $this;
}
public function loadConfigFile(): self
{
$this->merge($this->getConfigOptions());
return $this;
}
/** @return array<string, mixed> */
public function getConfigOptions(): array
{
return $this->manager->load();
}
/**
* @param array<string, mixed> $options
* @return bool
*/
public function saveValues(array $options): bool
{
return $this->manager->save($options);
}
public function hideSolutions(): bool
{
return $this->options['hide_solutions'] ?? false;
}
public function editor(): ?string
{
return $this->options['editor'] ?? null;
}
/**
* @return array<string, mixed> $options
*/
public function editorOptions(): array
{
return $this->options['editor_options'] ?? [];
}
public function remoteSitesPath(): ?string
{
return $this->options['remote_sites_path'] ?? null;
}
public function localSitesPath(): ?string
{
return $this->options['local_sites_path'] ?? null;
}
public function theme(): ?string
{
return $this->options['theme'] ?? null;
}
public function shareButtonEnabled(): bool
{
return (bool)($this->options['enable_share_button'] ?? false);
}
public function shareEndpoint(): string
{
return $this->options['share_endpoint']
?? $this->getDefaultOptions()['share_endpoint'];
}
public function runnableSolutionsEnabled(): bool
{
return (bool)($this->options['enable_runnable_solutions'] ?? false);
}
/** @return array<string, string|null|bool|array<string, mixed>> */
public function toArray(): array
{
return [
'editor' => $this->editor(),
'theme' => $this->theme(),
'hideSolutions' => $this->hideSolutions(),
'remoteSitesPath' => $this->remoteSitesPath(),
'localSitesPath' => $this->localSitesPath(),
'enableShareButton' => $this->shareButtonEnabled(),
'enableRunnableSolutions' => $this->runnableSolutionsEnabled(),
'directorySeparator' => DIRECTORY_SEPARATOR,
'editorOptions' => $this->editorOptions(),
'shareEndpoint' => $this->shareEndpoint(),
];
}
/**
* @return array<string, mixed> $options
*/
protected function getDefaultOptions(): array
{
return [
'share_endpoint' => 'https://flareapp.io/api/public-reports',
'theme' => 'light',
'editor' => 'vscode',
'editor_options' => [
'clipboard' => [
'label' => 'Clipboard',
'url' => '%path:%line',
'clipboard' => true,
],
'sublime' => [
'label' => 'Sublime',
'url' => 'subl://open?url=file://%path&line=%line',
],
'textmate' => [
'label' => 'TextMate',
'url' => 'txmt://open?url=file://%path&line=%line',
],
'emacs' => [
'label' => 'Emacs',
'url' => 'emacs://open?url=file://%path&line=%line',
],
'macvim' => [
'label' => 'MacVim',
'url' => 'mvim://open/?url=file://%path&line=%line',
],
'phpstorm' => [
'label' => 'PhpStorm',
'url' => 'phpstorm://open?file=%path&line=%line',
],
'phpstorm-remote' => [
'label' => 'PHPStorm Remote',
'url' => 'javascript:r = new XMLHttpRequest;r.open("get", "http://localhost:63342/api/file/%path:%line");r.send()',
],
'idea' => [
'label' => 'Idea',
'url' => 'idea://open?file=%path&line=%line',
],
'vscode' => [
'label' => 'VS Code',
'url' => 'vscode://file/%path:%line',
],
'vscode-insiders' => [
'label' => 'VS Code Insiders',
'url' => 'vscode-insiders://file/%path:%line',
],
'vscode-remote' => [
'label' => 'VS Code Remote',
'url' => 'vscode://vscode-remote/%path:%line',
],
'vscode-insiders-remote' => [
'label' => 'VS Code Insiders Remote',
'url' => 'vscode-insiders://vscode-remote/%path:%line',
],
'vscodium' => [
'label' => 'VS Codium',
'url' => 'vscodium://file/%path:%line',
],
'atom' => [
'label' => 'Atom',
'url' => 'atom://core/open/file?filename=%path&line=%line',
],
'nova' => [
'label' => 'Nova',
'url' => 'nova://open?path=%path&line=%line',
],
'netbeans' => [
'label' => 'NetBeans',
'url' => 'netbeans://open/?f=%path:%line',
],
'xdebug' => [
'label' => 'Xdebug',
'url' => 'xdebug://%path@%line',
],
],
];
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace Spatie\Ignition\Contracts;
class BaseSolution implements Solution
{
protected string $title;
protected string $description = '';
/** @var array<string, string> */
protected array $links = [];
public static function create(string $title = ''): static
{
// It's important to keep the return type as static because
// the old Facade Ignition contracts extend from this method.
/** @phpstan-ignore-next-line */
return new static($title);
}
public function __construct(string $title = '')
{
$this->title = $title;
}
public function getSolutionTitle(): string
{
return $this->title;
}
public function setSolutionTitle(string $title): self
{
$this->title = $title;
return $this;
}
public function getSolutionDescription(): string
{
return $this->description;
}
public function setSolutionDescription(string $description): self
{
$this->description = $description;
return $this;
}
/** @return array<string, string> */
public function getDocumentationLinks(): array
{
return $this->links;
}
/** @param array<string, string> $links */
public function setDocumentationLinks(array $links): self
{
$this->links = $links;
return $this;
}
}

View File

@@ -0,0 +1,15 @@
<?php
namespace Spatie\Ignition\Contracts;
interface ConfigManager
{
/** @return array<string, mixed> */
public function load(): array;
/** @param array<string, mixed> $options */
public function save(array $options): bool;
/** @return array<string, mixed> */
public function getPersistentInfo(): array;
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Spatie\Ignition\Contracts;
use Throwable;
/**
* Interface used for SolutionProviders.
*/
interface HasSolutionsForThrowable
{
public function canSolve(Throwable $throwable): bool;
/** @return array<int, \Spatie\Ignition\Contracts\Solution> */
public function getSolutions(Throwable $throwable): array;
}

View File

@@ -0,0 +1,11 @@
<?php
namespace Spatie\Ignition\Contracts;
/**
* Interface to be used on exceptions that provide their own solution.
*/
interface ProvidesSolution
{
public function getSolution(): Solution;
}

View File

@@ -0,0 +1,16 @@
<?php
namespace Spatie\Ignition\Contracts;
interface RunnableSolution extends Solution
{
public function getSolutionActionDescription(): string;
public function getRunButtonText(): string;
/** @param array<string, mixed> $parameters */
public function run(array $parameters = []): void;
/** @return array<string, mixed> */
public function getRunParameters(): array;
}

View File

@@ -0,0 +1,13 @@
<?php
namespace Spatie\Ignition\Contracts;
interface Solution
{
public function getSolutionTitle(): string;
public function getSolutionDescription(): string;
/** @return array<string, string> */
public function getDocumentationLinks(): array;
}

View File

@@ -0,0 +1,36 @@
<?php
namespace Spatie\Ignition\Contracts;
use Throwable;
interface SolutionProviderRepository
{
/**
* @param class-string<HasSolutionsForThrowable>|HasSolutionsForThrowable $solutionProvider
*
* @return $this
*/
public function registerSolutionProvider(string $solutionProvider): self;
/**
* @param array<class-string<HasSolutionsForThrowable>|HasSolutionsForThrowable> $solutionProviders
*
* @return $this
*/
public function registerSolutionProviders(array $solutionProviders): self;
/**
* @param Throwable $throwable
*
* @return array<int, Solution>
*/
public function getSolutionsForThrowable(Throwable $throwable): array;
/**
* @param class-string<Solution> $solutionClass
*
* @return null|Solution
*/
public function getSolutionForClass(string $solutionClass): ?Solution;
}

View File

@@ -0,0 +1,130 @@
<?php
namespace Spatie\Ignition\ErrorPage;
use Spatie\FlareClient\Report;
use Spatie\FlareClient\Truncation\ReportTrimmer;
use Spatie\Ignition\Config\IgnitionConfig;
use Spatie\Ignition\Contracts\Solution;
use Spatie\Ignition\Solutions\SolutionTransformer;
use Throwable;
class ErrorPageViewModel
{
/**
* @param \Throwable|null $throwable
* @param \Spatie\Ignition\Config\IgnitionConfig $ignitionConfig
* @param \Spatie\FlareClient\Report $report
* @param array<int, Solution> $solutions
* @param string|null $solutionTransformerClass
*/
public function __construct(
protected ?Throwable $throwable,
protected IgnitionConfig $ignitionConfig,
protected Report $report,
protected array $solutions,
protected ?string $solutionTransformerClass = null,
protected string $customHtmlHead = '',
protected string $customHtmlBody = ''
) {
$this->solutionTransformerClass ??= SolutionTransformer::class;
}
public function throwableString(): string
{
if (! $this->throwable) {
return '';
}
$throwableString = sprintf(
"%s: %s in file %s on line %d\n\n%s\n",
get_class($this->throwable),
$this->throwable->getMessage(),
$this->throwable->getFile(),
$this->throwable->getLine(),
$this->report->getThrowable()?->getTraceAsString()
);
return htmlspecialchars($throwableString);
}
public function title(): string
{
return htmlspecialchars($this->report->getMessage());
}
/**
* @return array<string, mixed>
*/
public function config(): array
{
return $this->ignitionConfig->toArray();
}
public function theme(): string
{
return $this->config()['theme'] ?? 'auto';
}
/**
* @return array<int, mixed>
*/
public function solutions(): array
{
return array_map(function (Solution $solution) {
/** @var class-string $transformerClass */
$transformerClass = $this->solutionTransformerClass;
/** @var SolutionTransformer $transformer */
$transformer = new $transformerClass($solution);
return ($transformer)->toArray();
}, $this->solutions);
}
/**
* @return array<string, mixed>
*/
public function report(): array
{
return $this->report->toArray();
}
public function jsonEncode(mixed $data): string
{
$jsonOptions = JSON_PARTIAL_OUTPUT_ON_ERROR | JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT;
return (string) json_encode($data, $jsonOptions);
}
public function getAssetContents(string $asset): string
{
$assetPath = __DIR__."/../../resources/compiled/{$asset}";
return (string) file_get_contents($assetPath);
}
/**
* @return array<int|string, mixed>
*/
public function shareableReport(): array
{
return (new ReportTrimmer())->trim($this->report());
}
public function updateConfigEndpoint(): string
{
// TODO: Should be based on Ignition config
return '/_ignition/update-config';
}
public function customHtmlHead(): string
{
return $this->customHtmlHead;
}
public function customHtmlBody(): string
{
return $this->customHtmlBody;
}
}

View File

@@ -0,0 +1,29 @@
<?php
namespace Spatie\Ignition\ErrorPage;
class Renderer
{
/**
* @param array<string, mixed> $data
*
* @return void
*/
public function render(array $data, string $viewPath): void
{
$viewFile = $viewPath;
extract($data, EXTR_OVERWRITE);
include $viewFile;
}
public function renderAsString(array $date, string $viewPath): string
{
ob_start();
$this->render($date, $viewPath);
return ob_get_clean();
}
}

382
vendor/spatie/ignition/src/Ignition.php vendored Normal file
View File

@@ -0,0 +1,382 @@
<?php
namespace Spatie\Ignition;
use ArrayObject;
use ErrorException;
use Spatie\FlareClient\Context\BaseContextProviderDetector;
use Spatie\FlareClient\Context\ContextProviderDetector;
use Spatie\FlareClient\Enums\MessageLevels;
use Spatie\FlareClient\Flare;
use Spatie\FlareClient\FlareMiddleware\AddDocumentationLinks;
use Spatie\FlareClient\FlareMiddleware\AddSolutions;
use Spatie\FlareClient\FlareMiddleware\FlareMiddleware;
use Spatie\FlareClient\Report;
use Spatie\Ignition\Config\IgnitionConfig;
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
use Spatie\Ignition\Contracts\SolutionProviderRepository as SolutionProviderRepositoryContract;
use Spatie\Ignition\ErrorPage\ErrorPageViewModel;
use Spatie\Ignition\ErrorPage\Renderer;
use Spatie\Ignition\Solutions\SolutionProviders\BadMethodCallSolutionProvider;
use Spatie\Ignition\Solutions\SolutionProviders\MergeConflictSolutionProvider;
use Spatie\Ignition\Solutions\SolutionProviders\SolutionProviderRepository;
use Spatie\Ignition\Solutions\SolutionProviders\UndefinedPropertySolutionProvider;
use Throwable;
class Ignition
{
protected Flare $flare;
protected bool $shouldDisplayException = true;
protected string $flareApiKey = '';
protected string $applicationPath = '';
/** @var array<int, FlareMiddleware> */
protected array $middleware = [];
protected IgnitionConfig $ignitionConfig;
protected ContextProviderDetector $contextProviderDetector;
protected SolutionProviderRepositoryContract $solutionProviderRepository;
protected ?bool $inProductionEnvironment = null;
protected ?string $solutionTransformerClass = null;
/** @var ArrayObject<int, callable(Throwable): mixed> */
protected ArrayObject $documentationLinkResolvers;
protected string $customHtmlHead = '';
protected string $customHtmlBody = '';
public static function make(): self
{
return new self();
}
public function __construct(
?Flare $flare = null,
) {
$this->flare = $flare ?? Flare::make();
$this->ignitionConfig = IgnitionConfig::loadFromConfigFile();
$this->solutionProviderRepository = new SolutionProviderRepository($this->getDefaultSolutionProviders());
$this->documentationLinkResolvers = new ArrayObject();
$this->contextProviderDetector = new BaseContextProviderDetector();
$this->middleware[] = new AddSolutions($this->solutionProviderRepository);
$this->middleware[] = new AddDocumentationLinks($this->documentationLinkResolvers);
}
public function setSolutionTransformerClass(string $solutionTransformerClass): self
{
$this->solutionTransformerClass = $solutionTransformerClass;
return $this;
}
/** @param callable(Throwable): mixed $callable */
public function resolveDocumentationLink(callable $callable): self
{
$this->documentationLinkResolvers[] = $callable;
return $this;
}
public function setConfig(IgnitionConfig $ignitionConfig): self
{
$this->ignitionConfig = $ignitionConfig;
return $this;
}
public function runningInProductionEnvironment(bool $boolean = true): self
{
$this->inProductionEnvironment = $boolean;
return $this;
}
public function getFlare(): Flare
{
return $this->flare;
}
public function setFlare(Flare $flare): self
{
$this->flare = $flare;
return $this;
}
public function setSolutionProviderRepository(SolutionProviderRepositoryContract $solutionProviderRepository): self
{
$this->solutionProviderRepository = $solutionProviderRepository;
return $this;
}
public function shouldDisplayException(bool $shouldDisplayException): self
{
$this->shouldDisplayException = $shouldDisplayException;
return $this;
}
public function applicationPath(string $applicationPath): self
{
$this->applicationPath = $applicationPath;
return $this;
}
/**
* @param string $name
* @param string $messageLevel
* @param array<int, mixed> $metaData
*
* @return $this
*/
public function glow(
string $name,
string $messageLevel = MessageLevels::INFO,
array $metaData = []
): self {
$this->flare->glow($name, $messageLevel, $metaData);
return $this;
}
/**
* @param array<int, HasSolutionsForThrowable|class-string<HasSolutionsForThrowable>> $solutionProviders
*
* @return $this
*/
public function addSolutionProviders(array $solutionProviders): self
{
$this->solutionProviderRepository->registerSolutionProviders($solutionProviders);
return $this;
}
/** @deprecated Use `setTheme('dark')` instead */
public function useDarkMode(): self
{
return $this->setTheme('dark');
}
/** @deprecated Use `setTheme($theme)` instead */
public function theme(string $theme): self
{
return $this->setTheme($theme);
}
public function setTheme(string $theme): self
{
$this->ignitionConfig->setOption('theme', $theme);
return $this;
}
public function setEditor(string $editor): self
{
$this->ignitionConfig->setOption('editor', $editor);
return $this;
}
public function sendToFlare(?string $apiKey): self
{
$this->flareApiKey = $apiKey ?? '';
return $this;
}
public function configureFlare(callable $callable): self
{
($callable)($this->flare);
return $this;
}
/**
* @param FlareMiddleware|array<int, FlareMiddleware> $middleware
*
* @return $this
*/
public function registerMiddleware(array|FlareMiddleware $middleware): self
{
if (! is_array($middleware)) {
$middleware = [$middleware];
}
foreach ($middleware as $singleMiddleware) {
$this->middleware = array_merge($this->middleware, $middleware);
}
return $this;
}
public function setContextProviderDetector(ContextProviderDetector $contextProviderDetector): self
{
$this->contextProviderDetector = $contextProviderDetector;
return $this;
}
public function reset(): self
{
$this->flare->reset();
return $this;
}
public function register(): self
{
error_reporting(-1);
/** @phpstan-ignore-next-line */
set_error_handler([$this, 'renderError']);
/** @phpstan-ignore-next-line */
set_exception_handler([$this, 'handleException']);
return $this;
}
/**
* @param int $level
* @param string $message
* @param string $file
* @param int $line
* @param array<int, mixed> $context
*
* @return void
* @throws \ErrorException
*/
public function renderError(
int $level,
string $message,
string $file = '',
int $line = 0,
array $context = []
): void {
if(error_reporting() === (E_ERROR | E_CORE_ERROR | E_COMPILE_ERROR | E_USER_ERROR | E_RECOVERABLE_ERROR | E_PARSE)) {
// This happens when PHP version is >=8 and we caught an error that was suppressed with the "@" operator
// See the first warning box in https://www.php.net/manual/en/language.operators.errorcontrol.php
return;
}
throw new ErrorException($message, 0, $level, $file, $line);
}
/**
* This is the main entry point for the framework agnostic Ignition package.
* Displays the Ignition page and optionally sends a report to Flare.
*/
public function handleException(Throwable $throwable): Report
{
$this->setUpFlare();
$report = $this->createReport($throwable);
if ($this->shouldDisplayException && $this->inProductionEnvironment !== true) {
$this->renderException($throwable, $report);
}
if ($this->flare->apiTokenSet() && $this->inProductionEnvironment !== false) {
$this->flare->report($throwable, report: $report);
}
return $report;
}
/**
* This is the main entrypoint for laravel-ignition. It only renders the exception.
* Sending the report to Flare is handled in the laravel-ignition log handler.
*/
public function renderException(Throwable $throwable, ?Report $report = null): void
{
$this->setUpFlare();
$report ??= $this->createReport($throwable);
$viewModel = new ErrorPageViewModel(
$throwable,
$this->ignitionConfig,
$report,
$this->solutionProviderRepository->getSolutionsForThrowable($throwable),
$this->solutionTransformerClass,
$this->customHtmlHead,
$this->customHtmlBody,
);
(new Renderer())->render(['viewModel' => $viewModel], self::viewPath('errorPage'));
}
public static function viewPath(string $viewName): string
{
return __DIR__ . "/../resources/views/{$viewName}.php";
}
/**
* Add custom HTML which will be added to the head tag of the error page.
*/
public function addCustomHtmlToHead(string $html): self
{
$this->customHtmlHead .= $html;
return $this;
}
/**
* Add custom HTML which will be added to the body tag of the error page.
*/
public function addCustomHtmlToBody(string $html): self
{
$this->customHtmlBody .= $html;
return $this;
}
protected function setUpFlare(): self
{
if (! $this->flare->apiTokenSet()) {
$this->flare->setApiToken($this->flareApiKey ?? '');
}
$this->flare->setContextProviderDetector($this->contextProviderDetector);
foreach ($this->middleware as $singleMiddleware) {
$this->flare->registerMiddleware($singleMiddleware);
}
if ($this->applicationPath !== '') {
$this->flare->applicationPath($this->applicationPath);
}
return $this;
}
/** @return array<class-string<HasSolutionsForThrowable>> */
protected function getDefaultSolutionProviders(): array
{
return [
BadMethodCallSolutionProvider::class,
MergeConflictSolutionProvider::class,
UndefinedPropertySolutionProvider::class,
];
}
protected function createReport(Throwable $throwable): Report
{
return $this->flare->createReport($throwable);
}
}

View File

@@ -0,0 +1,48 @@
<?php
namespace Spatie\Ignition\Solutions\OpenAi;
use Psr\SimpleCache\CacheInterface;
class DummyCache implements CacheInterface
{
public function get(string $key, mixed $default = null): mixed
{
return null;
}
public function set(string $key, mixed $value, \DateInterval|int|null $ttl = null): bool
{
return true;
}
public function delete(string $key): bool
{
return true;
}
public function clear(): bool
{
return true;
}
public function getMultiple(iterable $keys, mixed $default = null): iterable
{
return [];
}
public function setMultiple(iterable $values, \DateInterval|int|null $ttl = null): bool
{
return true;
}
public function deleteMultiple(iterable $keys): bool
{
return true;
}
public function has(string $key): bool
{
return false;
}
}

View File

@@ -0,0 +1,46 @@
<?php
namespace Spatie\Ignition\Solutions\OpenAi;
class OpenAiPromptViewModel
{
public function __construct(
protected string $file,
protected string $exceptionMessage,
protected string $exceptionClass,
protected string $snippet,
protected string $line,
protected string|null $applicationType = null,
) {
}
public function file(): string
{
return $this->file;
}
public function line(): string
{
return $this->line;
}
public function snippet(): string
{
return $this->snippet;
}
public function exceptionMessage(): string
{
return $this->exceptionMessage;
}
public function exceptionClass(): string
{
return $this->exceptionClass;
}
public function applicationType(): string|null
{
return $this->applicationType;
}
}

View File

@@ -0,0 +1,115 @@
<?php
namespace Spatie\Ignition\Solutions\OpenAi;
use OpenAI;
use Psr\SimpleCache\CacheInterface;
use Spatie\Backtrace\Backtrace;
use Spatie\Backtrace\Frame;
use Spatie\Ignition\Contracts\Solution;
use Spatie\Ignition\ErrorPage\Renderer;
use Spatie\Ignition\Ignition;
use Throwable;
class OpenAiSolution implements Solution
{
public bool $aiGenerated = true;
protected string $prompt;
protected OpenAiSolutionResponse $openAiSolutionResponse;
public function __construct(
protected Throwable $throwable,
protected string $openAiKey,
protected CacheInterface|null $cache = null,
protected int|null $cacheTtlInSeconds = 60,
protected string|null $applicationType = null,
protected string|null $applicationPath = null,
) {
$this->prompt = $this->generatePrompt();
$this->openAiSolutionResponse = $this->getAiSolution();
}
public function getSolutionTitle(): string
{
return 'AI Generated Solution';
}
public function getSolutionDescription(): string
{
return $this->openAiSolutionResponse->description();
}
public function getDocumentationLinks(): array
{
return $this->openAiSolutionResponse->links();
}
public function getAiSolution(): ?OpenAiSolutionResponse
{
$solution = $this->cache->get($this->getCacheKey());
if ($solution) {
return new OpenAiSolutionResponse($solution);
}
$solutionText = OpenAI::client($this->openAiKey)
->chat()
->create([
'model' => $this->getModel(),
'messages' => [['role' => 'user', 'content' => $this->prompt]],
'max_tokens' => 1000,
'temperature' => 0,
])->choices[0]->message->content;
$this->cache->set($this->getCacheKey(), $solutionText, $this->cacheTtlInSeconds);
return new OpenAiSolutionResponse($solutionText);
}
protected function getCacheKey(): string
{
$hash = sha1($this->prompt);
return "ignition-solution-{$hash}";
}
protected function generatePrompt(): string
{
$viewPath = Ignition::viewPath('aiPrompt');
$viewModel = new OpenAiPromptViewModel(
file: $this->throwable->getFile(),
exceptionMessage: $this->throwable->getMessage(),
exceptionClass: get_class($this->throwable),
snippet: $this->getApplicationFrame($this->throwable)->getSnippetAsString(15),
line: $this->throwable->getLine(),
applicationType: $this->applicationType,
);
return (new Renderer())->renderAsString(
['viewModel' => $viewModel],
$viewPath,
);
}
protected function getModel(): string
{
return 'gpt-3.5-turbo';
}
protected function getApplicationFrame(Throwable $throwable): ?Frame
{
$backtrace = Backtrace::createForThrowable($throwable);
if ($this->applicationPath) {
$backtrace->applicationPath($this->applicationPath);
}
$frames = $backtrace->frames();
return $frames[$backtrace->firstApplicationFrameIndex()] ?? null;
}
}

View File

@@ -0,0 +1,62 @@
<?php
namespace Spatie\Ignition\Solutions\OpenAi;
use Psr\SimpleCache\CacheInterface;
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
use Throwable;
class OpenAiSolutionProvider implements HasSolutionsForThrowable
{
public function __construct(
protected string $openAiKey,
protected ?CacheInterface $cache = null,
protected int $cacheTtlInSeconds = 60 * 60,
protected string|null $applicationType = null,
protected string|null $applicationPath = null,
) {
$this->cache ??= new DummyCache();
}
public function canSolve(Throwable $throwable): bool
{
return true;
}
public function getSolutions(Throwable $throwable): array
{
return [
new OpenAiSolution(
$throwable,
$this->openAiKey,
$this->cache,
$this->cacheTtlInSeconds,
$this->applicationType,
$this->applicationPath,
),
];
}
public function applicationType(string $applicationType): self
{
$this->applicationType = $applicationType;
return $this;
}
public function applicationPath(string $applicationPath): self
{
$this->applicationPath = $applicationPath;
return $this;
}
public function useCache(CacheInterface $cache, int $cacheTtlInSeconds = 60 * 60): self
{
$this->cache = $cache;
$this->cacheTtlInSeconds = $cacheTtlInSeconds;
return $this;
}
}

View File

@@ -0,0 +1,58 @@
<?php
namespace Spatie\Ignition\Solutions\OpenAi;
class OpenAiSolutionResponse
{
protected string $rawText;
public function __construct(string $rawText)
{
$this->rawText = trim($rawText);
}
public function description(): string
{
return $this->between('FIX', 'ENDFIX', $this->rawText);
}
public function links(): array
{
$textLinks = $this->between('LINKS', 'ENDLINKS', $this->rawText);
$textLinks = explode(PHP_EOL, $textLinks);
$textLinks = array_map(function ($textLink) {
$textLink = str_replace('\\', '\\\\', $textLink);
$textLink = str_replace('\\\\\\', '\\\\', $textLink);
return json_decode($textLink, true);
}, $textLinks);
array_filter($textLinks);
$links = [];
foreach ($textLinks as $textLink) {
$links[$textLink['title']] = $textLink['url'];
}
return $links;
}
protected function between(string $start, string $end, string $text): string
{
$startPosition = strpos($text, $start);
if ($startPosition === false) {
return "";
}
$startPosition += strlen($start);
$endPosition = strpos($text, $end, $startPosition);
if ($endPosition === false) {
return "";
}
return trim(substr($text, $startPosition, $endPosition - $startPosition));
}
}

View File

@@ -0,0 +1,98 @@
<?php
namespace Spatie\Ignition\Solutions\SolutionProviders;
use BadMethodCallException;
use Illuminate\Support\Collection;
use ReflectionClass;
use ReflectionMethod;
use Spatie\Ignition\Contracts\BaseSolution;
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
use Throwable;
class BadMethodCallSolutionProvider implements HasSolutionsForThrowable
{
protected const REGEX = '/([a-zA-Z\\\\]+)::([a-zA-Z]+)/m';
public function canSolve(Throwable $throwable): bool
{
if (! $throwable instanceof BadMethodCallException) {
return false;
}
if (is_null($this->getClassAndMethodFromExceptionMessage($throwable->getMessage()))) {
return false;
}
return true;
}
public function getSolutions(Throwable $throwable): array
{
return [
BaseSolution::create('Bad Method Call')
->setSolutionDescription($this->getSolutionDescription($throwable)),
];
}
public function getSolutionDescription(Throwable $throwable): string
{
if (! $this->canSolve($throwable)) {
return '';
}
/** @phpstan-ignore-next-line */
extract($this->getClassAndMethodFromExceptionMessage($throwable->getMessage()), EXTR_OVERWRITE);
$possibleMethod = $this->findPossibleMethod($class ?? '', $method ?? '');
$class ??= 'UnknownClass';
return "Did you mean {$class}::{$possibleMethod?->name}() ?";
}
/**
* @param string $message
*
* @return null|array<string, mixed>
*/
protected function getClassAndMethodFromExceptionMessage(string $message): ?array
{
if (! preg_match(self::REGEX, $message, $matches)) {
return null;
}
return [
'class' => $matches[1],
'method' => $matches[2],
];
}
/**
* @param class-string $class
* @param string $invalidMethodName
*
* @return \ReflectionMethod|null
*/
protected function findPossibleMethod(string $class, string $invalidMethodName): ?ReflectionMethod
{
return $this->getAvailableMethods($class)
->sortByDesc(function (ReflectionMethod $method) use ($invalidMethodName) {
similar_text($invalidMethodName, $method->name, $percentage);
return $percentage;
})->first();
}
/**
* @param class-string $class
*
* @return \Illuminate\Support\Collection<int, ReflectionMethod>
*/
protected function getAvailableMethods(string $class): Collection
{
$class = new ReflectionClass($class);
return Collection::make($class->getMethods());
}
}

Some files were not shown because too many files have changed in this diff Show More