Compare commits

..

5 Commits

Author SHA1 Message Date
Jerry Ma
63ab28097f Merge branch 'v3' into v3c/library-fixes 2026-06-16 13:59:12 +08:00
Jerry Ma
80ae7b093c Merge branch 'v3' into v3c/library-fixes 2026-06-04 16:08:37 +08:00
henderkes
daea8e10ad fix https://github.com/php/frankenphp/issues/1346 2026-05-28 12:22:14 +07:00
henderkes
727600a73a disable a whole lot of things we don't need to build 2026-05-26 21:10:00 +07:00
henderkes
29a8c9c196 libraries: honour SPC_DEFAULT_CFLAGS/CXXFLAGS/LDFLAGS and bug fixes
bzip2, fastlz, jbig, qdbm: thread SPC_DEFAULT_CFLAGS into the
hand-rolled Makefile patches and shell compile commands. Backward
compatible when the env var is empty.

icu: append SPC_DEFAULT_CXXFLAGS/LDFLAGS to runConfigureICU's CXXFLAGS
and LDFLAGS so user flags reach the bundled cxx invocation.

openssl: append user CFLAGS/LDFLAGS after the target name on Configure
so options like -flto and -fprofile-* reach the openssl build.

libheif: rewrite libheif 1.22+'s C-incompatible
`struct heif_bad_pixel { uint32_t row; uint32_t column; };` as a
typedef so C consumers compile.

ncurses: filter the clang/zig-cc "N warning(s) generated." stdout line
out of MKlib_gen.sh's preprocessor pipe before sed turns it into
invalid C in lib_gen.c.

libaom: detect target CPU from SystemTarget instead of hard-coding
generic, fall back to generic only when neither nasm nor yasm is
available, and turn off examples/tests/tools/docs.
2026-05-24 21:28:31 +07:00
107 changed files with 664 additions and 1873 deletions

View File

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

View File

@@ -12,8 +12,10 @@
"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

@@ -3,10 +3,6 @@ ncurses:
license-files:
- COPYING
source:
type: filelist
url: 'https://ftp.gnu.org/gnu/ncurses/'
regex: '/href="(?<file>ncurses-(?<version>[^"]+)\.tar\.gz)"/'
source-mirror:
type: filelist
url: 'https://ftpmirror.gnu.org/gnu/ncurses/'
regex: '/href="(?<file>ncurses-(?<version>[^"]+)\.tar\.gz)"/'

View File

@@ -68,8 +68,8 @@ SPC_PRESERVE_LOGS="no"
[windows]
; build target: win7-static
SPC_TARGET=native-windows
; MSYS2 root directory (msys64 subfolder), used by the Windows toolchain
SPC_MSYS2_PATH="${PKG_ROOT_PATH}\msys2-build-essentials\msys64"
; php-sdk-binary-tools path
PHP_SDK_PATH="${WORKING_DIR}\php-sdk-binary-tools"
; upx executable path
UPX_EXEC="${PKG_ROOT_PATH}\bin\upx.exe"
; phpmicro patches, for more info, see: https://github.com/easysoft/phpmicro/tree/master/patches

View File

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

View File

@@ -10,11 +10,6 @@ ext-zip:
license: PHP-3.01
depends:
- libzip
depends@windows:
- libzip
- zlib
- xz
- bzip2
php-extension:
arg-type: custom
arg-type@windows: enable

View File

@@ -2,10 +2,6 @@ gettext:
type: library
artifact:
source:
type: filelist
url: 'https://ftp.gnu.org/gnu/gettext/'
regex: '/href="(?<file>gettext-(?<version>[^"]+)\.tar\.xz)"/'
source-mirror:
type: filelist
url: 'https://ftpmirror.gnu.org/gnu/gettext/'
regex: '/href="(?<file>gettext-(?<version>[^"]+)\.tar\.xz)"/'

View File

@@ -2,13 +2,12 @@ gmp:
type: library
artifact:
source:
type: filelist
url: 'https://ftp.gnu.org/gnu/gmp/'
regex: '/href="(?<file>gmp-(?<version>[^"]+)\.tar\.xz)"/'
source-mirror:
type: filelist
url: 'https://ftpmirror.gnu.org/gnu/gmp/'
regex: '/href="(?<file>gmp-(?<version>[^"]+)\.tar\.xz)"/'
source-mirror:
type: url
url: 'https://dl.static-php.dev/static-php-cli/deps/gmp/gmp-6.3.0.tar.xz'
metadata:
license-files: ['@/gmp.txt']
license: Custom

View File

@@ -2,10 +2,6 @@ idn2:
type: library
artifact:
source:
type: filelist
url: 'https://ftp.gnu.org/gnu/libidn/'
regex: '/href="(?<file>libidn2-(?<version>[^"]+)\.tar\.gz)"/'
source-mirror:
type: filelist
url: 'https://ftpmirror.gnu.org/gnu/libidn/'
regex: '/href="(?<file>libidn2-(?<version>[^"]+)\.tar\.gz)"/'

View File

@@ -2,10 +2,6 @@ libiconv:
type: library
artifact:
source:
type: filelist
url: 'https://ftp.gnu.org/gnu/libiconv/'
regex: '/href="(?<file>libiconv-(?<version>[^"]+)\.tar\.gz)"/'
source-mirror:
type: filelist
url: 'https://ftpmirror.gnu.org/gnu/libiconv/'
regex: '/href="(?<file>libiconv-(?<version>[^"]+)\.tar\.gz)"/'

View File

@@ -9,10 +9,8 @@ libssh2:
metadata:
license-files: [COPYING]
license: BSD-3-Clause
depends@unix:
depends:
- openssl
depends@windows:
- zlib
headers:
- libssh2.h
- libssh2_publickey.h

View File

@@ -2,10 +2,6 @@ libunistring:
type: library
artifact:
source:
type: filelist
url: 'https://ftp.gnu.org/gnu/libunistring/'
regex: '/href="(?<file>libunistring-(?<version>[^"]+)\.tar\.gz)"/'
source-mirror:
type: filelist
url: 'https://ftpmirror.gnu.org/gnu/libunistring/'
regex: '/href="(?<file>libunistring-(?<version>[^"]+)\.tar\.gz)"/'

View File

@@ -2,10 +2,6 @@ readline:
type: library
artifact:
source:
type: filelist
url: 'https://ftp.gnu.org/gnu/readline/'
regex: '/href="(?<file>readline-(?<version>[^"]+)\.tar\.gz)"/'
source-mirror:
type: filelist
url: 'https://ftpmirror.gnu.org/gnu/readline/'
regex: '/href="(?<file>readline-(?<version>[^"]+)\.tar\.gz)"/'

View File

@@ -1,5 +0,0 @@
7za-win:
type: target
artifact:
binary:
windows-x86_64: { type: url, url: 'https://dl.static-php.dev/v3/tools/7zip/7za.exe', extract: '{pkg_root_path}/bin/7za.exe' }

View File

@@ -1,8 +0,0 @@
msys2-build-essentials:
type: target
artifact:
binary: custom
env:
SPC_MSYS2_PATH: '{pkg_root_path}/msys2-build-essentials/msys64'
path@windows:
- '{pkg_root_path}/msys2-build-essentials/msys64/usr/bin'

View File

@@ -2,4 +2,4 @@ nasm:
type: target
artifact:
binary:
windows-x86_64: { type: url, url: 'https://dl.static-php.dev/static-php-cli/deps/nasm/nasm-2.16.01-win64.zip', extract: { nasm.exe: '{pkg_root_path}/bin/nasm.exe', ndisasm.exe: '{pkg_root_path}/bin/ndisasm.exe' } }
windows-x86_64: { type: url, url: 'https://dl.static-php.dev/static-php-cli/deps/nasm/nasm-2.16.01-win64.zip', extract: { nasm.exe: '{php_sdk_path}/bin/nasm.exe', ndisasm.exe: '{php_sdk_path}/bin/ndisasm.exe' } }

View File

@@ -0,0 +1,5 @@
php-sdk-binary-tools:
type: target
artifact:
binary:
windows-x86_64: { type: git, rev: master, url: 'https://github.com/php/php-sdk-binary-tools.git', extract: '{php_sdk_path}' }

View File

@@ -229,7 +229,7 @@ The following path placeholders are supported in string values of the `path`, `e
| `{working_dir}` | Working directory (project root) |
| `{download_path}` | Download cache directory (`downloads/`) |
| `{source_path}` | Extracted source directory (`source/`) |
| `{spc_msys2_path}` | MSYS2 root directory (`msys64/`) — Windows only |
| `{php_sdk_path}` | Windows PHP SDK directory |
## target Package Type

View File

@@ -58,13 +58,7 @@ A single-file hook API for lightweight patches may be provided in a future relea
### Windows-only: `--with-sdk-binary-dir` and `--vs-ver`
These options are no longer accepted on the command line. In v3, the `php-sdk-binary-tools` dependency has been completely removed. v3 now manages its own **MSYS2** environment to support autotools-based library builds on Windows. Run `spc doctor --install` to download and configure MSYS2 automatically.
If you need to point to a custom MSYS2 installation, set the `SPC_MSYS2_PATH` environment variable to the `msys64` directory (e.g. `C:\msys64`). Visual Studio is now auto-detected by the toolchain — no manual version flag needed.
::: warning Migrating from v2
v2 relied on `php-sdk-binary-tools` and required `--with-sdk-binary-dir` and `--vs-ver` on every build invocation. In v3 these options are gone. Remove them from all CI scripts and run `spc doctor --install` once to set up the Windows build environment.
:::
These options are no longer accepted on the command line. Instead, set the `PHP_SDK_PATH` environment variable to point to your PHP SDK binary tools directory. The Visual Studio version is now managed by the toolchain configuration.
## Renamed / Deprecated Options

View File

@@ -223,7 +223,7 @@ openssl:
| `{working_dir}` | 工作目录(项目根目录) |
| `{download_path}` | 下载缓存目录(`downloads/` |
| `{source_path}` | 解压源码目录(`source/` |
| `{spc_msys2_path}` | MSYS2 根目录(`msys64/`)——仅 Windows |
| `{php_sdk_path}` | Windows PHP SDK 目录 |
## target 包类型

View File

@@ -58,13 +58,7 @@ curl -o spc https://dl.static-php.dev/v3/spc-bin/nightly/spc-linux-x86_64
### Windows 专有:`--with-sdk-binary-dir` 和 `--vs-ver`
这两个选项已不再被命令行接受。在 v3 中,`php-sdk-binary-tools` 依赖已被完全移除。v3 现在通过管理自己的 **MSYS2** 环境来支持 Windows 上基于 autotools 的库构建。运行 `spc doctor --install` 即可自动下载并配置 MSYS2
如需指向自定义 MSYS2 安装目录,请设置 `SPC_MSYS2_PATH` 环境变量,值为 `msys64` 目录路径(例如 `C:\msys64`。Visual Studio 版本现在由工具链自动检测,无需手动指定版本号。
::: warning 从 v2 迁移
v2 依赖 `php-sdk-binary-tools`,并在每次构建时需要传入 `--with-sdk-binary-dir``--vs-ver` 参数。在 v3 中这些选项已被移除。请从所有 CI 脚本中删除这些参数,并使用 `spc doctor --install` 一次性完成 Windows 构建环境的配置。
:::
这两个选项已不再被命令行接受。请改为设置 `PHP_SDK_PATH` 环境变量,指向你的 PHP SDK binary tools 目录。Visual Studio 版本现在由工具链配置统一管理
## 已重命名 / 已弃用的选项

View File

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

View File

@@ -1,93 +0,0 @@
<?php
declare(strict_types=1);
namespace Package\Artifact;
use StaticPHP\Artifact\ArtifactDownloader;
use StaticPHP\Artifact\Downloader\DownloadResult;
use StaticPHP\Attribute\Artifact\AfterBinaryExtract;
use StaticPHP\Attribute\Artifact\BinaryExtract;
use StaticPHP\Attribute\Artifact\CustomBinary;
use StaticPHP\Exception\DownloaderException;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\GlobalEnvManager;
class msys2_build_essentials
{
// MSYS subsystem packages required for autotools-based builds.
private const REQUIRED_PACKAGES = ['make', 'autoconf', 'automake', 'libtool', 'pkgconf', 'perl', 'bison', 're2c'];
#[CustomBinary('msys2-build-essentials', ['windows-x86_64'])]
public function downBinary(ArtifactDownloader $downloader): DownloadResult
{
// MSYS2 nightly self-extracting archive; running it with `-y -oTARGET` extracts to TARGET\msys64\.
$url = 'https://github.com/msys2/msys2-installer/releases/download/nightly-x86_64/msys2-base-x86_64-latest.sfx.exe';
$filename = 'msys2-base-x86_64-latest.sfx.exe';
$path = DOWNLOAD_PATH . DIRECTORY_SEPARATOR . $filename;
default_shell()->executeCurlDownload($url, $path, retries: $downloader->getRetry());
return DownloadResult::file(
$filename,
['url' => $url, 'version' => 'nightly'],
version: 'nightly',
extract: '{pkg_root_path}/msys2-build-essentials',
);
}
#[BinaryExtract('msys2-build-essentials', ['windows-x86_64'])]
public function extractBinary(string $source_file, string $target_path): void
{
$target_path = FileSystem::convertPath($target_path);
$source_file = FileSystem::convertPath($source_file);
// Guard: skip re-extraction if already initialized (marker written at end of this method).
$marker = "{$target_path}\\.spc-msys2-initialized";
if (file_exists($marker)) {
return;
}
if (!is_dir($target_path)) {
FileSystem::createDir($target_path);
}
cmd()->exec("\"{$source_file}\" -y -o\"{$target_path}\"");
$msys2_bin = "{$target_path}\\msys64\\usr\\bin";
if (!file_exists("{$msys2_bin}\\bash.exe")) {
throw new DownloaderException("MSYS2 extraction failed: bash.exe not found at {$msys2_bin}\\bash.exe");
}
// Add MSYS2 usr\bin to PATH so pacman.exe can load msys-2.0.dll.
GlobalEnvManager::addPathIfNotExists($msys2_bin);
GlobalEnvManager::putenv('CHERE_INVOKING=yes');
GlobalEnvManager::putenv('MSYSTEM=MSYS');
// Disable PGP signature checking: pacman-key --init requires a pseudo-TTY which is unavailable
// from PHP. Patching pacman.conf is the standard approach for CI pipelines.
$pacman_conf = "{$target_path}\\msys64\\etc\\pacman.conf";
FileSystem::replaceFileRegex($pacman_conf, '/^SigLevel\s*=.*$/m', 'SigLevel = Never');
$pacman = "{$target_path}\\msys64\\usr\\bin\\pacman.exe";
// Two-pass update as recommended by MSYS2 CI docs.
cmd()->exec("\"{$pacman}\" --noconfirm -Syuu");
cmd()->exec("\"{$pacman}\" --noconfirm -Syuu");
$pkgs = implode(' ', self::REQUIRED_PACKAGES);
cmd()->exec("\"{$pacman}\" --noconfirm -S --needed {$pkgs}");
FileSystem::writeFile($marker, date('Y-m-d H:i:s'));
}
#[AfterBinaryExtract('msys2-build-essentials', ['windows-x86_64'])]
public function afterExtract(string $target_path): void
{
$target_path = FileSystem::convertPath($target_path);
$msys2_root = "{$target_path}\\msys64";
GlobalEnvManager::putenv("SPC_MSYS2_PATH={$msys2_root}");
GlobalEnvManager::addPathIfNotExists("{$msys2_root}\\usr\\bin");
}
}

View File

@@ -1,57 +0,0 @@
<?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, 'buildconfForUnix'], 'ext-gmssl')]
#[BeforeStage('php', [php::class, 'buildconfForWindows'], 'ext-gmssl')]
#[PatchDescription('Fix ext-gmssl v1.1.1: pbkdf2_hmac_sm3_genkey was renamed to sm3_pbkdf2 in GmSSL >= 3.2.0')]
public function patchPbkdf2Rename(): void
{
FileSystem::replaceFileStr(
"{$this->getSourceDir()}/gmssl.c",
'pbkdf2_hmac_sm3_genkey',
'sm3_pbkdf2'
);
}
#[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,7 +27,10 @@ class brotli
{
UnixCMakeExecutor::create($lib)
->setBuildDir($lib->getSourceDir() . '/build-dir')
->addConfigureArgs("-DSHARE_INSTALL_PREFIX={$lib->getBuildRootPath()}")
->addConfigureArgs(
"-DSHARE_INSTALL_PREFIX={$lib->getBuildRootPath()}",
'-DBROTLI_DISABLE_TESTS=ON',
)
->build();
// Patch pkg-config files

View File

@@ -17,7 +17,9 @@ class bzip2
#[PatchBeforeBuild]
public function patchBeforeBuild(LibraryPackage $lib): void
{
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS=-Wall', 'CFLAGS=-fPIC -Wall');
// 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}");
}
#[BuildFor('Windows')]

View File

@@ -18,9 +18,11 @@ 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 -O3 -fPIC fastlz.c -o fastlz.o")
->exec("{$cc} -c {$extra} fastlz.c -o fastlz.o")
->exec("{$ar} rcs libfastlz.a fastlz.o");
// Copy header file

View File

@@ -22,7 +22,6 @@ 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!"),
@@ -45,9 +44,7 @@ class gettext_win
{
$vs_ver_dir = ApplicationContext::get('gettext_win_vs_ver_dir');
cmd()->cd("{$lib->getSourceDir()}{$vs_ver_dir}\\libintl_static")
// 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');
->exec('msbuild libintl_static.vcxproj /t:Rebuild /p:Configuration=Release /p:Platform=x64 /p:WindowsTargetPlatformVersion=10.0');
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,6 +8,7 @@ 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
@@ -16,10 +17,12 @@ class gmp
#[BuildFor('Darwin')]
public function build(LibraryPackage $lib): void
{
UnixAutoconfExecutor::create($lib)
->appendEnv(['CFLAGS' => '-std=c17'])
->configure('--enable-fat')
->make();
$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();
$lib->patchPkgconfPrefix(['gmp.pc']);
}
}

View File

@@ -18,9 +18,7 @@ class gmssl
#[BuildFor('Darwin')]
public function build(LibraryPackage $lib): void
{
UnixCMakeExecutor::create($lib)
->addConfigureArgs('-DENABLE_SM2_PRIVATE_KEY_EXPORT=ON')
->build();
UnixCMakeExecutor::create($lib)->build();
}
#[BuildFor('Windows')]
@@ -35,7 +33,6 @@ 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"',
@@ -45,13 +42,13 @@ class gmssl
->toStep(1)
->build();
cmd()->cd($buildDir)->exec('nmake gmssl XCFLAGS=/MT');
// fix cmake_install.cmake install prefix (GmSSL overrides it internally)
$installCmake = "{$buildDir}\\cmake_install.cmake";
FileSystem::writeFile(
$installCmake,
'set(CMAKE_INSTALL_PREFIX "' . str_replace('\\', '/', $lib->getBuildRootPath()) . '")' . PHP_EOL . FileSystem::readFile($installCmake)
);
$libPath = "{$lib->getBuildRootPath()}/lib";
$incPath = "{$lib->getBuildRootPath()}/include/gmssl";
FileSystem::createDir($libPath);
FileSystem::createDir($incPath);
FileSystem::copy("{$buildDir}\\bin\\gmssl.lib", "{$libPath}/gmssl.lib");
FileSystem::copyDir("{$lib->getSourceDir()}\\include\\gmssl", $incPath);
cmd()->cd($buildDir)->exec('nmake install XCFLAGS=/MT');
}
}

View File

@@ -24,9 +24,12 @@ 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"';
$ldflags = $toolchain->isStatic() ? 'LDFLAGS="-static"' : '';
$cxxflags = "CXXFLAGS=\"-std=c++17 -DPIC -fPIC -fno-ident {$userCxxFlags}\"";
$ldflags = $toolchain->isStatic() ? "LDFLAGS=\"-static {$userLdFlags}\"" : "LDFLAGS=\"{$userLdFlags}\"";
shell()->cd($lib->getSourceDir() . '/source')->initializeEnv($lib)
->exec(
"{$cppflags} {$cxxflags} {$ldflags} " .

View File

@@ -45,6 +45,9 @@ 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,7 +17,9 @@ class jbig
#[PatchBeforeBuild]
public function patchBeforeBuild(LibraryPackage $lib): void
{
FileSystem::replaceFileStr($lib->getSourceDir() . '/Makefile', 'CFLAGS = -O2 -W -Wno-unused-result', 'CFLAGS = -O2 -W -Wno-unused-result -fPIC');
$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}");
}
#[BuildFor('Darwin')]

View File

@@ -35,6 +35,7 @@ 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,8 +9,10 @@ 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
@@ -39,9 +41,23 @@ 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=generic')
->addConfigureArgs(
"-DAOM_TARGET_CPU={$targetCpu}",
'-DCONFIG_RUNTIME_CPU_DETECT=1',
'-DENABLE_EXAMPLES=OFF',
'-DENABLE_TESTS=OFF',
'-DENABLE_TOOLS=OFF',
'-DENABLE_DOCS=OFF',
)
->build();
f_putenv("SPC_COMPILER_EXTRA={$extra}");
$this->patchPkgconfPrefix(['aom.pc']);

View File

@@ -35,7 +35,12 @@ 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')
->addConfigureArgs(
'-DAVIF_LIBYUV=OFF',
'-DAVIF_BUILD_APPS=OFF',
'-DAVIF_BUILD_TESTS=OFF',
'-DAVIF_GTEST=OFF',
)
->build();
// patch pkgconfig
$lib->patchPkgconfPrefix(['libavif.pc']);
@@ -49,7 +54,7 @@ class libavif
'-DAVIF_BUILD_APPS=OFF',
'-DAVIF_BUILD_TESTS=OFF',
'-DAVIF_LIBYUV=OFF',
'-DAVIF_ENABLE_GTEST=OFF',
'-DAVIF_GTEST=OFF',
)
->build();
}

View File

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

View File

@@ -21,7 +21,6 @@ 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!"),
@@ -34,9 +33,7 @@ class libffi_win
{
$vs_ver_dir = ApplicationContext::get('libffi_win_vs_ver_dir');
cmd()->cd("{$lib->getSourceDir()}{$vs_ver_dir}")
// 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');
->exec('msbuild libffi-msvc.sln /t:Rebuild /p:Configuration=Release /p:Platform=x64');
FileSystem::createDir($lib->getLibDir());
FileSystem::createDir($lib->getIncludeDir());

View File

@@ -24,6 +24,17 @@ 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')]
@@ -36,6 +47,7 @@ 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,7 +21,6 @@ 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!"),
@@ -34,9 +33,7 @@ class libiconv_win
{
$vs_ver_dir = ApplicationContext::get('vs_ver_dir');
cmd()->cd("{$lib->getSourceDir()}{$vs_ver_dir}")
// 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');
->exec('msbuild libiconv.sln /t:Rebuild /p:Configuration=Release /p:Platform=x64');
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,6 +25,7 @@ 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,17 +12,25 @@ 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=""')
->addConfigureArgs('-DCMAKE_INSTALL_RPATH=""', ...self::DISABLE_ARGS)
->build();
}
#[BuildFor('Darwin')]
public function buildDarwin(): void
{
UnixCMakeExecutor::create($this)->build();
UnixCMakeExecutor::create($this)
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
}
}

View File

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

View File

@@ -13,17 +13,29 @@ 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')->build();
UnixCMakeExecutor::create($this)
->addConfigureArgs('-DBUILD_STATIC_LIBS=ON', ...self::DISABLE_ARGS)
->build();
}
#[BuildFor('Windows')]
public function buildWin(): void
{
WindowsCMakeExecutor::create($this)->build();
WindowsCMakeExecutor::create($this)
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
rename("{$this->getLibDir()}\\librabbitmq.4.lib", "{$this->getLibDir()}\\rabbitmq.4.lib");
}
}

View File

@@ -42,16 +42,13 @@ 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}")
// 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"');
->exec('msbuild libsodium.sln /t:Rebuild /p:Configuration=StaticRelease /p:Platform=x64 /p:PreprocessorDefinitions="SODIUM_STATIC=1"');
FileSystem::createDir($lib->getLibDir());
FileSystem::createDir($lib->getIncludeDir());

View File

@@ -18,7 +18,6 @@ class libssh2
{
WindowsCMakeExecutor::create($lib)
->addConfigureArgs(
'-DCRYPTO_BACKEND=WinCNG',
'-DENABLE_ZLIB_COMPRESSION=ON',
'-DBUILD_TESTING=OFF'
)

View File

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

View File

@@ -13,12 +13,18 @@ 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('-DLIBUV_BUILD_SHARED=OFF')
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
// patch pkgconfig
$lib->patchPkgconfPrefix(['libuv-static.pc']);
@@ -28,7 +34,7 @@ class libuv
public function buildWindows(LibraryPackage $lib): void
{
WindowsCMakeExecutor::create($lib)
->addConfigureArgs('-DLIBUV_BUILD_SHARED=OFF')
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
}
}

View File

@@ -34,6 +34,7 @@ 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,6 +21,7 @@ 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,7 +21,6 @@ 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,6 +6,8 @@ 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;
@@ -16,6 +18,24 @@ 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,6 +24,7 @@ class nghttp3
'-DBUILD_SHARED_LIBS=OFF',
'-DENABLE_STATIC_CRT=ON',
'-DENABLE_LIB_ONLY=ON',
'-DBUILD_TESTING=OFF',
)
->build();
}

View File

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

View File

@@ -24,7 +24,7 @@ class openssl
{
if (SystemTarget::getTargetOS() === 'Windows') {
global $argv;
$perl_path_native = PKG_ROOT_PATH . '\strawberry-perl\perl\bin\perl.exe';
$perl_path_native = PKG_ROOT_PATH . '\strawberry-perl-' . arch2gnu(php_uname('m')) . '-win\perl\bin\perl.exe';
$perl = file_exists($perl_path_native) ? ($perl_path_native) : WindowsUtil::findCommand('perl.exe');
if ($perl === null) {
throw new EnvironmentException(
@@ -111,6 +111,12 @@ 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 " .
@@ -121,7 +127,8 @@ class openssl
'enable-pie ' .
'no-legacy ' .
'no-tests ' .
"linux-{$arch}"
"linux-{$arch} " .
$userExtra
)
->exec('make clean')
->exec("make -j{$lib->getBuilder()->concurrency} CNF_EX_LIBS=\"{$ex_lib}\"")

View File

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

View File

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

View File

@@ -35,6 +35,7 @@ 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,6 +22,11 @@ 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,16 +14,20 @@ 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(
'-DZSTD_BUILD_STATIC=ON',
'-DZSTD_BUILD_SHARED=OFF',
)
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
FileSystem::copy($package->getLibDir() . '\zstd_static.lib', $package->getLibDir() . '/zstd.lib');
FileSystem::copy($package->getLibDir() . '\zstd_static.lib', $package->getLibDir() . '/libzstd.lib');
@@ -35,10 +39,7 @@ class zstd
{
UnixCMakeExecutor::create($lib)
->setBuildDir("{$lib->getSourceDir()}/build/cmake/build")
->addConfigureArgs(
'-DZSTD_BUILD_STATIC=ON',
'-DZSTD_BUILD_SHARED=OFF',
)
->addConfigureArgs(...self::DISABLE_ARGS)
->build();
$lib->patchPkgconfPrefix(['libzstd.pc'], PKGCONF_PATCH_PREFIX);

View File

@@ -40,9 +40,11 @@ class curl
->optionalPackage('brotli', ...cmake_boolean_args('CURL_BROTLI'))
->addConfigureArgs(
'-DBUILD_CURL_EXE=ON',
'-DZSTD_LIBRARY=' . BUILD_LIB_PATH . '/zstd_static.lib',
'-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',
@@ -81,6 +83,9 @@ 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

@@ -255,11 +255,6 @@ class php extends TargetPackage
$installer->addBuildPackage('php-embed');
}
// UPX compression: ensure the upx binary package is installed when requested
if ($package->getBuildOption('with-upx-pack')) {
$additional_packages[] = 'upx';
}
return [...$extensions_pkg, ...$additional_packages];
}

View File

@@ -39,13 +39,6 @@ trait windows
InteractiveTerm::setMessage('Building php: ' . ConsoleColor::yellow('./buildconf.bat'));
cmd()->cd($package->getSourceDir())->exec('.\buildconf.bat');
// Bypass the phpsdk_version check in configure.js: we use MSVC + msys2 instead of PHP SDK, so phpsdk_version is not available and the check would always fail.
FileSystem::replaceFileStr(
"{$package->getSourceDir()}\\configure.js",
'check_binary_tools_sdk();',
'/* check_binary_tools_sdk(); skipped: using MSVC + msys2 without PHP SDK */'
);
if ($package->getBuildOption('enable-micro-win32') && $installer->isPackageResolved('php-micro')) {
SourcePatcher::patchMicroWin32();
} else {
@@ -95,17 +88,6 @@ trait windows
cmd()->cd($package->getSourceDir())->exec(".\\configure.bat {$args} {$static_extension_str}");
}
#[BeforeStage('php', [self::class, 'makeCliForWindows'])]
#[PatchDescription('Patch Makefile to ensure buildroot/include comes before extension CFLAGS (fixes zip.h conflict with minizip)')]
public function patchMakefileIncludeOrder(TargetPackage $package): void
{
FileSystem::replaceFileStr(
"{$package->getSourceDir()}\\Makefile",
'$(CFLAGS_PHP_OBJ) $(CFLAGS)',
'$(CFLAGS) $(CFLAGS_PHP_OBJ)'
);
}
#[BeforeStage('php', [self::class, 'makeCliForWindows'])]
#[PatchDescription('Patch Windows Makefile for CLI target')]
public function patchCLITarget(TargetPackage $package): void
@@ -530,7 +512,6 @@ 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

@@ -644,7 +644,7 @@ class Artifact
'{artifact_name}' => $this->name,
'{pkg_root_path}' => PKG_ROOT_PATH,
'{build_root_path}' => BUILD_ROOT_PATH,
'{spc_msys2_path}' => getenv('SPC_MSYS2_PATH'),
'{php_sdk_path}' => getenv('PHP_SDK_PATH') ?: WORKING_DIR . '/php-sdk-binary-tools',
'{working_dir}' => WORKING_DIR,
'{download_path}' => DOWNLOAD_PATH,
'{source_path}' => SOURCE_PATH,

View File

@@ -614,7 +614,7 @@ class ArtifactExtractor
'{source_path}' => SOURCE_PATH,
'{download_path}' => DOWNLOAD_PATH,
'{working_dir}' => WORKING_DIR,
'{spc_msys2_path}' => getenv('SPC_MSYS2_PATH') ?: '',
'{php_sdk_path}' => getenv('PHP_SDK_PATH') ?: '',
];
return str_replace(array_keys($replacement), array_values($replacement), $path);
}

View File

@@ -76,10 +76,9 @@ class DownloadResult
?string $version = null,
array $metadata = [],
?string $downloader = null,
mixed $extract = null,
): DownloadResult {
$cache_type = self::isArchiveFile($filename) ? 'archive' : 'file';
return new self($cache_type, config: $config, filename: $filename, extract: $extract, verified: $verified, version: $version, metadata: $metadata, downloader: $downloader);
return new self($cache_type, config: $config, filename: $filename, verified: $verified, version: $version, metadata: $metadata, downloader: $downloader);
}
/**

View File

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

View File

@@ -1,14 +0,0 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Attribute\Package;
/**
* Indicates that the annotated class defines a tool package.
*/
#[\Attribute(\Attribute::TARGET_CLASS | \Attribute::IS_REPEATABLE)]
readonly class Tool
{
public function __construct(public string $name) {}
}

View File

@@ -54,10 +54,6 @@ 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

@@ -36,15 +36,6 @@ class CraftCommand extends BaseCommand
// set verbosity
$this->output->setVerbosity($craft['verbosity']);
// sync logger level and ApplicationContext debug mode to match the new verbosity
$level = match ($this->output->getVerbosity()) {
OutputInterface::VERBOSITY_VERBOSE => 'info',
OutputInterface::VERBOSITY_VERY_VERBOSE, OutputInterface::VERBOSITY_DEBUG => 'debug',
default => 'warning',
};
logger()->setLevel($level);
ApplicationContext::setDebug($this->output->getVerbosity() >= OutputInterface::VERBOSITY_DEBUG);
// apply env
array_walk($craft['extra-env'], fn ($v, $k) => f_putenv("{$k}={$v}"));
@@ -119,7 +110,7 @@ class CraftCommand extends BaseCommand
* shared-extensions: array<string>,
* packages: array<string>,
* sapi: array<string>,
* verbosity: 128|16|256|32|64|8,
* verbosity: int,
* debug: bool,
* clean-build: bool,
* build-options: array<string, mixed>,
@@ -180,16 +171,11 @@ class CraftCommand extends BaseCommand
}
// verbosity
$verbosity_level = $craft['verbosity'] ?? OutputInterface::VERBOSITY_NORMAL;
$debug = $craft['debug'] ?? false;
$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,
};
if ($debug) {
$verbosity_level = OutputInterface::VERBOSITY_DEBUG;
}
$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-2025', 'os_key' => 'Windows'],
'windows' => ['arch' => 'x86_64', 'runner' => 'windows-latest', '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' => $php_versions,
'php_versions' => array_values($php_versions),
'tier2' => $tier2,
'comment_body' => $comment_body,
];
@@ -253,13 +253,6 @@ class TestBotCommand extends BaseCommand
$fmt($targets),
);
$available_labels = implode(', ', [
'`need-test` (gate)',
'`test/linux` `test/windows` `test/macos` (platform)',
'`test/tier2` (extra arch)',
'`test/php-83` `test/php-84` (PHP version)',
]);
// Case 1: need-test absent → invite the author to add it
if (!$need_test) {
return implode("\n", [
@@ -268,9 +261,11 @@ class TestBotCommand extends BaseCommand
'',
$detected,
'',
'To trigger extension build tests on this PR, add the `need-test` label.',
'To trigger extension build tests on this PR, add the `need-test` label:',
'',
'**Available labels**: ' . $available_labels,
'**Gate**: `need-test`',
'**Platform filter** (optional, default all): `test/linux` `test/windows` `test/macos` · `test/tier2`',
'**PHP version** (optional, default 8.5): `test/php-83` `test/php-84`',
]);
}
@@ -312,7 +307,6 @@ class TestBotCommand extends BaseCommand
'',
$detected,
'**Active labels**: ' . $labels_str,
'**Available labels**: ' . $available_labels,
'**Config**: ' . implode(' + ', $platform_parts) . ' | ' . $php_str,
]);
}

View File

@@ -4,14 +4,13 @@ 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 Symfony\Component\Console\Question\ConfirmationQuestion;
use function Laravel\Prompts\confirm;
#[AsCommand('reset')]
class ResetCommand extends BaseCommand
@@ -47,11 +46,7 @@ class ResetCommand extends BaseCommand
// Confirm with user unless --yes is specified
if (!$this->input->getOption('yes')) {
$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))) {
if (!confirm('Are you sure you want to continue?', 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

@@ -19,7 +19,6 @@ enum ConfigType
'php-extension',
'target',
'virtual-target',
'tool',
];
public static function validateLicenseField(mixed $value): bool

View File

@@ -44,13 +44,6 @@ class ConfigValidator
'path' => ConfigType::LIST_ARRAY, // @
'env' => ConfigType::ASSOC_ARRAY, // @
'append-env' => ConfigType::ASSOC_ARRAY, // @
// tool type fields (nested under 'tool' key)
'tool' => ConfigType::ASSOC_ARRAY,
'provides' => ConfigType::LIST_ARRAY,
'binary-subdir' => ConfigType::STRING,
'install-root' => ConfigType::STRING,
'min-version' => ConfigType::STRING,
];
public const array PACKAGE_FIELDS = [
@@ -74,9 +67,6 @@ class ConfigValidator
'path' => false, // @
'env' => false, // @
'append-env' => false, // @
// tool fields (nested object)
'tool' => false,
];
public const array SUFFIX_ALLOWED_FIELDS = [
@@ -88,7 +78,6 @@ class ConfigValidator
'path',
'env',
'append-env',
'tools',
];
public const array PHP_EXTENSION_FIELDS = [
@@ -103,13 +92,6 @@ class ConfigValidator
'os' => false,
];
public const array TOOL_FIELDS = [
'provides' => true,
'binary-subdir' => false,
'install-root' => false,
'min-version' => false,
];
public const array ARTIFACT_TYPE_FIELDS = [ // [required_fields, optional_fields]
'filelist' => [['url', 'regex'], ['extract']],
'git' => [['url'], ['extract', 'submodules', 'rev', 'regex']],
@@ -238,8 +220,8 @@ class ConfigValidator
$fields = self::SUFFIX_ALLOWED_FIELDS;
self::validateSuffixAllowedFields($name, $pkg, $fields, $suffixes);
// check if "library|target|tool" package has artifact field
if (in_array($pkg['type'], ['target', 'library', 'tool']) && !isset($pkg['artifact'])) {
// check if "library|target" package has artifact field for target and library types
if (in_array($pkg['type'], ['target', 'library']) && !isset($pkg['artifact'])) {
throw new ValidationException("Package [{$name}] in {$config_file_name} of type '{$pkg['type']}' must have an 'artifact' field");
}
@@ -253,11 +235,6 @@ class ConfigValidator
self::validatePhpExtensionFields($name, $pkg);
}
// check if "tool" package has tool specific fields and validate inside
if ($pkg['type'] === 'tool') {
self::validateToolFields($name, $pkg);
}
// check for unknown fields
self::validateNoInvalidFields('package', $name, $pkg, array_keys(self::PACKAGE_FIELD_TYPES));
}
@@ -420,29 +397,6 @@ class ConfigValidator
self::validateNoInvalidFields('php-extension', $name, $pkg['php-extension'], array_keys(self::PHP_EXTENSION_FIELDS));
}
/**
* Validate tool specific fields for tool package type.
*/
private static function validateToolFields(int|string $name, mixed $pkg): void
{
if (!isset($pkg['tool'])) {
throw new ValidationException("Package {$name} of type 'tool' must have a 'tool' field");
}
if (!is_assoc_array($pkg['tool'])) {
throw new ValidationException("Package {$name} [tool] must be an object");
}
foreach (self::TOOL_FIELDS as $field => $required) {
if ($required && !isset($pkg['tool'][$field])) {
throw new ValidationException("Package {$name} [tool] must have required field [{$field}]");
}
if (isset($pkg['tool'][$field])) {
self::validatePackageFieldType($field, $pkg['tool'][$field], $name);
}
}
// check for unknown fields in tool
self::validateNoInvalidFields('tool', $name, $pkg['tool'], array_keys(self::TOOL_FIELDS));
}
private static function validateNoInvalidFields(string $config_type, int|string $item_name, mixed $item_content, array $allowed_fields): void
{
foreach ($item_content as $k => $v) {

View File

@@ -16,7 +16,7 @@ class PackageConfig
/**
* Load package configurations from a specified directory.
* Only processes .json, .yml, and .yaml files (skips .gitkeep etc.).
* It will look for files matching the pattern 'pkg.*.json' and 'pkg.json'.
*/
public static function loadFromDir(string $dir, string $registry_name): array
{
@@ -28,10 +28,6 @@ class PackageConfig
$files = FileSystem::scanDirFiles($dir, false);
if (is_array($files)) {
foreach ($files as $file) {
$ext = pathinfo($file, PATHINFO_EXTENSION);
if (!in_array($ext, ['json', 'yml', 'yaml'], true)) {
continue;
}
self::loadFromFile($file, $registry_name);
$loaded[] = $file;
}

View File

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

View File

@@ -11,14 +11,11 @@ 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)
@@ -128,14 +125,9 @@ readonly class Doctor
return false;
}
// prompt for fix
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;
}
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;
}
// perform fix
InteractiveTerm::indicateProgress("Fixing {$result->getFixItem()} ... ");

View File

@@ -54,24 +54,13 @@ class WindowsToolCheck
return CheckResult::ok();
}
#[CheckItem('if msys2-build-essentials is installed', limit_os: 'Windows', level: 996)]
public function checkMsys2(): ?CheckResult
#[CheckItem('if php-sdk-binary-tools are downloaded', limit_os: 'Windows', level: 996)]
public function checkSDK(): ?CheckResult
{
$marker = PKG_ROOT_PATH . '\msys2-build-essentials\.spc-msys2-initialized';
if (!file_exists($marker)) {
return CheckResult::fail('msys2-build-essentials not installed', 'install-msys2-build-essentials');
if (!file_exists(getenv('PHP_SDK_PATH') . DIRECTORY_SEPARATOR . 'phpsdk-starter.bat')) {
return CheckResult::fail('php-sdk-binary-tools not downloaded', 'install-php-sdk');
}
return CheckResult::ok(PKG_ROOT_PATH . '\msys2-build-essentials\msys64');
}
#[CheckItem('if 7za.exe is installed', limit_os: 'Windows', level: 999)]
public function check7zaWin(): ?CheckResult
{
$path = FileSystem::convertPath(PKG_ROOT_PATH . '\bin\7za.exe');
if (!file_exists($path)) {
return CheckResult::fail('7za.exe not found', 'install-7za-win');
}
return CheckResult::ok($path);
return CheckResult::ok(getenv('PHP_SDK_PATH'));
}
#[CheckItem('if nasm installed', level: 995)]
@@ -123,20 +112,12 @@ class WindowsToolCheck
return true;
}
#[FixItem('install-msys2-build-essentials')]
public function installMsys2(): bool
#[FixItem('install-php-sdk')]
public function installSDK(): bool
{
FileSystem::removeDir(getenv('PHP_SDK_PATH'));
$installer = new PackageInstaller(interactive: false);
$installer->addInstallPackage('msys2-build-essentials');
$installer->run(true);
return true;
}
#[FixItem('install-7za-win')]
public function install7zaWin(): bool
{
$installer = new PackageInstaller(interactive: false);
$installer->addInstallPackage('7za-win');
$installer->addInstallPackage('php-sdk-binary-tools');
$installer->run(true);
return true;
}

View File

@@ -120,20 +120,6 @@ abstract class Package
return false;
}
/**
* Get the target directory where this package's artifacts should be placed.
*
* Libraries install to BUILD_ROOT_PATH (static-libs, headers, pkg-configs).
* Tools install to PKG_ROOT_PATH (executables).
* Extensions install to php-src/ext/ (shared objects).
*
* Override in subclasses to change the default.
*/
public function getInstallTarget(): string
{
return BUILD_ROOT_PATH;
}
/**
* Add a stage to the package.
*/

View File

@@ -11,7 +11,6 @@ use StaticPHP\Artifact\ArtifactExtractor;
use StaticPHP\Artifact\DownloaderOptions;
use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext;
use StaticPHP\Exception\EnvironmentException;
use StaticPHP\Exception\WrongUsageException;
use StaticPHP\Registry\PackageLoader;
use StaticPHP\Runtime\SystemTarget;
@@ -76,9 +75,6 @@ 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;
}
@@ -168,9 +164,6 @@ class PackageInstaller
// Early validation: check if packages can be built or installed before downloading
$this->validatePackagesBeforeBuild();
// Check that all required tools are installed before proceeding
$this->ensureRequiredTools();
// check download
if ($this->download) {
$downloaderOptions = DownloaderOptions::extractFromConsoleOptions($this->options, 'dl');
@@ -578,66 +571,6 @@ class PackageInstaller
return null;
}
/**
* Collect all tool packages required by the currently resolved packages.
*
* Reads the 'tools' field from each resolved package's YAML config.
* The field supports platform suffixes (tools@windows, tools@linux, etc.)
* resolved automatically by PackageConfig::get().
*
* Tools are NOT part of the library dependency graph — they are
* build-time prerequisites that must be installed before any library
* build begins.
*
* @return string[] Unique tool package names required for this build
*/
public function collectRequiredTools(): array
{
$tools = [];
foreach ($this->packages as $package) {
$deps = PackageConfig::get($package->getName(), 'tools', []);
foreach ((array) $deps as $tool_name) {
$tools[$tool_name] = true;
}
}
return array_keys($tools);
}
/**
* Check that all required tools are installed.
*
* Iterates through tools collected by collectRequiredTools(),
* resolves each to a ToolPackage instance, and checks isInstalled().
*
* @return array{missing: array<string>, installed: array<string>}
*/
public function checkRequiredTools(): array
{
$missing = [];
$installed = [];
foreach ($this->collectRequiredTools() as $tool_name) {
try {
$tool = PackageLoader::getPackage($tool_name);
} catch (WrongUsageException) {
$missing[] = $tool_name;
logger()->warning("Required tool '{$tool_name}' is not registered as a package.");
continue;
}
if (!$tool instanceof ToolPackage) {
logger()->warning("Package '{$tool_name}' is declared as a tool dependency but is not a ToolPackage (type: {$tool->getType()}).");
continue;
}
if ($tool->isInstalled()) {
$installed[] = $tool_name;
} else {
$missing[] = $tool_name;
}
}
return ['missing' => $missing, 'installed' => $installed];
}
/**
* @param Package[] $packages
*/
@@ -700,27 +633,6 @@ class PackageInstaller
}
}
/**
* Ensure all required tools are installed, throwing if any are missing.
*
* Called early in the build pipeline (before download/extract).
* When tools are missing, lists them with install hints.
*/
private function ensureRequiredTools(): void
{
$status = $this->checkRequiredTools();
if (empty($status['missing'])) {
if (!empty($status['installed'])) {
logger()->info('Required tools: ' . implode(', ', $status['installed']) . ' — all installed.');
}
return;
}
$msg = 'Missing required build tools: ' . implode(', ', $status['missing']) . "\n";
$msg .= "Run 'bin/spc doctor' to check your environment, or install the missing tools manually.";
throw new EnvironmentException($msg);
}
private function injectPackageEnvs(Package $package): void
{
$name = $package->getName();

View File

@@ -1,151 +0,0 @@
<?php
declare(strict_types=1);
namespace StaticPHP\Package;
use StaticPHP\Config\PackageConfig;
use StaticPHP\Util\FileSystem;
use StaticPHP\Util\GlobalPathTrait;
/**
* Represents a build-time tool package.
*
* Tool packages are NOT link-time dependencies. They provide executables
* that are needed during the build process (compilers, code generators,
* assemblers, etc.) and are installed into PKG_ROOT_PATH.
*
* Tool packages do NOT produce static-libs, headers, or pkg-config files.
* They are resolved and installed independently from the library dependency graph.
*
* YAML config schema (config/pkg/tool/<name>.yml):
*
* nasm:
* type: tool
* tool:
* provides: [nasm.exe, ndisasm.exe] # executables this tool installs
* binary-subdir: '' # subdirectory under install root (default: '')
* min-version: '2.16' # minimum required version (optional)
* artifact:
* binary:
* windows-x86_64:
* type: url
* url: 'https://...'
* extract:
* nasm.exe: '{php_sdk_path}/bin/nasm.exe'
*/
class ToolPackage extends Package
{
use GlobalPathTrait;
/**
* Get the install root directory for this tool.
*
* Defaults to PKG_ROOT_PATH. Override via 'tool.install-root' in YAML
* or via the TOOL_INSTALL_ROOT_{NAME} environment variable.
*/
public function getInstallRoot(): string
{
$env_var = 'TOOL_INSTALL_ROOT_' . strtoupper(str_replace('-', '_', $this->name));
if ($root = getenv($env_var)) {
return $root;
}
$config_root = $this->getToolConfig()['install-root'] ?? null;
if ($config_root !== null) {
return FileSystem::replacePathVariable((string) $config_root);
}
return PKG_ROOT_PATH;
}
/**
* Get the directory where this tool's binaries reside.
*
* This is {install-root}/{binary-subdir}. If binary-subdir is not
* configured, returns the install root directly.
*/
public function getBinaryDir(): string
{
$subdir = $this->getToolConfig()['binary-subdir'] ?? '';
if ($subdir === '') {
return $this->getInstallRoot();
}
return $this->getInstallRoot() . DIRECTORY_SEPARATOR . $subdir;
}
/**
* Get the list of executables this tool provides.
*
* Reads from YAML 'tool.provides' field. Each entry is a bare filename
* (e.g. 'nasm.exe'), resolved relative to getBinaryDir().
*
* @return string[] Bare executable names (not full paths)
*/
public function getProvides(): array
{
return $this->getToolConfig()['provides'] ?? [];
}
/**
* Get the full path to a specific binary provided by this tool.
*
* @param string $name Bare executable name (must be listed in tool.provides).
* If empty, defaults to the first entry in provides.
* @return string Full absolute path to the binary
*/
public function getBinary(string $name = ''): string
{
$provides = $this->getProvides();
if ($name === '') {
$name = $provides[0] ?? throw new \RuntimeException("Tool '{$this->name}' has no 'tool.provides' configured.");
}
if (!in_array($name, $provides, true)) {
throw new \RuntimeException("Binary '{$name}' is not listed in tool.provides for '{$this->name}'. Available: " . implode(', ', $provides));
}
return $this->getBinaryDir() . DIRECTORY_SEPARATOR . $name;
}
/**
* Check whether this tool is installed (all provided binaries exist on disk).
*/
public function isInstalled(): bool
{
return array_all($this->getProvides(), fn ($binary) => file_exists($this->getBinary($binary)));
}
/**
* Get the minimum required version for this tool, if specified.
*
* Returns null if no version constraint is configured.
*/
public function getMinVersion(): ?string
{
$version = $this->getToolConfig()['min-version'] ?? null;
return $version !== null ? (string) $version : null;
}
/**
* Tools install to PKG_ROOT_PATH (or the configured install-root),
* not BUILD_ROOT_PATH.
*/
public function getInstallTarget(): string
{
return $this->getBinaryDir();
}
/**
* Get the 'tool' sub-config for this package.
*
* Returns the nested array under the 'tool' key in the package YAML,
* or an empty array if not configured.
*
* @return array<string, mixed>
*/
private function getToolConfig(): array
{
$config = PackageConfig::get($this->name);
if (!is_array($config) || !isset($config['tool']) || !is_array($config['tool'])) {
return [];
}
return $config['tool'];
}
}

View File

@@ -17,7 +17,6 @@ use StaticPHP\Attribute\Package\PatchBeforeBuild;
use StaticPHP\Attribute\Package\ResolveBuild;
use StaticPHP\Attribute\Package\Stage;
use StaticPHP\Attribute\Package\Target;
use StaticPHP\Attribute\Package\Tool;
use StaticPHP\Attribute\Package\Validate;
use StaticPHP\Config\PackageConfig;
use StaticPHP\DI\ApplicationContext;
@@ -28,7 +27,6 @@ use StaticPHP\Package\Package;
use StaticPHP\Package\PackageInstaller;
use StaticPHP\Package\PhpExtensionPackage;
use StaticPHP\Package\TargetPackage;
use StaticPHP\Package\ToolPackage;
use StaticPHP\Util\FileSystem;
class PackageLoader
@@ -90,7 +88,6 @@ class PackageLoader
'target', 'virtual-target' => new TargetPackage($name, $item['type']),
'library' => new LibraryPackage($name, $item['type']),
'php-extension' => new PhpExtensionPackage($name, $item['type']),
'tool' => new ToolPackage($name, $item['type']),
default => null,
};
if ($pkg !== null) {
@@ -193,8 +190,7 @@ class PackageLoader
$attribute_instance = $attribute->newInstance();
if ($attribute_instance instanceof Target === false &&
$attribute_instance instanceof Library === false &&
$attribute_instance instanceof Extension === false &&
$attribute_instance instanceof Tool === false) {
$attribute_instance instanceof Extension === false) {
// not a package attribute
continue;
}
@@ -220,7 +216,6 @@ class PackageLoader
Target::class => ['target', 'virtual-target'],
Library::class => ['library'],
Extension::class => ['php-extension'],
Tool::class => ['tool'],
default => null,
};
if (!in_array($package_type, $pkg_type_attr, true)) {
@@ -375,10 +370,7 @@ class PackageLoader
// match condition
$installer = ApplicationContext::get(PackageInstaller::class);
$stages = self::$before_stages[$package_name][$stage] ?? [];
foreach ($stages as $entry) {
$callback = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
$conditionals = $entry[2] ?? [];
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) {
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
continue;
}
@@ -397,10 +389,7 @@ class PackageLoader
$installer = ApplicationContext::get(PackageInstaller::class);
$stages = self::$after_stages[$package_name][$stage] ?? [];
$result = [];
foreach ($stages as $entry) {
$callback = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
$conditionals = $entry[2] ?? [];
foreach ($stages as [$callback, $only_when_package_resolved, $conditionals]) {
if ($only_when_package_resolved !== null && !$installer->isPackageResolved($only_when_package_resolved)) {
continue;
}
@@ -444,9 +433,7 @@ class PackageLoader
}
$pkg = self::getPackage($package_name);
foreach ($stages as $stage_name => $before_events) {
foreach ($before_events as $entry) {
$event_callable = $entry[0];
$only_when_package_resolved = $entry[1] ?? null;
foreach ($before_events as [$event_callable, $only_when_package_resolved, $conditionals]) {
// 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(string ...$args): static
public function addConfigureArgs(...$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(string ...$args): static
public function removeConfigureArgs(...$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(string ...$args): static
public function addConfigureArgs(...$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(string ...$args): static
public function removeConfigureArgs(...$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(string ...$args): static
public function addConfigureArgs(...$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(string ...$args): static
public function removeConfigureArgs(...$args): static
{
$this->ignore_args = [...$this->ignore_args, ...$args];
return $this;
@@ -189,10 +189,6 @@ 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

@@ -184,14 +184,12 @@ class DefaultShell extends Shell
*/
public function execute7zExtract(string $archive_path, string $target_path): bool
{
// 7za.exe is installed by the 7za-win target package into PKG_ROOT_PATH\bin,
// which is added to PATH by MSVCToolchain::initEnv().
$_7z_path = FileSystem::convertPath(PKG_ROOT_PATH . '\bin\7za.exe');
if (!file_exists($_7z_path)) {
throw new SPCInternalException('7za.exe not found. Please install the 7za-win target package.');
$sdk_path = getenv('PHP_SDK_PATH');
if ($sdk_path === false) {
throw new SPCInternalException('PHP_SDK_PATH environment variable is not set');
}
$_7z = escapeshellarg(FileSystem::convertPath($_7z_path));
$_7z = escapeshellarg(FileSystem::convertPath($sdk_path . '/bin/7za.exe'));
$archive_arg = escapeshellarg(FileSystem::convertPath($archive_path));
$target_arg = escapeshellarg(FileSystem::convertPath($target_path));

View File

@@ -14,14 +14,10 @@ class MSVCToolchain implements ToolchainInterface
public function initEnv(): void
{
GlobalEnvManager::addPathIfNotExists(PKG_ROOT_PATH . '\bin');
// msys2-build-essentials: add MSYS2 usr\bin to PATH so that 7za.exe, make, autoconf, etc. are available.
// This must be done here because msys2-build-essentials is not a dependency of any library package,
// so its path@windows entries are not automatically applied by the package installer at runtime.
$msys2_path = getenv('SPC_MSYS2_PATH') ?: (PKG_ROOT_PATH . '\msys2-build-essentials\msys64');
if (is_dir($msys2_path)) {
GlobalEnvManager::putenv("SPC_MSYS2_PATH={$msys2_path}");
GlobalEnvManager::addPathIfNotExists($msys2_path . '\usr\bin');
GlobalEnvManager::addPathIfNotExists("{$msys2_path}\\usr\\lib\\p7zip");
$sdk = getenv('PHP_SDK_PATH');
if ($sdk !== false) {
GlobalEnvManager::addPathIfNotExists($sdk . '\bin');
GlobalEnvManager::addPathIfNotExists($sdk . '\msys2\usr\bin');
}
// strawberry-perl
if (is_dir(PKG_ROOT_PATH . '\strawberry-perl')) {

View File

@@ -411,7 +411,7 @@ class FileSystem
$replacement = [
'{build_root_path}' => BUILD_ROOT_PATH,
'{pkg_root_path}' => PKG_ROOT_PATH,
'{spc_msys2_path}' => getenv('SPC_MSYS2_PATH') ?: (PKG_ROOT_PATH . DIRECTORY_SEPARATOR . 'msys2-build-essentials' . DIRECTORY_SEPARATOR . 'msys64'),
'{php_sdk_path}' => getenv('PHP_SDK_PATH') ? getenv('PHP_SDK_PATH') : WORKING_DIR . '/php-sdk-binary-tools',
'{working_dir}' => WORKING_DIR,
'{download_path}' => DOWNLOAD_PATH,
'{source_path}' => SOURCE_PATH,

View File

@@ -17,8 +17,8 @@ class InteractiveTerm
public static function notice(string $message, bool $indent = false): void
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
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 = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
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 = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
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 = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
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 = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
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 = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
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 = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$message = $no_ansi ? strip_ansi_colors($message) : $message;
$output = ApplicationContext::get(OutputInterface::class);
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
if ($output->isVerbose()) {
if ($status) {
logger()->info($message);
@@ -116,8 +116,8 @@ class InteractiveTerm
public static function indicateProgress(string $message): void
{
$no_ansi = (bool) ApplicationContext::get(InputInterface::class)->getOption('no-ansi');
$output = ApplicationContext::get(OutputInterface::class);
$no_ansi = ApplicationContext::get(InputInterface::class)?->getOption('no-ansi') ?? false;
$output = ApplicationContext::get(OutputInterface::class) ?? new ConsoleOutput();
if ($output->isVerbose()) {
logger()->info(strip_ansi_colors($message));
return;

View File

@@ -3,11 +3,22 @@
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
@@ -64,3 +75,31 @@ 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,8 +21,6 @@ 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,10 +23,12 @@ 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);
}
@@ -36,10 +38,12 @@ 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);
}
@@ -339,6 +343,7 @@ 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,10 +31,12 @@ 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();
@@ -49,10 +51,12 @@ 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();
@@ -153,6 +157,7 @@ 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);
@@ -176,6 +181,7 @@ 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);
@@ -198,6 +204,7 @@ 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,6 +29,7 @@ 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
@@ -44,6 +45,7 @@ class ArtifactTest extends TestCase
$reflection = new \ReflectionClass(ArtifactConfig::class);
$property = $reflection->getProperty('artifact_configs');
$property->setAccessible(true);
$property->setValue(null, []);
ApplicationContext::reset();
@@ -713,6 +715,7 @@ 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

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

Some files were not shown because too many files have changed in this diff Show More