From 7d320b6301be311a81c46580a705fc66539327ca Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Wed, 18 Nov 2026 08:34:48 -0500 Subject: [PATCH 1/9] feat: package discovery --- CHANGELOG.md | 6 + src/App.php | 19 +- src/Console/Commands/PackageDiscover.php | 33 +++ src/Console/Commands/VendorPublish.php | 142 +++++++++++++ src/Console/CommandsServiceProvider.php | 4 + src/Console/Phenix.php | 2 +- src/Database/Console/DatabaseCommand.php | 11 +- src/Packages/ComposerScripts.php | 19 ++ src/Packages/PackageManifest.php | 189 ++++++++++++++++++ src/Packages/PackageRegistry.php | 95 +++++++++ src/Providers/ServiceProvider.php | 54 +++++ src/Testing/Concerns/RefreshDatabase.php | 10 +- src/Translation/Translator.php | 51 ++++- src/Util/Path.php | 13 ++ src/Views/TemplateCache.php | 9 +- src/Views/TemplateEngine.php | 4 +- src/Views/ViewsConfig.php | 69 +++++++ .../Console/PackageDiscoverCommandTest.php | 20 ++ .../Unit/Console/VendorPublishCommandTest.php | 36 ++++ tests/Unit/Packages/PackageManifestTest.php | 66 ++++++ tests/Unit/Packages/PackageRegistryTest.php | 21 ++ tests/Unit/Translation/TranslatorTest.php | 22 ++ tests/Unit/Views/TemplateEngineTest.php | 21 ++ .../storage/framework/testing/.gitignore | 2 + 24 files changed, 899 insertions(+), 19 deletions(-) create mode 100644 src/Console/Commands/PackageDiscover.php create mode 100644 src/Console/Commands/VendorPublish.php create mode 100644 src/Packages/ComposerScripts.php create mode 100644 src/Packages/PackageManifest.php create mode 100644 src/Packages/PackageRegistry.php create mode 100644 src/Util/Path.php create mode 100644 tests/Unit/Console/PackageDiscoverCommandTest.php create mode 100644 tests/Unit/Console/VendorPublishCommandTest.php create mode 100644 tests/Unit/Packages/PackageManifestTest.php create mode 100644 tests/Unit/Packages/PackageRegistryTest.php create mode 100644 tests/fixtures/application/storage/framework/testing/.gitignore diff --git a/CHANGELOG.md b/CHANGELOG.md index b6b3451c..ca5b51a6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- Composer package discovery through `extra.phenix` metadata. +- Package resource registration and the `package:discover` and `vendor:publish` commands. +- Namespaced package views, translations, and package migration paths. + # Release Notes for 0.9.x ## [v0.10.1 (2026-10-07)](https://github.com/phenixphp/framework/compare/0.10.0...0.10.1) diff --git a/src/App.php b/src/App.php index bf73ef1e..e69a1af3 100644 --- a/src/App.php +++ b/src/App.php @@ -39,6 +39,9 @@ use Phenix\Http\ErrorHandler as AppErrorHandler; use Phenix\Http\ExceptionHandler as AppExceptionHandler; use Phenix\Logging\LoggerFactory; +use Phenix\Packages\PackageManifest; +use Phenix\Packages\PackageRegistry; +use Phenix\Providers\ServiceProvider; use Phenix\Runtime\Log; use Phenix\Session\SessionMiddlewareFactory; @@ -47,6 +50,7 @@ use function count; use function extension_loaded; use function is_array; +use function is_string; class App implements AppContract, Makeable { @@ -97,12 +101,25 @@ public function setup(): void self::$container->add(HttpClient::class); self::$container->add(HttpClientTestLogger::class)->setShared(true); + $manifest = new PackageManifest(self::$path); + self::$container->add(PackageManifest::class, $manifest)->setShared(true); + self::$container->add(PackageRegistry::class)->setShared(true); + self::$container->add(Phenix::class)->addMethodCall('registerCommands'); /** @var array $providers */ - $providers = Config::get('app.providers', []); + $providers = array_values(array_unique([ + ...Config::get('app.providers', []), + ...$manifest->providers(), + ])); foreach ($providers as $provider) { + if (! is_string($provider) || ! class_exists($provider) || ! is_subclass_of($provider, ServiceProvider::class)) { + $providerName = is_string($provider) ? $provider : get_debug_type($provider); + + throw new RuntimeError("Service provider {$providerName} is invalid."); + } + self::$container->addServiceProvider(new $provider()); } diff --git a/src/Console/Commands/PackageDiscover.php b/src/Console/Commands/PackageDiscover.php new file mode 100644 index 00000000..a96e99d8 --- /dev/null +++ b/src/Console/Commands/PackageDiscover.php @@ -0,0 +1,33 @@ +build(); + + $output->writeln('Discovered packages:'); + + foreach ($manifest->packages() as $package) { + $output->writeln(" {$package}"); + } + + return Command::SUCCESS; + } +} diff --git a/src/Console/Commands/VendorPublish.php b/src/Console/Commands/VendorPublish.php new file mode 100644 index 00000000..4b27d588 --- /dev/null +++ b/src/Console/Commands/VendorPublish.php @@ -0,0 +1,142 @@ +addOption('provider', null, InputOption::VALUE_REQUIRED, 'Service provider to publish.'); + $this->addOption('tag', null, InputOption::VALUE_REQUIRED, 'Resource tag to publish.'); + $this->addOption('all', null, InputOption::VALUE_NONE, 'Publish resources from all providers.'); + $this->addOption('force', 'f', InputOption::VALUE_NONE, 'Overwrite existing files.'); + } + + protected function execute(InputInterface $input, OutputInterface $output): int + { + /** @var PackageRegistry $registry */ + $registry = App::make(PackageRegistry::class); + $provider = $input->getOption('provider'); + $tag = $input->getOption('tag'); + + if (! $input->getOption('all') && $provider === null && $tag === null) { + $output->writeln('Specify --provider, --tag, or --all.'); + + return Command::FAILURE; + } + + $paths = $registry->pathsToPublish( + is_string($provider) ? $provider : null, + is_string($tag) ? $tag : null, + ); + + if ($paths === []) { + $output->writeln('No publishable resources were found.'); + + return Command::SUCCESS; + } + + $status = Command::SUCCESS; + + foreach ($paths as $source => $destination) { + try { + $published = $this->publish( + (string) $source, + (string) $destination, + (bool) $input->getOption('force'), + ); + $status = $published > 0 ? 'Published:' : 'Skipped:'; + $output->writeln("{$status} {$source} → {$destination}"); + } catch (Throwable $exception) { + $output->writeln('' . $exception->getMessage() . ''); + + $status = Command::FAILURE; + } + } + + return $status; + } + + private function publish(string $source, string $destination, bool $force): int + { + if (is_file($source)) { + return $this->copyFile($source, $this->migrationDestination($source, $destination), $force) ? 1 : 0; + } + + if (! is_dir($source)) { + throw new RuntimeError("Publish source {$source} does not exist."); + } + + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($source, FilesystemIterator::SKIP_DOTS), + ); + $published = 0; + + foreach ($iterator as $file) { + if (! $file->isFile()) { + continue; + } + + $relative = substr($file->getPathname(), strlen($source) + 1); + $target = Path::join(rtrim($destination, DIRECTORY_SEPARATOR), $relative); + + if ($this->copyFile($file->getPathname(), $this->migrationDestination($file->getPathname(), $target), $force)) { + $published++; + } + } + + return $published; + } + + private function copyFile(string $source, string $destination, bool $force): bool + { + if (is_file($destination) && ! $force) { + return false; + } + + $directory = dirname($destination); + + if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) { + throw new RuntimeError("Unable to create publish directory {$directory}."); + } + + if (! copy($source, $destination)) { + throw new RuntimeError("Unable to publish {$source} to {$destination}."); + } + + return true; + } + + private function migrationDestination(string $source, string $destination): string + { + $name = basename($destination); + + if (! str_contains(str_replace('\\', '/', $source), '/migrations/') + || preg_match('/^\d{14}_/', $name) !== 1) { + return $destination; + } + + return Path::join(dirname($destination), date('YmdHis') . '_' . substr($name, 15)); + } +} diff --git a/src/Console/CommandsServiceProvider.php b/src/Console/CommandsServiceProvider.php index 4a7c8d73..320d5435 100644 --- a/src/Console/CommandsServiceProvider.php +++ b/src/Console/CommandsServiceProvider.php @@ -13,6 +13,8 @@ use Phenix\Console\Commands\MakeRequest; use Phenix\Console\Commands\MakeServiceProvider; use Phenix\Console\Commands\MakeTest; +use Phenix\Console\Commands\PackageDiscover; +use Phenix\Console\Commands\VendorPublish; use Phenix\Console\Commands\ViewCache; use Phenix\Console\Commands\ViewClear; use Phenix\Providers\ServiceProvider; @@ -33,6 +35,8 @@ public function boot(): void GenerateKey::class, ViewClear::class, ViewCache::class, + PackageDiscover::class, + VendorPublish::class, ]); } } diff --git a/src/Console/Phenix.php b/src/Console/Phenix.php index d1c4e20f..6e7f24ec 100644 --- a/src/Console/Phenix.php +++ b/src/Console/Phenix.php @@ -8,7 +8,7 @@ class Phenix extends Application { - private static array $commands; + private static array $commands = []; public function __construct() { diff --git a/src/Database/Console/DatabaseCommand.php b/src/Database/Console/DatabaseCommand.php index e88a48b1..0a449b6c 100644 --- a/src/Database/Console/DatabaseCommand.php +++ b/src/Database/Console/DatabaseCommand.php @@ -4,8 +4,10 @@ namespace Phenix\Database\Console; +use Phenix\App; use Phenix\Database\Constants\Driver; use Phenix\Facades\Config; +use Phenix\Packages\PackageRegistry; use Phinx\Config\Config as MigrationConfig; use Phinx\Console\Command\AbstractCommand; use Symfony\Component\Console\Input\InputOption; @@ -33,9 +35,16 @@ public function __construct() $environment['suffix'] = ''; } + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $migrationPaths = array_values(array_unique([ + ...(array) Config::get('database.paths.migrations'), + ...$packages->migrationPaths(), + ])); + $this->config = new MigrationConfig([ 'paths' => [ - 'migrations' => Config::get('database.paths.migrations'), + 'migrations' => $migrationPaths, 'seeds' => Config::get('database.paths.seeds'), ], 'environments' => [ diff --git a/src/Packages/ComposerScripts.php b/src/Packages/ComposerScripts.php new file mode 100644 index 00000000..5f1dfa22 --- /dev/null +++ b/src/Packages/ComposerScripts.php @@ -0,0 +1,19 @@ +manifestPath ??= Path::join($basePath, 'storage', 'framework', 'cache', 'packages.php'); + $this->vendorPath ??= getenv('COMPOSER_VENDOR_DIR') ?: Path::join($basePath, 'vendor'); + } + + public function providers(): array + { + $providers = []; + + foreach ($this->getManifest() as $configuration) { + foreach ((array) ($configuration['providers'] ?? []) as $provider) { + if (is_string($provider) && $provider !== '') { + $providers[] = $provider; + } + } + } + + return array_values(array_unique($providers)); + } + + public function packages(): array + { + return array_keys($this->getManifest()); + } + + public function getManifest(): array + { + if ($this->manifest !== null) { + return $this->manifest; + } + + if (! is_file($this->manifestPath)) { + $this->build(); + } + + if (! is_file($this->manifestPath)) { + return $this->manifest = []; + } + + $manifest = require $this->manifestPath; + + return $this->manifest = is_array($manifest) ? $manifest : []; + } + + public function build(): void + { + $packages = $this->installedPackages(); + $ignored = $this->packagesToIgnore(); + $ignoreAll = in_array('*', $ignored, true); + $manifest = []; + + foreach ($packages as $package) { + if (! is_array($package) || ! isset($package['name']) || ! is_string($package['name'])) { + continue; + } + + $configuration = $package['extra']['phenix'] ?? []; + + if (! is_array($configuration)) { + continue; + } + + foreach ((array) ($configuration['dont-discover'] ?? []) as $packageToIgnore) { + if (is_string($packageToIgnore)) { + $ignored[] = $packageToIgnore; + } + } + + if ($configuration !== []) { + $manifest[$package['name']] = $configuration; + } + } + + $manifest = array_filter( + $manifest, + static fn (string $package): bool => ! $ignoreAll && ! in_array($package, $ignored, true), + ARRAY_FILTER_USE_KEY, + ); + + $this->write($manifest); + $this->manifest = $manifest; + } + + public function clear(): void + { + $this->manifest = null; + + if (is_file($this->manifestPath)) { + unlink($this->manifestPath); + } + } + + public function path(): string + { + return $this->manifestPath; + } + + private function installedPackages(): array + { + $path = Path::join($this->vendorPath, 'composer', 'installed.json'); + + if (! is_file($path)) { + return []; + } + + try { + $installed = json_decode((string) file_get_contents($path), true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException $exception) { + throw new RuntimeError("Unable to read Composer package metadata at {$path}.", 0, $exception); + } + + if (! is_array($installed)) { + return []; + } + + $packages = $installed['packages'] ?? $installed; + + return is_array($packages) ? $packages : []; + } + + private function packagesToIgnore(): array + { + $path = Path::join($this->basePath, 'composer.json'); + + if (! is_file($path)) { + return []; + } + + try { + $composer = json_decode((string) file_get_contents($path), true, flags: JSON_THROW_ON_ERROR); + } catch (JsonException $exception) { + throw new RuntimeError("Unable to read the application Composer file at {$path}.", 0, $exception); + } + + $ignored = $composer['extra']['phenix']['dont-discover'] ?? []; + + return is_array($ignored) ? $ignored : []; + } + + private function write(array $manifest): void + { + $directory = dirname($this->manifestPath); + + if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) { + throw new RuntimeError("The package cache directory {$directory} could not be created."); + } + + if (! is_writable($directory)) { + throw new RuntimeError("The package cache directory {$directory} must be writable."); + } + + $temporaryPath = tempnam($directory, 'packages-'); + + if ($temporaryPath === false) { + throw new RuntimeError("Unable to create a temporary package manifest in {$directory}."); + } + + $contents = 'manifestPath)) { + @unlink($temporaryPath); + + throw new RuntimeError("Unable to write the package manifest at {$this->manifestPath}."); + } + } +} diff --git a/src/Packages/PackageRegistry.php b/src/Packages/PackageRegistry.php new file mode 100644 index 00000000..98378e3a --- /dev/null +++ b/src/Packages/PackageRegistry.php @@ -0,0 +1,95 @@ +migrationPaths = array_values(array_unique([...$this->migrationPaths, ...(array) $paths])); + } + + public function migrationPaths(): array + { + return $this->migrationPaths; + } + + public function addViewPaths(array|string $paths, string $namespace): void + { + $this->viewPaths[$namespace] = array_values(array_unique([ + ...($this->viewPaths[$namespace] ?? []), + ...(array) $paths, + ])); + } + + public function viewPaths(string $namespace): array + { + return $this->viewPaths[$namespace] ?? []; + } + + public function addTranslationPath(string $path, string $namespace): void + { + $this->translationPaths[$namespace] = array_values(array_unique([ + ...($this->translationPaths[$namespace] ?? []), + $path, + ])); + } + + public function translationPaths(): array + { + return $this->translationPaths; + } + + public function addPublishPaths(string $provider, array $paths, array|string|null $groups = null): void + { + $this->publishes[$provider] = [...$this->publishes[$provider] ?? [], ...$paths]; + + foreach ((array) $groups as $group) { + $this->publishGroups[$group] = [...($this->publishGroups[$group] ?? []), ...$paths]; + } + } + + public function pathsToPublish(string|null $provider = null, string|null $group = null): array + { + if ($provider !== null && $group !== null) { + return array_intersect_key($this->publishes[$provider] ?? [], $this->publishGroups[$group] ?? []); + } + + if ($provider !== null) { + return $this->publishes[$provider] ?? []; + } + + return $group !== null + ? $this->publishGroups[$group] ?? [] + : $this->getPublishesPath(); + } + + public function publishableProviders(): array + { + return array_keys($this->publishes); + } + + public function publishableGroups(): array + { + return array_keys($this->publishGroups); + } + + protected function getPublishesPath(): array + { + $paths = $this->publishes ?: [[]]; + + return [...array_values($paths)]; + } +} diff --git a/src/Providers/ServiceProvider.php b/src/Providers/ServiceProvider.php index 77348f0d..747edb82 100644 --- a/src/Providers/ServiceProvider.php +++ b/src/Providers/ServiceProvider.php @@ -7,7 +7,13 @@ use League\Container\Definition\DefinitionInterface; use League\Container\ServiceProvider\AbstractServiceProvider; use League\Container\ServiceProvider\BootableServiceProviderInterface; +use Phenix\App; use Phenix\Console\Phenix; +use Phenix\Facades\Config; +use Phenix\Packages\PackageRegistry; + +use function in_array; +use function is_array; abstract class ServiceProvider extends AbstractServiceProvider implements BootableServiceProviderInterface { @@ -45,4 +51,52 @@ protected function commands(array|string $commands): void { Phenix::pushCommands((array) $commands); } + + protected function mergeConfigFrom(string $path, string $key): void + { + $defaults = require $path; + + if (! is_array($defaults)) { + return; + } + + Config::set($key, array_merge($defaults, (array) Config::get($key, []))); + } + + protected function loadRoutesFrom(string $path): void + { + if (is_file($path)) { + require $path; + } + } + + protected function loadMigrationsFrom(array|string $paths): void + { + $this->packages()->addMigrationPaths($paths); + } + + protected function loadViewsFrom(array|string $paths, string $namespace): void + { + $this->packages()->addViewPaths($paths, $namespace); + } + + protected function loadTranslationsFrom(string $path, string $namespace): void + { + $this->packages()->addTranslationPath($path, $namespace); + } + + protected function publishes(array $paths, array|string|null $groups = null): void + { + $this->packages()->addPublishPaths(static::class, $paths, $groups); + } + + protected function publishesMigrations(array $paths, array|string|null $groups = null): void + { + $this->publishes($paths, $groups); + } + + private function packages(): PackageRegistry + { + return App::make(PackageRegistry::class); + } } diff --git a/src/Testing/Concerns/RefreshDatabase.php b/src/Testing/Concerns/RefreshDatabase.php index 12b8010b..49a98501 100644 --- a/src/Testing/Concerns/RefreshDatabase.php +++ b/src/Testing/Concerns/RefreshDatabase.php @@ -9,6 +9,7 @@ use Phenix\Database\Constants\Connection; use Phenix\Database\Constants\Driver; use Phenix\Facades\Config; +use Phenix\Packages\PackageRegistry; use Phinx\Config\Config as MigrationConfig; use Phinx\Migration\Manager; use Symfony\Component\Console\Input\ArrayInput; @@ -56,9 +57,16 @@ protected function runMigrations(): void $environment['suffix'] = '.sqlite3'; } + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $migrationPaths = array_values(array_unique([ + ...(array) Config::get('database.paths.migrations'), + ...$packages->migrationPaths(), + ])); + $config = new MigrationConfig([ 'paths' => [ - 'migrations' => Config::get('database.paths.migrations'), + 'migrations' => $migrationPaths, 'seeds' => Config::get('database.paths.seeds'), ], 'environments' => [ diff --git a/src/Translation/Translator.php b/src/Translation/Translator.php index f435b8de..00cd47d1 100644 --- a/src/Translation/Translator.php +++ b/src/Translation/Translator.php @@ -6,10 +6,17 @@ use Adbar\Dot; use Countable; +use Phenix\App; use Phenix\Facades\Config; use Phenix\Facades\File; +use Phenix\Packages\PackageRegistry; +use Phenix\Util\Path; use Resend\Contracts\Stringable; +use function count; +use function is_array; +use function is_string; + class Translator { private Dot $catalogues; @@ -122,29 +129,57 @@ private function resolvePluralIndex(int $count, int $available): int private static function loadCatalogues(): array { $path = base_path('lang'); + $catalogues = []; - if (! File::exists($path)) { - return []; + if (File::exists($path)) { + self::loadPath($catalogues, $path); } - $catalogues = []; + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + + foreach ($packages->translationPaths() as $namespace => $paths) { + foreach ($paths as $translationPath) { + self::loadPath($catalogues, $translationPath, $namespace); + } + + $override = Path::join($path, 'vendor', $namespace); + if (File::exists($override)) { + self::loadPath($catalogues, $override, $namespace); + } + } + + return $catalogues; + } + + private static function loadPath(array &$catalogues, string $path, string|null $namespace = null): void + { foreach (File::listFiles($path, false) as $localeDir) { + if (! File::isDirectory($localeDir)) { + continue; + } + $locale = basename($localeDir); - $catalogues[$locale] = []; + $catalogues[$locale] ??= []; foreach (File::listFiles($localeDir) as $file) { - $group = basename($file, '.php'); + if (! File::isFile($file) || pathinfo($file, PATHINFO_EXTENSION) !== 'php') { + continue; + } + $group = basename($file, '.php'); + $key = $namespace === null ? $group : "{$namespace}::{$group}"; $data = require $file; if (is_array($data)) { - $catalogues[$locale][$group] = $data; + $catalogues[$locale][$key] = array_replace_recursive( + $catalogues[$locale][$key] ?? [], + $data, + ); } } } - - return $catalogues; } /** diff --git a/src/Util/Path.php b/src/Util/Path.php new file mode 100644 index 00000000..385449cc --- /dev/null +++ b/src/Util/Path.php @@ -0,0 +1,13 @@ +config->path(); + return $template === null ? $this->config->path() : $this->config->sourceBasePath($template); } public function getSourcePath(string $template): string { - return $this->config->path(ViewName::ensure($template)); + return $this->config->sourcePath($template); } public function getCacheFilePath(string $template): string { - return $this->config->compiledPath(Str::finish($template, '.php')); + return $this->config->cachePath($template); } public function isCached(string $template): bool diff --git a/src/Views/TemplateEngine.php b/src/Views/TemplateEngine.php index 25bd0855..0705663d 100644 --- a/src/Views/TemplateEngine.php +++ b/src/Views/TemplateEngine.php @@ -48,9 +48,9 @@ public function clearCache(): void public function compile(string $template): void { $filePath = realpath($this->cache->getSourcePath($template)); - $basePath = realpath($this->cache->getViewPath()); + $basePath = realpath($this->cache->getViewPath($template)); - if ($filePath === false || ! str_starts_with($filePath, $basePath)) { + if ($filePath === false || $basePath === false || ! str_starts_with($filePath, $basePath)) { throw new ViewNotFoundException("Template {$template} not found."); } diff --git a/src/Views/ViewsConfig.php b/src/Views/ViewsConfig.php index 88e8fb75..f0edb561 100644 --- a/src/Views/ViewsConfig.php +++ b/src/Views/ViewsConfig.php @@ -4,7 +4,10 @@ namespace Phenix\Views; +use Phenix\App; use Phenix\Facades\Config as Configuration; +use Phenix\Packages\PackageRegistry; +use Phenix\Util\Path; use Phenix\Util\Str; class ViewsConfig @@ -21,6 +24,41 @@ public function path(string|null $path = null): string return $this->buildPath($this->config['path'], $path); } + public function sourcePath(string $template): string + { + [$namespace, $name] = $this->parse($template); + $relativePath = ViewName::ensure($name); + + if ($namespace === null) { + return $this->path($relativePath); + } + + return $this->buildPath($this->resolveNamespacedBasePath($namespace, $relativePath), $relativePath); + } + + public function sourceBasePath(string $template): string + { + [$namespace, $name] = $this->parse($template); + + if ($namespace === null) { + return $this->path(); + } + + return $this->resolveNamespacedBasePath($namespace, ViewName::ensure($name)); + } + + public function cachePath(string $template): string + { + [$namespace, $name] = $this->parse($template); + $relativePath = Str::finish(str_replace([DIRECTORY_SEPARATOR, '/', '\\'], '.', $name), '.php'); + + if ($namespace !== null) { + $relativePath = "vendor.{$namespace}.{$relativePath}"; + } + + return $this->compiledPath($relativePath); + } + public function compiledPath(string|null $path = null): string { return $this->buildPath($this->config['compiled_path'], $path); @@ -32,4 +70,35 @@ private function buildPath(string $base, string|null $path = null): string return Str::finish($base, DIRECTORY_SEPARATOR) . $path; } + + private function resolveNamespacedBasePath(string $namespace, string $relativePath): string + { + $override = $this->path(Path::join('vendor', $namespace)); + + if (is_file($this->buildPath($override, $relativePath))) { + return $override; + } + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + + foreach ($packages->viewPaths($namespace) as $path) { + if (is_file($this->buildPath($path, $relativePath))) { + return $path; + } + } + + return $override; + } + + private function parse(string $template): array + { + if (! str_contains($template, '::')) { + return [null, $template]; + } + + [$namespace, $name] = explode('::', $template, 2); + + return [ViewName::clean($namespace), $name]; + } } diff --git a/tests/Unit/Console/PackageDiscoverCommandTest.php b/tests/Unit/Console/PackageDiscoverCommandTest.php new file mode 100644 index 00000000..aaf08ce8 --- /dev/null +++ b/tests/Unit/Console/PackageDiscoverCommandTest.php @@ -0,0 +1,20 @@ +phenix('package:discover'); + + $command->assertCommandIsSuccessful(); + + /** @var PackageManifest $manifest */ + $manifest = App::make(PackageManifest::class); + + expect($command->getDisplay())->toContain('Discovered packages:') + ->and($manifest->path())->toBeFile(); +}); diff --git a/tests/Unit/Console/VendorPublishCommandTest.php b/tests/Unit/Console/VendorPublishCommandTest.php new file mode 100644 index 00000000..387606a3 --- /dev/null +++ b/tests/Unit/Console/VendorPublishCommandTest.php @@ -0,0 +1,36 @@ +addPublishPaths('TestProvider', [$source => $destination], 'test-config'); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--tag' => 'test-config']); + + $command->assertCommandIsSuccessful(); + + expect($destination)->toBeFile() + ->and(file_get_contents($destination))->toBe('phenix('vendor:publish'); + + expect($command->getStatusCode())->toBe(1) + ->and($command->getDisplay())->toContain('Specify --provider, --tag, or --all.'); +}); diff --git a/tests/Unit/Packages/PackageManifestTest.php b/tests/Unit/Packages/PackageManifestTest.php new file mode 100644 index 00000000..9c8310f3 --- /dev/null +++ b/tests/Unit/Packages/PackageManifestTest.php @@ -0,0 +1,66 @@ +packageApp = base_path('storage/framework/testing/package-manifest-' . uniqid()); + + mkdir("{$this->packageApp}/vendor/composer", 0755, true); + mkdir("{$this->packageApp}/storage/framework/cache", 0755, true); +}); + +afterEach(function (): void { + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($this->packageApp, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST, + ); + + foreach ($iterator as $entry) { + $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + + rmdir($this->packageApp); +}); + +it('discovers providers from composer metadata', function (): void { + file_put_contents("{$this->packageApp}/composer.json", json_encode([ + 'extra' => ['phenix' => ['dont-discover' => []]], + ], JSON_THROW_ON_ERROR)); + + file_put_contents("{$this->packageApp}/vendor/composer/installed.json", json_encode([ + 'packages' => [ + [ + 'name' => 'acme/blog', + 'extra' => ['phenix' => ['providers' => ['Acme\\Blog\\BlogServiceProvider']]], + ], + ['name' => 'acme/plain'], + ], + ], JSON_THROW_ON_ERROR)); + + $manifest = new PackageManifest($this->packageApp); + $manifest->build(); + + expect($manifest->providers())->toBe(['Acme\\Blog\\BlogServiceProvider']) + ->and($manifest->packages())->toBe(['acme/blog']) + ->and($manifest->path())->toBeFile(); +}); + +it('honors application package discovery exclusions', function (): void { + file_put_contents("{$this->packageApp}/composer.json", json_encode([ + 'extra' => ['phenix' => ['dont-discover' => ['acme/blog']]], + ], JSON_THROW_ON_ERROR)); + + file_put_contents("{$this->packageApp}/vendor/composer/installed.json", json_encode([ + [ + 'name' => 'acme/blog', + 'extra' => ['phenix' => ['providers' => ['Acme\\Blog\\BlogServiceProvider']]], + ], + ], JSON_THROW_ON_ERROR)); + + $manifest = new PackageManifest($this->packageApp); + $manifest->build(); + + expect($manifest->providers())->toBe([]); +}); diff --git a/tests/Unit/Packages/PackageRegistryTest.php b/tests/Unit/Packages/PackageRegistryTest.php new file mode 100644 index 00000000..6b2a596c --- /dev/null +++ b/tests/Unit/Packages/PackageRegistryTest.php @@ -0,0 +1,21 @@ +addMigrationPaths(['/package/migrations', '/package/migrations']); + $packages->addViewPaths('/package/views', 'blog'); + $packages->addTranslationPath('/package/lang', 'blog'); + $packages->addPublishPaths('BlogProvider', [ + '/package/config.php' => '/app/config/blog.php', + ], 'blog-config'); + + expect($packages->migrationPaths())->toBe(['/package/migrations']) + ->and($packages->viewPaths('blog'))->toBe(['/package/views']) + ->and($packages->translationPaths())->toBe(['blog' => ['/package/lang']]) + ->and($packages->pathsToPublish('BlogProvider'))->toHaveKey('/package/config.php') + ->and($packages->pathsToPublish(group: 'blog-config'))->toHaveKey('/package/config.php'); +}); diff --git a/tests/Unit/Translation/TranslatorTest.php b/tests/Unit/Translation/TranslatorTest.php index f7e586e0..109b2e78 100644 --- a/tests/Unit/Translation/TranslatorTest.php +++ b/tests/Unit/Translation/TranslatorTest.php @@ -2,11 +2,33 @@ declare(strict_types=1); +use Phenix\App; use Phenix\Facades\Translator; use Phenix\Filesystem\Contracts\File; +use Phenix\Packages\PackageRegistry; use Phenix\Testing\Mock; use Phenix\Translation\Translator as Trans; +it('loads namespaced package translations', function (): void { + $path = base_path('storage/framework/testing/package-lang-' . uniqid()); + + mkdir("{$path}/en", 0755, true); + + file_put_contents("{$path}/en/messages.php", " 'Created by package'];"); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addTranslationPath($path, 'blog'); + + $translator = Trans::build(); + + expect($translator->get('blog::messages.created'))->toBe('Created by package'); + + unlink("{$path}/en/messages.php"); + rmdir("{$path}/en"); + rmdir($path); +}); + it('returns key when translation missing', function (): void { $translator = new Trans('en', 'en'); diff --git a/tests/Unit/Views/TemplateEngineTest.php b/tests/Unit/Views/TemplateEngineTest.php index cc182409..14795bf3 100644 --- a/tests/Unit/Views/TemplateEngineTest.php +++ b/tests/Unit/Views/TemplateEngineTest.php @@ -2,12 +2,33 @@ declare(strict_types=1); +use Phenix\App; use Phenix\Facades\View; +use Phenix\Packages\PackageRegistry; use Phenix\Views\Exceptions\ViewNotFoundException; use Phenix\Views\TemplateCache; use Phenix\Views\TemplateEngine; use Phenix\Views\TemplateFactory; +it('renders a namespaced package view', function (): void { + $path = base_path('storage/framework/testing/package-views-' . uniqid()); + + mkdir($path, 0755, true); + file_put_contents("{$path}/index.php", '

{{ $title }}

'); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addViewPaths($path, 'blog'); + + $template = new TemplateEngine(); + $output = $template->view('blog::index', ['title' => 'Package view'])->render(); + + expect($output)->toContain('Package view'); + + unlink("{$path}/index.php"); + rmdir($path); +}); + it('render a template successfully', function (): void { $template = new TemplateEngine(); $template->clearCache(); diff --git a/tests/fixtures/application/storage/framework/testing/.gitignore b/tests/fixtures/application/storage/framework/testing/.gitignore new file mode 100644 index 00000000..d6b7ef32 --- /dev/null +++ b/tests/fixtures/application/storage/framework/testing/.gitignore @@ -0,0 +1,2 @@ +* +!.gitignore From f529ce43c8512d6744326e914bc3298edab999b5 Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Wed, 18 Nov 2026 11:46:55 -0500 Subject: [PATCH 2/9] feat: exclude storage directory from PHP CS Fixer --- .php-cs-fixer.php | 1 + 1 file changed, 1 insertion(+) diff --git a/.php-cs-fixer.php b/.php-cs-fixer.php index 0d8bc2db..d2127fa6 100644 --- a/.php-cs-fixer.php +++ b/.php-cs-fixer.php @@ -37,6 +37,7 @@ __DIR__ . '/src', __DIR__ . '/tests', ]) + ->exclude('fixtures/application/storage') ->name('*.php') ->ignoreDotFiles(true) ->ignoreVCS(true); From 031ee14532d57dc7275a5d72c5eb1b3bd6979071 Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Wed, 18 Nov 2026 11:50:26 -0500 Subject: [PATCH 3/9] style: php cs --- src/Packages/PackageManifest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/src/Packages/PackageManifest.php b/src/Packages/PackageManifest.php index 074b54c5..f1d4d23f 100644 --- a/src/Packages/PackageManifest.php +++ b/src/Packages/PackageManifest.php @@ -7,7 +7,6 @@ use JsonException; use Phenix\Exceptions\RuntimeError; use Phenix\Util\Path; -use RuntimeException; use function in_array; use function is_array; From de93416991c802377b6e2bf67da0b95ed3537fef Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Wed, 18 Nov 2026 12:06:55 -0500 Subject: [PATCH 4/9] chore: rename exception class --- src/App.php | 8 ++++---- src/Concerns/ResolveHost.php | 8 ++++---- src/Console/Commands/VendorPublish.php | 8 ++++---- src/Exceptions/RuntimeError.php | 12 ------------ src/Exceptions/RuntimeException.php | 12 ++++++++++++ src/Logging/LoggerFactory.php | 4 ++-- src/Packages/PackageManifest.php | 14 +++++++------- tests/Feature/AppErrorHandlingTest.php | 12 ++++++------ tests/Feature/AppTest.php | 8 ++++---- tests/Unit/Events/EventEmitterTest.php | 14 +++++++------- tests/Unit/Logging/LoggerFactoryTest.php | 4 ++-- tests/Unit/Runtime/LogTest.php | 4 ++-- 12 files changed, 54 insertions(+), 54 deletions(-) delete mode 100644 src/Exceptions/RuntimeError.php create mode 100644 src/Exceptions/RuntimeException.php diff --git a/src/App.php b/src/App.php index e69a1af3..0003e677 100644 --- a/src/App.php +++ b/src/App.php @@ -30,7 +30,7 @@ use Phenix\Constants\ServerMode; use Phenix\Contracts\App as AppContract; use Phenix\Contracts\Makeable; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Facades\Config; use Phenix\Facades\Route; use Phenix\Http\Client\HttpClient; @@ -117,7 +117,7 @@ public function setup(): void if (! is_string($provider) || ! class_exists($provider) || ! is_subclass_of($provider, ServiceProvider::class)) { $providerName = is_string($provider) ? $provider : get_debug_type($provider); - throw new RuntimeError("Service provider {$providerName} is invalid."); + throw new RuntimeException("Service provider {$providerName} is invalid."); } self::$container->addServiceProvider(new $provider()); @@ -270,7 +270,7 @@ protected function createServer(): SocketHttpServer $trustedProxies = Config::get('app.trusted_proxies', []); if (is_array($trustedProxies) && count($trustedProxies) === 0) { - throw new RuntimeError('Trusted proxies must be an array of IP addresses or CIDRs.'); + throw new RuntimeException('Trusted proxies must be an array of IP addresses or CIDRs.'); } return SocketHttpServer::createForBehindProxy( @@ -303,7 +303,7 @@ protected function createClusterServer(): SocketHttpServer $trustedProxies = Config::get('app.trusted_proxies', []); if (is_array($trustedProxies) && count($trustedProxies) === 0) { - throw new RuntimeError('Trusted proxies must be an array of IP addresses or CIDRs.'); + throw new RuntimeException('Trusted proxies must be an array of IP addresses or CIDRs.'); } $middleware[] = new Middleware\ForwardedMiddleware(ForwardedHeaderType::XForwardedFor, $trustedProxies); diff --git a/src/Concerns/ResolveHost.php b/src/Concerns/ResolveHost.php index ec0a7d10..fbd586ea 100644 --- a/src/Concerns/ResolveHost.php +++ b/src/Concerns/ResolveHost.php @@ -5,7 +5,7 @@ namespace Phenix\Concerns; use League\Uri\Uri; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Facades\Config; use function in_array; @@ -19,7 +19,7 @@ protected function resolvePublicHost(): string $host = $uri->getHost(); if (! in_array($uri->getScheme(), ['http', 'https'], true) || $host === '') { - throw new RuntimeError('App URL must be an absolute HTTP or HTTPS URL with a host.'); + throw new RuntimeException('App URL must be an absolute HTTP or HTTPS URL with a host.'); } return $host; @@ -30,7 +30,7 @@ protected function resolveBindHost(): string $host = trim((string) Config::get('app.host')); if ($host === '') { - throw new RuntimeError('Bind host must not be empty.'); + throw new RuntimeException('Bind host must not be empty.'); } return trim($host, '[]'); @@ -41,7 +41,7 @@ protected function resolveBindPort(): int $port = (int) Config::get('app.port'); if ($port < 1 || $port > 65535) { - throw new RuntimeError('Bind port must be between 1 and 65535.'); + throw new RuntimeException('Bind port must be between 1 and 65535.'); } return $port; diff --git a/src/Console/Commands/VendorPublish.php b/src/Console/Commands/VendorPublish.php index 4b27d588..96bd793d 100644 --- a/src/Console/Commands/VendorPublish.php +++ b/src/Console/Commands/VendorPublish.php @@ -6,7 +6,7 @@ use FilesystemIterator; use Phenix\App; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Packages\PackageRegistry; use Phenix\Util\Path; use RecursiveDirectoryIterator; @@ -85,7 +85,7 @@ private function publish(string $source, string $destination, bool $force): int } if (! is_dir($source)) { - throw new RuntimeError("Publish source {$source} does not exist."); + throw new RuntimeException("Publish source {$source} does not exist."); } $iterator = new RecursiveIteratorIterator( @@ -118,11 +118,11 @@ private function copyFile(string $source, string $destination, bool $force): boo $directory = dirname($destination); if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) { - throw new RuntimeError("Unable to create publish directory {$directory}."); + throw new RuntimeException("Unable to create publish directory {$directory}."); } if (! copy($source, $destination)) { - throw new RuntimeError("Unable to publish {$source} to {$destination}."); + throw new RuntimeException("Unable to publish {$source} to {$destination}."); } return true; diff --git a/src/Exceptions/RuntimeError.php b/src/Exceptions/RuntimeError.php deleted file mode 100644 index 5941ef50..00000000 --- a/src/Exceptions/RuntimeError.php +++ /dev/null @@ -1,12 +0,0 @@ - self::fileHandler($level), 'stream' => self::streamHandler($level), - default => throw new RuntimeError("Unsupported logging channel: {$key}"), + default => throw new RuntimeException("Unsupported logging channel: {$key}"), }; } diff --git a/src/Packages/PackageManifest.php b/src/Packages/PackageManifest.php index f1d4d23f..3d51a986 100644 --- a/src/Packages/PackageManifest.php +++ b/src/Packages/PackageManifest.php @@ -5,7 +5,7 @@ namespace Phenix\Packages; use JsonException; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Util\Path; use function in_array; @@ -128,7 +128,7 @@ private function installedPackages(): array try { $installed = json_decode((string) file_get_contents($path), true, flags: JSON_THROW_ON_ERROR); } catch (JsonException $exception) { - throw new RuntimeError("Unable to read Composer package metadata at {$path}.", 0, $exception); + throw new RuntimeException("Unable to read Composer package metadata at {$path}.", 0, $exception); } if (! is_array($installed)) { @@ -151,7 +151,7 @@ private function packagesToIgnore(): array try { $composer = json_decode((string) file_get_contents($path), true, flags: JSON_THROW_ON_ERROR); } catch (JsonException $exception) { - throw new RuntimeError("Unable to read the application Composer file at {$path}.", 0, $exception); + throw new RuntimeException("Unable to read the application Composer file at {$path}.", 0, $exception); } $ignored = $composer['extra']['phenix']['dont-discover'] ?? []; @@ -164,17 +164,17 @@ private function write(array $manifest): void $directory = dirname($this->manifestPath); if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) { - throw new RuntimeError("The package cache directory {$directory} could not be created."); + throw new RuntimeException("The package cache directory {$directory} could not be created."); } if (! is_writable($directory)) { - throw new RuntimeError("The package cache directory {$directory} must be writable."); + throw new RuntimeException("The package cache directory {$directory} must be writable."); } $temporaryPath = tempnam($directory, 'packages-'); if ($temporaryPath === false) { - throw new RuntimeError("Unable to create a temporary package manifest in {$directory}."); + throw new RuntimeException("Unable to create a temporary package manifest in {$directory}."); } $contents = 'manifestPath)) { @unlink($temporaryPath); - throw new RuntimeError("Unable to write the package manifest at {$this->manifestPath}."); + throw new RuntimeException("Unable to write the package manifest at {$this->manifestPath}."); } } } diff --git a/tests/Feature/AppErrorHandlingTest.php b/tests/Feature/AppErrorHandlingTest.php index b78153f4..c43773e7 100644 --- a/tests/Feature/AppErrorHandlingTest.php +++ b/tests/Feature/AppErrorHandlingTest.php @@ -2,7 +2,7 @@ declare(strict_types=1); -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Facades\Config; use Phenix\Facades\Crypto; use Phenix\Facades\Route; @@ -17,7 +17,7 @@ Config::set('app.debug', false); Route::get('/fails', function (): Response { - throw new RuntimeError('Sensitive failure'); + throw new RuntimeException('Sensitive failure'); }); $this->app->run(); @@ -38,7 +38,7 @@ Config::set('app.debug', true); Route::get('/debug-fails', function (): Response { - throw new RuntimeError('Visible local failure'); + throw new RuntimeException('Visible local failure'); }); $this->app->run(); @@ -48,7 +48,7 @@ ->assertJsonPath('success', false) ->assertJsonPath('error', 'Visible local failure') ->assertJsonPath('status', HttpStatus::INTERNAL_SERVER_ERROR->value) - ->assertJsonPath('debug.exception', RuntimeError::class) + ->assertJsonPath('debug.exception', RuntimeException::class) ->assertJsonPath('debug.path', '/debug-fails'); }); @@ -56,7 +56,7 @@ Config::set('app.debug', true); Route::get('/production-fails', function (): Response { - throw new RuntimeError('Production secret'); + throw new RuntimeException('Production secret'); }); $this->app->run(); @@ -67,7 +67,7 @@ ->assertStatusCode(HttpStatus::INTERNAL_SERVER_ERROR) ->assertJsonPath('success', false) ->assertJsonPath('error', 'Production secret') - ->assertJsonPath('debug.exception', RuntimeError::class) + ->assertJsonPath('debug.exception', RuntimeException::class) ->assertJsonPath('debug.path', '/production-fails'); }); diff --git a/tests/Feature/AppTest.php b/tests/Feature/AppTest.php index 14b78b7e..33018320 100644 --- a/tests/Feature/AppTest.php +++ b/tests/Feature/AppTest.php @@ -3,7 +3,7 @@ declare(strict_types=1); use Phenix\Constants\AppMode; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Facades\Config; use Phenix\Facades\Crypto; use Phenix\Facades\Route; @@ -50,7 +50,7 @@ Config::set('app.app_mode', AppMode::PROXIED->value); $this->app->run(); -})->throws(RuntimeError::class); +})->throws(RuntimeException::class); it('starts server with TLS certificate', function (): void { Config::set('app.url', 'https://public.example.com'); @@ -72,10 +72,10 @@ Config::set('app.url', 'not-an-absolute-url'); $this->app->run(); -})->throws(RuntimeError::class, 'App URL must be an absolute HTTP or HTTPS URL with a host.'); +})->throws(RuntimeException::class, 'App URL must be an absolute HTTP or HTTPS URL with a host.'); it('rejects an invalid bind port', function (): void { Config::set('app.port', 70000); $this->app->run(); -})->throws(RuntimeError::class, 'Bind port must be between 1 and 65535.'); +})->throws(RuntimeException::class, 'Bind port must be between 1 and 65535.'); diff --git a/tests/Unit/Events/EventEmitterTest.php b/tests/Unit/Events/EventEmitterTest.php index af315b3b..bf1b7a4c 100644 --- a/tests/Unit/Events/EventEmitterTest.php +++ b/tests/Unit/Events/EventEmitterTest.php @@ -7,7 +7,7 @@ use Phenix\Events\Event; use Phenix\Events\EventEmitter; use Phenix\Events\Exceptions\EventException; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Facades\Config; use Phenix\Facades\Event as EventFacade; use Phenix\Facades\Log; @@ -336,7 +336,7 @@ $emitter = new EventEmitter(); $emitter->on('error.event', function (): never { - throw new RuntimeError('Listener error'); + throw new RuntimeException('Listener error'); }); Log::shouldReceive('error') @@ -350,7 +350,7 @@ $emitter->setEmitWarnings(true); $emitter->on('error.event', function (): never { - throw new RuntimeError('Listener error'); + throw new RuntimeException('Listener error'); }); Log::shouldReceive('error') @@ -366,7 +366,7 @@ $emitter->setEmitWarnings(false); $emitter->on('error.event', function (): never { - throw new RuntimeError('Listener error'); + throw new RuntimeException('Listener error'); }); Log::shouldReceive('error')->once(); @@ -760,10 +760,10 @@ it('fakes multiple events provided sequentially', function (): void { EventFacade::on('list.one', function (): never { - throw new RuntimeError('Should not run'); + throw new RuntimeException('Should not run'); }); EventFacade::on('list.two', function (): never { - throw new RuntimeError('Should not run'); + throw new RuntimeException('Should not run'); }); $executedThree = false; @@ -814,7 +814,7 @@ }); EventFacade::fakeWhen('closure.exception.event', function (Collection $log): bool { - throw new RuntimeError('Predicate error'); + throw new RuntimeException('Predicate error'); }); EventFacade::emit('closure.exception.event'); diff --git a/tests/Unit/Logging/LoggerFactoryTest.php b/tests/Unit/Logging/LoggerFactoryTest.php index d2bcf4f6..3ae16566 100644 --- a/tests/Unit/Logging/LoggerFactoryTest.php +++ b/tests/Unit/Logging/LoggerFactoryTest.php @@ -4,7 +4,7 @@ use Amp\Log\ConsoleFormatter; use Monolog\Formatter\LineFormatter; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Logging\LoggerFactory; it('makes all supported logger channels', function (string $channel, string $formatter) { @@ -22,5 +22,5 @@ it('throws error on unsupported channel', function () { expect(function () { LoggerFactory::make('unsupported'); - })->toThrow(RuntimeError::class); + })->toThrow(RuntimeException::class); }); diff --git a/tests/Unit/Runtime/LogTest.php b/tests/Unit/Runtime/LogTest.php index 19e71429..f54afecf 100644 --- a/tests/Unit/Runtime/LogTest.php +++ b/tests/Unit/Runtime/LogTest.php @@ -5,7 +5,7 @@ use Monolog\Handler\TestHandler; use Monolog\Logger; use Monolog\LogRecord; -use Phenix\Exceptions\RuntimeError; +use Phenix\Exceptions\RuntimeException; use Phenix\Runtime\Log; it('can log messages successfully', function () { @@ -42,7 +42,7 @@ $this->app->swap(Log::class, $log); try { - throw new RuntimeError('This is an exception'); + throw new RuntimeException('This is an exception'); } catch (Exception $e) { report($e); } From dbe5e7fa84e4eca95feb5dc570495517e042d9ec Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Wed, 18 Nov 2026 12:35:08 -0500 Subject: [PATCH 5/9] fix: rename var to prevent name collision --- src/Console/Commands/VendorPublish.php | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/Console/Commands/VendorPublish.php b/src/Console/Commands/VendorPublish.php index 96bd793d..79dedf6c 100644 --- a/src/Console/Commands/VendorPublish.php +++ b/src/Console/Commands/VendorPublish.php @@ -57,7 +57,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int return Command::SUCCESS; } - $status = Command::SUCCESS; + $commandStatus = Command::SUCCESS; foreach ($paths as $source => $destination) { try { @@ -71,11 +71,11 @@ protected function execute(InputInterface $input, OutputInterface $output): int } catch (Throwable $exception) { $output->writeln('' . $exception->getMessage() . ''); - $status = Command::FAILURE; + $commandStatus = Command::FAILURE; } } - return $status; + return $commandStatus; } private function publish(string $source, string $destination, bool $force): int From 32311dce7896b5cd25406ded8aefadd74c34b9d8 Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Wed, 18 Nov 2026 17:22:06 -0500 Subject: [PATCH 6/9] tests: package registry flow --- src/Console/Commands/VendorPublish.php | 4 +- src/Packages/PackageRegistry.php | 4 +- .../Unit/Console/VendorPublishCommandTest.php | 187 +++++++++++++++++- tests/Unit/Packages/ComposerScriptsTest.php | 43 ++++ tests/Unit/Packages/PackageRegistryTest.php | 48 +++++ tests/Unit/Providers/ServiceProviderTest.php | 96 +++++++++ tests/fixtures/PackageServiceProvider.php | 45 +++++ 7 files changed, 417 insertions(+), 10 deletions(-) create mode 100644 tests/Unit/Packages/ComposerScriptsTest.php create mode 100644 tests/Unit/Providers/ServiceProviderTest.php create mode 100644 tests/fixtures/PackageServiceProvider.php diff --git a/src/Console/Commands/VendorPublish.php b/src/Console/Commands/VendorPublish.php index 79dedf6c..2d3ece01 100644 --- a/src/Console/Commands/VendorPublish.php +++ b/src/Console/Commands/VendorPublish.php @@ -117,11 +117,11 @@ private function copyFile(string $source, string $destination, bool $force): boo $directory = dirname($destination); - if (! is_dir($directory) && ! mkdir($directory, 0755, true) && ! is_dir($directory)) { + if (! is_dir($directory) && ! @mkdir($directory, 0755, true) && ! is_dir($directory)) { throw new RuntimeException("Unable to create publish directory {$directory}."); } - if (! copy($source, $destination)) { + if (! @copy($source, $destination)) { throw new RuntimeException("Unable to publish {$source} to {$destination}."); } diff --git a/src/Packages/PackageRegistry.php b/src/Packages/PackageRegistry.php index 98378e3a..dc28abb7 100644 --- a/src/Packages/PackageRegistry.php +++ b/src/Packages/PackageRegistry.php @@ -88,8 +88,6 @@ public function publishableGroups(): array protected function getPublishesPath(): array { - $paths = $this->publishes ?: [[]]; - - return [...array_values($paths)]; + return array_merge(...array_values($this->publishes)); } } diff --git a/tests/Unit/Console/VendorPublishCommandTest.php b/tests/Unit/Console/VendorPublishCommandTest.php index 387606a3..45460a18 100644 --- a/tests/Unit/Console/VendorPublishCommandTest.php +++ b/tests/Unit/Console/VendorPublishCommandTest.php @@ -6,9 +6,28 @@ use Phenix\Packages\PackageRegistry; use Symfony\Component\Console\Tester\CommandTester; +beforeEach(function (): void { + $this->publishPath = base_path('storage/framework/testing/vendor-publish-' . uniqid()); + + mkdir($this->publishPath, 0755, true); +}); + +afterEach(function (): void { + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($this->publishPath, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST, + ); + + foreach ($iterator as $entry) { + $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + + rmdir($this->publishPath); +}); + it('publishes tagged package files', function (): void { - $source = base_path('storage/framework/testing/package-source-' . uniqid() . '.php'); - $destination = base_path('storage/framework/testing/package-destination-' . uniqid() . '.php'); + $source = "{$this->publishPath}/package-source.php"; + $destination = "{$this->publishPath}/package-destination.php"; file_put_contents($source, 'toBeFile() ->and(file_get_contents($destination))->toBe('getStatusCode())->toBe(1) ->and($command->getDisplay())->toContain('Specify --provider, --tag, or --all.'); }); + +it('reports when no publishable resources are registered', function (): void { + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--all' => true]); + + $command->assertCommandIsSuccessful(); + + expect($command->getDisplay())->toContain('No publishable resources were found.'); +}); + +it('publishes package directories recursively', function (): void { + $source = "{$this->publishPath}/package/views"; + $destination = "{$this->publishPath}/resources/views/vendor/blog"; + mkdir("{$source}/posts", 0755, true); + file_put_contents("{$source}/posts/index.php", '

Posts

'); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addPublishPaths('BlogProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--provider' => 'BlogProvider']); + + $command->assertCommandIsSuccessful(); + + expect("{$destination}/posts/index.php")->toBeFile() + ->and(file_get_contents("{$destination}/posts/index.php"))->toBe('

Posts

'); +}); + +it('ignores non-file entries while publishing package directories', function (): void { + $source = "{$this->publishPath}/package/views"; + $destination = "{$this->publishPath}/resources/views/vendor/blog"; + mkdir($source, 0755, true); + file_put_contents("{$source}/index.php", '

Blog

'); + symlink("{$source}/missing.php", "{$source}/broken-link.php"); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addPublishPaths('BlogProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--provider' => 'BlogProvider']); + + $command->assertCommandIsSuccessful(); + + expect("{$destination}/index.php")->toBeFile() + ->and("{$destination}/broken-link.php")->not->toBeFile(); +}); + +it('reports missing package publication sources', function (): void { + $source = "{$this->publishPath}/missing.php"; + $destination = "{$this->publishPath}/published.php"; + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addPublishPaths('MissingProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--provider' => 'MissingProvider']); + + expect($command->getStatusCode())->toBe(1) + ->and($command->getDisplay())->toContain("Publish source {$source} does not exist.") + ->and($destination)->not->toBeFile(); +}); + +it('preserves published files unless force is used', function (): void { + $source = "{$this->publishPath}/source.php"; + $destination = "{$this->publishPath}/destination.php"; + file_put_contents($source, 'package'); + file_put_contents($destination, 'application'); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addPublishPaths('ConfigProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--provider' => 'ConfigProvider']); + + $command->assertCommandIsSuccessful(); + + expect($command->getDisplay())->toContain('Skipped:') + ->and(file_get_contents($destination))->toBe('application'); +}); + +it('overwrites published files when force is used', function (): void { + $source = "{$this->publishPath}/source.php"; + $destination = "{$this->publishPath}/destination.php"; + file_put_contents($source, 'package'); + file_put_contents($destination, 'application'); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addPublishPaths('ConfigProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', [ + '--provider' => 'ConfigProvider', + '--force' => true, + ]); + + $command->assertCommandIsSuccessful(); + + expect($command->getDisplay())->toContain('Published:') + ->and(file_get_contents($destination))->toBe('package'); +}); + +it('reports when the publication directory cannot be created', function (): void { + $source = "{$this->publishPath}/source.php"; + $blockedDirectory = "{$this->publishPath}/blocked"; + $destination = "{$blockedDirectory}/destination.php"; + file_put_contents($source, 'package'); + file_put_contents($blockedDirectory, 'not-a-directory'); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addPublishPaths('BlockedProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--provider' => 'BlockedProvider']); + + expect($command->getStatusCode())->toBe(1) + ->and($command->getDisplay())->toContain("Unable to create publish directory {$blockedDirectory}."); +}); + +it('reports when a package file cannot be copied', function (): void { + $source = "{$this->publishPath}/source.php"; + $destination = "{$this->publishPath}/destination"; + file_put_contents($source, 'package'); + mkdir($destination); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + $packages->addPublishPaths('UnreadableProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--provider' => 'UnreadableProvider']); + + expect($command->getStatusCode())->toBe(1) + ->and($command->getDisplay())->toContain("Unable to publish {$source} to {$destination}."); +}); + +it('replaces package migration timestamps when publishing', function (): void { + $source = "{$this->publishPath}/package/migrations/20240101000000_create_posts.php"; + $destination = "{$this->publishPath}/database/migrations/20240101000000_create_posts.php"; + mkdir(dirname($source), 0755, true); + file_put_contents($source, 'addPublishPaths('MigrationProvider', [$source => $destination]); + + /** @var CommandTester $command */ + $command = $this->phenix('vendor:publish', ['--provider' => 'MigrationProvider']); + + $command->assertCommandIsSuccessful(); + $published = glob("{$this->publishPath}/database/migrations/*_create_posts.php"); + + expect($published)->toHaveCount(1) + ->and(basename($published[0]))->toMatch('/^\d{14}_create_posts\.php$/') + ->not->toBe('20240101000000_create_posts.php'); +}); diff --git a/tests/Unit/Packages/ComposerScriptsTest.php b/tests/Unit/Packages/ComposerScriptsTest.php new file mode 100644 index 00000000..246a5566 --- /dev/null +++ b/tests/Unit/Packages/ComposerScriptsTest.php @@ -0,0 +1,43 @@ +originalDirectory = getcwd(); + $this->composerApp = base_path('storage/framework/testing/composer-scripts-' . uniqid()); + + mkdir("{$this->composerApp}/storage/framework/cache", 0755, true); + chdir($this->composerApp); +}); + +afterEach(function (): void { + chdir($this->originalDirectory); + + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($this->composerApp, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST, + ); + + foreach ($iterator as $entry) { + $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + + rmdir($this->composerApp); +}); + +it('removes the cached package manifest after an autoload dump', function (): void { + $manifest = "{$this->composerApp}/storage/framework/cache/packages.php"; + file_put_contents($manifest, 'not->toBeFile(); +}); + +it('does nothing when the cached package manifest does not exist', function (): void { + ComposerScripts::postAutoloadDump(); + + expect("{$this->composerApp}/storage/framework/cache")->toBeDirectory(); +}); diff --git a/tests/Unit/Packages/PackageRegistryTest.php b/tests/Unit/Packages/PackageRegistryTest.php index 6b2a596c..183755ee 100644 --- a/tests/Unit/Packages/PackageRegistryTest.php +++ b/tests/Unit/Packages/PackageRegistryTest.php @@ -19,3 +19,51 @@ ->and($packages->pathsToPublish('BlogProvider'))->toHaveKey('/package/config.php') ->and($packages->pathsToPublish(group: 'blog-config'))->toHaveKey('/package/config.php'); }); + +it('lists publishable providers and groups', function (): void { + $packages = new PackageRegistry(); + $packages->addPublishPaths('BlogProvider', [ + '/package/blog.php' => '/app/blog.php', + ], 'blog'); + $packages->addPublishPaths('ShopProvider', [ + '/package/shop.php' => '/app/shop.php', + ], ['shop', 'config']); + + expect($packages->publishableProviders())->toBe(['BlogProvider', 'ShopProvider']) + ->and($packages->publishableGroups())->toBe(['blog', 'shop', 'config']); +}); + +it('returns all publishable paths', function (): void { + $packages = new PackageRegistry(); + $packages->addPublishPaths('BlogProvider', [ + '/package/blog.php' => '/app/blog.php', + ]); + $packages->addPublishPaths('ShopProvider', [ + '/package/shop.php' => '/app/shop.php', + ]); + + expect($packages->pathsToPublish())->toBe([ + '/package/blog.php' => '/app/blog.php', + '/package/shop.php' => '/app/shop.php', + ]); +}); + +it('filters publishable paths by provider and group', function (): void { + $packages = new PackageRegistry(); + $packages->addPublishPaths('BlogProvider', [ + '/package/config.php' => '/app/config.php', + '/package/views/index.php' => '/app/views/index.php', + ], ['config', 'views']); + $packages->addPublishPaths('ShopProvider', [ + '/shop/config.php' => '/app/shop.php', + ], 'config'); + + expect($packages->pathsToPublish('BlogProvider', 'config'))->toBe([ + '/package/config.php' => '/app/config.php', + '/package/views/index.php' => '/app/views/index.php', + ]); +}); + +it('returns no publishable paths when the registry is empty', function (): void { + expect((new PackageRegistry())->pathsToPublish())->toBe([]); +}); diff --git a/tests/Unit/Providers/ServiceProviderTest.php b/tests/Unit/Providers/ServiceProviderTest.php new file mode 100644 index 00000000..59026912 --- /dev/null +++ b/tests/Unit/Providers/ServiceProviderTest.php @@ -0,0 +1,96 @@ +providerPath = base_path('storage/framework/testing/service-provider-' . uniqid()); + $this->provider = new PackageServiceProvider(); + + mkdir($this->providerPath, 0755, true); +}); + +afterEach(function (): void { + $iterator = new RecursiveIteratorIterator( + new RecursiveDirectoryIterator($this->providerPath, FilesystemIterator::SKIP_DOTS), + RecursiveIteratorIterator::CHILD_FIRST, + ); + + foreach ($iterator as $entry) { + $entry->isDir() ? rmdir($entry->getPathname()) : unlink($entry->getPathname()); + } + + rmdir($this->providerPath); +}); + +it('merges package configuration without replacing application values', function (): void { + $config = "{$this->providerPath}/package.php"; + file_put_contents($config, " true, 'driver' => 'package'];"); + Config::set('package-coverage', ['driver' => 'application']); + + $this->provider->mergePackageConfig($config, 'package-coverage'); + + expect(Config::get('package-coverage'))->toBe([ + 'enabled' => true, + 'driver' => 'application', + ]); +}); + +it('ignores package configuration files that do not return arrays', function (): void { + $config = "{$this->providerPath}/invalid.php"; + file_put_contents($config, "provider->mergePackageConfig($config, 'invalid-package-coverage'); + + expect(Config::has('invalid-package-coverage'))->toBeFalse(); +}); + +it('loads an existing package routes file', function (): void { + $routes = "{$this->providerPath}/routes.php"; + $marker = "{$this->providerPath}/routes-loaded"; + file_put_contents($routes, 'provider->loadPackageRoutes($routes); + + expect($marker)->toBeFile() + ->and(file_get_contents($marker))->toBe('loaded'); +}); + +it('ignores a missing package routes file', function (): void { + $this->provider->loadPackageRoutes("{$this->providerPath}/missing.php"); + + expect($this->providerPath)->toBeDirectory(); +}); + +it('registers package resource paths', function (): void { + $this->provider->loadPackageMigrations(['/package/migrations', '/package/migrations-extra']); + $this->provider->loadPackageViews('/package/views', 'blog'); + $this->provider->loadPackageTranslations('/package/lang', 'blog'); + $this->provider->publishPackagePaths([ + '/package/config.php' => '/app/config.php', + ], 'config'); + $this->provider->publishPackageMigrations([ + '/package/migrations/create_posts.php' => '/app/migrations/create_posts.php', + ], 'migrations'); + + /** @var PackageRegistry $packages */ + $packages = App::make(PackageRegistry::class); + + expect($packages->migrationPaths())->toBe(['/package/migrations', '/package/migrations-extra']) + ->and($packages->viewPaths('blog'))->toBe(['/package/views']) + ->and($packages->translationPaths())->toBe(['blog' => ['/package/lang']]) + ->and($packages->pathsToPublish(PackageServiceProvider::class))->toBe([ + '/package/config.php' => '/app/config.php', + '/package/migrations/create_posts.php' => '/app/migrations/create_posts.php', + ]) + ->and($packages->pathsToPublish(group: 'config'))->toBe([ + '/package/config.php' => '/app/config.php', + ]) + ->and($packages->pathsToPublish(group: 'migrations'))->toBe([ + '/package/migrations/create_posts.php' => '/app/migrations/create_posts.php', + ]); +}); diff --git a/tests/fixtures/PackageServiceProvider.php b/tests/fixtures/PackageServiceProvider.php new file mode 100644 index 00000000..d8790cb7 --- /dev/null +++ b/tests/fixtures/PackageServiceProvider.php @@ -0,0 +1,45 @@ +mergeConfigFrom($path, $key); + } + + public function loadPackageRoutes(string $path): void + { + $this->loadRoutesFrom($path); + } + + public function loadPackageMigrations(array|string $paths): void + { + $this->loadMigrationsFrom($paths); + } + + public function loadPackageViews(array|string $paths, string $namespace): void + { + $this->loadViewsFrom($paths, $namespace); + } + + public function loadPackageTranslations(string $path, string $namespace): void + { + $this->loadTranslationsFrom($path, $namespace); + } + + public function publishPackagePaths(array $paths, array|string|null $groups = null): void + { + $this->publishes($paths, $groups); + } + + public function publishPackageMigrations(array $paths, array|string|null $groups = null): void + { + $this->publishesMigrations($paths, $groups); + } +} From f0ed5eca69720a48317951c00a544c2b3be89c37 Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Thu, 19 Nov 2026 15:34:02 -0500 Subject: [PATCH 7/9] fix: move internal class to correct namespace --- .../Providers/Internal}/PackageServiceProvider.php | 2 +- tests/Unit/Providers/ServiceProviderTest.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) rename tests/{fixtures => Unit/Providers/Internal}/PackageServiceProvider.php (96%) diff --git a/tests/fixtures/PackageServiceProvider.php b/tests/Unit/Providers/Internal/PackageServiceProvider.php similarity index 96% rename from tests/fixtures/PackageServiceProvider.php rename to tests/Unit/Providers/Internal/PackageServiceProvider.php index d8790cb7..8e76ee2e 100644 --- a/tests/fixtures/PackageServiceProvider.php +++ b/tests/Unit/Providers/Internal/PackageServiceProvider.php @@ -2,7 +2,7 @@ declare(strict_types=1); -namespace Tests\Fixtures; +namespace Tests\Unit\Providers\Internal; use Phenix\Providers\ServiceProvider; diff --git a/tests/Unit/Providers/ServiceProviderTest.php b/tests/Unit/Providers/ServiceProviderTest.php index 59026912..afa95caf 100644 --- a/tests/Unit/Providers/ServiceProviderTest.php +++ b/tests/Unit/Providers/ServiceProviderTest.php @@ -5,7 +5,7 @@ use Phenix\App; use Phenix\Facades\Config; use Phenix\Packages\PackageRegistry; -use Tests\Fixtures\PackageServiceProvider; +use Tests\Unit\Providers\Internal\PackageServiceProvider; beforeEach(function (): void { $this->providerPath = base_path('storage/framework/testing/service-provider-' . uniqid()); From 865b61291814f57b33875821a0dc9c0b0d561dab Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Tue, 24 Nov 2026 12:03:44 -0500 Subject: [PATCH 8/9] refactor: apply changes of PR review --- src/Console/Commands/VendorPublish.php | 15 +--- src/Database/Console/DatabaseCommand.php | 20 ++++++ src/Database/MigrationManager.php | 69 +++++++++++++++++++ src/Packages/PackageManifest.php | 42 ++++++++--- src/Testing/Concerns/RefreshDatabase.php | 4 +- src/Views/ViewsConfig.php | 9 +-- .../Unit/Console/VendorPublishCommandTest.php | 4 +- tests/Unit/Packages/MigrationManagerTest.php | 48 +++++++++++++ tests/Unit/Packages/PackageManifestTest.php | 34 +++++++++ tests/Unit/Views/TemplateEngineTest.php | 12 +++- 10 files changed, 221 insertions(+), 36 deletions(-) create mode 100644 src/Database/MigrationManager.php create mode 100644 tests/Unit/Packages/MigrationManagerTest.php diff --git a/src/Console/Commands/VendorPublish.php b/src/Console/Commands/VendorPublish.php index 2d3ece01..e1e674f4 100644 --- a/src/Console/Commands/VendorPublish.php +++ b/src/Console/Commands/VendorPublish.php @@ -81,7 +81,7 @@ protected function execute(InputInterface $input, OutputInterface $output): int private function publish(string $source, string $destination, bool $force): int { if (is_file($source)) { - return $this->copyFile($source, $this->migrationDestination($source, $destination), $force) ? 1 : 0; + return $this->copyFile($source, $destination, $force) ? 1 : 0; } if (! is_dir($source)) { @@ -101,7 +101,7 @@ private function publish(string $source, string $destination, bool $force): int $relative = substr($file->getPathname(), strlen($source) + 1); $target = Path::join(rtrim($destination, DIRECTORY_SEPARATOR), $relative); - if ($this->copyFile($file->getPathname(), $this->migrationDestination($file->getPathname(), $target), $force)) { + if ($this->copyFile($file->getPathname(), $target, $force)) { $published++; } } @@ -128,15 +128,4 @@ private function copyFile(string $source, string $destination, bool $force): boo return true; } - private function migrationDestination(string $source, string $destination): string - { - $name = basename($destination); - - if (! str_contains(str_replace('\\', '/', $source), '/migrations/') - || preg_match('/^\d{14}_/', $name) !== 1) { - return $destination; - } - - return Path::join(dirname($destination), date('YmdHis') . '_' . substr($name, 15)); - } } diff --git a/src/Database/Console/DatabaseCommand.php b/src/Database/Console/DatabaseCommand.php index 0a449b6c..a0c6e83e 100644 --- a/src/Database/Console/DatabaseCommand.php +++ b/src/Database/Console/DatabaseCommand.php @@ -6,11 +6,14 @@ use Phenix\App; use Phenix\Database\Constants\Driver; +use Phenix\Database\MigrationManager; use Phenix\Facades\Config; use Phenix\Packages\PackageRegistry; use Phinx\Config\Config as MigrationConfig; use Phinx\Console\Command\AbstractCommand; use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Output\OutputInterface; abstract class DatabaseCommand extends AbstractCommand { @@ -57,6 +60,23 @@ public function __construct() parent::__construct(); } + protected function loadManager(InputInterface $input, OutputInterface $output): void + { + if ($this->getManager() === null) { + $manager = new MigrationManager($this->getConfig(), $input, $output); + $manager->setVerbosityLevel($this->verbosityLevel); + $container = $this->getConfig()->getContainer(); + + if ($container !== null) { + $manager->setContainer($container); + } + + $this->setManager($manager); + } + + parent::loadManager($input, $output); + } + /** * {@inheritDoc} * diff --git a/src/Database/MigrationManager.php b/src/Database/MigrationManager.php new file mode 100644 index 00000000..35604a8b --- /dev/null +++ b/src/Database/MigrationManager.php @@ -0,0 +1,69 @@ +pathsToPublish(); + $excluded = []; + + foreach ($files as $file) { + foreach ($published as $source => $destination) { + $filePath = realpath($file); + $target = $this->publishedTarget($file, $source, $destination); + + if ($target === null || $filePath === false) { + continue; + } + + if ($this->isPublishedMigration($target, $filePath, $files)) { + $excluded[] = $file; + } + } + } + + return array_values(array_diff($files, $excluded)); + } + + private function isPublishedMigration(string $target, string $filePath, array $files): bool + { + return basename($target) === basename($filePath) + && is_file($target) && realpath($target) !== $filePath + && in_array(realpath($target), array_map('realpath', $files), true); + } + + private function publishedTarget(string $file, string $source, string $destination): string|null + { + $sourcePath = realpath($source); + $filePath = realpath($file); + + if ($sourcePath === false || $filePath === false) { + return null; + } + + if ($sourcePath === $filePath) { + return $destination; + } + + $target = null; + + if (is_dir($sourcePath) && str_starts_with($filePath, rtrim($sourcePath, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR)) { + $target = rtrim($destination, DIRECTORY_SEPARATOR) . substr($filePath, strlen($sourcePath)); + } + + return $target; + } +} diff --git a/src/Packages/PackageManifest.php b/src/Packages/PackageManifest.php index 3d51a986..24d68848 100644 --- a/src/Packages/PackageManifest.php +++ b/src/Packages/PackageManifest.php @@ -5,6 +5,7 @@ namespace Phenix\Packages; use JsonException; +use Throwable; use Phenix\Exceptions\RuntimeException; use Phenix\Util\Path; @@ -51,20 +52,24 @@ public function getManifest(): array return $this->manifest; } - if (! is_file($this->manifestPath)) { - $this->build(); - } + $cached = null; - if (! is_file($this->manifestPath)) { - return $this->manifest = []; + if (is_file($this->manifestPath)) { + try { + $cached = require $this->manifestPath; + } catch (Throwable) { + $cached = null; + } } - $manifest = require $this->manifestPath; + if ($this->needsRebuild($cached)) { + return $this->build(); + } - return $this->manifest = is_array($manifest) ? $manifest : []; + return $this->manifest = $cached['packages']; } - public function build(): void + public function build(): array { $packages = $this->installedPackages(); $ignored = $this->packagesToIgnore(); @@ -99,8 +104,10 @@ public function build(): void ARRAY_FILTER_USE_KEY, ); - $this->write($manifest); + $this->write(['fingerprint' => $this->fingerprint(), 'packages' => $manifest]); $this->manifest = $manifest; + + return $manifest; } public function clear(): void @@ -117,6 +124,23 @@ public function path(): string return $this->manifestPath; } + /** + * @phpstan-assert-if-false array{fingerprint: string, packages: array} $cached + */ + private function needsRebuild(mixed $cached): bool + { + return ! is_array($cached) || ($cached['fingerprint'] ?? null) !== $this->fingerprint() + || ! is_array($cached['packages'] ?? null); + } + + private function fingerprint(): string + { + $path = Path::join($this->vendorPath, 'composer', 'installed.json'); + $installed = is_file($path) ? file_get_contents($path) : false; + + return hash('sha256', serialize([$installed, $this->packagesToIgnore()])); + } + private function installedPackages(): array { $path = Path::join($this->vendorPath, 'composer', 'installed.json'); diff --git a/src/Testing/Concerns/RefreshDatabase.php b/src/Testing/Concerns/RefreshDatabase.php index 49a98501..a3f5d0b9 100644 --- a/src/Testing/Concerns/RefreshDatabase.php +++ b/src/Testing/Concerns/RefreshDatabase.php @@ -11,7 +11,7 @@ use Phenix\Facades\Config; use Phenix\Packages\PackageRegistry; use Phinx\Config\Config as MigrationConfig; -use Phinx\Migration\Manager; +use Phenix\Database\MigrationManager; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; use Throwable; @@ -76,7 +76,7 @@ protected function runMigrations(): void ], ]); - $manager = new Manager($config, new ArrayInput([]), new NullOutput()); + $manager = new MigrationManager($config, new ArrayInput([]), new NullOutput()); try { $manager->migrate('default'); diff --git a/src/Views/ViewsConfig.php b/src/Views/ViewsConfig.php index f0edb561..dc50ac02 100644 --- a/src/Views/ViewsConfig.php +++ b/src/Views/ViewsConfig.php @@ -49,14 +49,7 @@ public function sourceBasePath(string $template): string public function cachePath(string $template): string { - [$namespace, $name] = $this->parse($template); - $relativePath = Str::finish(str_replace([DIRECTORY_SEPARATOR, '/', '\\'], '.', $name), '.php'); - - if ($namespace !== null) { - $relativePath = "vendor.{$namespace}.{$relativePath}"; - } - - return $this->compiledPath($relativePath); + return $this->compiledPath(hash('sha256', $template) . '.php'); } public function compiledPath(string|null $path = null): string diff --git a/tests/Unit/Console/VendorPublishCommandTest.php b/tests/Unit/Console/VendorPublishCommandTest.php index 45460a18..d69eca49 100644 --- a/tests/Unit/Console/VendorPublishCommandTest.php +++ b/tests/Unit/Console/VendorPublishCommandTest.php @@ -191,7 +191,7 @@ ->and($command->getDisplay())->toContain("Unable to publish {$source} to {$destination}."); }); -it('replaces package migration timestamps when publishing', function (): void { +it('preserves package migration timestamps when publishing', function (): void { $source = "{$this->publishPath}/package/migrations/20240101000000_create_posts.php"; $destination = "{$this->publishPath}/database/migrations/20240101000000_create_posts.php"; mkdir(dirname($source), 0755, true); @@ -209,5 +209,5 @@ expect($published)->toHaveCount(1) ->and(basename($published[0]))->toMatch('/^\d{14}_create_posts\.php$/') - ->not->toBe('20240101000000_create_posts.php'); + ->toBe('20240101000000_create_posts.php'); }); diff --git a/tests/Unit/Packages/MigrationManagerTest.php b/tests/Unit/Packages/MigrationManagerTest.php new file mode 100644 index 00000000..a851b98c --- /dev/null +++ b/tests/Unit/Packages/MigrationManagerTest.php @@ -0,0 +1,48 @@ +addPublishPaths('MigrationProvider', [$source => $destination]); + + $config = new Config(['paths' => ['migrations' => [$source, $destination]], 'environments' => []]); + $manager = new class($config, new ArrayInput([]), new NullOutput()) extends MigrationManager { + public function files(): array + { + return $this->getMigrationFiles(); + } + }; + + $files = $manager->files(); + + expect($files)->toContain("{$destination}/{$name}") + ->not->toContain("{$source}/{$name}") + ->toContain("{$source}/20240101000001_create_tags.php"); + + unlink("{$source}/{$name}"); + unlink("{$destination}/{$name}"); + unlink("{$source}/20240101000001_create_tags.php"); + rmdir($source); + rmdir($destination); + rmdir($root); +}); diff --git a/tests/Unit/Packages/PackageManifestTest.php b/tests/Unit/Packages/PackageManifestTest.php index 9c8310f3..9955213f 100644 --- a/tests/Unit/Packages/PackageManifestTest.php +++ b/tests/Unit/Packages/PackageManifestTest.php @@ -64,3 +64,37 @@ expect($manifest->providers())->toBe([]); }); + + +it('refreshes cached packages when composer metadata or exclusions change', function (): void { + $installed = "{$this->packageApp}/vendor/composer/installed.json"; + $composer = "{$this->packageApp}/composer.json"; + + file_put_contents($composer, '{}'); + file_put_contents($installed, json_encode(['packages' => [[ + 'name' => 'acme/blog', 'extra' => ['phenix' => ['providers' => ['BlogProvider']]], + ]]], JSON_THROW_ON_ERROR)); + + expect((new PackageManifest($this->packageApp))->providers())->toBe(['BlogProvider']); + + file_put_contents($composer, json_encode(['extra' => ['phenix' => ['dont-discover' => ['acme/blog']]]], JSON_THROW_ON_ERROR)); + + expect((new PackageManifest($this->packageApp))->providers())->toBe([]); + + file_put_contents($composer, '{}'); + file_put_contents($installed, '{"packages":[]}'); + + expect((new PackageManifest($this->packageApp))->providers())->toBe([]); +}); + +it('rebuilds invalid and legacy manifests', function (): void { + $path = "{$this->packageApp}/storage/framework/cache/packages.php"; + + file_put_contents($path, 'packageApp))->providers())->toBe([]); + + file_put_contents($path, " ['providers' => ['MissingProvider']]];"); + + expect((new PackageManifest($this->packageApp))->providers())->toBe([]); +}); diff --git a/tests/Unit/Views/TemplateEngineTest.php b/tests/Unit/Views/TemplateEngineTest.php index 14795bf3..b1a32f0b 100644 --- a/tests/Unit/Views/TemplateEngineTest.php +++ b/tests/Unit/Views/TemplateEngineTest.php @@ -4,11 +4,12 @@ use Phenix\App; use Phenix\Facades\View; -use Phenix\Packages\PackageRegistry; -use Phenix\Views\Exceptions\ViewNotFoundException; +use Phenix\Views\ViewsConfig; use Phenix\Views\TemplateCache; use Phenix\Views\TemplateEngine; use Phenix\Views\TemplateFactory; +use Phenix\Packages\PackageRegistry; +use Phenix\Views\Exceptions\ViewNotFoundException; it('renders a namespaced package view', function (): void { $path = base_path('storage/framework/testing/package-views-' . uniqid()); @@ -205,3 +206,10 @@ expect($output)->toBeString(); expect($output)->toContain($action); }); + + +it('uses distinct cache files for package and application view names', function (): void { + $config = new ViewsConfig(); + + expect($config->cachePath('blog::index'))->not->toBe($config->cachePath('vendor.blog.index')); +}); From 1238fcf7c58b984a203ad16e02bc700c8340f237 Mon Sep 17 00:00:00 2001 From: barbosa89 Date: Tue, 24 Nov 2026 12:04:33 -0500 Subject: [PATCH 9/9] style: php cs --- src/Console/Commands/VendorPublish.php | 1 - src/Database/Console/DatabaseCommand.php | 2 +- src/Packages/PackageManifest.php | 2 +- src/Testing/Concerns/RefreshDatabase.php | 2 +- tests/Unit/Packages/MigrationManagerTest.php | 2 +- tests/Unit/Views/TemplateEngineTest.php | 6 +++--- 6 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/Console/Commands/VendorPublish.php b/src/Console/Commands/VendorPublish.php index e1e674f4..82fcb862 100644 --- a/src/Console/Commands/VendorPublish.php +++ b/src/Console/Commands/VendorPublish.php @@ -127,5 +127,4 @@ private function copyFile(string $source, string $destination, bool $force): boo return true; } - } diff --git a/src/Database/Console/DatabaseCommand.php b/src/Database/Console/DatabaseCommand.php index a0c6e83e..c66331e0 100644 --- a/src/Database/Console/DatabaseCommand.php +++ b/src/Database/Console/DatabaseCommand.php @@ -11,8 +11,8 @@ use Phenix\Packages\PackageRegistry; use Phinx\Config\Config as MigrationConfig; use Phinx\Console\Command\AbstractCommand; -use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputInterface; +use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Output\OutputInterface; abstract class DatabaseCommand extends AbstractCommand diff --git a/src/Packages/PackageManifest.php b/src/Packages/PackageManifest.php index 24d68848..06c383c3 100644 --- a/src/Packages/PackageManifest.php +++ b/src/Packages/PackageManifest.php @@ -5,9 +5,9 @@ namespace Phenix\Packages; use JsonException; -use Throwable; use Phenix\Exceptions\RuntimeException; use Phenix\Util\Path; +use Throwable; use function in_array; use function is_array; diff --git a/src/Testing/Concerns/RefreshDatabase.php b/src/Testing/Concerns/RefreshDatabase.php index a3f5d0b9..96d5119e 100644 --- a/src/Testing/Concerns/RefreshDatabase.php +++ b/src/Testing/Concerns/RefreshDatabase.php @@ -8,10 +8,10 @@ use Phenix\App; use Phenix\Database\Constants\Connection; use Phenix\Database\Constants\Driver; +use Phenix\Database\MigrationManager; use Phenix\Facades\Config; use Phenix\Packages\PackageRegistry; use Phinx\Config\Config as MigrationConfig; -use Phenix\Database\MigrationManager; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; use Throwable; diff --git a/tests/Unit/Packages/MigrationManagerTest.php b/tests/Unit/Packages/MigrationManagerTest.php index a851b98c..9fad7294 100644 --- a/tests/Unit/Packages/MigrationManagerTest.php +++ b/tests/Unit/Packages/MigrationManagerTest.php @@ -26,7 +26,7 @@ App::make(PackageRegistry::class)->addPublishPaths('MigrationProvider', [$source => $destination]); $config = new Config(['paths' => ['migrations' => [$source, $destination]], 'environments' => []]); - $manager = new class($config, new ArrayInput([]), new NullOutput()) extends MigrationManager { + $manager = new class ($config, new ArrayInput([]), new NullOutput()) extends MigrationManager { public function files(): array { return $this->getMigrationFiles(); diff --git a/tests/Unit/Views/TemplateEngineTest.php b/tests/Unit/Views/TemplateEngineTest.php index b1a32f0b..a48a1ee9 100644 --- a/tests/Unit/Views/TemplateEngineTest.php +++ b/tests/Unit/Views/TemplateEngineTest.php @@ -4,12 +4,12 @@ use Phenix\App; use Phenix\Facades\View; -use Phenix\Views\ViewsConfig; +use Phenix\Packages\PackageRegistry; +use Phenix\Views\Exceptions\ViewNotFoundException; use Phenix\Views\TemplateCache; use Phenix\Views\TemplateEngine; use Phenix\Views\TemplateFactory; -use Phenix\Packages\PackageRegistry; -use Phenix\Views\Exceptions\ViewNotFoundException; +use Phenix\Views\ViewsConfig; it('renders a namespaced package view', function (): void { $path = base_path('storage/framework/testing/package-views-' . uniqid());