Compare commits

..

10 Commits

Author SHA1 Message Date
Jerry Ma
227b8f0b0a fix(test): fix redundant terminal output during phpunit (#1194) 2026-06-22 08:08:47 +08:00
Marc
408d8f755c Remove laravel/prompts from box.json (#1190) 2026-06-16 19:05:39 +07:00
Marc
1f291a9036 Add Visual Studio 2026 support (#1191) 2026-06-16 19:05:09 +07:00
crazywhalecc
127fb1989f Add vs 18 support 2026-06-16 19:21:18 +08:00
Jerry Ma
af771cf2b5 feat: enhance type hints and improve verbosity handling in commands (#1186) 2026-06-16 18:50:18 +08:00
crazywhalecc
5df65d926c Remove laravel/prompts from box.json 2026-06-16 18:49:22 +08:00
Jerry Ma
bdc7bbe1f1 v3: Fix gmssl build (#1188) 2026-06-16 18:45:43 +08:00
Jerry Ma
89dca1f0fb refactor: remove unused symfony/process and unnecessary laravel/prompts (#1187) 2026-06-16 18:15:03 +08:00
crazywhalecc
064a1f05ae Fix phpstan 2026-06-16 15:17:51 +08:00
crazywhalecc
88cb6749b8 Remove laravel/prompts and symfony/process 2026-06-16 15:11:48 +08:00
73 changed files with 1277 additions and 611 deletions

View File

@@ -10,7 +10,6 @@
"config",
"src",
"vendor/psr",
"vendor/laravel/prompts",
"vendor/symfony",
"vendor/php-di",
"vendor/zhamao"

View File

@@ -12,10 +12,8 @@
"php": ">=8.4",
"ext-mbstring": "*",
"ext-zlib": "*",
"laravel/prompts": "~0.1",
"php-di/php-di": "^7.1",
"symfony/console": "^5.4 || ^6 || ^7",
"symfony/process": "^7.2",
"symfony/yaml": "^7.2",
"zhamao/logger": "^1.1.4"
},

568
composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,3 +10,5 @@ ext-gmssl:
license: PHP-3.01
depends:
- gmssl
php-extension:
arg-type: with-path

View File

@@ -1,6 +1,6 @@
parameters:
reportUnmatchedIgnoredErrors: false
level: 4
level: 5
phpVersion: 80400
paths:
- ./src/

View File

@@ -0,0 +1,45 @@
<?php
declare(strict_types=1);
namespace Package\Extension;
use Package\Target\php;
use StaticPHP\Attribute\Package\BeforeStage;
use StaticPHP\Attribute\Package\Extension;
use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Util\FileSystem;
#[Extension('gmssl')]
class gmssl extends PhpExtensionPackage
{
#[BeforeStage('php', [php::class, 'buildconfForUnix'], 'ext-gmssl')]
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-gmssl')]
#[PatchDescription('Fix ext-gmssl v1.1.1 compatibility with GmSSL >= 3.1.0 where SM2_VERIFY_CTX was removed (unified into SM2_SIGN_CTX)')]
public function patchSm2VerifyCtx(): void
{
// See: https://github.com/crazywhalecc/static-php-cli/issues/1182
FileSystem::replaceFileStr(
"{$this->getSourceDir()}/gmssl.c",
'SM2_VERIFY_CTX',
'SM2_SIGN_CTX'
);
}
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-gmssl')]
#[PatchDescription('Add CHECK_LIB to config.w32 for static Windows builds')]
public function patchBeforeBuildconfWin(): bool
{
$configW32 = "{$this->getSourceDir()}/config.w32";
if (str_contains(FileSystem::readFile($configW32), 'CHECK_LIB(')) {
return false;
}
FileSystem::replaceFileStr(
$configW32,
'AC_DEFINE(',
'CHECK_LIB("gmssl.lib", "gmssl", PHP_GMSSL);' . PHP_EOL . 'AC_DEFINE('
);
return true;
}
}

View File

@@ -27,10 +27,7 @@ class brotli
{
UnixCMakeExecutor::create($lib)
->setBuildDir($lib->getSourceDir() . '/build-dir')
->addConfigureArgs(
"-DSHARE_INSTALL_PREFIX={$lib->getBuildRootPath()}",
'-DBROTLI_DISABLE_TESTS=ON',
)
->addConfigureArgs("-DSHARE_INSTALL_PREFIX={$lib->getBuildRootPath()}")
->build();
// Patch pkg-config files

View File

@@ -17,9 +17,7 @@ class bzip2
#[PatchBeforeBuild]
public function patchBeforeBuild(LibraryPackage $lib): void
{
// Makefile pins -O2 -fPIC; inject SPC_DEFAULT_CFLAGS
$extra = deduplicate_flags(trim((string) getenv('SPC_DEFAULT_CFLAGS')) . ' -fPIC -Wall');
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', "CFLAGS={$extra}");
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', 'CFLAGS=-fPIC -Wall');
}
#[BuildFor('Windows')]

View File

@@ -18,11 +18,9 @@ class fastlz
{
$cc = getenv('CC') ?: 'cc';
$ar = getenv('AR') ?: 'ar';
$extra = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
$extra = $extra !== '' ? $extra . ' -fPIC' : '-O3 -fPIC';
shell()->cd($lib->getSourceDir())->initializeEnv($lib)
->exec("{$cc} -c {$extra} fastlz.c -o fastlz.o")
->exec("{$cc} -c -O3 -fPIC fastlz.c -o fastlz.o")
->exec("{$ar} rcs libfastlz.a fastlz.o");
// Copy header file

View File

@@ -22,6 +22,7 @@ class gettext_win
{
$ver = WindowsUtil::findVisualStudio();
$vs_ver_dir = match ($ver['major_version']) {
'18', // VS 2026 reuses the VS2022 (MSVC17) solution, which msbuild builds via forward compatibility.
'17' => '\MSVC17',
'16' => '\MSVC16',
default => throw new EnvironmentException("Current VS version {$ver['major_version']} is not supported yet!"),
@@ -44,7 +45,9 @@ class gettext_win
{
$vs_ver_dir = ApplicationContext::get('gettext_win_vs_ver_dir');
cmd()->cd("{$lib->getSourceDir()}{$vs_ver_dir}\\libintl_static")
->exec('msbuild libintl_static.vcxproj /t:Rebuild /p:Configuration=Release /p:Platform=x64 /p:WindowsTargetPlatformVersion=10.0');
// WholeProgramOptimization (/GL) emits LTCG objects that frankenphp's lld-link cannot
// read ("is not a native COFF file"); disable it so the .lib stays plain COFF.
->exec('msbuild libintl_static.vcxproj /t:Rebuild /p:Configuration=Release /p:Platform=x64 /p:WindowsTargetPlatformVersion=10.0 /p:WholeProgramOptimization=false');
FileSystem::createDir($lib->getLibDir());
FileSystem::createDir($lib->getIncludeDir());
// libintl_a.lib is the static library output; copy as libintl.lib for linker compatibility

View File

@@ -8,7 +8,6 @@ use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Library;
use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Runtime\SystemTarget;
#[Library('gmp')]
class gmp
@@ -17,12 +16,10 @@ class gmp
#[BuildFor('Darwin')]
public function build(LibraryPackage $lib): void
{
$make = UnixAutoconfExecutor::create($lib)->appendEnv(['CFLAGS' => '-std=c17']);
if (SystemTarget::getTargetArch() === 'x86_64' && SystemTarget::getTargetOS() === 'Linux') {
$libc = SystemTarget::getLibc() === 'glibc' ? 'gnu' : 'musl';
$make->addConfigureArgs(["--host=x86_64-pc-linux-{$libc}"]);
}
$make->configure('--enable-fat')->make();
UnixAutoconfExecutor::create($lib)
->appendEnv(['CFLAGS' => '-std=c17'])
->configure('--enable-fat')
->make();
$lib->patchPkgconfPrefix(['gmp.pc']);
}
}

View File

@@ -18,7 +18,9 @@ class gmssl
#[BuildFor('Darwin')]
public function build(LibraryPackage $lib): void
{
UnixCMakeExecutor::create($lib)->build();
UnixCMakeExecutor::create($lib)
->addConfigureArgs('-DENABLE_SM2_PRIVATE_KEY_EXPORT=ON')
->build();
}
#[BuildFor('Windows')]
@@ -33,6 +35,7 @@ class gmssl
'-G "NMake Makefiles"',
'-DWIN32=ON',
'-DBUILD_SHARED_LIBS=OFF',
'-DENABLE_SM2_PRIVATE_KEY_EXPORT=ON',
'-DCMAKE_BUILD_TYPE=Release',
'-DCMAKE_C_FLAGS_RELEASE="/MT /O2 /Ob2 /DNDEBUG"',
'-DCMAKE_CXX_FLAGS_RELEASE="/MT /O2 /Ob2 /DNDEBUG"',

View File

@@ -24,12 +24,9 @@ class icu
#[BuildFor('Linux')]
public function buildLinux(LibraryPackage $lib, ToolchainInterface $toolchain, PackageBuilder $builder): void
{
// runConfigureICU bakes CXXFLAGS/LDFLAGS, apply user flags too
$userCxxFlags = trim((string) getenv('SPC_DEFAULT_CXXFLAGS'));
$userLdFlags = trim((string) getenv('SPC_DEFAULT_LDFLAGS'));
$cppflags = 'CPPFLAGS="-DU_CHARSET_IS_UTF8=1 -DU_USING_ICU_NAMESPACE=1 -DU_STATIC_IMPLEMENTATION=1 -DPIC -fPIC"';
$cxxflags = "CXXFLAGS=\"-std=c++17 -DPIC -fPIC -fno-ident {$userCxxFlags}\"";
$ldflags = $toolchain->isStatic() ? "LDFLAGS=\"-static {$userLdFlags}\"" : "LDFLAGS=\"{$userLdFlags}\"";
$cxxflags = 'CXXFLAGS="-std=c++17 -DPIC -fPIC -fno-ident"';
$ldflags = $toolchain->isStatic() ? 'LDFLAGS="-static"' : '';
shell()->cd($lib->getSourceDir() . '/source')->initializeEnv($lib)
->exec(
"{$cppflags} {$cxxflags} {$ldflags} " .

View File

@@ -45,9 +45,6 @@ class imagemagick
// implicit --with-gcc-arch
// bleeds host cpu features into built binaries
'--without-gcc-arch',
'--disable-docs',
'--without-utilities',
'--disable-dpc',
);
// special: linux-static target needs `-static`

View File

@@ -17,9 +17,7 @@ class jbig
#[PatchBeforeBuild]
public function patchBeforeBuild(LibraryPackage $lib): void
{
$extra = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
$cflags = ($extra !== '' ? $extra : '-O2') . ' -W -Wno-unused-result -fPIC';
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS = -O2 -W -Wno-unused-result', "CFLAGS = {$cflags}");
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS = -O2 -W -Wno-unused-result', 'CFLAGS = -O2 -W -Wno-unused-result -fPIC');
}
#[BuildFor('Darwin')]

View File

@@ -35,7 +35,6 @@ class ldap
->optionalPackage('libsodium', '--with-argon2=libsodium', '--enable-argon2=no')
->addConfigureArgs(
'--disable-slapd',
'--disable-debug',
'--without-systemd',
'--without-cyrus-sasl',
'ac_cv_func_pthread_kill_other_threads_np=no'

View File

@@ -9,10 +9,8 @@ use StaticPHP\Attribute\Package\Library;
use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixCMakeExecutor;
use StaticPHP\Runtime\Executor\WindowsCMakeExecutor;
use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Toolchain\Interface\ToolchainInterface;
use StaticPHP\Toolchain\ZigToolchain;
use StaticPHP\Util\System\UnixUtil;
#[Library('libaom')]
class libaom extends LibraryPackage
@@ -41,23 +39,9 @@ class libaom extends LibraryPackage
$new = trim($extra . ' -D_GNU_SOURCE');
f_putenv("SPC_COMPILER_EXTRA={$new}");
}
$targetCpu = SystemTarget::getTargetArch();
if (str_starts_with($targetCpu, 'aarch')) {
$targetCpu = str_replace('aarch', 'arm', $targetCpu);
}
if (!UnixUtil::findCommand('nasm') && !UnixUtil::findCommand('yasm')) {
$targetCpu = 'generic';
}
UnixCMakeExecutor::create($this)
->setBuildDir("{$this->getSourceDir()}/builddir")
->addConfigureArgs(
"-DAOM_TARGET_CPU={$targetCpu}",
'-DCONFIG_RUNTIME_CPU_DETECT=1',
'-DENABLE_EXAMPLES=OFF',
'-DENABLE_TESTS=OFF',
'-DENABLE_TOOLS=OFF',
'-DENABLE_DOCS=OFF',
)
->addConfigureArgs('-DAOM_TARGET_CPU=generic')
->build();
f_putenv("SPC_COMPILER_EXTRA={$extra}");
$this->patchPkgconfPrefix(['aom.pc']);

View File

@@ -35,12 +35,7 @@ class libavif
->optionalPackage('libjpeg', '-DAVIF_JPEG=SYSTEM', '-DAVIF_JPEG=OFF')
->optionalPackage('libxml2', '-DAVIF_LIBXML2=SYSTEM', '-DAVIF_LIBXML2=OFF')
->optionalPackage('libpng', '-DAVIF_LIBPNG=SYSTEM', '-DAVIF_LIBPNG=OFF')
->addConfigureArgs(
'-DAVIF_LIBYUV=OFF',
'-DAVIF_BUILD_APPS=OFF',
'-DAVIF_BUILD_TESTS=OFF',
'-DAVIF_GTEST=OFF',
)
->addConfigureArgs('-DAVIF_LIBYUV=OFF')
->build();
// patch pkgconfig
$lib->patchPkgconfPrefix(['libavif.pc']);
@@ -54,7 +49,7 @@ class libavif
'-DAVIF_BUILD_APPS=OFF',
'-DAVIF_BUILD_TESTS=OFF',
'-DAVIF_LIBYUV=OFF',
'-DAVIF_GTEST=OFF',
'-DAVIF_ENABLE_GTEST=OFF',
)
->build();
}

View File

@@ -16,7 +16,7 @@ class libffi extends LibraryPackage
public function buildLinux(): void
{
UnixAutoconfExecutor::create($this)
->configure('--disable-docs')->make();
->configure()->make();
if (is_file("{$this->getBuildRootPath()}/lib64/libffi.a")) {
copy("{$this->getBuildRootPath()}/lib64/libffi.a", "{$this->getBuildRootPath()}/lib/libffi.a");
@@ -33,7 +33,6 @@ class libffi extends LibraryPackage
->configure(
"--host={$arch}-apple-darwin",
"--target={$arch}-apple-darwin",
'--disable-docs',
)
->make();
$this->patchPkgconfPrefix(['libffi.pc']);

View File

@@ -21,6 +21,7 @@ class libffi_win
{
$ver = WindowsUtil::findVisualStudio();
$vs_ver_dir = match ($ver['major_version']) {
'18', // VS 2026 reuses the vs17 solution, which msbuild builds via forward compatibility.
'17' => '\win32\vs17_x64',
'16' => '\win32\vs16_x64',
default => throw new EnvironmentException("Current VS version {$ver['major_version']} is not supported!"),
@@ -33,7 +34,9 @@ class libffi_win
{
$vs_ver_dir = ApplicationContext::get('libffi_win_vs_ver_dir');
cmd()->cd("{$lib->getSourceDir()}{$vs_ver_dir}")
->exec('msbuild libffi-msvc.sln /t:Rebuild /p:Configuration=Release /p:Platform=x64');
// WholeProgramOptimization (/GL) emits LTCG objects that frankenphp's lld-link cannot
// read ("is not a native COFF file"); disable it so the .lib stays plain COFF.
->exec('msbuild libffi-msvc.sln /t:Rebuild /p:Configuration=Release /p:Platform=x64 /p:WholeProgramOptimization=false');
FileSystem::createDir($lib->getLibDir());
FileSystem::createDir($lib->getIncludeDir());

View File

@@ -24,17 +24,6 @@ class libheif
'list(APPEND REQUIRES_PRIVATE "libbrotlidec")' . "\n" . ' list(APPEND REQUIRES_PRIVATE "libbrotlienc")'
);
}
// libheif 1.22+ ships a C-incompatible header: `struct heif_bad_pixel`
$heif_properties = $lib->getSourceDir() . '/libheif/api/libheif/heif_properties.h';
if (file_exists($heif_properties)
&& str_contains(file_get_contents($heif_properties), 'struct heif_bad_pixel { uint32_t row; uint32_t column; };')
) {
FileSystem::replaceFileStr(
$heif_properties,
'struct heif_bad_pixel { uint32_t row; uint32_t column; };',
'typedef struct heif_bad_pixel { uint32_t row; uint32_t column; } heif_bad_pixel;'
);
}
}
#[BuildFor('Darwin')]
@@ -47,7 +36,6 @@ class libheif
'-DWITH_EXAMPLES=OFF',
'-DWITH_GDK_PIXBUF=OFF',
'-DBUILD_TESTING=OFF',
'-DBUILD_DOCUMENTATION=OFF',
'-DWITH_LIBSHARPYUV=ON', // optional: libwebp
'-DENABLE_PLUGIN_LOADING=OFF',
)

View File

@@ -21,6 +21,7 @@ class libiconv_win
{
$ver = WindowsUtil::findVisualStudio();
$vs_ver_dir = match ($ver['major_version']) {
'18', // VS 2026 reuses the VS2022 (MSVC17) solution, which msbuild builds via forward compatibility.
'17' => '\MSVC17',
'16' => '\MSVC16',
default => throw new EnvironmentException("Current VS version {$ver['major_version']} is not supported yet!"),
@@ -33,7 +34,9 @@ class libiconv_win
{
$vs_ver_dir = ApplicationContext::get('vs_ver_dir');
cmd()->cd("{$lib->getSourceDir()}{$vs_ver_dir}")
->exec('msbuild libiconv.sln /t:Rebuild /p:Configuration=Release /p:Platform=x64');
// WholeProgramOptimization (/GL) emits LTCG objects that frankenphp's lld-link cannot
// read ("is not a native COFF file"); disable it so the .lib stays plain COFF.
->exec('msbuild libiconv.sln /t:Rebuild /p:Configuration=Release /p:Platform=x64 /p:WholeProgramOptimization=false');
FileSystem::createDir($lib->getLibDir());
FileSystem::createDir($lib->getIncludeDir());
FileSystem::copy("{$lib->getSourceDir()}{$vs_ver_dir}\\x64\\lib\\libiconv.lib", "{$lib->getLibDir()}\\libiconv.lib");

View File

@@ -25,7 +25,6 @@ class libjxl extends LibraryPackage
'-DJPEGXL_ENABLE_MANPAGES=OFF',
'-DJPEGXL_ENABLE_BENCHMARK=OFF',
'-DJPEGXL_ENABLE_PLUGINS=OFF',
'-DJPEGXL_ENABLE_DOXYGEN=OFF',
'-DJPEGXL_ENABLE_SJPEG=ON',
'-DJPEGXL_ENABLE_JNI=OFF',
'-DJPEGXL_ENABLE_TRANSCODE_JPEG=ON',

View File

@@ -12,25 +12,17 @@ use StaticPHP\Runtime\Executor\UnixCMakeExecutor;
#[Library('libmemcached')]
class libmemcached extends LibraryPackage
{
private const array DISABLE_ARGS = [
'-DBUILD_TESTING=OFF',
'-DBUILD_DOCS=OFF',
'-DENABLE_MEMASLAP=OFF',
];
#[BuildFor('Linux')]
public function buildLinux(): void
{
UnixCMakeExecutor::create($this)
->addConfigureArgs('-DCMAKE_INSTALL_RPATH=""', ...self::DISABLE_ARGS)
->addConfigureArgs('-DCMAKE_INSTALL_RPATH=""')
->build();
}
#[BuildFor('Darwin')]
public function buildDarwin(): void
{
UnixCMakeExecutor::create($this)
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
UnixCMakeExecutor::create($this)->build();
}
}

View File

@@ -20,8 +20,6 @@ class libpng
{
$args = [
'--enable-hardware-optimizations',
'--disable-tests',
'--disable-tools',
"--with-zlib-prefix={$lib->getBuildRootPath()}",
];

View File

@@ -13,29 +13,17 @@ use StaticPHP\Runtime\Executor\WindowsCMakeExecutor;
#[Library('librabbitmq')]
class librabbitmq extends LibraryPackage
{
private const array DISABLE_ARGS = [
'-DBUILD_EXAMPLES=OFF',
'-DBUILD_TESTING=OFF',
'-DBUILD_TOOLS=OFF',
'-DBUILD_TOOLS_DOCS=OFF',
'-DBUILD_API_DOCS=OFF',
];
#[BuildFor('Darwin')]
#[BuildFor('Linux')]
public function buildUnix(): void
{
UnixCMakeExecutor::create($this)
->addConfigureArgs('-DBUILD_STATIC_LIBS=ON', ...self::DISABLE_ARGS)
->build();
UnixCMakeExecutor::create($this)->addConfigureArgs('-DBUILD_STATIC_LIBS=ON')->build();
}
#[BuildFor('Windows')]
public function buildWin(): void
{
WindowsCMakeExecutor::create($this)
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
WindowsCMakeExecutor::create($this)->build();
rename("{$this->getLibDir()}\\librabbitmq.4.lib", "{$this->getLibDir()}\\rabbitmq.4.lib");
}
}

View File

@@ -42,13 +42,16 @@ class libsodium
{
$ver = WindowsUtil::findVisualStudio();
$vs_ver_dir = match ($ver['major_version']) {
'18', // VS 2026 reuses the vs2022 solution, which msbuild builds via forward compatibility.
'17' => '\vs2022',
'16' => '\vs2019',
default => throw new EnvironmentException("Current VS version {$ver['major_version']} is not supported yet!"),
};
cmd()->cd("{$lib->getSourceDir()}\\builds\\msvc{$vs_ver_dir}")
->exec('msbuild libsodium.sln /t:Rebuild /p:Configuration=StaticRelease /p:Platform=x64 /p:PreprocessorDefinitions="SODIUM_STATIC=1"');
// WholeProgramOptimization (/GL) emits LTCG objects that frankenphp's lld-link cannot
// read ("is not a native COFF file"); disable it so the .lib stays plain COFF.
->exec('msbuild libsodium.sln /t:Rebuild /p:Configuration=StaticRelease /p:Platform=x64 /p:WholeProgramOptimization=false /p:PreprocessorDefinitions="SODIUM_STATIC=1"');
FileSystem::createDir($lib->getLibDir());
FileSystem::createDir($lib->getIncludeDir());

View File

@@ -41,9 +41,6 @@ class libtiff
'--disable-libdeflate',
'--disable-tools',
'--disable-contrib',
'--disable-tests',
'--disable-docs',
'--disable-sphinx',
'--disable-cxx',
'--without-x',
)

View File

@@ -13,18 +13,12 @@ use StaticPHP\Runtime\Executor\WindowsCMakeExecutor;
#[Library('libuv')]
class libuv
{
private const array DISABLE_ARGS = [
'-DLIBUV_BUILD_SHARED=OFF',
'-DLIBUV_BUILD_TESTS=OFF',
'-DLIBUV_BUILD_BENCH=OFF',
];
#[BuildFor('Darwin')]
#[BuildFor('Linux')]
public function buildUnix(LibraryPackage $lib): void
{
UnixCMakeExecutor::create($lib)
->addConfigureArgs(...self::DISABLE_ARGS)
->addConfigureArgs('-DLIBUV_BUILD_SHARED=OFF')
->build();
// patch pkgconfig
$lib->patchPkgconfPrefix(['libuv-static.pc']);
@@ -34,7 +28,7 @@ class libuv
public function buildWindows(LibraryPackage $lib): void
{
WindowsCMakeExecutor::create($lib)
->addConfigureArgs(...self::DISABLE_ARGS)
->addConfigureArgs('-DLIBUV_BUILD_SHARED=OFF')
->build();
}
}

View File

@@ -34,7 +34,6 @@ class libxslt
'--without-crypto',
'--without-debug',
'--without-debugger',
'--without-profiler',
"--with-libxml-prefix={$lib->getBuildRootPath()}",
);
if (getenv('SPC_LD_LIBRARY_PATH') && getenv('SPC_LIBRARY_PATH')) {

View File

@@ -21,7 +21,6 @@ class mimalloc
->addConfigureArgs(
'-DMI_BUILD_SHARED=OFF',
'-DMI_BUILD_OBJECT=OFF',
'-DMI_BUILD_TESTS=OFF',
'-DMI_INSTALL_TOPLEVEL=ON',
);
if (SystemTarget::getLibc() === 'musl') {

View File

@@ -21,6 +21,7 @@ class mpir
{
$ver = WindowsUtil::findVisualStudio();
$vs_ver_dir = match ($ver['major_version']) {
'18', // VS 2026 reuses the build.vc17 solution, which msbuild builds via forward compatibility.
'17' => '\build.vc17',
'16' => '\build.vc16',
default => throw new EnvironmentException("Current VS version {$ver['major_version']} is not supported yet!"),

View File

@@ -6,8 +6,6 @@ namespace Package\Library;
use StaticPHP\Attribute\Package\BuildFor;
use StaticPHP\Attribute\Package\Library;
use StaticPHP\Attribute\Package\PatchBeforeBuild;
use StaticPHP\Attribute\PatchDescription;
use StaticPHP\Package\LibraryPackage;
use StaticPHP\Runtime\Executor\UnixAutoconfExecutor;
use StaticPHP\Toolchain\Interface\ToolchainInterface;
@@ -18,24 +16,6 @@ use StaticPHP\Util\FileSystem;
#[Library('ncursesw')]
class ncurses
{
#[PatchBeforeBuild]
#[PatchDescription('Filter clang/zig "N warning(s) generated." line out of MKlib_gen.sh preprocessor pipe')]
public function patchBeforeBuild(LibraryPackage $lib): void
{
// MKlib_gen.sh feeds the C preprocessor's stdout through a sed/awk
// pipeline into lib_gen.c. zig-cc/clang emits "N warning(s) generated."
// on stdout (not stderr), and that line ends up as invalid C in the
// generated source. Filter it out of the pipe before sed sees it.
$mklibGen = $lib->getSourceDir() . '/ncurses/base/MKlib_gen.sh';
if (is_file($mklibGen) && !str_contains((string) file_get_contents($mklibGen), "| grep -v ' generated")) {
FileSystem::replaceFileStr(
$mklibGen,
'$preprocessor $TMP 2>/dev/null \\',
"\$preprocessor \$TMP 2>/dev/null \\\n| grep -v ' generated\\.\$' \\",
);
}
}
#[BuildFor('Darwin')]
#[BuildFor('Linux')]
public function build(LibraryPackage $package, ToolchainInterface $toolchain): void

View File

@@ -24,7 +24,6 @@ class nghttp3
'-DBUILD_SHARED_LIBS=OFF',
'-DENABLE_STATIC_CRT=ON',
'-DENABLE_LIB_ONLY=ON',
'-DBUILD_TESTING=OFF',
)
->build();
}

View File

@@ -25,7 +25,6 @@ class ngtcp2
'-DENABLE_STATIC_CRT=ON',
'-DENABLE_LIB_ONLY=ON',
'-DENABLE_OPENSSL=OFF',
'-DBUILD_TESTING=OFF',
)
->build();
}

View File

@@ -111,12 +111,6 @@ class openssl
$openssl_dir ??= LinuxUtil::getOSRelease()['dist'] === 'redhat' ? '/etc/pki/tls' : '/etc/ssl';
$ex_lib = trim($ex_lib);
// anything we want included (PGO -fprofile-*, LTO, custom hardening)
// has to be appended on the command line *after* the target name.
$userCFlags = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
$userLdFlags = trim((string) getenv('SPC_DEFAULT_LDFLAGS'));
$userExtra = trim($userCFlags . ' ' . $userLdFlags);
shell()->cd($lib->getSourceDir())->initializeEnv($lib)
->exec(
"{$env} ./Configure no-shared zlib " .
@@ -127,8 +121,7 @@ class openssl
'enable-pie ' .
'no-legacy ' .
'no-tests ' .
"linux-{$arch} " .
$userExtra
"linux-{$arch}"
)
->exec('make clean')
->exec("make -j{$lib->getBuilder()->concurrency} CNF_EX_LIBS=\"{$ex_lib}\"")

View File

@@ -20,11 +20,6 @@ class qdbm
{
$ac = UnixAutoconfExecutor::create($lib)->configure();
FileSystem::replaceFileRegex($lib->getSourceDir() . '/Makefile', '/MYLIBS = libqdbm.a.*/m', 'MYLIBS = libqdbm.a');
// Makefile pins -O3, replace with SPC_DEFAULT_CFLAGS
$extra = trim((string) getenv('SPC_DEFAULT_CFLAGS'));
if ($extra !== '') {
FileSystem::replaceFileRegex($lib->getSourceDir() . '/Makefile', '/^CFLAGS = .*$/m', "CFLAGS = -Wall {$extra}");
}
$ac->make(SystemTarget::getTargetOS() === 'Darwin' ? 'mac' : '');
$lib->patchPkgconfPrefix(['qdbm.pc']);
}

View File

@@ -20,7 +20,6 @@ class readline
->configure(
'--with-curses',
'--enable-multibyte=yes',
'--disable-install-examples',
)
->make();
$lib->patchPkgconfPrefix(['readline.pc']);

View File

@@ -22,8 +22,7 @@ class tidy
->setBuildDir("{$lib->getSourceDir()}/build-dir")
->addConfigureArgs(
'-DSUPPORT_CONSOLE_APP=OFF',
'-DBUILD_SHARED_LIB=OFF',
'-DSUPPORT_LOCALIZATIONS=OFF',
'-DBUILD_SHARED_LIB=OFF'
);
if (version_compare(get_cmake_version(), '4.0.0', '>=')) {
$cmake->addConfigureArgs('-DCMAKE_POLICY_VERSION_MINIMUM=3.5');
@@ -39,8 +38,7 @@ class tidy
->setBuildDir("{$lib->getSourceDir()}/build-dir")
->addConfigureArgs(
'-DSUPPORT_CONSOLE_APP=OFF',
'-DBUILD_SHARED_LIB=OFF',
'-DSUPPORT_LOCALIZATIONS=OFF',
'-DBUILD_SHARED_LIB=OFF'
)->build();
// rename tidy_static.lib to tidy_a.lib

View File

@@ -35,7 +35,6 @@ class unixodbc extends LibraryPackage
'--with-included-ltdl',
"--sysconfdir={$sysconf_selector}",
'--enable-gui=no',
'--enable-readline=no',
)
->make();
$this->patchPkgconfPrefix(['odbc.pc', 'odbccr.pc', 'odbcinst.pc']);

View File

@@ -22,11 +22,6 @@ class xz
->configure(
'--disable-scripts',
'--disable-doc',
'--disable-xz',
'--disable-xzdec',
'--disable-lzmadec',
'--disable-lzmainfo',
'--disable-lzma-links',
'--with-libiconv',
'--bindir=/tmp/xz', // xz binary will corrupt `tar` command, that's really strange.
)

View File

@@ -14,20 +14,16 @@ use StaticPHP\Util\FileSystem;
#[Library('zstd')]
class zstd
{
private const array DISABLE_ARGS = [
'-DZSTD_BUILD_STATIC=ON',
'-DZSTD_BUILD_SHARED=OFF',
'-DZSTD_BUILD_PROGRAMS=OFF',
'-DZSTD_BUILD_TESTS=OFF',
];
#[BuildFor('Windows')]
public function buildWin(LibraryPackage $package): void
{
WindowsCMakeExecutor::create($package)
->setWorkingDir("{$package->getSourceDir()}/build/cmake")
->setBuildDir("{$package->getSourceDir()}/build/cmake/build")
->addConfigureArgs(...self::DISABLE_ARGS)
->addConfigureArgs(
'-DZSTD_BUILD_STATIC=ON',
'-DZSTD_BUILD_SHARED=OFF',
)
->build();
FileSystem::copy($package->getLibDir() . '\zstd_static.lib', $package->getLibDir() . '/zstd.lib');
FileSystem::copy($package->getLibDir() . '\zstd_static.lib', $package->getLibDir() . '/libzstd.lib');
@@ -39,7 +35,10 @@ class zstd
{
UnixCMakeExecutor::create($lib)
->setBuildDir("{$lib->getSourceDir()}/build/cmake/build")
->addConfigureArgs(...self::DISABLE_ARGS)
->addConfigureArgs(
'-DZSTD_BUILD_STATIC=ON',
'-DZSTD_BUILD_SHARED=OFF',
)
->build();
$lib->patchPkgconfPrefix(['libzstd.pc'], PKGCONF_PATCH_PREFIX);

View File

@@ -43,8 +43,6 @@ class curl
'-DZSTD_LIBRARY=zstd_static.lib',
'-DBUILD_TESTING=OFF',
'-DBUILD_EXAMPLES=OFF',
'-DBUILD_LIBCURL_DOCS=OFF',
'-DENABLE_CURL_MANUAL=OFF',
'-DUSE_LIBIDN2=OFF',
'-DCURL_USE_LIBPSL=OFF',
'-DUSE_WINDOWS_SSPI=ON',
@@ -83,9 +81,6 @@ class curl
->addConfigureArgs(
'-DBUILD_CURL_EXE=ON',
'-DBUILD_LIBCURL_DOCS=OFF',
'-DBUILD_TESTING=OFF',
'-DBUILD_EXAMPLES=OFF',
'-DENABLE_CURL_MANUAL=OFF',
'-DOPENSSL_ROOT_DIR=' . BUILD_ROOT_PATH,
)
->build();

View File

@@ -512,6 +512,7 @@ HEADER;
$vc_matches = ['unknown', 'unknown'];
} else {
$vc_matches = match ($vc['major_version']) {
'18', // VS 2026 shares the VS2022 (v143) runtime conventions, so it reports as VS17.
'17' => ['VS17', 'Visual C++ 2022'],
'16' => ['VS16', 'Visual C++ 2019'],
default => ['unknown', 'unknown'],

View File

@@ -45,7 +45,11 @@ class FileList implements DownloadTypeInterface, CheckUpdateInterface
throw new DownloaderException("Failed to get {$name} file list from {$config['url']}");
}
$versions = [];
logger()->debug('Matched ' . count($matches['version']) . " versions for {$name}");
$cnt = count($matches['version']);
if ($cnt === 0) {
throw new DownloaderException("Failed to get {$name} file list from {$config['url']}: no version parsed");
}
logger()->debug("Matched {$cnt} versions for {$name}");
foreach ($matches['version'] as $i => $version) {
$lower = strtolower($version);
foreach (['alpha', 'beta', 'rc', 'pre', 'nightly', 'snapshot', 'dev'] as $beta) {

View File

@@ -54,6 +54,10 @@ abstract class BaseCommand extends Command
}
set_error_handler(static function ($error_no, $error_msg, $error_file, $error_line) {
// Respect the @ suppression operator (error_reporting() returns 0 when @ is used)
if (error_reporting() === 0) {
return true;
}
$tips = [
E_WARNING => ['PHP Warning: ', 'warning'],
E_NOTICE => ['PHP Notice: ', 'notice'],

View File

@@ -110,7 +110,7 @@ class CraftCommand extends BaseCommand
* shared-extensions: array<string>,
* packages: array<string>,
* sapi: array<string>,
* verbosity: int,
* verbosity: 128|16|256|32|64|8,
* debug: bool,
* clean-build: bool,
* build-options: array<string, mixed>,
@@ -171,11 +171,16 @@ class CraftCommand extends BaseCommand
}
// verbosity
$verbosity_level = $craft['verbosity'] ?? OutputInterface::VERBOSITY_NORMAL;
$debug = $craft['debug'] ?? false;
if ($debug) {
$verbosity_level = OutputInterface::VERBOSITY_DEBUG;
}
$verbosity_level = $debug
? OutputInterface::VERBOSITY_DEBUG
: match ((int) ($craft['verbosity'] ?? 0)) {
OutputInterface::VERBOSITY_QUIET => OutputInterface::VERBOSITY_QUIET,
OutputInterface::VERBOSITY_VERBOSE => OutputInterface::VERBOSITY_VERBOSE,
OutputInterface::VERBOSITY_VERY_VERBOSE => OutputInterface::VERBOSITY_VERY_VERBOSE,
OutputInterface::VERBOSITY_DEBUG => OutputInterface::VERBOSITY_DEBUG,
default => OutputInterface::VERBOSITY_NORMAL,
};
$craft['verbosity'] = $verbosity_level;
// clean-build (if true, reset before all builds)

View File

@@ -16,7 +16,7 @@ class GenExtTestMatrixCommand extends BaseCommand
private const array OS_RUNNERS = [
'linux' => ['arch' => 'x86_64', 'runner' => 'ubuntu-latest', 'os_key' => 'Linux'],
'windows' => ['arch' => 'x86_64', 'runner' => 'windows-latest', 'os_key' => 'Windows'],
'windows' => ['arch' => 'x86_64', 'runner' => 'windows-2025', 'os_key' => 'Windows'],
'macos' => ['arch' => 'aarch64', 'runner' => 'macos-15', 'os_key' => 'Darwin'],
];

View File

@@ -154,7 +154,7 @@ class TestBotCommand extends BaseCommand
'targets' => array_values($targets),
'gen_matrix_args' => $gen_matrix_args,
'gen_matrix_args_tier2' => $gen_matrix_args_tier2,
'php_versions' => array_values($php_versions),
'php_versions' => $php_versions,
'tier2' => $tier2,
'comment_body' => $comment_body,
];

View File

@@ -4,13 +4,14 @@ declare(strict_types=1);
namespace StaticPHP\Command;
use StaticPHP\Exception\SPCInternalException;
use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\InputOption;
use function Laravel\Prompts\confirm;
use Symfony\Component\Console\Question\ConfirmationQuestion;
#[AsCommand('reset')]
class ResetCommand extends BaseCommand
@@ -46,7 +47,11 @@ class ResetCommand extends BaseCommand
// Confirm with user unless --yes is specified
if (!$this->input->getOption('yes')) {
if (!confirm('Are you sure you want to continue?', false)) {
$helper = $this->getHelper('question');
if (!$helper instanceof QuestionHelper) {
throw new SPCInternalException('Question helper not provided');
}
if (!$helper->ask($this->input, $this->output, new ConfirmationQuestion('Are you sure you want to continue? [y/N] ', false))) {
InteractiveTerm::error(message: 'Reset operation cancelled.');
return static::SUCCESS;
}

View File

@@ -38,7 +38,7 @@ class ArtifactConfig
*/
public static function loadFromFile(string $file, string $registry_name): string
{
$content = file_get_contents($file);
$content = @file_get_contents($file);
if ($content === false) {
throw new WrongUsageException("Failed to read artifact config file: {$file}");
}

View File

@@ -46,7 +46,7 @@ class PackageConfig
*/
public static function loadFromFile(string $file, string $registry_name): string
{
$content = file_get_contents($file);
$content = @file_get_contents($file);
if ($content === false) {
throw new WrongUsageException("Failed to read package config file: {$file}");
}

View File

@@ -79,11 +79,11 @@ class ApplicationContext
/**
* Get a service from the container.
*
* @template T
* @template T of object
*
* @param class-string<T> $id Service identifier
* @param class-string<T>|string $id Service identifier
*
* @return null|T
* @return ($id is class-string<T> ? T : mixed)
*/
public static function get(string $id): mixed
{

View File

@@ -11,11 +11,14 @@ use StaticPHP\Registry\DoctorLoader;
use StaticPHP\Runtime\Shell\Shell;
use StaticPHP\Runtime\SystemTarget;
use StaticPHP\Util\InteractiveTerm;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use ZM\Logger\ConsoleColor;
use function Laravel\Prompts\confirm;
readonly class Doctor
{
public function __construct(private ?OutputInterface $output = null, private int $auto_fix = FIX_POLICY_PROMPT, public readonly bool $interactive = true)
@@ -125,9 +128,14 @@ readonly class Doctor
return false;
}
// prompt for fix
if ($this->auto_fix === FIX_POLICY_PROMPT && !confirm('Do you want to try to fix this issue now?')) {
$this->output?->writeln('<comment>You canceled fix.</comment>');
return false;
if ($this->auto_fix === FIX_POLICY_PROMPT) {
$helper = new QuestionHelper();
$input = ApplicationContext::has(InputInterface::class) ? ApplicationContext::get(InputInterface::class) : new ArrayInput([]);
$output = ApplicationContext::has(OutputInterface::class) ? ApplicationContext::get(OutputInterface::class) : $this->output ?? new ConsoleOutput();
if (!$helper->ask($input, $output, new ConfirmationQuestion('Do you want to try to fix this issue now? [Y/n] ', true))) {
$this->output?->writeln('<comment>You canceled fix.</comment>');
return false;
}
}
// perform fix
InteractiveTerm::indicateProgress("Fixing {$result->getFixItem()} ... ");

View File

@@ -75,6 +75,9 @@ class PackageInstaller
}
// special check for php target packages
if (in_array($package->getName(), ['php', 'php-cli', 'php-fpm', 'php-micro', 'php-cgi', 'php-embed', 'frankenphp'], true)) {
if (!$package instanceof TargetPackage) {
throw new WrongUsageException("Package '{$package->getName()}' is expected to be a TargetPackage.");
}
$this->handlePhpTargetPackage($package);
return $this;
}

View File

@@ -370,7 +370,10 @@ class PackageLoader
// match condition
$installer = ApplicationContext::get(PackageInstaller::class);
$stages = self::$before_stages[$package_name][$stage] ?? [];
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) {
foreach ($stages as $entry) {
$callback = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
$conditionals = $entry[2] ?? [];
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
continue;
}
@@ -389,7 +392,10 @@ class PackageLoader
$installer = ApplicationContext::get(PackageInstaller::class);
$stages = self::$after_stages[$package_name][$stage] ?? [];
$result = [];
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) {
foreach ($stages as $entry) {
$callback = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
$conditionals = $entry[2] ?? [];
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
continue;
}
@@ -433,7 +439,9 @@ class PackageLoader
}
$pkg = self::getPackage($package_name);
foreach ($stages as $stage_name => $before_events) {
foreach ($before_events as [$event_callable, $only_when_package_resolved, $conditionals]) {
foreach ($before_events as $entry) {
$event_callable = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
// 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}].");

View File

@@ -117,7 +117,7 @@ class UnixAutoconfExecutor extends Executor
/**
* Add configure args.
*/
public function addConfigureArgs(...$args): static
public function addConfigureArgs(string ...$args): static
{
$this->configure_args = [...$this->configure_args, ...$args];
return $this;
@@ -126,7 +126,7 @@ class UnixAutoconfExecutor extends Executor
/**
* Remove some configure args, to bypass the configure option checking for some libs.
*/
public function removeConfigureArgs(...$args): static
public function removeConfigureArgs(string ...$args): static
{
$this->configure_args = array_diff($this->configure_args, $args);
return $this;

View File

@@ -135,7 +135,7 @@ class UnixCMakeExecutor extends Executor
/**
* Add configure args.
*/
public function addConfigureArgs(...$args): static
public function addConfigureArgs(string ...$args): static
{
$this->configure_args = [...$this->configure_args, ...$args];
return $this;
@@ -144,7 +144,7 @@ class UnixCMakeExecutor extends Executor
/**
* Remove some configure args, to bypass the configure option checking for some libs.
*/
public function removeConfigureArgs(...$args): static
public function removeConfigureArgs(string ...$args): static
{
$this->ignore_args = [...$this->ignore_args, ...$args];
return $this;

View File

@@ -99,7 +99,7 @@ class WindowsCMakeExecutor extends Executor
/**
* Add configure args.
*/
public function addConfigureArgs(...$args): static
public function addConfigureArgs(string ...$args): static
{
$this->configure_args = [...$this->configure_args, ...$args];
return $this;
@@ -108,7 +108,7 @@ class WindowsCMakeExecutor extends Executor
/**
* Remove some configure args, to bypass the configure option checking for some libs.
*/
public function removeConfigureArgs(...$args): static
public function removeConfigureArgs(string ...$args): static
{
$this->ignore_args = [...$this->ignore_args, ...$args];
return $this;
@@ -189,6 +189,10 @@ class WindowsCMakeExecutor extends Executor
{
return $this->custom_default_args ?? [
'-A x64',
// CMake 4.x hard-errors on projects requesting compatibility with CMake < 3.5
// (e.g. wineditline). This is the documented escape hatch; modern projects and
// older CMake releases ignore it.
'-DCMAKE_POLICY_VERSION_MINIMUM=3.5',
'-DCMAKE_BUILD_TYPE=Release',
'-DBUILD_SHARED_LIBS=OFF',
'-DBUILD_STATIC_LIBS=ON',

View File

@@ -17,8 +17,8 @@ class InteractiveTerm
public static function notice(string $message, bool $indent = false): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
if ($output->isVerbose()) {
logger()->notice(strip_ansi_colors($message));
} else {
@@ -29,8 +29,8 @@ class InteractiveTerm
public static function success(string $message, bool $indent = false): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
if ($output->isVerbose()) {
logger()->info(strip_ansi_colors($message));
} else {
@@ -41,8 +41,8 @@ class InteractiveTerm
public static function plain(string $message, string $level = 'info'): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
if ($output->isVerbose()) {
match ($level) {
'debug' => logger()->debug(strip_ansi_colors($message)),
@@ -59,8 +59,8 @@ class InteractiveTerm
public static function info(string $message): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
if (!$output->isVerbose()) {
$output->writeln(($no_ansi ? 'strip_ansi_colors' : 'strval')(ConsoleColor::green('▶ ') . $message));
}
@@ -69,8 +69,8 @@ class InteractiveTerm
public static function error(string $message, bool $indent = true): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
if ($output->isVerbose()) {
logger()->error(strip_ansi_colors($message));
} else {
@@ -86,16 +86,16 @@ class InteractiveTerm
public static function setMessage(string $message): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
self::$indicator?->setMessage(($no_ansi ? 'strip_ansi_colors' : 'strval')($message));
logger()->debug(strip_ansi_colors($message));
}
public static function finish(string $message, bool $status = true): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$message = $no_ansi ? strip_ansi_colors($message) : $message;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
$output = ApplicationContext::get(OutputInterface::class);
if ($output->isVerbose()) {
if ($status) {
logger()->info($message);
@@ -116,8 +116,8 @@ class InteractiveTerm
public static function indicateProgress(string $message): void
{
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
if ($output->isVerbose()) {
logger()->info(strip_ansi_colors($message));
return;

View File

@@ -3,22 +3,11 @@
declare(strict_types=1);
// static-php-cli version string
use Laravel\Prompts\ConfirmPrompt;
use Laravel\Prompts\Prompt;
use Laravel\Prompts\TextPrompt;
use StaticPHP\ConsoleApplication;
use StaticPHP\DI\ApplicationContext;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\System\LinuxUtil;
use StaticPHP\Util\System\MacOSUtil;
use StaticPHP\Util\System\WindowsUtil;
use Symfony\Component\Console\Helper\QuestionHelper;
use Symfony\Component\Console\Input\ArrayInput;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\ConsoleOutput;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Question\ConfirmationQuestion;
use Symfony\Component\Console\Question\Question;
const SPC_VERSION = ConsoleApplication::VERSION;
// output path for everything, other paths are defined relative to this by default
@@ -75,31 +64,3 @@ putenv('CPU_COUNT=' . CPU_COUNT);
putenv('SPC_ARCH=' . php_uname('m'));
putenv('GNU_ARCH=' . GNU_ARCH);
putenv('MAC_ARCH=' . MAC_ARCH);
// initialize windows prompt fallback for laravel-prompts
Prompt::fallbackWhen(PHP_OS_FAMILY === 'Windows');
ConfirmPrompt::fallbackUsing(function (ConfirmPrompt $prompt) {
$helper = new QuestionHelper();
$case = $prompt->default ? ' [Y/n] ' : ' [y/N] ';
$question = new ConfirmationQuestion($prompt->label . $case, $prompt->default);
if (ApplicationContext::has(InputInterface::class) && ApplicationContext::has(OutputInterface::class)) {
$input = ApplicationContext::get(InputInterface::class);
$output = ApplicationContext::get(OutputInterface::class);
} else {
$input = new ArrayInput([]);
$output = new ConsoleOutput();
}
return $helper->ask($input, $output, $question);
});
TextPrompt::fallbackUsing(function (TextPrompt $prompt) {
$helper = new QuestionHelper();
$question = new Question($prompt->label . ' ', $prompt->default);
if (ApplicationContext::has(InputInterface::class) && ApplicationContext::has(OutputInterface::class)) {
$input = ApplicationContext::get(InputInterface::class);
$output = ApplicationContext::get(OutputInterface::class);
} else {
$input = new ArrayInput([]);
$output = new ConsoleOutput();
}
return $helper->ask($input, $output, $question);
});

View File

@@ -21,6 +21,8 @@ class GlobalsFunctionsTest extends TestCase
protected function tearDown(): void
{
$GLOBALS['spc_log_filters'] = null;
// Restore logger level to avoid polluting other tests with DEBUG noise
logger()->setLevel(LogLevel::ERROR);
}
public function testAddLogFilterDeduplicates(): void

View File

@@ -23,12 +23,10 @@ class ArtifactDownloaderTest extends TestCase
// Reset ArtifactConfig and ArtifactLoader static state
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue(null, []);
$loaderReflection = new \ReflectionClass(ArtifactLoader::class);
$loaderProperty = $loaderReflection->getProperty('artifacts');
$loaderProperty->setAccessible(true);
$loaderProperty->setValue(null, null);
}
@@ -38,12 +36,10 @@ class ArtifactDownloaderTest extends TestCase
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue(null, []);
$loaderReflection = new \ReflectionClass(ArtifactLoader::class);
$loaderProperty = $loaderReflection->getProperty('artifacts');
$loaderProperty->setAccessible(true);
$loaderProperty->setValue(null, null);
}
@@ -343,7 +339,6 @@ class ArtifactDownloaderTest extends TestCase
{
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$configs = $property->getValue(null) ?? [];
$configs[$name] = $config;
$property->setValue(null, $configs);

View File

@@ -31,12 +31,10 @@ class ArtifactExtractorTest extends TestCase
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue(null, []);
$loaderReflection = new \ReflectionClass(ArtifactLoader::class);
$loaderProperty = $loaderReflection->getProperty('artifacts');
$loaderProperty->setAccessible(true);
$loaderProperty->setValue(null, null);
ApplicationContext::reset();
@@ -51,12 +49,10 @@ class ArtifactExtractorTest extends TestCase
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue(null, []);
$loaderReflection = new \ReflectionClass(ArtifactLoader::class);
$loaderProperty = $loaderReflection->getProperty('artifacts');
$loaderProperty->setAccessible(true);
$loaderProperty->setValue(null, null);
ApplicationContext::reset();
@@ -157,7 +153,6 @@ class ArtifactExtractorTest extends TestCase
// Pre-populate the extracted map for 'my-pkg' via reflection
$reflection = new \ReflectionClass(ArtifactExtractor::class);
$extractedProperty = $reflection->getProperty('extracted');
$extractedProperty->setAccessible(true);
$extractedProperty->setValue($extractor, ['my-pkg' => true]);
$result = $extractor->extract($artifact, false);
@@ -181,7 +176,6 @@ class ArtifactExtractorTest extends TestCase
// Pre-populate the extracted map so we don't need actual downloads
$reflection = new \ReflectionClass(ArtifactExtractor::class);
$extractedProperty = $reflection->getProperty('extracted');
$extractedProperty->setAccessible(true);
$extractedProperty->setValue($extractor, ['my-pkg' => true]);
$result = $extractor->extract('my-pkg', false);
@@ -204,7 +198,6 @@ class ArtifactExtractorTest extends TestCase
{
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$configs = $property->getValue(null) ?? [];
$configs[$name] = $config;
$property->setValue(null, $configs);

View File

@@ -29,7 +29,6 @@ class ArtifactTest extends TestCase
// Reset ArtifactConfig static state
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue(null, []);
// Reset DI container
@@ -45,7 +44,6 @@ class ArtifactTest extends TestCase
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue(null, []);
ApplicationContext::reset();
@@ -715,7 +713,6 @@ class ArtifactTest extends TestCase
{
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$configs = $property->getValue(null) ?? [];
$configs[$name] = $config;
$property->setValue(null, $configs);

View File

@@ -0,0 +1,291 @@
<?php
declare(strict_types=1);
namespace Tests\StaticPHP\Command\Dev;
use PHPUnit\Framework\TestCase;
use Psr\Log\LogLevel;
use StaticPHP\Command\Dev\GenExtTestMatrixCommand;
use StaticPHP\Config\PackageConfig;
use Symfony\Component\Console\Application;
use Symfony\Component\Console\Tester\CommandTester;
/**
* @internal
*/
class GenExtTestMatrixCommandTest extends TestCase
{
private Application $app;
protected function setUp(): void
{
parent::setUp();
// Reset PackageConfig static state
$ref = new \ReflectionClass(PackageConfig::class);
$prop = $ref->getProperty('package_configs');
$prop->setValue(null, []);
// Register fixture packages
PackageConfig::loadFromArray(self::buildFixture(), 'test');
// Set up Symfony Application with the command under test
$this->app = new Application();
$this->app->add(new GenExtTestMatrixCommand());
$this->app->setAutoExit(false);
}
protected function tearDown(): void
{
parent::tearDown();
// Reset PackageConfig static state
$ref = new \ReflectionClass(PackageConfig::class);
$prop = $ref->getProperty('package_configs');
$prop->setValue(null, []);
// Restore logger level (BaseCommand::execute() may have changed it)
logger()->setLevel(LogLevel::ERROR);
}
// ──────────────────────────────────────────────────────────────────────────
// Tests
// ──────────────────────────────────────────────────────────────────────────
/**
* swoole entry must contain all swoole-hook-* virtuals and nothing else.
*/
public function testSwooleBundlesHookVirtuals(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux']);
$swooleEntries = $this->findEntriesContaining($matrix, 'swoole');
$this->assertCount(1, $swooleEntries, 'Expected exactly one entry containing swoole');
$parts = explode(',', $swooleEntries[0]['extension']);
sort($parts);
$this->assertContains('swoole', $parts);
$this->assertContains('swoole-hook-mysql', $parts);
$this->assertContains('swoole-hook-pgsql', $parts);
}
/**
* curl must NOT appear in the same entry as swoole, even though swoole depends on it.
*/
public function testCurlIsNotPulledIntoSwooleEntry(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux']);
// The swoole entry must not contain 'curl'
$swooleEntries = $this->findEntriesContaining($matrix, 'swoole');
$this->assertCount(1, $swooleEntries);
$parts = explode(',', $swooleEntries[0]['extension']);
$this->assertNotContains('curl', $parts, 'curl must not appear inside the swoole matrix entry');
// curl must appear in a separate entry
$curlEntries = $this->findEntriesContaining($matrix, 'curl');
$this->assertNotEmpty($curlEntries, 'curl must have its own matrix entry');
}
/**
* swow must be fully isolated — its entry should only contain 'swow'.
*/
public function testSwowIsIsolated(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux']);
$swowEntries = $this->findEntriesContaining($matrix, 'swow');
$this->assertCount(1, $swowEntries, 'Expected exactly one entry containing swow');
$this->assertSame('swow', $swowEntries[0]['extension'], 'swow entry must contain only swow');
}
/**
* dom and xml must appear in the same matrix entry (DFS chain).
*/
public function testDomXmlChain(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux']);
$chainEntries = $this->findEntriesContaining($matrix, 'dom', 'xml');
$this->assertNotEmpty($chainEntries, 'dom and xml must appear in the same matrix entry');
}
/**
* --os=Windows must exclude ext-linux-only.
*/
public function testOsFilterExcludesLinuxOnlyFromWindows(): void
{
$matrix = $this->runMatrix(['--os' => 'Windows']);
$linuxOnlyEntries = $this->findEntriesContaining($matrix, 'linux-only');
$this->assertEmpty($linuxOnlyEntries, 'ext-linux-only must not appear in the Windows matrix');
}
/**
* --os=Linux must include ext-linux-only.
*/
public function testOsFilterIncludesLinuxOnly(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux']);
$linuxOnlyEntries = $this->findEntriesContaining($matrix, 'linux-only');
$this->assertNotEmpty($linuxOnlyEntries, 'ext-linux-only must appear in the Linux matrix');
}
/**
* All returned entries must reference the requested OS runner when --os is specified.
*/
public function testOsFilterRestrictsRunners(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux']);
foreach ($matrix as $entry) {
$this->assertSame('linux', $entry['os'], "Entry {$entry['extension']} must only target Linux");
}
}
/**
* --for-extensions=redis must return only entries that contain 'redis'.
*/
public function testForExtensionsFilter(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux', '--for-extensions' => 'redis']);
$this->assertNotEmpty($matrix, '--for-extensions=redis must yield at least one entry');
foreach ($matrix as $entry) {
$parts = explode(',', $entry['extension']);
$this->assertContains('redis', $parts, "Entry {$entry['extension']} does not contain redis");
}
}
/**
* --for-libs=libxml2 must return only entries whose extension(s) depend on libxml2.
*/
public function testForLibsFilter(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux', '--for-libs' => 'libxml2']);
$this->assertNotEmpty($matrix, '--for-libs=libxml2 must yield at least one entry');
foreach ($matrix as $entry) {
$parts = explode(',', $entry['extension']);
// xml depends on libxml2 directly; dom depends on xml (which depends on libxml2)
$match = count(array_intersect($parts, ['xml', 'dom'])) > 0;
$this->assertTrue($match, "Entry {$entry['extension']} should not appear in --for-libs=libxml2 results");
}
}
/**
* --tier2 must produce only Tier2 runners and no Windows entries.
*/
public function testTier2Flag(): void
{
$matrix = $this->runMatrix(['--tier2' => true]);
$this->assertNotEmpty($matrix);
foreach ($matrix as $entry) {
$this->assertNotSame('windows', $entry['os'], '--tier2 must not include Windows entries');
$this->assertContains(
$entry['runner'],
['ubuntu-24.04-arm', 'macos-15-intel'],
"Runner {$entry['runner']} is not a valid Tier2 runner"
);
}
}
/**
* Each entry must have the mandatory keys and correct types.
*/
public function testEntryShape(): void
{
$matrix = $this->runMatrix(['--os' => 'Linux']);
$this->assertNotEmpty($matrix);
foreach ($matrix as $entry) {
$this->assertArrayHasKey('runner', $entry);
$this->assertArrayHasKey('os', $entry);
$this->assertArrayHasKey('arch', $entry);
$this->assertArrayHasKey('extension', $entry);
$this->assertArrayHasKey('build-args', $entry);
$this->assertIsString($entry['extension']);
$this->assertIsString($entry['build-args']);
$this->assertStringContainsString($entry['extension'], $entry['build-args']);
}
}
// ──────────────────────────────────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────────────────────────────────
/**
* Run the command with the given options and return the parsed JSON matrix.
*/
private function runMatrix(array $options = []): array
{
$tester = new CommandTester($this->app->find('dev:gen-ext-test-matrix'));
$tester->execute($options, ['decorated' => false]);
$output = $tester->getDisplay();
$matrix = json_decode($output, true);
$this->assertIsArray($matrix, "Command output is not valid JSON. Output:\n{$output}");
return $matrix;
}
/**
* Find matrix entries whose 'extension' field contains all of the given names.
*
* @return array[] matching entries
*/
private function findEntriesContaining(array $matrix, string ...$names): array
{
return array_values(array_filter($matrix, static function (array $entry) use ($names): bool {
$parts = explode(',', $entry['extension']);
foreach ($names as $name) {
if (!in_array($name, $parts, true)) {
return false;
}
}
return true;
}));
}
/**
* Minimal valid php-extension fixture.
*
* Layout:
* - ext-swow standalone isolated, no ext deps
* - ext-swoole standalone isolated, depends on ext-curl
* - ext-swoole-hook-* virtual (arg-type: none) — must be bundled with swoole
* - ext-curl simple orphan, depended on by swoole but must NOT be pulled into swoole entry
* - ext-redis simple orphan
* - ext-xml depends on lib 'libxml2'
* - ext-dom depends on ext-xml (DFS chain)
* - ext-linux-only restricted to Linux via os: [Linux]
*/
private static function buildFixture(): array
{
// php-extension must be a non-empty assoc array ([] fails is_assoc_array() check).
$ext = static fn (array $phpExt = ['arg-type' => 'standard'], array $topLevel = []): array => array_merge(['type' => 'php-extension', 'php-extension' => $phpExt], $topLevel);
return [
// Isolated standalones
'ext-swow' => $ext(),
'ext-swoole' => $ext(['arg-type' => 'standard'], ['depends' => ['ext-curl']]),
// Swoole hook virtuals (arg-type: none → virtual)
'ext-swoole-hook-mysql' => $ext(['arg-type' => 'none']),
'ext-swoole-hook-pgsql' => $ext(['arg-type' => 'none']),
// Simple orphans
'ext-curl' => $ext(),
'ext-redis' => $ext(),
// DFS chain: dom depends on xml; xml depends on lib 'libxml2'
'ext-xml' => $ext(['arg-type' => 'standard'], ['depends' => ['libxml2']]),
'ext-dom' => $ext(['arg-type' => 'standard'], ['depends' => ['ext-xml']]),
// OS-restricted to Linux only
'ext-linux-only' => $ext(['os' => ['Linux']]),
];
}
}

View File

@@ -25,7 +25,6 @@ class ArtifactConfigTest extends TestCase
// Reset static state
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue([]);
}
@@ -41,7 +40,6 @@ class ArtifactConfigTest extends TestCase
// Reset static state
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue([]);
}

View File

@@ -26,7 +26,6 @@ class PackageConfigTest extends TestCase
// Reset static state
$reflection = new \ReflectionClass(PackageConfig::class);
$property = $reflection->getProperty('package_configs');
$property->setAccessible(true);
$property->setValue([]);
}
@@ -41,7 +40,6 @@ class PackageConfigTest extends TestCase
// Reset static state
$reflection = new \ReflectionClass(PackageConfig::class);
$property = $reflection->getProperty('package_configs');
$property->setAccessible(true);
$property->setValue([]);
}

View File

@@ -32,12 +32,10 @@ class ArtifactLoaderTest extends TestCase
// Reset ArtifactLoader and ArtifactConfig state
$reflection = new \ReflectionClass(ArtifactLoader::class);
$property = $reflection->getProperty('artifacts');
$property->setAccessible(true);
$property->setValue(null, null);
$configReflection = new \ReflectionClass(ArtifactConfig::class);
$configProperty = $configReflection->getProperty('artifact_configs');
$configProperty->setAccessible(true);
$configProperty->setValue(null, []);
}
@@ -52,12 +50,10 @@ class ArtifactLoaderTest extends TestCase
// Reset ArtifactLoader and ArtifactConfig state
$reflection = new \ReflectionClass(ArtifactLoader::class);
$property = $reflection->getProperty('artifacts');
$property->setAccessible(true);
$property->setValue(null, null);
$configReflection = new \ReflectionClass(ArtifactConfig::class);
$configProperty = $configReflection->getProperty('artifact_configs');
$configProperty->setAccessible(true);
$configProperty->setValue(null, []);
}
@@ -429,7 +425,6 @@ class TestArtifact1 {
{
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$configs = $property->getValue();
$configs[$name] = [
'type' => 'source',

View File

@@ -26,11 +26,9 @@ class DoctorLoaderTest extends TestCase
// Reset DoctorLoader state
$reflection = new \ReflectionClass(DoctorLoader::class);
$property = $reflection->getProperty('doctor_items');
$property->setAccessible(true);
$property->setValue(null, []);
$property = $reflection->getProperty('fix_items');
$property->setAccessible(true);
$property->setValue(null, []);
}
@@ -45,11 +43,9 @@ class DoctorLoaderTest extends TestCase
// Reset DoctorLoader state
$reflection = new \ReflectionClass(DoctorLoader::class);
$property = $reflection->getProperty('doctor_items');
$property->setAccessible(true);
$property->setValue(null, []);
$property = $reflection->getProperty('fix_items');
$property->setAccessible(true);
$property->setValue(null, []);
}

View File

@@ -33,25 +33,20 @@ class PackageLoaderTest extends TestCase
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('packages');
$property->setAccessible(true);
$property->setValue(null, null);
$property = $reflection->getProperty('before_stages');
$property->setAccessible(true);
$property->setValue(null, []);
$property = $reflection->getProperty('after_stages');
$property->setAccessible(true);
$property->setValue(null, []);
$property = $reflection->getProperty('loaded_classes');
$property->setAccessible(true);
$property->setValue(null, []);
// Reset PackageConfig state
$configReflection = new \ReflectionClass(PackageConfig::class);
$configProperty = $configReflection->getProperty('package_configs');
$configProperty->setAccessible(true);
$configProperty->setValue(null, []);
}
@@ -67,25 +62,20 @@ class PackageLoaderTest extends TestCase
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('packages');
$property->setAccessible(true);
$property->setValue(null, null);
$property = $reflection->getProperty('before_stages');
$property->setAccessible(true);
$property->setValue(null, []);
$property = $reflection->getProperty('after_stages');
$property->setAccessible(true);
$property->setValue(null, []);
$property = $reflection->getProperty('loaded_classes');
$property->setAccessible(true);
$property->setValue(null, []);
// Reset PackageConfig state
$configReflection = new \ReflectionClass(PackageConfig::class);
$configProperty = $configReflection->getProperty('package_configs');
$configProperty->setAccessible(true);
$configProperty->setValue(null, []);
}
@@ -359,7 +349,6 @@ class PackageLoaderTest extends TestCase
// Manually add a before_stage for non-existent package
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('before_stages');
$property->setAccessible(true);
$property->setValue(null, [
'non-existent-package' => [
'stage-name' => [[fn () => null, null]],
@@ -384,7 +373,6 @@ class PackageLoaderTest extends TestCase
// Manually add a before_stage for non-existent stage
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('before_stages');
$property->setAccessible(true);
$property->setValue(null, [
'test-lib' => [
'non-existent-stage' => [[fn () => null, null]],
@@ -408,7 +396,6 @@ class PackageLoaderTest extends TestCase
// Manually add a before_stage with unknown only_when_package_resolved
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('before_stages');
$property->setAccessible(true);
$property->setValue(null, [
'test-lib' => [
'test-stage' => [[fn () => null, 'non-existent-package']],
@@ -435,7 +422,6 @@ class PackageLoaderTest extends TestCase
// This should NOT throw an exception because the package has no build function for current OS
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('before_stages');
$property->setAccessible(true);
$property->setValue(null, [
'test-lib' => [
'build' => [[fn () => null, null]],
@@ -458,7 +444,6 @@ class PackageLoaderTest extends TestCase
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('before_stages');
$property->setAccessible(true);
$property->setValue(null, [
'test-package' => [
'test-stage' => [
@@ -482,7 +467,6 @@ class PackageLoaderTest extends TestCase
$reflection = new \ReflectionClass(PackageLoader::class);
$property = $reflection->getProperty('after_stages');
$property->setAccessible(true);
$property->setValue(null, [
'test-package' => [
'test-stage' => [
@@ -570,7 +554,6 @@ class TestPackage1 {
{
$reflection = new \ReflectionClass(PackageConfig::class);
$property = $reflection->getProperty('package_configs');
$property->setAccessible(true);
$configs = $property->getValue();
$configs[$name] = [
'type' => $type,

View File

@@ -0,0 +1,531 @@
<?php
declare(strict_types=1);
namespace Tests\StaticPHP\Util;
use PHPUnit\Framework\TestCase;
use StaticPHP\Config\PackageConfig;
use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Util\DependencyResolver;
/**
* Tests for the DependencyResolver — the topological sort engine that
* determines the order in which packages (libraries, extensions, targets)
* must be built.
*
* @internal
*/
class DependencyResolverTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
$this->resetPackageConfig();
}
protected function tearDown(): void
{
parent::tearDown();
$this->resetPackageConfig();
}
// ──────────────────────────────────────────────
// Basic resolution
// ──────────────────────────────────────────────
public function testResolveSinglePackageNoDependencies(): void
{
$this->loadConfig([
'zlib' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['zlib']);
$this->assertSame(['zlib'], $result);
}
public function testResolveLinearChain(): void
{
// a -> b -> c (a depends on b, b depends on c)
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b']],
'b' => ['type' => 'library', 'depends' => ['c']],
'c' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['a']);
// c must be first, then b, then a
$this->assertSame(['c', 'b', 'a'], $result);
}
public function testResolveMultipleIndependentChains(): void
{
// a -> b, x -> y (two independent dependency chains)
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b']],
'b' => ['type' => 'library'],
'x' => ['type' => 'library', 'depends' => ['y']],
'y' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['a', 'x']);
// Dependencies must come before their dependants
$posB = array_search('b', $result, true);
$posA = array_search('a', $result, true);
$posY = array_search('y', $result, true);
$posX = array_search('x', $result, true);
$this->assertIsInt($posB);
$this->assertIsInt($posA);
$this->assertIsInt($posY);
$this->assertIsInt($posX);
$this->assertLessThan($posA, $posB, 'b should come before a');
$this->assertLessThan($posX, $posY, 'y should come before x');
}
public function testResolveSharedDependency(): void
{
// a -> c, b -> c (c is shared)
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['c']],
'b' => ['type' => 'library', 'depends' => ['c']],
'c' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['a', 'b']);
// c must appear exactly once and before both a and b
$cCount = count(array_keys($result, 'c', true));
$this->assertSame(1, $cCount, 'Shared dependency c should appear exactly once');
$posC = array_search('c', $result, true);
$posA = array_search('a', $result, true);
$posB = array_search('b', $result, true);
$this->assertLessThan($posA, $posC, 'c should come before a');
$this->assertLessThan($posB, $posC, 'c should come before b');
}
public function testResolveDiamondDependency(): void
{
// a
// / \
// b c
// \ /
// d
$this->loadConfig([
'a' => ['type' => 'target', 'depends' => ['b', 'c']],
'b' => ['type' => 'library', 'depends' => ['d']],
'c' => ['type' => 'library', 'depends' => ['d']],
'd' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['a']);
// d must appear exactly once and before everything
$dCount = count(array_keys($result, 'd', true));
$this->assertSame(1, $dCount);
$posD = array_search('d', $result, true);
$posB = array_search('b', $result, true);
$posC = array_search('c', $result, true);
$posA = array_search('a', $result, true);
$this->assertLessThan($posB, $posD, 'd should come before b');
$this->assertLessThan($posC, $posD, 'd should come before c');
$this->assertLessThan($posA, $posB, 'b should come before a');
$this->assertLessThan($posA, $posC, 'c should come before a');
}
// ──────────────────────────────────────────────
// Suggests (optional dependencies)
// ──────────────────────────────────────────────
public function testResolveSuggestsAreExcludedByDefault(): void
{
// a depends on b, suggests c
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b'], 'suggests' => ['c']],
'b' => ['type' => 'library'],
'c' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['a']);
// c should NOT be in the resolved list (it's only suggested, not depended)
$this->assertNotContains('c', $result);
$this->assertSame(['b', 'a'], $result);
}
public function testResolveSuggestsIncludedWhenFlagSet(): void
{
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b'], 'suggests' => ['c']],
'b' => ['type' => 'library'],
'c' => ['type' => 'library', 'depends' => ['b']],
]);
$result = DependencyResolver::resolve(['a'], include_suggests: true);
// c IS a suggest of a and should be included when flag is set
$this->assertContains('c', $result);
$posB = array_search('b', $result, true);
$posC = array_search('c', $result, true);
$posA = array_search('a', $result, true);
$this->assertLessThan($posA, $posB, 'b should come before a');
$this->assertLessThan($posA, $posC, 'c should come before a');
}
// ──────────────────────────────────────────────
// Virtual-target promotion
// ──────────────────────────────────────────────
public function testResolveVirtualTargetPromotesDepsToParent(): void
{
// php-cli (virtual-target) depends on [php, ext-ctype]
// When php-cli is in the input, ext-ctype should be promoted to php's deps
$this->loadConfig([
'php-cli' => ['type' => 'virtual-target', 'depends' => ['php', 'ext-ctype']],
'php' => ['type' => 'target', 'depends' => ['libxml2']],
'ext-ctype' => ['type' => 'php-extension', 'depends' => []],
'libxml2' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['php-cli']);
$posPhp = array_search('php', $result, true);
$posCtype = array_search('ext-ctype', $result, true);
$posLibxml2 = array_search('libxml2', $result, true);
$this->assertIsInt($posPhp);
$this->assertIsInt($posCtype);
$this->assertIsInt($posLibxml2);
// ext-ctype was promoted to php's deps, so it must come before php
$this->assertLessThan($posPhp, $posCtype, 'ext-ctype should come before php (promoted dep)');
// libxml2 is a native dep of php, so it must also come before php
$this->assertLessThan($posPhp, $posLibxml2, 'libxml2 should come before php');
}
public function testResolveVirtualTargetNotInInputDoesNotPromote(): void
{
// php-cli is a virtual-target but NOT in the input request,
// so its deps should NOT be injected into php
$this->loadConfig([
'php-cli' => ['type' => 'virtual-target', 'depends' => ['php', 'ext-ctype']],
'php' => ['type' => 'target', 'depends' => ['libxml2']],
'ext-ctype' => ['type' => 'php-extension'],
'libxml2' => ['type' => 'library'],
]);
// Only php is requested, not php-cli
$result = DependencyResolver::resolve(['php']);
// ext-ctype should NOT be in the result since php-cli was not requested
$this->assertNotContains('ext-ctype', $result);
$this->assertSame(['libxml2', 'php'], $result);
}
// ──────────────────────────────────────────────
// Dependency overrides
// ──────────────────────────────────────────────
public function testResolveDependencyOverridesAddDeps(): void
{
$this->loadConfig([
'a' => ['type' => 'library'],
'b' => ['type' => 'library'],
'c' => ['type' => 'library'],
]);
// Override: a now depends on b and c
$result = DependencyResolver::resolve(['a'], dependency_overrides: [
'a' => ['b', 'c'],
]);
$posA = array_search('a', $result, true);
$posB = array_search('b', $result, true);
$posC = array_search('c', $result, true);
$this->assertLessThan($posA, $posB, 'b should come before a (override)');
$this->assertLessThan($posA, $posC, 'c should come before a (override)');
}
public function testResolveDependencyOverridesMergeWithExisting(): void
{
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b']],
'b' => ['type' => 'library'],
'c' => ['type' => 'library'],
]);
// a natively depends on b, override adds c
$result = DependencyResolver::resolve(['a'], dependency_overrides: [
'a' => ['c'],
]);
$this->assertContains('b', $result);
$this->assertContains('c', $result);
$posA = array_search('a', $result, true);
$posB = array_search('b', $result, true);
$posC = array_search('c', $result, true);
$this->assertLessThan($posA, $posB, 'b should come before a');
$this->assertLessThan($posA, $posC, 'c should come before a');
}
// ──────────────────────────────────────────────
// Error handling
// ──────────────────────────────────────────────
public function testResolveUnknownPackageThrowsException(): void
{
$this->loadConfig([
'zlib' => ['type' => 'library'],
]);
$this->expectException(WrongUsageException::class);
$this->expectExceptionMessage('does not exist in config');
DependencyResolver::resolve(['nonexistent']);
}
public function testResolveUnregisteredDependencyThrowsException(): void
{
// a depends on b, but b is not in the config
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b']],
]);
$this->expectException(WrongUsageException::class);
$this->expectExceptionMessage('not exist');
DependencyResolver::resolve(['a']);
}
// ──────────────────────────────────────────────
// Reverse dependency map ($why parameter)
// ──────────────────────────────────────────────
public function testReverseDependencyMap(): void
{
// a -> b -> c
$this->loadConfig([
'a' => ['type' => 'target', 'depends' => ['b']],
'b' => ['type' => 'library', 'depends' => ['c']],
'c' => ['type' => 'library'],
]);
$why = [];
DependencyResolver::resolve(['a'], why: $why);
$this->assertArrayHasKey('c', $why, 'c is depended upon');
$this->assertContains('b', $why['c'], 'b depends on c');
$this->assertArrayHasKey('b', $why, 'b is depended upon');
$this->assertContains('a', $why['b'], 'a depends on b');
}
public function testReverseDependencyMapOnlyIncludesResolvedPackages(): void
{
// a -> b -> c, but only requesting a
// d is not in the resolved set
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b']],
'b' => ['type' => 'library', 'depends' => ['c']],
'c' => ['type' => 'library'],
'd' => ['type' => 'library', 'depends' => ['c']], // not in input
]);
$why = [];
DependencyResolver::resolve(['a'], why: $why);
// d should NOT appear in the reverse map since it's not in the resolved set
$this->assertArrayNotHasKey('d', $why);
}
// ──────────────────────────────────────────────
// getSubDependencies
// ──────────────────────────────────────────────
public function testGetSubDependenciesLinearChain(): void
{
// a -> b -> c -> d
$this->loadConfig([
'a' => ['type' => 'target', 'depends' => ['b']],
'b' => ['type' => 'library', 'depends' => ['c']],
'c' => ['type' => 'library', 'depends' => ['d']],
'd' => ['type' => 'library'],
]);
$subDeps = DependencyResolver::getSubDependencies('a', ['a', 'b', 'c', 'd']);
// Should return [d, c, b] in dependency order (a not included)
$this->assertNotContains('a', $subDeps);
$this->assertSame(['d', 'c', 'b'], $subDeps);
}
public function testGetSubDependenciesPackageNotInResolvedSet(): void
{
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b']],
'b' => ['type' => 'library'],
]);
$subDeps = DependencyResolver::getSubDependencies('nonexistent', ['a', 'b']);
$this->assertSame([], $subDeps);
}
public function testGetSubDependenciesWithSuggests(): void
{
$this->loadConfig([
'a' => ['type' => 'target', 'depends' => ['b'], 'suggests' => ['c']],
'b' => ['type' => 'library'],
'c' => ['type' => 'library'],
]);
// Without include_suggests: only b is a sub-dep
$without = DependencyResolver::getSubDependencies('a', ['a', 'b', 'c'], include_suggests: false);
$this->assertSame(['b'], $without);
// With include_suggests: both b and c are sub-deps
$with = DependencyResolver::getSubDependencies('a', ['a', 'b', 'c'], include_suggests: true);
$this->assertContains('b', $with);
$this->assertContains('c', $with);
}
public function testGetSubDependenciesOnlyIncludesResolvedDeps(): void
{
// a depends on b and c, but c is not in the resolved set
$this->loadConfig([
'a' => ['type' => 'target', 'depends' => ['b', 'c']],
'b' => ['type' => 'library'],
'c' => ['type' => 'library'],
]);
// c is NOT in the resolved set
$subDeps = DependencyResolver::getSubDependencies('a', ['a', 'b']);
$this->assertContains('b', $subDeps);
$this->assertNotContains('c', $subDeps, 'c is not in the resolved set, should be excluded');
}
// ──────────────────────────────────────────────
// Edge cases & defensive
// ──────────────────────────────────────────────
public function testResolveEmptyInput(): void
{
$this->loadConfig([
'zlib' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve([]);
$this->assertSame([], $result);
}
public function testResolveWithStringAndPackageInstanceMixed(): void
{
$this->loadConfig([
'a' => ['type' => 'library'],
'b' => ['type' => 'library'],
]);
// Pass one as string, one as a mock Package
$mockPackage = $this->createMockPackage('a');
$result = DependencyResolver::resolve([$mockPackage, 'b']);
$this->assertContains('a', $result);
$this->assertContains('b', $result);
}
public function testResolveDuplicateInputPackages(): void
{
// Requesting the same package twice should not duplicate it in output
$this->loadConfig([
'zlib' => ['type' => 'library'],
]);
$result = DependencyResolver::resolve(['zlib', 'zlib']);
$this->assertSame(['zlib'], $result);
}
/**
* Documents the current behavior for circular dependencies.
* The algorithm does not detect cycles; it silently resolves them
* using the visited-set to break infinite recursion. This test
* locks in the current behavior so any intentional change is caught.
*/
public function testCircularDependencyDoesNotLoopInfinitely(): void
{
// a -> b -> a (circular)
$this->loadConfig([
'a' => ['type' => 'library', 'depends' => ['b']],
'b' => ['type' => 'library', 'depends' => ['a']],
]);
// Must not hang — should complete and return both packages
$result = DependencyResolver::resolve(['a']);
$this->assertCount(2, $result);
$this->assertContains('a', $result);
$this->assertContains('b', $result);
}
// ──────────────────────────────────────────────
// Helpers
// ──────────────────────────────────────────────
/**
* Load package configurations directly into PackageConfig.
* Uses reflection to inject fixture data without needing YAML files on disk.
*
* @param array<string, array{type: string, depends?: string[], suggests?: string[]}> $configs
*/
private function loadConfig(array $configs): void
{
$reflection = new \ReflectionClass(PackageConfig::class);
$property = $reflection->getProperty('package_configs');
$existing = $property->getValue();
if (!is_array($existing)) {
$existing = [];
}
foreach ($configs as $name => $config) {
$existing[$name] = $config;
}
$property->setValue(null, $existing);
}
/**
* Reset PackageConfig to empty state.
*/
private function resetPackageConfig(): void
{
$reflection = new \ReflectionClass(PackageConfig::class);
$property = $reflection->getProperty('package_configs');
$property->setValue(null, []);
}
/**
* Create a minimal mock Package object that returns a given name.
*/
private function createMockPackage(string $name): object
{
return new class($name) {
public function __construct(private string $name) {}
public function getName(): string
{
return $this->name;
}
};
}
}

View File

@@ -2,8 +2,10 @@
declare(strict_types=1);
use Psr\Log\LogLevel;
use StaticPHP\Registry\Registry;
require_once __DIR__ . '/../src/bootstrap.php';
\StaticPHP\Registry\Registry::resolve();
logger()->setLevel(LogLevel::ERROR);
Registry::resolve();