Fix bin/publish: copy docs.dist from project root

Fix bin/publish: use correct .env path for rspade_system
Fix bin/publish script: prevent grep exit code 1 from terminating script

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
root
2025-10-21 02:08:33 +00:00
commit f6fac6c4bc
79758 changed files with 10547827 additions and 0 deletions

21
vendor/spatie/flare-client-php/LICENSE.md vendored Executable file
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.

415
vendor/spatie/flare-client-php/README.md vendored Executable file
View File

@@ -0,0 +1,415 @@
# 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
When creating a new project on Flare, we'll display installation instructions for your PHP app. Even though the default settings will work fine for all projects, we offer some customization options that you might like.
### Ignoring errors
The Flare client will always send all exceptions to Flare, you can change this behaviour by filtering the exceptions with a callable:
```php
// Where you registered your client...
$flare = Flare::make('YOUR-FLARE-API-KEY')
->registerFlareHandlers();
$flare->filterExceptionsUsing(
fn(Throwable $throwable) => !$throwable instanceof AuthorizationException
);
```
Additionally, you can provide a callable to the `Flare::filterReportsUsing` method to stop a report from being sent to Flare. Compared to `filterExceptionsCallable`, this can also prevent logs and errors from being sent.
```php
use Spatie\FlareClient\Flare;
$flare = Flare::make('YOUR-API-KEY')
->registerFlareHandlers();
Flare::filterReportsUsing(function(Report $report) {
// return a boolean to control whether the report should be sent to Flare
return true;
});
```
Finally, it is also possible to set the levels of errors reported to Flare as such:
```php
$flare->reportErrorLevels(E_ALL & ~E_NOTICE); // Will send all errors except E_NOTICE errors
```
### Controlling collected data
Just like the Laravel configuration, the generic PHP client allows you to configure which information should be sent to Flare.
#### Anonymizing IPs
By default, the Flare client collects information about the IP address of your application users. If you want to disable this information, you can call the `anonymizeIp()` method on your Flare client instance.
```php
// Where you registered your client...
$flare = Flare::make('YOUR-FLARE-API-KEY')
->registerFlareHandlers();
$flare->anonymizeIp();
```
#### 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 call `censorRequestBodyFields`. You should pass it the names of the fields you wish to censor.
```php
// Where you registered your client...
$flare = Flare::make('YOUR-FLARE-API-KEY')
->registerFlareHandlers();
$flare->censorRequestBodyFields('password');
```
This will replace the value of any sent fields named "password" with the value "<CENSORED>".
### Identifying users
When reporting an error to Flare, you can tell the Flare client, what information you have about the currently authenticated user. You can do this by providing a `user` group that holds all the information you want to share.
```php
$user = YourAuthenticatedUserInstance();
$flare->group('user', [
'email' => $user->email,
'name' => $user->name,
'additional_information' => $user->additional,
]);
```
### Linking to errors
When an error occurs in web request, your application will likely display a minimal error page when it's in production.
If a user sees this page and wants to report this error to you, the user usually only reports the URL and the time the error was seen.
To let your users pinpoint the exact error they saw, you can display the UUID of the error sent to Flare.
You can do this by displaying the UUID returned by `Flare::sentReports()->latestUuid()` in your view. Optionally, you can use `Flare::sentReports()->latestUrl()` to get a link to the error in Flare. That link isn't publicly accessible, it is only visible to Flare users that have access to the project on Flare.
In certain cases, multiple error can be reported to Flare in a single request. To get a hold of the UUIDs of all sent errors, you can call `Flare::sentReports()->uuids()`. You can get links to all sent errors with `Flare::sentReports()->urls()`.
It is possible to search for certain errors in Flare using the UUID, you can find more information about that [here](http://flareapp.io/docs/flare/general/searching-errors).
### Adding custom context
When you send an error to Flare within a non-Laravel application, we do not collect your application information - since we don't know about your specific application.
In order to provide more information, you can add custom context to your application 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.
The Flare client allows you to set custom context items like this:
```php
// Get access to your registered Flare client instance
$flare->context('Tenant', 'My-Tenant-Identifier');
```
This could for example be set automatically in a Laravel service provider or an event. So the next time an exception happens, this value will be sent along to Flare and you can find it on the "Context" tab.
#### Grouping multiple context items
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
// Get access to your registered Flare client instance
$flare->group('Custom information', [
'key' => 'value',
'another key' => 'another value',
]);
```
### Adding glows
In addition to custom context items, you can also add "Glows" to your application.
Glows allow you to add little pieces of information, that can later be found in a chronological order in the "Debug" tab of your application.
You can think of glows as breadcrumbs that can help you track down which parts of your code an exception went through.
The Flare PHP client allows you to add a glows to your application like this:
### Stacktrace arguments
When an error occurs in your application, Flare will send the stacktrace of the error to Flare. This stacktrace contains the file and line number where the error occurred and the argument values passed to the function or method that caused the error.
These argument values have been significantly reduced to make them easier to read and reduce the amount of data sent to Flare, which means that the arguments are not always complete. To see the full arguments, you can always use a glow to send the whole parameter to Flare.
For example, let's say you have the following Carbon object:
```php
new DateTime('2020-05-16 14:00:00', new DateTimeZone('Europe/Brussels'))
```
Flare will automatically reduce this to the following:
```
16 May 2020 14:00:00 +02:00
```
It is possible to configure how these arguments are reduced. You can even implement your own reducers!
By default, the following reducers are used:
- BaseTypeArgumentReducer
- ArrayArgumentReducer
- StdClassArgumentReducer
- EnumArgumentReducer
- ClosureArgumentReducer
- DateTimeArgumentReducer
- DateTimeZoneArgumentReducer
- SymphonyRequestArgumentReducer
- StringableArgumentReducer
#### Implementing your reducer
Each reducer implements `Spatie\FlareClient\Arguments\Reducers\ArgumentReducer`. This interface contains a single method, `execute` which provides the original argument value:
```php
interface ArgumentReducer
{
public function execute(mixed $argument): ReducedArgumentContract;
}
```
In the end, three types of values can be returned:
When the reducer could not reduce this type of argument value:
```php
return UnReducedArgument::create();
```
When the reducer could reduce the argument value, but a part was truncated due to the size:
```php
return new TruncatedReducedArgument(
array_slice($argument, 0, 25), // The reduced value
'array' // The original type of the argument
);
```
When the reducer could reduce the full argument value:
```php
return new TruncatedReducedArgument(
$argument, // The reduced value
'array' // The original type of the argument
);
```
For example, the `DateTimeArgumentReducer` from the example above looks like this:
```php
class DateTimeArgumentReducer implements ArgumentReducer
{
public function execute(mixed $argument): ReducedArgumentContract
{
if (! $argument instanceof \DateTimeInterface) {
return UnReducedArgument::create();
}
return new ReducedArgument(
$argument->format('d M Y H:i:s p'),
get_class($argument),
);
}
}
```
#### Configuring the reducers
Reducers can be added as such:
```php
// Where you registered your client...
$flare = Flare::make('YOUR-FLARE-API-KEY')
->registerFlareHandlers();
$flare->argumentReducers([
BaseTypeArgumentReducer::class,
ArrayArgumentReducer::class,
StdClassArgumentReducer::class,
EnumArgumentReducer::class,
ClosureArgumentReducer::class,
DateTimeArgumentReducer::class,
DateTimeZoneArgumentReducer::class,
SymphonyRequestArgumentReducer::class,
StringableArgumentReducer::class,
])
```
Reducers are executed from top to bottom. The first reducer which doesn't return an `UnReducedArgument` will be used. Always add the default reducers when you want to define your own reducer. Otherwise, a very rudimentary reduced argument value will be used.
#### Disabling stack frame arguments
If you don't want to send any arguments to Flare, you can turn off this behavior as such:
```php
// Where you registered your client...
$flare = Flare::make('YOUR-FLARE-API-KEY')
->registerFlareHandlers();
$flare->withStackFrameArguments(false);
```
#### Missing arguments?
- Make sure you've got the latest version of Flare / Ignition
- Check that `withStackFrameArguments` is not disabled
- Check your ini file whether `zend.exception_ignore_args` is enabled, it should be `0`
```php
use Spatie\FlareClient\Enums\MessageLevels;
// Get access to your registered Flare client instance
$flare->glow('This is a message from glow!', MessageLevels::DEBUG, func_get_args());
```
### Handling exceptions
When an exception is thrown in an application, the application stops executing and the exception is reported to Flare.
However, there are cases where you might want to handle the exception so that the application can continue running. And
the user isn't presented with an error message.
In such cases it might still be useful to report the exception to Flare, so you'll have a correct overview of what's
going on within your application. We call such exceptions "handled exceptions".
When you've caught an exception in PHP it can still be reported to Flare:
```php
try {
// Code that might throw an exception
} catch (Exception $exception) {
$flare->reportHandled($exception);
}
```
In Flare, we'll show that the exception was handled, it is possible to filter these exceptions. You'll find more about filtering exceptions [here](https://flareapp.io/docs/flare/general/searching-errors).
### Writing custom middleware
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.
Just like with the Flare client itself, you can add custom context information to your report as well. This allows you to structure your code so that you have all context related changes in one place.
You can register a custom middleware by using the `registerMiddleware` method on the `Spatie\FlareClient\Flare` class, like this:
```php
use Spatie\FlareClient\Report;
// Get access to your registered Flare client instance
$flare->registerMiddleware(function (Report $report, $next) {
// Add custom information to the report
$report->context('key', 'value');
return $next($report);
});
```
To create a middleware that, for example, removes all the session data before your report gets sent to Flare, the middleware implementation might look like this:
```php
use Spatie\FlareClient\Report;
class FlareMiddleware
{
public function handle(Report $report, $next)
{
$context = $report->allContext();
$context['session'] = null;
$report->userProvidedContext($context);
return $next($report);
}
}
```
### Identifying users
When reporting an error to Flare, you can tell the Flare client, what information you have about the currently authenticated user. You can do this by providing a `user` group that holds all the information you want to share.
```php
$user = YourAuthenticatedUserInstance();
$flare->group('user', [
'email' => $user->email,
'name' => $user->name,
'additional_information' => $user->additional,
]);
```
### Customizing error grouping
Flare has a [special grouping](https://flareapp.io/docs/flare/general/error-grouping) algorithm that groups similar error occurrences into errors to make understanding what's going on in your application easier.
While the default grouping algorithm works for 99% of the cases, there are some cases where you might want to customize the grouping.
This can be done on an exception class base, you can tell Flare to group all exceptions of a specific class together:
```php
use Spatie\FlareClient\Enums\OverriddenGrouping;
$flare->overrideGrouping(SomeExceptionClass::class, OverriddenGrouping::ExceptionClass);
```
In this case every exception of the `SomeExceptionClass` will be grouped together no matter what the message or stack trace is.
It is also possible to group exceptions of the same class together, but also take the message into account:
```php
use Spatie\FlareClient\Enums\OverriddenGrouping;
$flare->overrideGrouping(SomeExceptionClass::class, OverriddenGrouping::ExceptionMessageAndClass);
```
Be careful when grouping by class and message, since every occurrence might have a slightly different message, this could lead to a lot of different errors.
## 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.

63
vendor/spatie/flare-client-php/composer.json vendored Executable file
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|^12.0",
"spatie/backtrace": "^1.6.1",
"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/pest-plugin-snapshots": "^1.0|^2.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"
}
}
}

86
vendor/spatie/flare-client-php/src/Api.php vendored Executable file
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,174 @@
<?php
namespace Spatie\FlareClient\Context;
use RuntimeException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\InputBag;
use Symfony\Component\HttpFoundation\ParameterBag;
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->getInputBag()->all() + $this->request->query->all(),
'files' => $this->getFiles(),
];
}
protected function getInputBag(): InputBag|ParameterBag
{
$contentType = $this->request->headers->get('CONTENT_TYPE', 'text/html');
$isJson = str_contains($contentType, '/json') || str_contains($contentType, '+json');
if ($isJson) {
return new InputBag((array) json_decode($this->request->getContent(), true));
}
return in_array($this->request->getMethod(), ['GET', 'HEAD'])
? $this->request->query
: $this->request->request;
}
/** @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,10 @@
<?php
namespace Spatie\FlareClient\Enums;
class OverriddenGrouping
{
const ExceptionClass = 'exception_class';
const ExceptionMessage = 'exception_message';
const ExceptionMessageAndClass = 'exception_message_and_class';
}

494
vendor/spatie/flare-client-php/src/Flare.php vendored Executable file
View File

@@ -0,0 +1,494 @@
<?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\Enums\OverriddenGrouping;
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 Spatie\FlareClient\Support\PhpStackFrameArgumentsFixer;
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 mixed $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;
/** @var array<class-string, string> */
protected array $overriddenGroupings = [];
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,
bool $forcePHPIniSetting = false,
): self {
$this->withStackFrameArguments = $withStackFrameArguments;
if ($forcePHPIniSetting) {
(new PhpStackFrameArgumentsFixer())->enable();
}
return $this;
}
/**
* @param class-string $exceptionClass
*/
public function overrideGrouping(
string $exceptionClass,
string $type = OverriddenGrouping::ExceptionMessageAndClass,
): self {
$this->overriddenGroupings[$exceptionClass] = $type;
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
{
$this->previousExceptionHandler = set_exception_handler([$this, 'handleException']);
return $this;
}
public function registerErrorHandler(?int $errorLevels = null): self
{
$this->previousErrorHandler = $errorLevels
? set_error_handler([$this, 'handleError'], $errorLevels)
: 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,
$code,
$message,
$file,
$line
);
}
}
public function applicationPath(string $applicationPath): self
{
$this->applicationPath = $applicationPath;
return $this;
}
public function report(Throwable $throwable, ?callable $callback = null, ?Report $report = null, ?bool $handled = null): ?Report
{
if (! $this->shouldSendReport($throwable)) {
return null;
}
$report ??= $this->createReport($throwable);
if ($handled) {
$report->handled();
}
if (! is_null($callback)) {
call_user_func($callback, $report);
}
$this->recorder->reset();
$this->sendReportToApi($report);
return $report;
}
public function reportHandled(Throwable $throwable): ?Report
{
return $this->report($throwable, null, null, true);
}
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,
$this->overriddenGroupings,
);
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,31 @@
<?php
namespace Spatie\FlareClient\FlareMiddleware;
use Closure;
use Spatie\ErrorSolutions\Contracts\SolutionProviderRepository;
use Spatie\FlareClient\Report;
use Spatie\Ignition\Contracts\SolutionProviderRepository as IgnitionSolutionProviderRepository;
class AddSolutions implements FlareMiddleware
{
protected SolutionProviderRepository|IgnitionSolutionProviderRepository $solutionProviderRepository;
public function __construct(SolutionProviderRepository|IgnitionSolutionProviderRepository $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);
}
}

32
vendor/spatie/flare-client-php/src/Frame.php vendored Executable file
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'];
}
}

432
vendor/spatie/flare-client-php/src/Report.php vendored Executable file
View File

@@ -0,0 +1,432 @@
<?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\ErrorSolutions\Contracts\Solution;
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 as IgnitionSolution;
use Spatie\LaravelFlare\Exceptions\ViewException;
use Spatie\LaravelIgnition\Exceptions\ViewException as IgnitionViewException;
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;
protected ?bool $handled = null;
protected ?string $overriddenGrouping = null;
/**
* @param array<class-string<ArgumentReducer>|ArgumentReducer>|ArgumentReducers|null $argumentReducers
* @param array<class-string, string> $overriddenGroupings
*/
public static function createForThrowable(
Throwable $throwable,
ContextProvider $context,
?string $applicationPath = null,
?string $version = null,
null|array|ArgumentReducers $argumentReducers = null,
bool $withStackTraceArguments = true,
array $overriddenGroupings = [],
): self {
$stacktrace = Backtrace::createForThrowable($throwable)
->withArguments($withStackTraceArguments)
->reduceArguments($argumentReducers)
->applicationPath($applicationPath ?? '');
$exceptionClass = self::getClassForThrowable($throwable);
$report = (new self())
->setApplicationPath($applicationPath)
->throwable($throwable)
->useContext($context)
->exceptionClass($exceptionClass)
->message($throwable->getMessage())
->stackTrace($stacktrace)
->exceptionContext($throwable)
->setApplicationVersion($version);
if (array_key_exists($exceptionClass, $overriddenGroupings)) {
$report->overriddenGrouping($overriddenGroupings[$exceptionClass]);
}
return $report;
}
protected static function getClassForThrowable(Throwable $throwable): string
{
/** @phpstan-ignore-next-line */
if ($throwable::class === IgnitionViewException::class || $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|IgnitionSolution $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);
}
public function handled(?bool $handled = true): self
{
$this->handled = $handled;
return $this;
}
public function overriddenGrouping(?string $overriddenGrouping): self
{
$this->overriddenGrouping = $overriddenGrouping;
return $this;
}
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,
'handled' => $this->handled,
'overridden_grouping' => $this->overriddenGrouping,
];
}
/*
* 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,42 @@
<?php
namespace Spatie\FlareClient\Solutions;
use Spatie\ErrorSolutions\Contracts\RunnableSolution;
use Spatie\ErrorSolutions\Contracts\Solution;
use Spatie\Ignition\Contracts\RunnableSolution as IgnitionRunnableSolution;
use Spatie\Ignition\Contracts\Solution as IgnitionSolution;
class ReportSolution
{
protected Solution|IgnitionSolution $solution;
public function __construct(Solution|IgnitionSolution $solution)
{
$this->solution = $solution;
}
public static function fromSolution(Solution|IgnitionSolution $solution): self
{
return new self($solution);
}
/**
* @return array<string, mixed>
*/
public function toArray(): array
{
$isRunnable = ($this->solution instanceof RunnableSolution || $this->solution instanceof IgnitionRunnableSolution);
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,24 @@
<?php
namespace Spatie\FlareClient\Support;
class PhpStackFrameArgumentsFixer
{
public function enable(): void
{
if (! $this->isCurrentlyIgnoringStackFrameArguments()) {
return;
}
ini_set('zend.exception_ignore_args', '0');
}
protected function isCurrentlyIgnoringStackFrameArguments(): bool
{
return match (ini_get('zend.exception_ignore_args')) {
'1' => true,
'0' => false,
default => 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;
}

65
vendor/spatie/flare-client-php/src/View.php vendored Executable file
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;
}
}