From ab0cef4031a438e43e984133b90eb2f66bd41ca7 Mon Sep 17 00:00:00 2001 From: Freek Van der Herten Date: Wed, 12 Jun 2024 14:46:48 +0200 Subject: [PATCH] add DiscoverSolutionProviders --- phpunit.xml.dist | 7 -- src/DiscoverSolutionProviders.php | 85 +++++++++++++++++++++++++ tests/DiscoverSolutionProvidersTest.php | 20 ++++++ 3 files changed, 105 insertions(+), 7 deletions(-) create mode 100644 src/DiscoverSolutionProviders.php create mode 100644 tests/DiscoverSolutionProvidersTest.php diff --git a/phpunit.xml.dist b/phpunit.xml.dist index 6a137c1..b3678bf 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -20,13 +20,6 @@ tests - - - - - - - diff --git a/src/DiscoverSolutionProviders.php b/src/DiscoverSolutionProviders.php new file mode 100644 index 0000000..33ebf0f --- /dev/null +++ b/src/DiscoverSolutionProviders.php @@ -0,0 +1,85 @@ + 'SolutionProviders/OpenAi', + 'php' => 'SolutionProviders', + 'laravel' => 'SolutionProviders/Laravel' + ]; + + /** @return arrayget(); + } + + /** + * @param array $types + */ + public function __construct(protected array $types) + { + + } + + /** @return arraytypes as $type) { + $providers = array_merge($providers, $this->getProviderClassesForType($type)); + } + + return $providers; + } + + protected function getProviderClassesForType(string $type): array + { + $relativePath = $this->config[$type] ?? null; + + if (! $relativePath) { + return []; + } + + $namespace = $this->getNamespaceForPath($relativePath); + + $globPattern = __DIR__ . '/' . $relativePath . '/*.php'; + + $files = glob($globPattern); + + if (!$files) { + return []; + } + + $solutionProviders = array_map(function (string $solutionProviderFilePath) use ($namespace) { + $fileName = pathinfo($solutionProviderFilePath, PATHINFO_FILENAME); + + $fqcn = $namespace . '\\' . $fileName; + + $validClass = in_array(HasSolutionsForThrowable::class, class_implements($fqcn) ?: []); + + return $validClass ? $fqcn : null; + }, $files); + + return array_values(array_filter($solutionProviders)); + } + + protected function getNamespaceForPath(string $relativePath): string + { + $namespacePath = str_replace('/', '\\', $relativePath); + + $namespace = 'Spatie\\ErrorSolutions\\' . $namespacePath; + + return $namespace; + + } +} diff --git a/tests/DiscoverSolutionProvidersTest.php b/tests/DiscoverSolutionProvidersTest.php new file mode 100644 index 0000000..54c9a74 --- /dev/null +++ b/tests/DiscoverSolutionProvidersTest.php @@ -0,0 +1,20 @@ +not()->toBeEmpty() + ->toImplement(HasSolutionsForThrowable::class); +}); + +it('will discover more solution providers for more types', function() { + $phpProviders = DiscoverSolutionProviders::for(['php']); + + $laravelProviders = DiscoverSolutionProviders::for(['php', 'laravel']); + + expect(count($laravelProviders))->toBeGreaterThan(count($phpProviders)); +});