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/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());
}
}

View File

@@ -0,0 +1,74 @@
<?php
namespace Spatie\Ignition\Solutions\SolutionProviders;
use Illuminate\Support\Str;
use ParseError;
use Spatie\Ignition\Contracts\BaseSolution;
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
use Throwable;
class MergeConflictSolutionProvider implements HasSolutionsForThrowable
{
public function canSolve(Throwable $throwable): bool
{
if (! ($throwable instanceof ParseError)) {
return false;
}
if (! $this->hasMergeConflictExceptionMessage($throwable)) {
return false;
}
$file = (string)file_get_contents($throwable->getFile());
if (! str_contains($file, '=======')) {
return false;
}
if (! str_contains($file, '>>>>>>>')) {
return false;
}
return true;
}
public function getSolutions(Throwable $throwable): array
{
$file = (string)file_get_contents($throwable->getFile());
preg_match('/\>\>\>\>\>\>\> (.*?)\n/', $file, $matches);
$source = $matches[1];
$target = $this->getCurrentBranch(basename($throwable->getFile()));
return [
BaseSolution::create("Merge conflict from branch '$source' into $target")
->setSolutionDescription('You have a Git merge conflict. To undo your merge do `git reset --hard HEAD`'),
];
}
protected function getCurrentBranch(string $directory): string
{
$branch = "'".trim((string)shell_exec("cd {$directory}; git branch | grep \\* | cut -d ' ' -f2"))."'";
if ($branch === "''") {
$branch = 'current branch';
}
return $branch;
}
protected function hasMergeConflictExceptionMessage(Throwable $throwable): bool
{
// For PHP 7.x and below
if (Str::startsWith($throwable->getMessage(), 'syntax error, unexpected \'<<\'')) {
return true;
}
// For PHP 8+
if (Str::startsWith($throwable->getMessage(), 'syntax error, unexpected token "<<"')) {
return true;
}
return false;
}
}

View File

@@ -0,0 +1,101 @@
<?php
namespace Spatie\Ignition\Solutions\SolutionProviders;
use Illuminate\Support\Collection;
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
use Spatie\Ignition\Contracts\ProvidesSolution;
use Spatie\Ignition\Contracts\Solution;
use Spatie\Ignition\Contracts\SolutionProviderRepository as SolutionProviderRepositoryContract;
use Throwable;
class SolutionProviderRepository implements SolutionProviderRepositoryContract
{
/** @var Collection<int, class-string<HasSolutionsForThrowable>|HasSolutionsForThrowable> */
protected Collection $solutionProviders;
/** @param array<int, class-string<HasSolutionsForThrowable>|HasSolutionsForThrowable> $solutionProviders */
public function __construct(array $solutionProviders = [])
{
$this->solutionProviders = Collection::make($solutionProviders);
}
public function registerSolutionProvider(string|HasSolutionsForThrowable $solutionProvider): SolutionProviderRepositoryContract
{
$this->solutionProviders->push($solutionProvider);
return $this;
}
public function registerSolutionProviders(array $solutionProviderClasses): SolutionProviderRepositoryContract
{
$this->solutionProviders = $this->solutionProviders->merge($solutionProviderClasses);
return $this;
}
public function getSolutionsForThrowable(Throwable $throwable): array
{
$solutions = [];
if ($throwable instanceof Solution) {
$solutions[] = $throwable;
}
if ($throwable instanceof ProvidesSolution) {
$solutions[] = $throwable->getSolution();
}
$providedSolutions = $this
->initialiseSolutionProviderRepositories()
->filter(function (HasSolutionsForThrowable $solutionProvider) use ($throwable) {
try {
return $solutionProvider->canSolve($throwable);
} catch (Throwable $exception) {
return false;
}
})
->map(function (HasSolutionsForThrowable $solutionProvider) use ($throwable) {
try {
return $solutionProvider->getSolutions($throwable);
} catch (Throwable $exception) {
return [];
}
})
->flatten()
->toArray();
return array_merge($solutions, $providedSolutions);
}
public function getSolutionForClass(string $solutionClass): ?Solution
{
if (! class_exists($solutionClass)) {
return null;
}
if (! in_array(Solution::class, class_implements($solutionClass) ?: [])) {
return null;
}
if (! function_exists('app')) {
return null;
}
return app($solutionClass);
}
/** @return Collection<int, HasSolutionsForThrowable> */
protected function initialiseSolutionProviderRepositories(): Collection
{
return $this->solutionProviders
->filter(fn (HasSolutionsForThrowable|string $provider) => in_array(HasSolutionsForThrowable::class, class_implements($provider) ?: []))
->map(function (string|HasSolutionsForThrowable $provider): HasSolutionsForThrowable {
if (is_string($provider)) {
return new $provider;
}
return $provider;
});
}
}

View File

@@ -0,0 +1,121 @@
<?php
namespace Spatie\Ignition\Solutions\SolutionProviders;
use ErrorException;
use Illuminate\Support\Collection;
use ReflectionClass;
use ReflectionProperty;
use Spatie\Ignition\Contracts\BaseSolution;
use Spatie\Ignition\Contracts\HasSolutionsForThrowable;
use Throwable;
class UndefinedPropertySolutionProvider implements HasSolutionsForThrowable
{
protected const REGEX = '/([a-zA-Z\\\\]+)::\$([a-zA-Z]+)/m';
protected const MINIMUM_SIMILARITY = 80;
public function canSolve(Throwable $throwable): bool
{
if (! $throwable instanceof ErrorException) {
return false;
}
if (is_null($this->getClassAndPropertyFromExceptionMessage($throwable->getMessage()))) {
return false;
}
if (! $this->similarPropertyExists($throwable)) {
return false;
}
return true;
}
public function getSolutions(Throwable $throwable): array
{
return [
BaseSolution::create('Unknown Property')
->setSolutionDescription($this->getSolutionDescription($throwable)),
];
}
public function getSolutionDescription(Throwable $throwable): string
{
if (! $this->canSolve($throwable) || ! $this->similarPropertyExists($throwable)) {
return '';
}
extract(
/** @phpstan-ignore-next-line */
$this->getClassAndPropertyFromExceptionMessage($throwable->getMessage()),
EXTR_OVERWRITE,
);
$possibleProperty = $this->findPossibleProperty($class ?? '', $property ?? '');
$class = $class ?? '';
return "Did you mean {$class}::\${$possibleProperty->name} ?";
}
protected function similarPropertyExists(Throwable $throwable): bool
{
/** @phpstan-ignore-next-line */
extract($this->getClassAndPropertyFromExceptionMessage($throwable->getMessage()), EXTR_OVERWRITE);
$possibleProperty = $this->findPossibleProperty($class ?? '', $property ?? '');
return $possibleProperty !== null;
}
/**
* @param string $message
*
* @return null|array<string, string>
*/
protected function getClassAndPropertyFromExceptionMessage(string $message): ?array
{
if (! preg_match(self::REGEX, $message, $matches)) {
return null;
}
return [
'class' => $matches[1],
'property' => $matches[2],
];
}
/**
* @param class-string $class
* @param string $invalidPropertyName
*
* @return mixed
*/
protected function findPossibleProperty(string $class, string $invalidPropertyName): mixed
{
return $this->getAvailableProperties($class)
->sortByDesc(function (ReflectionProperty $property) use ($invalidPropertyName) {
similar_text($invalidPropertyName, $property->name, $percentage);
return $percentage;
})
->filter(function (ReflectionProperty $property) use ($invalidPropertyName) {
similar_text($invalidPropertyName, $property->name, $percentage);
return $percentage >= self::MINIMUM_SIMILARITY;
})->first();
}
/**
* @param class-string $class
*
* @return Collection<int, ReflectionProperty>
*/
protected function getAvailableProperties(string $class): Collection
{
$class = new ReflectionClass($class);
return Collection::make($class->getProperties());
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Spatie\Ignition\Solutions;
use Illuminate\Contracts\Support\Arrayable;
use Spatie\Ignition\Contracts\Solution;
/** @implements Arrayable<string, array<string,string>|string|false> */
class SolutionTransformer implements Arrayable
{
protected Solution $solution;
public function __construct(Solution $solution)
{
$this->solution = $solution;
}
/** @return array<string, array<string,string>|string|false> */
public function toArray(): array
{
return [
'class' => get_class($this->solution),
'title' => $this->solution->getSolutionTitle(),
'links' => $this->solution->getDocumentationLinks(),
'description' => $this->solution->getSolutionDescription(),
'is_runnable' => false,
'ai_generated' => $this->solution->aiGenerated ?? false,
];
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace Spatie\Ignition\Solutions;
use Spatie\Ignition\Contracts\Solution;
class SuggestCorrectVariableNameSolution implements Solution
{
protected ?string $variableName;
protected ?string $viewFile;
protected ?string $suggested;
public function __construct(string $variableName = null, string $viewFile = null, string $suggested = null)
{
$this->variableName = $variableName;
$this->viewFile = $viewFile;
$this->suggested = $suggested;
}
public function getSolutionTitle(): string
{
return 'Possible typo $'.$this->variableName;
}
public function getDocumentationLinks(): array
{
return [];
}
public function getSolutionDescription(): string
{
return "Did you mean `$$this->suggested`?";
}
public function isRunnable(): bool
{
return false;
}
}

View File

@@ -0,0 +1,30 @@
<?php
namespace Spatie\Ignition\Solutions;
use Spatie\Ignition\Contracts\Solution;
class SuggestImportSolution implements Solution
{
protected string $class;
public function __construct(string $class)
{
$this->class = $class;
}
public function getSolutionTitle(): string
{
return 'A class import is missing';
}
public function getSolutionDescription(): string
{
return 'You have a missing class import. Try importing this class: `'.$this->class.'`.';
}
public function getDocumentationLinks(): array
{
return [];
}
}