Refactor package stage handling and update class structures for improved flexibility

This commit is contained in:
crazywhalecc 2025-12-09 14:58:11 +08:00
parent e004d10861
commit 808aed2a66
No known key found for this signature in database
GPG Key ID: 1F4BDD59391F2680
29 changed files with 416 additions and 115 deletions

View File

@ -13,6 +13,7 @@
"ext-mbstring": "*", "ext-mbstring": "*",
"ext-zlib": "*", "ext-zlib": "*",
"laravel/prompts": "~0.1", "laravel/prompts": "~0.1",
"nette/php-generator": "^4.2",
"php-di/php-di": "^7.1", "php-di/php-di": "^7.1",
"symfony/console": "^5.4 || ^6 || ^7", "symfony/console": "^5.4 || ^6 || ^7",
"symfony/process": "^7.2", "symfony/process": "^7.2",

163
composer.lock generated
View File

@ -4,7 +4,7 @@
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically" "This file is @generated automatically"
], ],
"content-hash": "14b3ad42c138807fa9288e6b510ac69f", "content-hash": "edb3243ddaa8b05d8f6545266a146e93",
"packages": [ "packages": [
{ {
"name": "laravel/prompts", "name": "laravel/prompts",
@ -126,6 +126,167 @@
}, },
"time": "2025-11-21T20:52:36+00:00" "time": "2025-11-21T20:52:36+00:00"
}, },
{
"name": "nette/php-generator",
"version": "v4.2.0",
"source": {
"type": "git",
"url": "https://github.com/nette/php-generator.git",
"reference": "4707546a1f11badd72f5d82af4f8a6bc64bd56ac"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nette/php-generator/zipball/4707546a1f11badd72f5d82af4f8a6bc64bd56ac",
"reference": "4707546a1f11badd72f5d82af4f8a6bc64bd56ac",
"shasum": ""
},
"require": {
"nette/utils": "^4.0.6",
"php": "8.1 - 8.5"
},
"require-dev": {
"jetbrains/phpstorm-attributes": "^1.2",
"nette/tester": "^2.4",
"nikic/php-parser": "^5.0",
"phpstan/phpstan-nette": "^2.0@stable",
"tracy/tracy": "^2.8"
},
"suggest": {
"nikic/php-parser": "to use ClassType::from(withBodies: true) & ClassType::fromCode()"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "4.2-dev"
}
},
"autoload": {
"psr-4": {
"Nette\\": "src"
},
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause",
"GPL-2.0-only",
"GPL-3.0-only"
],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "https://nette.org/contributors"
}
],
"description": "🐘 Nette PHP Generator: generates neat PHP code for you. Supports new PHP 8.5 features.",
"homepage": "https://nette.org",
"keywords": [
"code",
"nette",
"php",
"scaffolding"
],
"support": {
"issues": "https://github.com/nette/php-generator/issues",
"source": "https://github.com/nette/php-generator/tree/v4.2.0"
},
"time": "2025-08-06T18:24:31+00:00"
},
{
"name": "nette/utils",
"version": "v4.1.0",
"source": {
"type": "git",
"url": "https://github.com/nette/utils.git",
"reference": "fa1f0b8261ed150447979eb22e373b7b7ad5a8e0"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/nette/utils/zipball/fa1f0b8261ed150447979eb22e373b7b7ad5a8e0",
"reference": "fa1f0b8261ed150447979eb22e373b7b7ad5a8e0",
"shasum": ""
},
"require": {
"php": "8.2 - 8.5"
},
"conflict": {
"nette/finder": "<3",
"nette/schema": "<1.2.2"
},
"require-dev": {
"jetbrains/phpstorm-attributes": "^1.2",
"nette/tester": "^2.5",
"phpstan/phpstan-nette": "^2.0@stable",
"tracy/tracy": "^2.9"
},
"suggest": {
"ext-gd": "to use Image",
"ext-iconv": "to use Strings::webalize(), toAscii(), chr() and reverse()",
"ext-intl": "to use Strings::webalize(), toAscii(), normalize() and compare()",
"ext-json": "to use Nette\\Utils\\Json",
"ext-mbstring": "to use Strings::lower() etc...",
"ext-tokenizer": "to use Nette\\Utils\\Reflection::getUseStatements()"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "4.1-dev"
}
},
"autoload": {
"psr-4": {
"Nette\\": "src"
},
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause",
"GPL-2.0-only",
"GPL-3.0-only"
],
"authors": [
{
"name": "David Grudl",
"homepage": "https://davidgrudl.com"
},
{
"name": "Nette Community",
"homepage": "https://nette.org/contributors"
}
],
"description": "🛠 Nette Utils: lightweight utilities for string & array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.",
"homepage": "https://nette.org",
"keywords": [
"array",
"core",
"datetime",
"images",
"json",
"nette",
"paginator",
"password",
"slugify",
"string",
"unicode",
"utf-8",
"utility",
"validation"
],
"support": {
"issues": "https://github.com/nette/utils/issues",
"source": "https://github.com/nette/utils/tree/v4.1.0"
},
"time": "2025-12-01T17:49:23+00:00"
},
{ {
"name": "php-di/invoker", "name": "php-di/invoker",
"version": "2.3.7", "version": "2.3.7",

View File

@ -9,7 +9,7 @@ use StaticPHP\Artifact\ArtifactDownloader;
use StaticPHP\Artifact\DownloaderOptions; use StaticPHP\Artifact\DownloaderOptions;
use StaticPHP\Command\BaseCommand; use StaticPHP\Command\BaseCommand;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Package\PackageLoader; use StaticPHP\Registry\PackageLoader;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Attribute\AsCommand;

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Package\Extension; namespace Package\Extension;
use Package\Target\php;
use StaticPHP\Attribute\Package\AfterStage; use StaticPHP\Attribute\Package\AfterStage;
use StaticPHP\Attribute\Package\BeforeStage; use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\Extension; use StaticPHP\Attribute\Package\Extension;
@ -15,7 +16,7 @@ use StaticPHP\Util\SourcePatcher;
#[Extension('readline')] #[Extension('readline')]
class readline class readline
{ {
#[BeforeStage('php', 'unix-make-cli', 'ext-readline')] #[BeforeStage('php', [php::class, 'makeCliForUnix'], 'ext-readline')]
#[PatchDescription('Fix readline static build with musl')] #[PatchDescription('Fix readline static build with musl')]
public function beforeMakeLinuxCli(PackageInstaller $installer, ToolchainInterface $toolchain): void public function beforeMakeLinuxCli(PackageInstaller $installer, ToolchainInterface $toolchain): void
{ {
@ -25,7 +26,7 @@ class readline
} }
} }
#[AfterStage('php', 'unix-make-cli', 'ext-readline')] #[AfterStage('php', [php::class, 'makeCliForUnix'], 'ext-readline')]
public function afterMakeLinuxCli(PackageInstaller $installer, ToolchainInterface $toolchain): void public function afterMakeLinuxCli(PackageInstaller $installer, ToolchainInterface $toolchain): void
{ {
if ($toolchain->isStatic()) { if ($toolchain->isStatic()) {

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Package\Library; namespace Package\Library;
use Package\Target\php;
use StaticPHP\Attribute\Package\AfterStage; use StaticPHP\Attribute\Package\AfterStage;
use StaticPHP\Attribute\Package\Library; use StaticPHP\Attribute\Package\Library;
use StaticPHP\Attribute\PatchDescription; use StaticPHP\Attribute\PatchDescription;
@ -13,7 +14,7 @@ use StaticPHP\Util\FileSystem;
#[Library('imap')] #[Library('imap')]
class imap class imap
{ {
#[AfterStage('php', 'patch-embed-scripts', 'imap')] #[AfterStage('php', [php::class, 'patchEmbedScripts'], 'imap')]
#[PatchDescription('Fix missing -lcrypt in php-config libs on glibc systems')] #[PatchDescription('Fix missing -lcrypt in php-config libs on glibc systems')]
public function afterPatchScripts(): void public function afterPatchScripts(): void
{ {

View File

@ -14,7 +14,7 @@ use StaticPHP\Util\FileSystem;
#[Library('libedit')] #[Library('libedit')]
class libedit extends LibraryPackage class libedit extends LibraryPackage
{ {
#[BeforeStage('libedit', 'build')] #[BeforeStage(stage: 'build')]
public function patchBeforeBuild(): void public function patchBeforeBuild(): void
{ {
FileSystem::replaceFileRegex( FileSystem::replaceFileRegex(

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace Package\Library; namespace Package\Library;
use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage; use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\Library; use StaticPHP\Attribute\Package\Library;
use StaticPHP\Attribute\PatchDescription; use StaticPHP\Attribute\PatchDescription;
@ -12,7 +13,7 @@ use StaticPHP\Package\TargetPackage;
#[Library('postgresql')] #[Library('postgresql')]
class postgresql class postgresql
{ {
#[BeforeStage('php', 'unix-configure', 'postgresql')] #[BeforeStage('php', [php::class, 'configureForUnix'], 'postgresql')]
#[PatchDescription('Patch to avoid explicit_bzero detection issues on some systems')] #[PatchDescription('Patch to avoid explicit_bzero detection issues on some systems')]
public function patchBeforePHPConfigure(TargetPackage $package): void public function patchBeforePHPConfigure(TargetPackage $package): void
{ {

View File

@ -13,7 +13,7 @@ use StaticPHP\Util\FileSystem;
#[Target('php-micro')] #[Target('php-micro')]
class micro class micro
{ {
#[BeforeStage('php', 'unix-make-embed', 'php-micro')] #[BeforeStage('php', [php::class, 'makeEmbedForUnix'], 'php-micro')]
#[PatchDescription('Patch Makefile to build only libphp.la for embedding')] #[PatchDescription('Patch Makefile to build only libphp.la for embedding')]
public function patchBeforeEmbed(TargetPackage $package): void public function patchBeforeEmbed(TargetPackage $package): void
{ {

View File

@ -4,7 +4,6 @@ declare(strict_types=1);
namespace Package\Target; namespace Package\Target;
use StaticPHP\Artifact\ArtifactLoader;
use StaticPHP\Attribute\Package\BeforeStage; use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\BuildFor; use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Info; use StaticPHP\Attribute\Package\Info;
@ -21,9 +20,10 @@ use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Package\Package; use StaticPHP\Package\Package;
use StaticPHP\Package\PackageBuilder; use StaticPHP\Package\PackageBuilder;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PackageLoader;
use StaticPHP\Package\PhpExtensionPackage; use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Registry\PackageLoader;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\Interface\ToolchainInterface; use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ToolchainManager; use StaticPHP\Toolchain\ToolchainManager;
@ -241,7 +241,7 @@ class php
FileSystem::removeDir(BUILD_MODULES_PATH); FileSystem::removeDir(BUILD_MODULES_PATH);
} }
#[BeforeStage('php', 'unix-buildconf')] #[BeforeStage('php', [self::class, 'buildconfForUnix'], 'php')]
#[PatchDescription('Patch configure.ac for musl and musl-toolchain')] #[PatchDescription('Patch configure.ac for musl and musl-toolchain')]
#[PatchDescription('Let php m4 tools use static pkg-config')] #[PatchDescription('Let php m4 tools use static pkg-config')]
public function patchBeforeBuildconf(TargetPackage $package): void public function patchBeforeBuildconf(TargetPackage $package): void
@ -259,7 +259,7 @@ class php
FileSystem::replaceFileStr("{$package->getSourceDir()}/build/php.m4", 'PKG_CHECK_MODULES(', 'PKG_CHECK_MODULES_STATIC('); FileSystem::replaceFileStr("{$package->getSourceDir()}/build/php.m4", 'PKG_CHECK_MODULES(', 'PKG_CHECK_MODULES_STATIC(');
} }
#[Stage('unix-buildconf')] #[Stage]
public function buildconfForUnix(TargetPackage $package): void public function buildconfForUnix(TargetPackage $package): void
{ {
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./buildconf')); InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./buildconf'));
@ -267,7 +267,7 @@ class php
shell()->cd($package->getSourceDir())->exec(getenv('SPC_CMD_PREFIX_PHP_BUILDCONF')); shell()->cd($package->getSourceDir())->exec(getenv('SPC_CMD_PREFIX_PHP_BUILDCONF'));
} }
#[Stage('unix-configure')] #[Stage]
public function configureForUnix(TargetPackage $package, PackageInstaller $installer): void public function configureForUnix(TargetPackage $package, PackageInstaller $installer): void
{ {
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./configure')); InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./configure'));
@ -317,7 +317,7 @@ class php
])->exec("{$cmd} {$args} {$static_extension_str}"), $package->getSourceDir()); ])->exec("{$cmd} {$args} {$static_extension_str}"), $package->getSourceDir());
} }
#[Stage('unix-make')] #[Stage]
public function makeForUnix(TargetPackage $package, PackageInstaller $installer): void public function makeForUnix(TargetPackage $package, PackageInstaller $installer): void
{ {
V2CompatLayer::emitPatchPoint('before-php-make'); V2CompatLayer::emitPatchPoint('before-php-make');
@ -326,23 +326,23 @@ class php
shell()->cd($package->getSourceDir())->exec('make clean'); shell()->cd($package->getSourceDir())->exec('make clean');
if ($installer->isPackageResolved('php-cli')) { if ($installer->isPackageResolved('php-cli')) {
$package->runStage('unix-make-cli'); $package->runStage([self::class, 'makeCliForUnix']);
} }
if ($installer->isPackageResolved('php-cgi')) { if ($installer->isPackageResolved('php-cgi')) {
$package->runStage('unix-make-cgi'); $package->runStage([self::class, 'makeCgiForUnix']);
} }
if ($installer->isPackageResolved('php-fpm')) { if ($installer->isPackageResolved('php-fpm')) {
$package->runStage('unix-make-fpm'); $package->runStage([self::class, 'makeFpmForUnix']);
} }
if ($installer->isPackageResolved('php-micro')) { if ($installer->isPackageResolved('php-micro')) {
$package->runStage('unix-make-micro'); $package->runStage([self::class, 'makeMicroForUnix']);
} }
if ($installer->isPackageResolved('php-embed')) { if ($installer->isPackageResolved('php-embed')) {
$package->runStage('unix-make-embed'); $package->runStage([self::class, 'makeEmbedForUnix']);
} }
} }
#[Stage('unix-make-cli')] #[Stage]
public function makeCliForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void public function makeCliForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
{ {
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make cli')); InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make cli'));
@ -352,7 +352,7 @@ class php
->exec("make -j{$concurrency} cli"); ->exec("make -j{$concurrency} cli");
} }
#[Stage('unix-make-cgi')] #[Stage]
public function makeCgiForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void public function makeCgiForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
{ {
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make cgi')); InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make cgi'));
@ -362,7 +362,7 @@ class php
->exec("make -j{$concurrency} cgi"); ->exec("make -j{$concurrency} cgi");
} }
#[Stage('unix-make-fpm')] #[Stage]
public function makeFpmForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void public function makeFpmForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
{ {
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make fpm')); InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make fpm'));
@ -372,7 +372,7 @@ class php
->exec("make -j{$concurrency} fpm"); ->exec("make -j{$concurrency} fpm");
} }
#[Stage('unix-make-micro')] #[Stage]
#[PatchDescription('Patch phar extension for micro SAPI to support compressed phar')] #[PatchDescription('Patch phar extension for micro SAPI to support compressed phar')]
public function makeMicroForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void public function makeMicroForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
{ {
@ -399,7 +399,7 @@ class php
} }
} }
#[Stage('unix-make-embed')] #[Stage]
public function makeEmbedForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void public function makeEmbedForUnix(TargetPackage $package, PackageInstaller $installer, PackageBuilder $builder): void
{ {
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make embed')); InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('make embed'));
@ -452,10 +452,10 @@ class php
UnixUtil::exportDynamicSymbols($libphp_a); UnixUtil::exportDynamicSymbols($libphp_a);
// deploy embed php scripts // deploy embed php scripts
$package->runStage('patch-embed-scripts'); $package->runStage([$this, 'patchEmbedScripts']);
} }
#[Stage('unix-build-shared-ext')] #[Stage]
public function unixBuildSharedExt(PackageInstaller $installer, ToolchainInterface $toolchain): void public function unixBuildSharedExt(PackageInstaller $installer, ToolchainInterface $toolchain): void
{ {
// collect shared extensions // collect shared extensions
@ -506,18 +506,18 @@ class php
return; return;
} }
$package->runStage('unix-buildconf'); $package->runStage([$this, 'buildconfForUnix']);
$package->runStage('unix-configure'); $package->runStage([$this, 'configureForUnix']);
$package->runStage('unix-make'); $package->runStage([$this, 'makeForUnix']);
$package->runStage('unix-build-shared-ext'); $package->runStage([$this, 'unixBuildSharedExt']);
} }
/** /**
* Patch phpize and php-config if needed * Patch phpize and php-config if needed
*/ */
#[Stage('patch-embed-scripts')] #[Stage]
public function patchPhpScripts(): void public function patchEmbedScripts(): void
{ {
// patch phpize // patch phpize
if (file_exists(BUILD_BIN_PATH . '/phpize')) { if (file_exists(BUILD_BIN_PATH . '/phpize')) {

View File

@ -24,6 +24,7 @@ use StaticPHP\Exception\ExecutionException;
use StaticPHP\Exception\SPCException; use StaticPHP\Exception\SPCException;
use StaticPHP\Exception\ValidationException; use StaticPHP\Exception\ValidationException;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Runtime\Shell\Shell; use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;

View File

@ -9,6 +9,7 @@ use StaticPHP\Exception\FileSystemException;
use StaticPHP\Exception\SPCInternalException; use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Package\Package; use StaticPHP\Package\Package;
use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Runtime\Shell\Shell; use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Runtime\SystemTarget; use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;

View File

@ -10,5 +10,5 @@ namespace StaticPHP\Attribute\Package;
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] #[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
readonly class AfterStage readonly class AfterStage
{ {
public function __construct(public string $package_name, public string $stage, public ?string $only_when_package_resolved = null) {} public function __construct(public string $package_name, public array|string $stage, public ?string $only_when_package_resolved = null) {}
} }

View File

@ -8,7 +8,12 @@ namespace StaticPHP\Attribute\Package;
* Indicates that the annotated method should be executed before a specific stage of the build process for a given package. * Indicates that the annotated method should be executed before a specific stage of the build process for a given package.
*/ */
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] #[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
readonly class BeforeStage class BeforeStage
{ {
public function __construct(public string $package_name, public string $stage, public ?string $only_when_package_resolved = null) {} public readonly array|string $stage;
public function __construct(public string $package_name = '', array|callable|string $stage = '', public ?string $only_when_package_resolved = null)
{
$this->stage = $stage;
}
} }

View File

@ -10,5 +10,5 @@ namespace StaticPHP\Attribute\Package;
#[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] #[\Attribute(\Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
readonly class Stage readonly class Stage
{ {
public function __construct(public string $name) {} public function __construct(public ?string $function = null) {}
} }

View File

@ -6,7 +6,7 @@ namespace StaticPHP\Command;
use StaticPHP\Artifact\DownloaderOptions; use StaticPHP\Artifact\DownloaderOptions;
use StaticPHP\Package\PackageInstaller; use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PackageLoader; use StaticPHP\Registry\PackageLoader;
use StaticPHP\Util\V2CompatLayer; use StaticPHP\Util\V2CompatLayer;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;

View File

@ -6,7 +6,7 @@ namespace StaticPHP\Command;
use StaticPHP\Artifact\ArtifactDownloader; use StaticPHP\Artifact\ArtifactDownloader;
use StaticPHP\Artifact\DownloaderOptions; use StaticPHP\Artifact\DownloaderOptions;
use StaticPHP\Package\PackageLoader; use StaticPHP\Registry\PackageLoader;
use StaticPHP\Util\DependencyResolver; use StaticPHP\Util\DependencyResolver;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;

View File

@ -6,9 +6,9 @@ namespace StaticPHP\Command;
use StaticPHP\Artifact\ArtifactCache; use StaticPHP\Artifact\ArtifactCache;
use StaticPHP\Artifact\ArtifactExtractor; use StaticPHP\Artifact\ArtifactExtractor;
use StaticPHP\Artifact\ArtifactLoader;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Package\PackageLoader; use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Registry\PackageLoader;
use StaticPHP\Util\DependencyResolver; use StaticPHP\Util\DependencyResolver;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Attribute\AsCommand; use Symfony\Component\Console\Attribute\AsCommand;

View File

@ -13,8 +13,9 @@ use StaticPHP\Command\DownloadCommand;
use StaticPHP\Command\ExtractCommand; use StaticPHP\Command\ExtractCommand;
use StaticPHP\Command\InstallPackageCommand; use StaticPHP\Command\InstallPackageCommand;
use StaticPHP\Command\SPCConfigCommand; use StaticPHP\Command\SPCConfigCommand;
use StaticPHP\Package\PackageLoader;
use StaticPHP\Package\TargetPackage; use StaticPHP\Package\TargetPackage;
use StaticPHP\Registry\PackageLoader;
use StaticPHP\Registry\Registry;
use Symfony\Component\Console\Application; use Symfony\Component\Console\Application;
class ConsoleApplication extends Application class ConsoleApplication extends Application
@ -29,6 +30,9 @@ class ConsoleApplication extends Application
require_once ROOT_DIR . '/src/bootstrap.php'; require_once ROOT_DIR . '/src/bootstrap.php';
// check registry
Registry::checkLoadedRegistries();
/** /**
* @var string $name * @var string $name
* @var TargetPackage $package * @var TargetPackage $package

View File

@ -7,6 +7,7 @@ namespace StaticPHP\Doctor;
use StaticPHP\Attribute\Doctor\CheckItem; use StaticPHP\Attribute\Doctor\CheckItem;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\SPCException; use StaticPHP\Exception\SPCException;
use StaticPHP\Registry\DoctorLoader;
use StaticPHP\Runtime\Shell\Shell; use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Output\OutputInterface;

View File

@ -38,13 +38,6 @@ class ZigCheck
#[FixItem('install-zig')] #[FixItem('install-zig')]
public function installZig(): bool public function installZig(): bool
{ {
$arch = arch2gnu(php_uname('m'));
$os = match (PHP_OS_FAMILY) {
'Windows' => 'win',
'Darwin' => 'macos',
'BSD' => 'freebsd',
default => 'linux',
};
$installer = new PackageInstaller(); $installer = new PackageInstaller();
$installer->addInstallPackage('zig'); $installer->addInstallPackage('zig');
$installer->run(false); $installer->run(false);

View File

@ -25,11 +25,13 @@ class ExceptionHandler
SPCInternalException::class, SPCInternalException::class,
ValidationException::class, ValidationException::class,
WrongUsageException::class, WrongUsageException::class,
RegistryException::class,
]; ];
public const array MINOR_LOG_EXCEPTIONS = [ public const array MINOR_LOG_EXCEPTIONS = [
InterruptException::class, InterruptException::class,
WrongUsageException::class, WrongUsageException::class,
RegistryException::class,
]; ];
/** @var null|BuilderBase Builder binding */ /** @var null|BuilderBase Builder binding */
@ -52,6 +54,7 @@ class ExceptionHandler
SPCInternalException::class => "✗ SPC internal error: {$e->getMessage()}", SPCInternalException::class => "✗ SPC internal error: {$e->getMessage()}",
ValidationException::class => "⚠ Validation failed: {$e->getMessage()}", ValidationException::class => "⚠ Validation failed: {$e->getMessage()}",
WrongUsageException::class => $e->getMessage(), WrongUsageException::class => $e->getMessage(),
RegistryException::class => "✗ Registry parsing error: {$e->getMessage()}",
default => "✗ Unknown SPC exception {$class}: {$e->getMessage()}", default => "✗ Unknown SPC exception {$class}: {$e->getMessage()}",
}; };
self::logError($head_msg); self::logError($head_msg);

View File

@ -0,0 +1,7 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Exception;
class RegistryException extends SPCException {}

View File

@ -5,10 +5,11 @@ declare(strict_types=1);
namespace StaticPHP\Package; namespace StaticPHP\Package;
use StaticPHP\Artifact\Artifact; use StaticPHP\Artifact\Artifact;
use StaticPHP\Artifact\ArtifactLoader;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\SPCInternalException; use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Registry\ArtifactLoader;
use StaticPHP\Registry\PackageLoader;
abstract class Package abstract class Package
{ {
@ -32,15 +33,25 @@ abstract class Package
* Run a defined stage of the package. * Run a defined stage of the package.
* If the stage is not defined, an exception should be thrown. * If the stage is not defined, an exception should be thrown.
* *
* @param string $name Name of the stage to run * @param array|callable|string $name Name of the stage to run (can be callable)
* @param array $context Additional context to pass to the stage callback * @param array $context Additional context to pass to the stage callback
* @return mixed Based on the stage definition, return the result of the stage * @return mixed Based on the stage definition, return the result of the stage
*/ */
public function runStage(string $name, array $context = []): mixed public function runStage(mixed $name, array $context = []): mixed
{ {
if (!isset($this->stages[$name])) { if (!$this->hasStage($name)) {
$name = match (true) {
is_string($name) => $name,
is_array($name) && count($name) === 2 => $name[1], // use function name
default => '{' . gettype($name) . '}',
};
throw new SPCInternalException("Stage '{$name}' is not defined for package '{$this->name}'."); throw new SPCInternalException("Stage '{$name}' is not defined for package '{$this->name}'.");
} }
$name = match (true) {
is_string($name) => $name,
is_array($name) && count($name) === 2 => $name[1], // use function name
default => throw new SPCInternalException('Invalid stage name type: ' . gettype($name)),
};
// Merge package context with provided context // Merge package context with provided context
/** @noinspection PhpDuplicateArrayKeysInspection */ /** @noinspection PhpDuplicateArrayKeysInspection */
@ -80,9 +91,6 @@ abstract class Package
/** /**
* Add a stage to the package. * Add a stage to the package.
*
* @param string $name Stage name
* @param callable $stage Stage callable
*/ */
public function addStage(string $name, callable $stage): void public function addStage(string $name, callable $stage): void
{ {
@ -92,11 +100,17 @@ abstract class Package
/** /**
* Check if the package has a specific stage defined. * Check if the package has a specific stage defined.
* *
* @param string $name Stage name * @param mixed $name Stage name
*/ */
public function hasStage(string $name): bool public function hasStage(mixed $name): bool
{ {
return isset($this->stages[$name]); if (is_array($name) && count($name) === 2) {
return isset($this->stages[$name[1]]); // use function name
}
if (is_string($name)) {
return isset($this->stages[$name]); // use defined name
}
return false;
} }
/** /**

View File

@ -11,6 +11,7 @@ use StaticPHP\Artifact\ArtifactExtractor;
use StaticPHP\Artifact\DownloaderOptions; use StaticPHP\Artifact\DownloaderOptions;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Registry\PackageLoader;
use StaticPHP\Util\DependencyResolver; use StaticPHP\Util\DependencyResolver;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm; use StaticPHP\Util\InteractiveTerm;

View File

@ -4,6 +4,7 @@ declare(strict_types=1);
namespace StaticPHP\Package; namespace StaticPHP\Package;
use StaticPHP\Attribute\Package\Stage;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\ValidationException; use StaticPHP\Exception\ValidationException;
@ -100,22 +101,6 @@ class PhpExtensionPackage extends Package
public function setBuildShared(bool $build_shared = true): void public function setBuildShared(bool $build_shared = true): void
{ {
$this->build_shared = $build_shared; $this->build_shared = $build_shared;
// Add build stages for shared build on Unix-like systems
// TODO: Windows shared build support
if ($build_shared && in_array(SystemTarget::getTargetOS(), ['Linux', 'Darwin'])) {
if (!$this->hasStage('build')) {
$this->addBuildFunction(SystemTarget::getTargetOS(), [$this, '_buildSharedUnix']);
}
if (!$this->hasStage('phpize')) {
$this->addStage('phpize', [$this, '_phpize']);
}
if (!$this->hasStage('configure')) {
$this->addStage('configure', [$this, '_configure']);
}
if (!$this->hasStage('make')) {
$this->addStage('make', [$this, '_make']);
}
}
} }
public function setBuildStatic(bool $build_static = true): void public function setBuildStatic(bool $build_static = true): void
@ -180,18 +165,18 @@ class PhpExtensionPackage extends Package
/** /**
* @internal * @internal
* #[Stage('phpize')]
*/ */
public function _phpize(array $env, PhpExtensionPackage $package): void #[Stage]
public function phpizeForUnix(array $env, PhpExtensionPackage $package): void
{ {
shell()->cd($package->getSourceDir())->setEnv($env)->exec(BUILD_BIN_PATH . '/phpize'); shell()->cd($package->getSourceDir())->setEnv($env)->exec(BUILD_BIN_PATH . '/phpize');
} }
/** /**
* @internal * @internal
* #[Stage('configure')]
*/ */
public function _configure(array $env, PhpExtensionPackage $package): void #[Stage]
public function configureForUnix(array $env, PhpExtensionPackage $package): void
{ {
$phpvars = getenv('SPC_EXTRA_PHP_VARS') ?: ''; $phpvars = getenv('SPC_EXTRA_PHP_VARS') ?: '';
shell()->cd($package->getSourceDir()) shell()->cd($package->getSourceDir())
@ -205,9 +190,9 @@ class PhpExtensionPackage extends Package
/** /**
* @internal * @internal
* #[Stage('make')]
*/ */
public function _make(array $env, PhpExtensionPackage $package, PackageBuilder $builder): void #[Stage]
public function makeForUnix(array $env, PhpExtensionPackage $package, PackageBuilder $builder): void
{ {
shell()->cd($package->getSourceDir()) shell()->cd($package->getSourceDir())
->setEnv($env) ->setEnv($env)
@ -222,13 +207,13 @@ class PhpExtensionPackage extends Package
* @internal * @internal
* #[Stage('build')] * #[Stage('build')]
*/ */
public function _buildSharedUnix(PackageBuilder $builder): void public function buildSharedForUnix(PackageBuilder $builder): void
{ {
$env = $this->getSharedExtensionEnv(); $env = $this->getSharedExtensionEnv();
$this->runStage('phpize', ['env' => $env]); $this->runStage('phpizeForUnix', ['env' => $env]);
$this->runStage('configure', ['env' => $env]); $this->runStage('configureForUnix', ['env' => $env]);
$this->runStage('make', ['env' => $env]); $this->runStage('makeForUnix', ['env' => $env]);
// process *.so file // process *.so file
$soFile = BUILD_MODULES_PATH . '/' . $this->getExtensionName() . '.so'; $soFile = BUILD_MODULES_PATH . '/' . $this->getExtensionName() . '.so';
@ -238,6 +223,32 @@ class PhpExtensionPackage extends Package
$builder->deployBinary($soFile, $soFile, false); $builder->deployBinary($soFile, $soFile, false);
} }
/**
* Register default stages if not already defined by attributes.
* This is called after all attributes have been loaded.
*
* @internal Called by PackageLoader after loading attributes
*/
public function registerDefaultStages(): void
{
// Add build stages for shared build on Unix-like systems
// TODO: Windows shared build support
if ($this->build_shared && in_array(SystemTarget::getTargetOS(), ['Linux', 'Darwin'])) {
if (!$this->hasStage('build')) {
$this->addBuildFunction(SystemTarget::getTargetOS(), [$this, 'buildSharedForUnix']);
}
if (!$this->hasStage('phpizeForUnix')) {
$this->addStage('phpizeForUnix', [$this, 'phpizeForUnix']);
}
if (!$this->hasStage('configureForUnix')) {
$this->addStage('configureForUnix', [$this, 'configureForUnix']);
}
if (!$this->hasStage('makeForUnix')) {
$this->addStage('makeForUnix', [$this, 'makeForUnix']);
}
}
}
/** /**
* Splits a given string of library flags into static and shared libraries. * Splits a given string of library flags into static and shared libraries.
* *

View File

@ -2,8 +2,9 @@
declare(strict_types=1); declare(strict_types=1);
namespace StaticPHP\Artifact; namespace StaticPHP\Registry;
use StaticPHP\Artifact\Artifact;
use StaticPHP\Attribute\Artifact\AfterBinaryExtract; use StaticPHP\Attribute\Artifact\AfterBinaryExtract;
use StaticPHP\Attribute\Artifact\AfterSourceExtract; use StaticPHP\Attribute\Artifact\AfterSourceExtract;
use StaticPHP\Attribute\Artifact\BinaryExtract; use StaticPHP\Attribute\Artifact\BinaryExtract;

View File

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace StaticPHP\Doctor; namespace StaticPHP\Registry;
use StaticPHP\Attribute\Doctor\CheckItem; use StaticPHP\Attribute\Doctor\CheckItem;
use StaticPHP\Attribute\Doctor\FixItem; use StaticPHP\Attribute\Doctor\FixItem;

View File

@ -2,7 +2,7 @@
declare(strict_types=1); declare(strict_types=1);
namespace StaticPHP\Package; namespace StaticPHP\Registry;
use StaticPHP\Attribute\Package\AfterStage; use StaticPHP\Attribute\Package\AfterStage;
use StaticPHP\Attribute\Package\BeforeStage; use StaticPHP\Attribute\Package\BeforeStage;
@ -19,8 +19,13 @@ use StaticPHP\Attribute\Package\Target;
use StaticPHP\Attribute\Package\Validate; use StaticPHP\Attribute\Package\Validate;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext; use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\ValidationException; use StaticPHP\Exception\RegistryException;
use StaticPHP\Exception\WrongUsageException; use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Package\LibraryPackage;
use StaticPHP\Package\Package;
use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Package\TargetPackage;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
class PackageLoader class PackageLoader
@ -30,9 +35,7 @@ class PackageLoader
private static array $before_stages = []; private static array $before_stages = [];
private static array $after_stage = []; private static array $after_stages = [];
private static array $patch_before_builds = [];
/** @var array<string, true> Track loaded classes to prevent duplicates */ /** @var array<string, true> Track loaded classes to prevent duplicates */
private static array $loaded_classes = []; private static array $loaded_classes = [];
@ -53,7 +56,7 @@ class PackageLoader
if ($pkg !== null) { if ($pkg !== null) {
self::$packages[$name] = $pkg; self::$packages[$name] = $pkg;
} else { } else {
throw new WrongUsageException("Package [{$name}] has unknown type [{$item['type']}]"); throw new RegistryException("Package [{$name}] has unknown type [{$item['type']}]");
} }
} }
} }
@ -156,7 +159,7 @@ class PackageLoader
} }
$package_type = PackageConfig::get($attribute_instance->name, 'type'); $package_type = PackageConfig::get($attribute_instance->name, 'type');
if ($package_type === null) { if ($package_type === null) {
throw new WrongUsageException("Package [{$attribute_instance->name}] not defined in config, please check your config files."); throw new RegistryException("Package [{$attribute_instance->name}] not defined in config, please check your config files.");
} }
// if class has parent class and matches the attribute instance, use custom class // if class has parent class and matches the attribute instance, use custom class
@ -181,10 +184,10 @@ class PackageLoader
default => null, default => null,
}; };
if (!in_array($package_type, $pkg_type_attr, true)) { if (!in_array($package_type, $pkg_type_attr, true)) {
throw new ValidationException("Package [{$attribute_instance->name}] type mismatch: config type is [{$package_type}], but attribute type is [" . implode('|', $pkg_type_attr) . '].'); throw new RegistryException("Package [{$attribute_instance->name}] type mismatch: config type is [{$package_type}], but attribute type is [" . implode('|', $pkg_type_attr) . '].');
} }
if ($pkg !== null && !PackageConfig::isPackageExists($pkg->getName())) { if ($pkg !== null && !PackageConfig::isPackageExists($pkg->getName())) {
throw new ValidationException("Package [{$pkg->getName()}] config not found for class {$class}"); throw new RegistryException("Package [{$pkg->getName()}] config not found for class {$class}");
} }
// init method attributes // init method attributes
@ -199,7 +202,7 @@ class PackageLoader
// #[CustomPhpConfigureArg(PHP_OS_FAMILY)] // #[CustomPhpConfigureArg(PHP_OS_FAMILY)]
CustomPhpConfigureArg::class => self::bindCustomPhpConfigureArg($pkg, $method_attribute->newInstance(), [$instance_class, $method->getName()]), CustomPhpConfigureArg::class => self::bindCustomPhpConfigureArg($pkg, $method_attribute->newInstance(), [$instance_class, $method->getName()]),
// #[Stage('stage_name')] // #[Stage('stage_name')]
Stage::class => $pkg->addStage($method_attribute->newInstance()->name, [$instance_class, $method->getName()]), Stage::class => self::addStage($method, $pkg, $instance_class, $method_instance),
// #[InitPackage] (run now with package context) // #[InitPackage] (run now with package context)
InitPackage::class => ApplicationContext::invoke([$instance_class, $method->getName()], [ InitPackage::class => ApplicationContext::invoke([$instance_class, $method->getName()], [
Package::class => $pkg, Package::class => $pkg,
@ -232,9 +235,9 @@ class PackageLoader
$method_instance = $method_attribute->newInstance(); $method_instance = $method_attribute->newInstance();
match ($method_attribute->getName()) { match ($method_attribute->getName()) {
// #[BeforeStage('package_name', 'stage')] and #[AfterStage('package_name', 'stage')] // #[BeforeStage('package_name', 'stage')] and #[AfterStage('package_name', 'stage')]
BeforeStage::class => self::$before_stages[$method_instance->package_name][$method_instance->stage][] = [[$instance_class, $method->getName()], $method_instance->only_when_package_resolved], BeforeStage::class => self::addBeforeStage($method, $pkg ?? null, $instance_class, $method_instance),
AfterStage::class => self::$after_stage[$method_instance->package_name][$method_instance->stage][] = [[$instance_class, $method->getName()], $method_instance->only_when_package_resolved], AfterStage::class => self::addAfterStage($method, $pkg ?? null, $instance_class, $method_instance),
// #[PatchBeforeBuild()
default => null, default => null,
}; };
} }
@ -258,7 +261,7 @@ class PackageLoader
{ {
// match condition // match condition
$installer = ApplicationContext::get(PackageInstaller::class); $installer = ApplicationContext::get(PackageInstaller::class);
$stages = self::$after_stage[$package_name][$stage] ?? []; $stages = self::$after_stages[$package_name][$stage] ?? [];
$result = []; $result = [];
foreach ($stages as [$callback, $only_when_package_resolved]) { foreach ($stages as [$callback, $only_when_package_resolved]) {
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) { if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
@ -269,9 +272,53 @@ class PackageLoader
return $result; return $result;
} }
public static function getPatchBeforeBuildCallbacks(string $package_name): array /**
* Register default stages for all PhpExtensionPackage instances.
* Should be called after all registries have been loaded.
*/
public static function registerAllDefaultStages(): void
{ {
return self::$patch_before_builds[$package_name] ?? []; foreach (self::$packages as $pkg) {
if ($pkg instanceof PhpExtensionPackage) {
$pkg->registerDefaultStages();
}
}
}
/**
* Check loaded stage events for consistency.
*/
public static function checkLoadedStageEvents(): void
{
foreach (['BeforeStage' => self::$before_stages, 'AfterStage' => self::$after_stages] as $event_name => $ev_all) {
foreach ($ev_all as $package_name => $stages) {
// check package exists
if (!self::hasPackage($package_name)) {
throw new RegistryException(
"{$event_name} event registered for unknown package [{$package_name}]."
);
}
$pkg = self::getPackage($package_name);
foreach ($stages as $stage_name => $before_events) {
foreach ($before_events as [$event_callable, $only_when_package_resolved]) {
// check only_when_package_resolved package exists
if ($only_when_package_resolved !== null && !self::hasPackage($only_when_package_resolved)) {
throw new RegistryException("{$event_name} event in package [{$package_name}] for stage [{$stage_name}] has unknown only_when_package_resolved package [{$only_when_package_resolved}].");
}
// check callable is valid
if (!is_callable($event_callable)) {
throw new RegistryException(
"{$event_name} event in package [{$package_name}] for stage [{$stage_name}] has invalid callable.",
);
}
}
// check stage exists
if (!$pkg->hasStage($stage_name)) {
throw new RegistryException("Package stage [{$stage_name}] is not registered in package [{$package_name}].");
}
}
}
}
} }
/** /**
@ -280,7 +327,7 @@ class PackageLoader
private static function bindCustomPhpConfigureArg(Package $pkg, object $attr, callable $fn): void private static function bindCustomPhpConfigureArg(Package $pkg, object $attr, callable $fn): void
{ {
if (!$pkg instanceof PhpExtensionPackage) { if (!$pkg instanceof PhpExtensionPackage) {
throw new ValidationException("Class [{$pkg->getName()}] must implement PhpExtensionPackage for CustomPhpConfigureArg attribute."); throw new RegistryException("Class [{$pkg->getName()}] must implement PhpExtensionPackage for CustomPhpConfigureArg attribute.");
} }
$pkg->addCustomPhpConfigureArgCallback($attr->os, $fn); $pkg->addCustomPhpConfigureArgCallback($attr->os, $fn);
} }
@ -289,4 +336,44 @@ class PackageLoader
{ {
$pkg->addBuildFunction($attr->os, $fn); $pkg->addBuildFunction($attr->os, $fn);
} }
private static function addStage(\ReflectionMethod $method, Package $pkg, object $instance_class, object $method_instance): void
{
$name = $method_instance->function;
if ($name === null) {
$name = $method->getName();
}
$pkg->addStage($name, [$instance_class, $method->getName()]);
}
private static function addBeforeStage(\ReflectionMethod $method, ?Package $pkg, mixed $instance_class, object $method_instance): void
{
/** @var BeforeStage $method_instance */
$stage = $method_instance->stage;
$stage = match (true) {
is_string($stage) => $stage,
is_array($stage) && count($stage) === 2 => $stage[1],
default => throw new RegistryException('Invalid stage definition in BeforeStage attribute.'),
};
if ($method_instance->package_name === '' && $pkg === null) {
throw new RegistryException('Package name must not be empty when no package context is available for BeforeStage attribute.');
}
$package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name;
self::$before_stages[$package_name][$stage][] = [[$instance_class, $method->getName()], $method_instance->only_when_package_resolved];
}
private static function addAfterStage(\ReflectionMethod $method, ?Package $pkg, mixed $instance_class, object $method_instance): void
{
$stage = $method_instance->stage;
$stage = match (true) {
is_string($stage) => $stage,
is_array($stage) && count($stage) === 2 => $stage[1],
default => throw new RegistryException('Invalid stage definition in AfterStage attribute.'),
};
if ($method_instance->package_name === '' && $pkg === null) {
throw new RegistryException('Package name must not be empty when no package context is available for AfterStage attribute.');
}
$package_name = $method_instance->package_name === '' ? $pkg->getName() : $method_instance->package_name;
self::$after_stages[$package_name][$stage][] = [[$instance_class, $method->getName()], $method_instance->only_when_package_resolved];
}
} }

View File

@ -4,13 +4,10 @@ declare(strict_types=1);
namespace StaticPHP\Registry; namespace StaticPHP\Registry;
use StaticPHP\Artifact\ArtifactLoader;
use StaticPHP\Config\ArtifactConfig; use StaticPHP\Config\ArtifactConfig;
use StaticPHP\Config\PackageConfig; use StaticPHP\Config\PackageConfig;
use StaticPHP\ConsoleApplication; use StaticPHP\ConsoleApplication;
use StaticPHP\Doctor\DoctorLoader; use StaticPHP\Exception\RegistryException;
use StaticPHP\Exception\EnvironmentException;
use StaticPHP\Package\PackageLoader;
use StaticPHP\Util\FileSystem; use StaticPHP\Util\FileSystem;
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
@ -30,19 +27,19 @@ class Registry
{ {
$yaml = file_get_contents($registry_file); $yaml = file_get_contents($registry_file);
if ($yaml === false) { if ($yaml === false) {
throw new EnvironmentException("Failed to read registry file: {$registry_file}"); throw new RegistryException("Failed to read registry file: {$registry_file}");
} }
$data = match (pathinfo($registry_file, PATHINFO_EXTENSION)) { $data = match (pathinfo($registry_file, PATHINFO_EXTENSION)) {
'json' => json_decode($yaml, true), 'json' => json_decode($yaml, true),
'yaml', 'yml' => Yaml::parse($yaml), 'yaml', 'yml' => Yaml::parse($yaml),
default => throw new EnvironmentException("Unsupported registry file format: {$registry_file}"), default => throw new RegistryException("Unsupported registry file format: {$registry_file}"),
}; };
if (!is_array($data)) { if (!is_array($data)) {
throw new EnvironmentException("Invalid registry format in file: {$registry_file}"); throw new RegistryException("Invalid registry format in file: {$registry_file}");
} }
$registry_name = $data['name'] ?? null; $registry_name = $data['name'] ?? null;
if (!is_string($registry_name) || empty($registry_name)) { if (!is_string($registry_name) || empty($registry_name)) {
throw new EnvironmentException("Registry 'name' is missing or invalid in file: {$registry_file}"); throw new RegistryException("Registry 'name' is missing or invalid in file: {$registry_file}");
} }
// Prevent loading the same registry twice // Prevent loading the same registry twice
@ -190,6 +187,16 @@ class Registry
} }
} }
public static function checkLoadedRegistries(): void
{
// Register default stages for all PhpExtensionPackage instances
// This must be done after all registries are loaded to ensure custom stages take precedence
PackageLoader::registerAllDefaultStages();
// check BeforeStage, AfterStage is valid
PackageLoader::checkLoadedStageEvents();
}
/** /**
* Get list of loaded registry names. * Get list of loaded registry names.
* *
@ -252,7 +259,7 @@ class Registry
} }
// Class not found and no file path provided // Class not found and no file path provided
throw new EnvironmentException( throw new RegistryException(
"Class '{$class}' not found. For external registries, either:\n" . "Class '{$class}' not found. For external registries, either:\n" .
" 1. Add an 'autoload' entry pointing to your composer autoload file\n" . " 1. Add an 'autoload' entry pointing to your composer autoload file\n" .
" 2. Use 'psr-4' instead of 'classes' for auto-discovery\n" . " 2. Use 'psr-4' instead of 'classes' for auto-discovery\n" .
@ -272,7 +279,7 @@ class Registry
$path = $relative_path_base . DIRECTORY_SEPARATOR . $path; $path = $relative_path_base . DIRECTORY_SEPARATOR . $path;
} }
if (!file_exists($path)) { if (!file_exists($path)) {
throw new EnvironmentException("Path does not exist: {$path}"); throw new RegistryException("Path does not exist: {$path}");
} }
return FileSystem::convertPath($path); return FileSystem::convertPath($path);
} }