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..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; @@ -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 RuntimeException("Service provider {$providerName} is invalid."); + } + self::$container->addServiceProvider(new $provider()); } @@ -253,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( @@ -286,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/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..82fcb862 --- /dev/null +++ b/src/Console/Commands/VendorPublish.php @@ -0,0 +1,130 @@ +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; + } + + $commandStatus = 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() . ''); + + $commandStatus = Command::FAILURE; + } + } + + return $commandStatus; + } + + private function publish(string $source, string $destination, bool $force): int + { + if (is_file($source)) { + return $this->copyFile($source, $destination, $force) ? 1 : 0; + } + + if (! is_dir($source)) { + throw new RuntimeException("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(), $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 RuntimeException("Unable to create publish directory {$directory}."); + } + + if (! @copy($source, $destination)) { + throw new RuntimeException("Unable to publish {$source} to {$destination}."); + } + + return true; + } +} 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..c66331e0 100644 --- a/src/Database/Console/DatabaseCommand.php +++ b/src/Database/Console/DatabaseCommand.php @@ -4,11 +4,16 @@ namespace Phenix\Database\Console; +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\InputInterface; use Symfony\Component\Console\Input\InputOption; +use Symfony\Component\Console\Output\OutputInterface; abstract class DatabaseCommand extends AbstractCommand { @@ -33,9 +38,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' => [ @@ -48,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/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/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; + } + + $cached = null; + + if (is_file($this->manifestPath)) { + try { + $cached = require $this->manifestPath; + } catch (Throwable) { + $cached = null; + } + } + + if ($this->needsRebuild($cached)) { + return $this->build(); + } + + return $this->manifest = $cached['packages']; + } + + public function build(): array + { + $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(['fingerprint' => $this->fingerprint(), 'packages' => $manifest]); + $this->manifest = $manifest; + + return $manifest; + } + + public function clear(): void + { + $this->manifest = null; + + if (is_file($this->manifestPath)) { + unlink($this->manifestPath); + } + } + + 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'); + + 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 RuntimeException("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 RuntimeException("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 RuntimeException("The package cache directory {$directory} could not be created."); + } + + if (! is_writable($directory)) { + throw new RuntimeException("The package cache directory {$directory} must be writable."); + } + + $temporaryPath = tempnam($directory, 'packages-'); + + if ($temporaryPath === false) { + throw new RuntimeException("Unable to create a temporary package manifest in {$directory}."); + } + + $contents = 'manifestPath)) { + @unlink($temporaryPath); + + throw new RuntimeException("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..dc28abb7 --- /dev/null +++ b/src/Packages/PackageRegistry.php @@ -0,0 +1,93 @@ +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 + { + return array_merge(...array_values($this->publishes)); + } +} 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..96d5119e 100644 --- a/src/Testing/Concerns/RefreshDatabase.php +++ b/src/Testing/Concerns/RefreshDatabase.php @@ -8,9 +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 Phinx\Migration\Manager; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Output\NullOutput; use Throwable; @@ -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' => [ @@ -68,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/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..dc50ac02 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,34 @@ 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 + { + return $this->compiledPath(hash('sha256', $template) . '.php'); + } + public function compiledPath(string|null $path = null): string { return $this->buildPath($this->config['compiled_path'], $path); @@ -32,4 +63,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/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/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..d69eca49 --- /dev/null +++ b/tests/Unit/Console/VendorPublishCommandTest.php @@ -0,0 +1,213 @@ +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 = "{$this->publishPath}/package-source.php"; + $destination = "{$this->publishPath}/package-destination.php"; + file_put_contents($source, '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.'); +}); + +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('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); + 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$/') + ->toBe('20240101000000_create_posts.php'); +}); 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/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/MigrationManagerTest.php b/tests/Unit/Packages/MigrationManagerTest.php new file mode 100644 index 00000000..9fad7294 --- /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 new file mode 100644 index 00000000..9955213f --- /dev/null +++ b/tests/Unit/Packages/PackageManifestTest.php @@ -0,0 +1,100 @@ +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([]); +}); + + +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/Packages/PackageRegistryTest.php b/tests/Unit/Packages/PackageRegistryTest.php new file mode 100644 index 00000000..183755ee --- /dev/null +++ b/tests/Unit/Packages/PackageRegistryTest.php @@ -0,0 +1,69 @@ +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'); +}); + +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/Internal/PackageServiceProvider.php b/tests/Unit/Providers/Internal/PackageServiceProvider.php new file mode 100644 index 00000000..8e76ee2e --- /dev/null +++ b/tests/Unit/Providers/Internal/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); + } +} diff --git a/tests/Unit/Providers/ServiceProviderTest.php b/tests/Unit/Providers/ServiceProviderTest.php new file mode 100644 index 00000000..afa95caf --- /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/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); } 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..a48a1ee9 100644 --- a/tests/Unit/Views/TemplateEngineTest.php +++ b/tests/Unit/Views/TemplateEngineTest.php @@ -2,11 +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; +use Phenix\Views\ViewsConfig; + +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(); @@ -184,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')); +}); 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