From 87b1d16a3e6ed092424dbdd96e16afabf6477f1a Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 10:39:07 -0600 Subject: [PATCH 01/18] Prepare Foundation 2.0 container, logging, shutdown and view packages --- .../workflows/check-for-required-files.yml | 1 - .github/workflows/tests.yml | 34 ++ AGENTS.md | 9 +- README.md | 6 +- UPGRADING-2.0.md | 36 ++ composer.json | 13 +- phpstan.neon.dist | 1 + .../.github/workflows/close-pull-request.yml | 13 - src/Cli/CliProvider.php | 14 +- .../Package/PackageFilesValidator.php | 4 +- .../Commands/Package/PackageScaffolder.php | 27 +- src/Cli/bin/foundation | 14 +- .../.github/workflows/close-pull-request.yml | 13 - .../Configuration/ArrayConfiguration.php | 47 +++ src/Container/ContainerAdapter.php | 233 ++++++++++-- src/Container/ContainerFactory.php | 29 ++ src/Container/Contracts/Configuration.php | 34 ++ src/Container/Contracts/Container.php | 44 ++- src/Container/Contracts/Providable.php | 22 +- src/Container/Contracts/Provider.php | 43 +-- src/Container/Contracts/Resolver.php | 34 ++ .../Exceptions/ContainerException.php | 13 + .../Exceptions/NotFoundException.php | 12 + src/Container/README.md | 140 ++------ src/Container/composer.json | 1 + .../.github/workflows/close-pull-request.yml | 13 - src/Log/Formatters/ColoredLineFormatter.php | 6 +- src/Log/Handlers/NullHandler.php | 9 +- src/Log/LogLevel.php | 2 +- src/Log/LogProvider.php | 164 ++++----- src/Log/README.md | 82 +++-- src/Log/composer.json | 2 +- .../.github/workflows/close-pull-request.yml | 13 - src/Shutdown/.gitattributes | 7 + src/Shutdown/.gitignore | 2 + src/Shutdown/Contracts/ShutdownRunner.php | 10 + src/Shutdown/Contracts/Terminable.php | 14 + src/Shutdown/README.md | 57 +++ src/Shutdown/ResponseFinishingRunner.php | 43 +++ src/Shutdown/Runner.php | 117 ++++++ src/Shutdown/ShutdownProvider.php | 44 +++ src/Shutdown/Task.php | 17 + src/Shutdown/composer.json | 25 ++ src/View/.gitattributes | 7 + src/View/.gitignore | 2 + src/View/Contracts/DirectoryAwareView.php | 18 + src/View/Contracts/View.php | 20 ++ src/View/Exceptions/ViewNotFoundException.php | 12 + src/View/PhpView.php | 167 +++++++++ src/View/README.md | 42 +++ src/View/ViewProvider.php | 45 +++ src/View/composer.json | 24 ++ .../.github/workflows/close-pull-request.yml | 13 - tests/Feature/Log/ConfiguredLoggerTest.php | 333 ++++++++++++++++++ .../Feature/Log/Handlers/NullHandlerTest.php | 50 +-- tests/Feature/Log/InvalidLoggerTest.php | 2 +- tests/Feature/Log/NullLoggerTest.php | 1 + tests/Feature/Log/StackLoggerTest.php | 6 +- .../Log/UnavailableErrorLogLoggerTest.php | 3 +- .../Fixtures/Container/CallbackListener.php | 18 + .../ConfigurationReadingProvider.php | 14 + .../Fixtures/Container/FixedConfiguration.php | 71 ++++ .../Container/IndependentProvider.php | 23 ++ .../Fixtures/Container/TestProvider.php | 7 +- .../Container/ThrowingContainerService.php | 15 + .../Fixtures/Shutdown/BufferedLogFlush.php | 19 + .../Fixtures/Shutdown/CallbackTerminable.php | 18 + .../Shutdown/finish-request-functions.php | 21 ++ .../Shutdown/litespeed-finish-request.php | 9 + .../Fixtures/Shutdown/uninstall-request.php | 29 ++ .../Fixtures/View/DelegatingDirectoryView.php | 24 ++ tests/Support/Fixtures/View/JsonView.php | 22 ++ tests/TestCase.php | 16 +- tests/Unit/Cli/CliProviderTest.php | 14 +- .../Commands/Package/CreateCommandTest.php | 1 - .../Package/PackageFilesValidatorTest.php | 1 - .../Package/PackageScaffolderTest.php | 1 - .../Configuration/ArrayConfigurationTest.php | 61 ++++ tests/Unit/Container/ContainerAdapterTest.php | 239 ++++++++++++- tests/Unit/Container/ContainerFactoryTest.php | 24 ++ tests/Unit/Container/ProvidableTest.php | 57 +++ tests/Unit/Container/ProviderTest.php | 18 +- .../Formatters/ColoredLineFormatterTest.php | 60 +++- .../Shutdown/ResponseFinishingRunnerTest.php | 92 +++++ tests/Unit/Shutdown/RunnerTest.php | 154 ++++++++ tests/Unit/View/PhpViewTest.php | 229 ++++++++++++ tests/Unit/View/ViewContractTest.php | 30 ++ tests/Unit/View/ViewProviderTest.php | 40 +++ tests/WPUnitSupport/WPTestCase.php | 12 + .../View/default/admin/product-summary.php | 1 + tests/_data/View/default/balanced-buffer.php | 7 + tests/_data/View/default/closes-buffer.php | 3 + tests/_data/View/default/flushes-buffer.php | 4 + tests/_data/View/default/greeting.php | 8 + tests/_data/View/default/replaces-buffer.php | 5 + tests/_data/View/default/throws.php | 6 + tests/_data/View/default/unclosed-buffer.php | 4 + tests/_data/View/outside.php | 1 + tests/_data/View/runtime/greeting.php | 1 + .../.github/workflows/close-pull-request.yml | 5 - tests/wpunit/Shutdown/BufferedLoggingTest.php | 61 ++++ .../wpunit/Shutdown/ShutdownProviderTest.php | 146 ++++++++ 102 files changed, 3263 insertions(+), 537 deletions(-) create mode 100644 UPGRADING-2.0.md delete mode 100644 src/Cli/.github/workflows/close-pull-request.yml delete mode 100644 src/Container/.github/workflows/close-pull-request.yml create mode 100644 src/Container/Configuration/ArrayConfiguration.php create mode 100644 src/Container/ContainerFactory.php create mode 100644 src/Container/Contracts/Configuration.php create mode 100644 src/Container/Contracts/Resolver.php create mode 100644 src/Container/Exceptions/ContainerException.php create mode 100644 src/Container/Exceptions/NotFoundException.php delete mode 100644 src/Log/.github/workflows/close-pull-request.yml delete mode 100644 src/Pipeline/.github/workflows/close-pull-request.yml create mode 100644 src/Shutdown/.gitattributes create mode 100644 src/Shutdown/.gitignore create mode 100644 src/Shutdown/Contracts/ShutdownRunner.php create mode 100644 src/Shutdown/Contracts/Terminable.php create mode 100644 src/Shutdown/README.md create mode 100644 src/Shutdown/ResponseFinishingRunner.php create mode 100644 src/Shutdown/Runner.php create mode 100644 src/Shutdown/ShutdownProvider.php create mode 100644 src/Shutdown/Task.php create mode 100644 src/Shutdown/composer.json create mode 100644 src/View/.gitattributes create mode 100644 src/View/.gitignore create mode 100644 src/View/Contracts/DirectoryAwareView.php create mode 100644 src/View/Contracts/View.php create mode 100644 src/View/Exceptions/ViewNotFoundException.php create mode 100644 src/View/PhpView.php create mode 100644 src/View/README.md create mode 100644 src/View/ViewProvider.php create mode 100644 src/View/composer.json delete mode 100644 src/WPCli/.github/workflows/close-pull-request.yml create mode 100644 tests/Feature/Log/ConfiguredLoggerTest.php create mode 100644 tests/Support/Fixtures/Container/CallbackListener.php create mode 100644 tests/Support/Fixtures/Container/ConfigurationReadingProvider.php create mode 100644 tests/Support/Fixtures/Container/FixedConfiguration.php create mode 100644 tests/Support/Fixtures/Container/IndependentProvider.php create mode 100644 tests/Support/Fixtures/Container/ThrowingContainerService.php create mode 100644 tests/Support/Fixtures/Shutdown/BufferedLogFlush.php create mode 100644 tests/Support/Fixtures/Shutdown/CallbackTerminable.php create mode 100644 tests/Support/Fixtures/Shutdown/finish-request-functions.php create mode 100644 tests/Support/Fixtures/Shutdown/litespeed-finish-request.php create mode 100644 tests/Support/Fixtures/Shutdown/uninstall-request.php create mode 100644 tests/Support/Fixtures/View/DelegatingDirectoryView.php create mode 100644 tests/Support/Fixtures/View/JsonView.php create mode 100644 tests/Unit/Container/Configuration/ArrayConfigurationTest.php create mode 100644 tests/Unit/Container/ContainerFactoryTest.php create mode 100644 tests/Unit/Container/ProvidableTest.php create mode 100644 tests/Unit/Shutdown/ResponseFinishingRunnerTest.php create mode 100644 tests/Unit/Shutdown/RunnerTest.php create mode 100644 tests/Unit/View/PhpViewTest.php create mode 100644 tests/Unit/View/ViewContractTest.php create mode 100644 tests/Unit/View/ViewProviderTest.php create mode 100644 tests/_data/View/default/admin/product-summary.php create mode 100644 tests/_data/View/default/balanced-buffer.php create mode 100644 tests/_data/View/default/closes-buffer.php create mode 100644 tests/_data/View/default/flushes-buffer.php create mode 100644 tests/_data/View/default/greeting.php create mode 100644 tests/_data/View/default/replaces-buffer.php create mode 100644 tests/_data/View/default/throws.php create mode 100644 tests/_data/View/default/unclosed-buffer.php create mode 100644 tests/_data/View/outside.php create mode 100644 tests/_data/View/runtime/greeting.php delete mode 100644 tests/_data/cli/package/valid-root/src/Log/.github/workflows/close-pull-request.yml create mode 100644 tests/wpunit/Shutdown/BufferedLoggingTest.php create mode 100644 tests/wpunit/Shutdown/ShutdownProviderTest.php diff --git a/.github/workflows/check-for-required-files.yml b/.github/workflows/check-for-required-files.yml index 92406a74..04fa5128 100644 --- a/.github/workflows/check-for-required-files.yml +++ b/.github/workflows/check-for-required-files.yml @@ -20,7 +20,6 @@ jobs: # Find all subdirectories in src/ and look for required files for folder in */; do file_paths=( - "$folder.github/workflows/close-pull-request.yml" "$folder/.gitattributes" "$folder/.gitignore" ) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 8d67e887..cc715e2a 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -36,6 +36,40 @@ jobs: - name: Run Feature Tests run: vendor/bin/phpunit --configuration ./phpunit.xml.dist --colors=always --testsuite Feature + monolog: + runs-on: ubuntu-latest + name: Monolog ${{ matrix.monolog }} compatibility + strategy: + fail-fast: false + matrix: + monolog: [ '2.11.0', '3.10.0' ] + + steps: + - name: Checkout code + uses: actions/checkout@v6 + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + coverage: none + + - name: Install Composer dependencies + uses: ramsey/composer-install@v4 + with: + dependency-versions: highest + + - name: Install supported Monolog floor + run: composer update monolog/monolog:${{ matrix.monolog }} --with-all-dependencies --no-interaction --prefer-dist + + - name: Analyze supported Monolog APIs + run: composer analyze + + - name: Test logging behavior + run: | + vendor/bin/phpunit --configuration phpunit.xml.dist tests/Unit/Log + vendor/bin/phpunit --configuration phpunit.xml.dist tests/Feature/Log + slic: runs-on: ubuntu-latest name: SLIC Tests diff --git a/AGENTS.md b/AGENTS.md index b07274f1..954a42c2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,8 @@ Initial packages: - `stellarwp/foundation-container` - `stellarwp/foundation-log` +- `stellarwp/foundation-shutdown` +- `stellarwp/foundation-view` - `stellarwp/foundation-pipeline` - `stellarwp/foundation-wpcli` - `stellarwp/foundation-cli` @@ -73,6 +75,12 @@ When writing providers or container registration code, prefer container-driven c Use contextual bindings with `$this->container->when()->needs()->give()` for scalar constructor arguments, command lists, or feature-specific substitutions. Use a factory closure only when the value must be computed or resolved from the container, and keep that closure focused on supplying the constructor dependency rather than constructing the full object. +Ordinary providers extend `Provider`, whose final constructor supplies the shared container and configuration snapshot. Applications with their own registration abstraction may implement `Providable`; it requires only `register(): void`. Keep the default examples on `Provider` and document the interface as an integration extension point. Do not restore DI52's deferred provider lifecycle. Register providers once per container in dependency order. + +Use Foundation's `Resolver` contract for factory callbacks. Keep raw DI52 access inside the adapter and factory. Bootstrap configuration before registering providers using `ContainerFactory` and `ArrayConfiguration`. + +Package READMEs and the root upgrade guide contain the release documentation. This release does not ship the Foundation documentation-site package. + ## Split Packages Split packages live in `src//` and are split to read-only repositories named `stellarwp/foundation-`. @@ -91,7 +99,6 @@ Each split package should include: - `README.md` - `.gitattributes` - `.gitignore` -- `.github/workflows/close-pull-request.yml` When adding a new split package, add its `stellarwp/foundation-` repository link to the root `README.md` repositories list. diff --git a/README.md b/README.md index 3a83a889..6aaa3c0e 100644 --- a/README.md +++ b/README.md @@ -9,9 +9,13 @@ Foundation is a StellarWP Composer monorepo for reusable PHP packages intended f - [stellarwp/foundation-container](https://github.com/stellarwp/foundation-container) - [stellarwp/foundation-pipeline](https://github.com/stellarwp/foundation-pipeline) - [stellarwp/foundation-log](https://github.com/stellarwp/foundation-log) +- [stellarwp/foundation-shutdown](https://github.com/stellarwp/foundation-shutdown) +- [stellarwp/foundation-view](https://github.com/stellarwp/foundation-view) - [stellarwp/foundation-wpcli](https://github.com/stellarwp/foundation-wpcli) - [stellarwp/foundation-cli](https://github.com/stellarwp/foundation-cli) +See [Upgrading to 2.0](UPGRADING-2.0.md) when moving from Foundation 1.x. Package READMEs contain the setup and API guidance for this release. + ## Installation Install the aggregate package when you want the convenient all-in-one Foundation package: @@ -137,7 +141,6 @@ composer run foundation -- package:create The package argument can be a new package component such as `WPCli`, an existing package directory, short package name, or Composer package name, for example `Log`, `foundation-log`, or `stellarwp/foundation-log`. -If the package does not exist yet, the command asks whether to create the local scaffold in `src/` and asks for the Composer package name with a default such as `stellarwp/foundation-wpcli`. The scaffold includes the required `composer.json`, `README.md`, `.gitattributes`, `.gitignore`, and `close-pull-request.yml` files. After scaffolding, the command runs `composer monorepo merge` so the root `composer.json` includes the new package. The command runs as a dry run by default. It validates the required split package files, prints the target repository name and description, and shows the GitHub CLI commands it will run. @@ -151,7 +154,6 @@ The command runs as a dry run by default. It validates the required split packag composer run foundation -- package:create --apply ``` -The command creates the `stellarwp/foundation-` repository with the standard `[READ ONLY]` description and disables issues, wiki, projects, and pull requests. The package's `close-pull-request.yml` workflow is still included as a fallback guard for read-only split repositories. #### Generating WP-CLI Commands diff --git a/UPGRADING-2.0.md b/UPGRADING-2.0.md new file mode 100644 index 00000000..87b42cf0 --- /dev/null +++ b/UPGRADING-2.0.md @@ -0,0 +1,36 @@ +# Upgrading to Foundation 2.0 + +Foundation 2.0 requires PHP 8.3 or later. Upgrade the Foundation packages used by an application together; their internal dependencies require `^2.0`. + +## Container and configuration + +Create the container through `ContainerFactory::create()` with an `ArrayConfiguration` snapshot. This replaces application bootstrap code that constructed DI52 and bound `Adbar\Dot` directly. See the [Container setup](src/Container/README.md). + +Ordinary providers extend `Contracts\Provider`, whose final constructor accepts the container and resolves the registered `Contracts\Configuration`. Remove constructors that only forwarded container/configuration arguments. Put runtime collaborators in the services registered by the provider. + +Applications that own a registration base class can instead implement `Contracts\Providable`. Its only method is `register(): void`; its constructor belongs to the application. The container accepts both styles. `isDeferred()`, `provides()` and `boot()` are no longer invoked: move required registration into `register()` and defer expensive construction through lazy bindings. + +The former `foundation-container-wordpress` package is removed. Register WordPress hooks in application providers and use lazy container callbacks where appropriate. + +Factory callbacks receive `Contracts\Resolver`, not DI52. Change callback parameter types and use its `get()` and `has()` methods. Raw-container access through `getContainer()` and magic forwarding of undocumented DI52 operations are removed. Use the declared Foundation container operations. Catch Foundation's `Exceptions\ContainerException` or `Exceptions\NotFoundException` instead of DI52 exceptions. + +Configuration is a read-only application-lifetime snapshot. Assemble plugin settings before registering their providers. Replacing configuration after providers have been constructed does not update their stored snapshot. + +## Logging + +[Foundation Log](src/Log/README.md) supports Monolog `^2.11 || ^3.10`. Composer selects a compatible major for the application. Custom handlers and processors must support the selected major's record representation. + +The configured PSR-3 logger is now a singleton. Handlers and processors added to it persist for that container's lifetime. Audit code that previously expected a fresh logger on each resolution. + +The former public `LogProvider::LOG_LEVEL`, `CHANNEL_ERRORLOG` and `CHANNELS` implementation constants are no longer exposed. Configure the level and channels through `log.level`, `log.channel` and `log.channels`. + +Custom channels and stacks can resolve application-defined handlers. Built-in channel names remain `errorlog`, `console`, `null` and `stack`; use those strings in configuration. Duplicate handler instances in a stack are rejected to prevent conflicting destination setup. + +## New packages + +- [Shutdown](src/Shutdown/README.md) runs application-owned termination tasks with failure isolation and deterministic ordering. It does not add an Axiom transport, retry queue or automatic log buffering. +- [View](src/View/README.md) renders trusted PHP templates inside a configured directory and supports immutable directory selection. + +## Split repositories + +Package scaffolding and validation no longer require `.github/workflows/close-pull-request.yml`. The repository-creation command disables pull requests through GitHub's API. Existing repositories need that setting configured before their closing workflow is removed. Release assembly does not change remote repository settings. diff --git a/composer.json b/composer.json index 75959329..8c1681b5 100644 --- a/composer.json +++ b/composer.json @@ -14,7 +14,8 @@ "ext-exif": "*", "adbario/php-dot-notation": ">=2.5", "lucatume/di52": ">=4.1", - "monolog/monolog": "^2.11", + "monolog/monolog": "^2.11 || ^3.10", + "psr/container": ">=1.1", "psr/log": ">=1.0", "stellarwp/container-contract": "^1.1", "symfony/console": ">=5.4", @@ -37,6 +38,8 @@ "stellarwp/foundation-container": "self.version", "stellarwp/foundation-log": "self.version", "stellarwp/foundation-pipeline": "self.version", + "stellarwp/foundation-shutdown": "self.version", + "stellarwp/foundation-view": "self.version", "stellarwp/foundation-wpcli": "self.version" }, "minimum-stability": "dev", @@ -47,11 +50,14 @@ "StellarWP\\Foundation\\Container\\": "src/Container/", "StellarWP\\Foundation\\Log\\": "src/Log/", "StellarWP\\Foundation\\Pipeline\\": "src/Pipeline/", + "StellarWP\\Foundation\\Shutdown\\": "src/Shutdown/", + "StellarWP\\Foundation\\View\\": "src/View/", "StellarWP\\Foundation\\WPCli\\": "src/WPCli/" }, "exclude-from-classmap": [ "src/*/vendor/", - "tests/CodeceptionSupport/" + "tests/CodeceptionSupport/", + "tests/_data/temp/" ] }, "autoload-dev": { @@ -69,6 +75,9 @@ "sort-packages": true, "allow-plugins": { "phpstan/extension-installer": true + }, + "platform": { + "php": "8.3.28" } }, "scripts": { diff --git a/phpstan.neon.dist b/phpstan.neon.dist index 0d0bfe28..db90cb1e 100644 --- a/phpstan.neon.dist +++ b/phpstan.neon.dist @@ -9,3 +9,4 @@ parameters: analyse: - src/*/vendor/* - tests/CodeceptionSupport/* + - tests/_data/temp/* diff --git a/src/Cli/.github/workflows/close-pull-request.yml b/src/Cli/.github/workflows/close-pull-request.yml deleted file mode 100644 index 6bfbabee..00000000 --- a/src/Cli/.github/workflows/close-pull-request.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Close Pull Request - -on: - pull_request_target: - types: [opened] - -jobs: - run: - runs-on: ubuntu-latest - steps: - - uses: superbrothers/close-pull-request@v3 - with: - comment: "This is a read-only repository. Please submit your PR on the https://github.com/stellarwp/foundation repository.

Thanks!" diff --git a/src/Cli/CliProvider.php b/src/Cli/CliProvider.php index f56297d0..875512c9 100644 --- a/src/Cli/CliProvider.php +++ b/src/Cli/CliProvider.php @@ -2,7 +2,6 @@ namespace StellarWP\Foundation\Cli; -use lucatume\DI52\Container; use StellarWP\Foundation\Cli\Commands\Make\WPCliCommand; use StellarWP\Foundation\Cli\Commands\Package\Contracts\PackageRepositoryCreator; use StellarWP\Foundation\Cli\Commands\Package\CreateCommand; @@ -19,6 +18,7 @@ use StellarWP\Foundation\Cli\Process\Contracts\ProcessRunner; use StellarWP\Foundation\Cli\Process\ShellProcessRunner; use StellarWP\Foundation\Container\Contracts\Provider; +use StellarWP\Foundation\Container\Contracts\Resolver as C; /** * Registers the default Foundation CLI application and command dependencies. @@ -35,27 +35,27 @@ public function register(): void { $this->container->when(PackageResolver::class) ->needs('$rootPath') - ->give(static fn (Container $c): string => $c->get(self::ROOT_PATH)); + ->give(static fn (C $c): string => $c->get(self::ROOT_PATH)); $this->container->when(PackageScaffolder::class) ->needs('$rootPath') - ->give(static fn (Container $c): string => $c->get(self::ROOT_PATH)); + ->give(static fn (C $c): string => $c->get(self::ROOT_PATH)); $this->container->when(ComposerAutoloadResolver::class) ->needs('$rootPath') - ->give(static fn (Container $c): string => $c->get(self::ROOT_PATH)); + ->give(static fn (C $c): string => $c->get(self::ROOT_PATH)); $this->container->when(StubResolver::class) ->needs('$rootPath') - ->give(static fn (Container $c): string => $c->get(self::ROOT_PATH)); + ->give(static fn (C $c): string => $c->get(self::ROOT_PATH)); $this->container->when(WPCliCommand::class) ->needs('$rootPath') - ->give(static fn (Container $c): string => $c->get(self::ROOT_PATH)); + ->give(static fn (C $c): string => $c->get(self::ROOT_PATH)); $this->container->when(Application::class) ->needs('$commands') - ->give(static fn (Container $c): array => [ + ->give(static fn (C $c): array => [ $c->get(CreateCommand::class), $c->get(WPCliCommand::class), ]); diff --git a/src/Cli/Commands/Package/PackageFilesValidator.php b/src/Cli/Commands/Package/PackageFilesValidator.php index 417b057f..281abfec 100644 --- a/src/Cli/Commands/Package/PackageFilesValidator.php +++ b/src/Cli/Commands/Package/PackageFilesValidator.php @@ -5,8 +5,7 @@ /** * Validates that a split package has the files required for repository creation. * - * Use this before creating the external repository so missing package metadata, - * read-only warnings, or pull-request closing workflow files are caught early. + * Check required package files before attempting to create the external repository. */ final class PackageFilesValidator { @@ -18,7 +17,6 @@ final class PackageFilesValidator 'README.md', '.gitattributes', '.gitignore', - '.github/workflows/close-pull-request.yml', ]; /** diff --git a/src/Cli/Commands/Package/PackageScaffolder.php b/src/Cli/Commands/Package/PackageScaffolder.php index 48670816..9bdd5a69 100644 --- a/src/Cli/Commands/Package/PackageScaffolder.php +++ b/src/Cli/Commands/Package/PackageScaffolder.php @@ -82,11 +82,10 @@ private function normalizePackageName(string $packageName): string { */ private function writeFiles(Package $package): array { $files = [ - 'composer.json' => $this->composerJson($package), - 'README.md' => $this->readme($package), - '.gitattributes' => $this->gitAttributes(), - '.gitignore' => $this->gitIgnore(), - '.github/workflows/close-pull-request.yml' => $this->closePullRequestWorkflow(), + 'composer.json' => $this->composerJson($package), + 'README.md' => $this->readme($package), + '.gitattributes' => $this->gitAttributes(), + '.gitignore' => $this->gitIgnore(), ]; $createdFiles = []; @@ -209,22 +208,4 @@ private function gitIgnore(): string { composer.lock GITIGNORE . PHP_EOL; } - - private function closePullRequestWorkflow(): string { - return <<<'WORKFLOW' - name: Close Pull Request - - on: - pull_request_target: - types: [opened] - - jobs: - run: - runs-on: ubuntu-latest - steps: - - uses: superbrothers/close-pull-request@v3 - with: - comment: "This is a read-only repository. Please submit your PR on the https://github.com/stellarwp/foundation repository.

Thanks!" - WORKFLOW . PHP_EOL; - } } diff --git a/src/Cli/bin/foundation b/src/Cli/bin/foundation index a9dedcc2..63da83b0 100644 --- a/src/Cli/bin/foundation +++ b/src/Cli/bin/foundation @@ -1,13 +1,10 @@ #!/usr/bin/env php bind(Container::class, $container); - $container->bind(ContainerInterface::class, $container); - $container->singleton(Dot::class, new Dot()); + $configuration = new ArrayConfiguration(); + $factory = new ContainerFactory(); + $container = $factory->create($configuration); $container->register(CliProvider::class); exit($container->get(Application::class)->run()); diff --git a/src/Container/.github/workflows/close-pull-request.yml b/src/Container/.github/workflows/close-pull-request.yml deleted file mode 100644 index 7c34d2eb..00000000 --- a/src/Container/.github/workflows/close-pull-request.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Close Pull Request - -on: - pull_request_target: - types: [opened] - -jobs: - run: - runs-on: ubuntu-latest - steps: - - uses: superbrothers/close-pull-request@v3 - with: - comment: "This is a read-only repository. Please submit your PR on the https://github.com/stellarwp/prophecy-monorepo repository.

Thanks!" diff --git a/src/Container/Configuration/ArrayConfiguration.php b/src/Container/Configuration/ArrayConfiguration.php new file mode 100644 index 00000000..9a69f651 --- /dev/null +++ b/src/Container/Configuration/ArrayConfiguration.php @@ -0,0 +1,47 @@ + + */ + private Dot $configuration; + + /** + * Create configuration backed by the supplied application values. + * + * @param array $configuration + */ + public function __construct(array $configuration = []) { + $this->configuration = new Dot($configuration); + } + + /** + * {@inheritDoc} + */ + public function all(): array { + return $this->configuration->all(); + } + + /** + * {@inheritDoc} + */ + public function has(string $key): bool { + return $this->configuration->has($key); + } + + /** + * {@inheritDoc} + */ + public function get(string $key, mixed $default = null): mixed { + return $this->configuration->get($key, $default); + } +} diff --git a/src/Container/ContainerAdapter.php b/src/Container/ContainerAdapter.php index 679cb82c..e6f11234 100644 --- a/src/Container/ContainerAdapter.php +++ b/src/Container/ContainerAdapter.php @@ -4,41 +4,52 @@ use Closure; use lucatume\DI52\Container as DI52Container; -use lucatume\DI52\ContainerException; +use lucatume\DI52\ContainerException as DI52ContainerException; +use lucatume\DI52\NotFoundException as DI52NotFoundException; use StellarWP\Foundation\Container\Contracts\Container; +use StellarWP\Foundation\Container\Contracts\Providable; +use StellarWP\Foundation\Container\Exceptions\ContainerException; +use StellarWP\Foundation\Container\Exceptions\NotFoundException; +use Throwable; /** - * @method mixed make(string $id) - * @method mixed getVar(string $key, mixed|null $default = null) + * Adapts DI52 to Foundation's stable container and resolver contracts. + * + * Prefer {@see ContainerFactory} for application setup. A custom composition + * root that constructs this adapter directly must register Foundation's core + * contracts, including Configuration, before it registers any Provider. */ final class ContainerAdapter implements Container { + /** + * @var array + */ + private array $callbacks = []; + + /** + * Wrap the underlying DI52 container without exposing it to application services. + */ public function __construct( private readonly DI52Container $container ) { } /** + * Register a transient service binding with the underlying container. + * * @param string[]|null $afterBuildMethods * - * @throws \lucatume\DI52\ContainerException + * @throws ContainerException When the binding cannot be registered. */ public function bind(string $id, mixed $implementation = null, ?array $afterBuildMethods = null): void { - $this->container->bind($id, $implementation, $afterBuildMethods); + $this->call(fn () => $this->container->bind($id, $this->adaptImplementation($implementation), $afterBuildMethods)); } /** * {@inheritDoc} */ public function get(string $id): mixed { - return $this->container->get($id); - } - - /** - * @codeCoverageIgnore - */ - public function getContainer(): DI52Container { - return $this->container; + return $this->call(fn (): mixed => $this->container->get($id)); } /** @@ -51,26 +62,64 @@ public function has(string $id): bool { } /** + * Register a shared service binding with the underlying container. + * * @param string[]|null $afterBuildMethods * - * @throws \lucatume\DI52\ContainerException + * @throws ContainerException When the singleton cannot be registered. */ public function singleton(string $id, mixed $implementation = null, ?array $afterBuildMethods = null): void { - $this->container->singleton($id, $implementation, $afterBuildMethods); + $this->call(fn () => $this->container->singleton($id, $this->adaptImplementation($implementation), $afterBuildMethods)); } /** - * {@inheritDoc} + * Validate, resolve, and register a Foundation provider with optional aliases. + * + * @param class-string $serviceProviderClass + * + * @throws ContainerException When the class is not a Foundation provider or cannot be registered. */ public function register(string $serviceProviderClass, ...$alias): void { - $this->container->register($serviceProviderClass, ...$alias); + if (! is_a($serviceProviderClass, Providable::class, true)) { + throw new ContainerException(sprintf( + '%s must implement %s to be registered as a provider.', + $serviceProviderClass, + Providable::class + )); + } + + $provider = $this->resolveProvider($serviceProviderClass); + $provider->register(); + $this->singleton($serviceProviderClass, $provider); + + foreach ($alias as $providerAlias) { + $this->singleton($providerAlias, $provider); + } + } + + /** + * Check the resolved binding as applications can replace a provider class with a factory. + */ + private function resolveProvider(string $id): Providable { + $provider = $this->get($id); + + if (! $provider instanceof Providable) { + throw new ContainerException(sprintf( + 'The binding for %s must resolve to %s; received %s.', + $id, + Providable::class, + get_debug_type($provider) + )); + } + + return $provider; } /** * {@inheritDoc} */ public function when(string $class): Container { - $this->container->when($class); + $this->call(fn () => $this->container->when($class)); return $this; } @@ -79,36 +128,66 @@ public function when(string $class): Container { * {@inheritDoc} */ public function needs(string $id): Container { - $this->container->needs($id); + $this->call(fn () => $this->container->needs($id)); return $this; } + /** + * {@inheritDoc} + */ public function give(mixed $implementation): void { - $this->container->give($implementation); - } - - public function instance(mixed $id, array $buildArgs = [], ?array $afterBuildMethods = null): Closure { - // @phpstan-ignore-next-line invalid DocBlock comments in DI52 - return $this->container->instance($id, $buildArgs, $afterBuildMethods); + $this->call(fn () => $this->container->give($this->adaptImplementation($implementation))); } /** * {@inheritDoc} * - * @throws ContainerException + * @throws ContainerException When the additive binding cannot be registered. */ public function mergeArrayVar(string $id, mixed $implementation): void { - $this->container->mergeArrayVar($id, $implementation); + $this->call(fn () => $this->container->mergeArrayVar($id, $this->adaptImplementation($implementation))); + } + + /** + * {@inheritDoc} + */ + public function instance(mixed $id, array $buildArgs = [], ?array $afterBuildMethods = null): Closure { + /** + * @var Closure $factory + */ + $factory = $this->call( + // @phpstan-ignore-next-line invalid DocBlock comments in DI52 + fn (): Closure => $this->container->instance($id, $buildArgs, $afterBuildMethods) + ); + + return fn (): mixed => $this->resolveDeferred(static fn (): mixed => $factory()); } /** + * Create a stable callable that resolves its target service when invoked. + * * @param class-string|string|object $id * * @throws ContainerException */ public function callback(object|string $id, string $method): callable { - return $this->container->callback($id, $method); + $callbackId = (is_object($id) ? 'object:' . spl_object_id($id) : 'service:' . $id) + . '::' . $method; + + return $this->callbacks[$callbackId] ??= function (mixed ...$args) use ($id, $method): mixed { + $instance = is_object($id) ? $id : $this->get($id); + + if (! is_callable([$instance, $method])) { + throw new ContainerException(sprintf( + '%s::%s is not a callable container callback.', + is_object($instance) ? $instance::class : get_debug_type($instance), + $method + )); + } + + return $instance->{$method}(...$args); + }; } /** @@ -120,7 +199,14 @@ public function singletonDecorators( ?array $afterBuildMethods = null, bool $afterBuildAll = false ): void { - $this->container->singletonDecorators($id, $decorators, $afterBuildMethods, $afterBuildAll); + $this->call( + fn () => $this->container->singletonDecorators( + $id, + array_map($this->adaptImplementation(...), $decorators), + $afterBuildMethods, + $afterBuildAll + ) + ); } /** @@ -132,15 +218,94 @@ public function bindDecorators( ?array $afterBuildMethods = null, bool $afterBuildAll = false ): void { - $this->container->bindDecorators($id, $decorators, $afterBuildMethods, $afterBuildAll); + $this->call( + fn () => $this->container->bindDecorators( + $id, + array_map($this->adaptImplementation(...), $decorators), + $afterBuildMethods, + $afterBuildAll + ) + ); + } + + /** + * Adapt a factory closure so it receives Foundation's resolver rather than DI52. + */ + private function adaptImplementation(mixed $implementation): mixed { + if (! $implementation instanceof Closure) { + return $implementation; + } + + $resolver = $this; + + return static fn (): mixed => $implementation($resolver); + } + + /** + * Invoke a DI52 operation while keeping backend exceptions behind Foundation's API. + * + * @template T + * + * @param Closure(): T $operation + * + * @throws ContainerException When the underlying container operation fails. + * @throws NotFoundException When a requested entry does not exist. + * + * @return T + */ + private function call(Closure $operation): mixed { + try { + return $operation(); + } catch (DI52NotFoundException $exception) { + throw new NotFoundException( + $exception->getMessage(), + $exception->getCode(), + $this->previous($exception) + ); + } catch (DI52ContainerException $exception) { + throw new ContainerException( + $exception->getMessage(), + $exception->getCode(), + $this->previous($exception) + ); + } } /** - * Defer all other calls to the container object. + * Resolve a deferred factory while normalizing failures that bypass DI52's get() boundary. + * + * @template T * - * @param mixed[] $args + * @param Closure(): T $operation + * + * @throws ContainerException When the deferred service cannot be resolved. + * + * @return T + */ + private function resolveDeferred(Closure $operation): mixed { + try { + return $this->call($operation); + } catch (ContainerException $exception) { + throw $exception; + } catch (Throwable $exception) { + throw new ContainerException( + $exception->getMessage(), + $exception->getCode(), + $exception + ); + } + } + + /** + * Preserve the application failure wrapped by DI52 when one is available. */ - public function __call(string $name, array $args): mixed { - return $this->container->{$name}(...$args); + private function previous(DI52ContainerException $exception): ?Throwable { + $previous = $exception->getPrevious(); + + while ($previous instanceof DI52ContainerException) { + $previous = $previous->getPrevious(); + } + + return $previous; } } diff --git a/src/Container/ContainerFactory.php b/src/Container/ContainerFactory.php new file mode 100644 index 00000000..df06c6bf --- /dev/null +++ b/src/Container/ContainerFactory.php @@ -0,0 +1,29 @@ +bind(Container::class, $container); + $container->bind(Resolver::class, $container); + $container->bind(ContainerInterface::class, $container); + $container->singleton(Configuration::class, $configuration); + + return $container; + } +} diff --git a/src/Container/Contracts/Configuration.php b/src/Container/Contracts/Configuration.php new file mode 100644 index 00000000..c4feafc7 --- /dev/null +++ b/src/Container/Contracts/Configuration.php @@ -0,0 +1,34 @@ + + */ + public function all(): array; + + /** + * Determine whether a dotted configuration key exists. + * + * A key with a null value still exists. An exact top-level key takes + * precedence over traversing the same dotted path. + */ + public function has(string $key): bool; + + /** + * Return a configuration value by its dotted key. + * + * The default applies only when the key is absent. An existing key whose + * value is null must return null. An exact top-level key takes precedence + * over traversing the same dotted path. The configuration mapping should + * remain stable after application providers begin registration. + */ + public function get(string $key, mixed $default = null): mixed; +} diff --git a/src/Container/Contracts/Container.php b/src/Container/Contracts/Container.php index f899816b..899f46f5 100644 --- a/src/Container/Contracts/Container.php +++ b/src/Container/Contracts/Container.php @@ -4,24 +4,29 @@ use Closure; use StellarWP\ContainerContract\ContainerInterface; +use StellarWP\Foundation\Container\Exceptions\ContainerException; /** - * Extend the StellarWP ContainerInterface to include - * some must have methods. + * Registers and resolves Foundation application services. + * + * Factory closures receive the narrower {@see Resolver} contract so callers + * do not depend on the underlying container engine. */ -interface Container extends ContainerInterface +interface Container extends ContainerInterface, Resolver { /** * Register a service provider. * - * @param class-string $serviceProviderClass - * @param string ...$alias + * @param class-string $serviceProviderClass + * @param string ...$alias * - * @throws \lucatume\DI52\ContainerException + * @throws ContainerException When the provider cannot be registered. */ public function register(string $serviceProviderClass, ...$alias): void; /** + * Begin a contextual binding for one consuming class. + * * @param class-string|string $class * * @return $this @@ -29,12 +34,20 @@ public function register(string $serviceProviderClass, ...$alias): void; public function when(string $class): Container; /** + * Select the constructor dependency supplied by the current contextual binding. + * * @param class-string|string $id * * @return $this */ public function needs(string $id): Container; + /** + * Complete a contextual binding. + * + * Closure implementations receive a Foundation {@see Resolver}, never the + * underlying container implementation. + */ public function give(mixed $implementation): void; /** @@ -42,7 +55,10 @@ public function give(mixed $implementation): void; * * @param class-string|string $id * - * @throws \lucatume\DI52\ContainerException + * Closure implementations receive a Foundation {@see Resolver}, never the + * underlying container implementation. + * + * @throws ContainerException When the additive binding cannot be registered. */ public function mergeArrayVar(string $id, mixed $implementation): void; @@ -52,11 +68,17 @@ public function mergeArrayVar(string $id, mixed $implementation): void; * * @param array $buildArgs The arguments passed to the constructor in the order they are provided. * @param string[]|null $afterBuildMethods An array of methods that should be called after the instance is resolved. + * + * @throws ContainerException When the factory cannot be created or its service cannot be resolved. */ public function instance(mixed $id, array $buildArgs = [], ?array $afterBuildMethods = null): Closure; /** + * Create a stable callable that resolves its service when invoked. + * * @param class-string|string|object $id + * + * @throws ContainerException When the callback cannot be created or its service cannot be resolved. */ public function callback(string|object $id, string $method): callable; @@ -64,12 +86,14 @@ public function callback(string|object $id, string $method): callable; * Bind a decorator chain that resolves to the same instance on every request. * * The base implementation must be the last decorator. + * Closure decorators receive a Foundation {@see Resolver}, never the + * underlying container implementation. * * @param class-string|string $id * @param non-empty-list $decorators * @param list|null $afterBuildMethods * - * @throws \lucatume\DI52\ContainerException + * @throws ContainerException When a decorator binding cannot be registered. */ public function singletonDecorators( string $id, @@ -82,12 +106,14 @@ public function singletonDecorators( * Bind a decorator chain that resolves to a new instance on every request. * * The base implementation must be the last decorator. + * Closure decorators receive a Foundation {@see Resolver}, never the + * underlying container implementation. * * @param class-string|string $id * @param non-empty-list $decorators * @param list|null $afterBuildMethods * - * @throws \lucatume\DI52\ContainerException + * @throws ContainerException When a decorator binding cannot be registered. */ public function bindDecorators( string $id, diff --git a/src/Container/Contracts/Providable.php b/src/Container/Contracts/Providable.php index 34b7e742..55cf1e4e 100644 --- a/src/Container/Contracts/Providable.php +++ b/src/Container/Contracts/Providable.php @@ -2,27 +2,13 @@ namespace StellarWP\Foundation\Container\Contracts; +/** + * Allows application-owned registration classes to integrate without inheriting Foundation's provider base. + */ interface Providable { /** - * Registers bindings in the container. + * Register this feature's bindings and hooks before application services are resolved. */ public function register(): void; - - /** - * Whether the service provider will be a deferred one or not. - */ - public function isDeferred(): bool; - - /** - * Returns an array of the class or interfaces bound and provided by the service provider. - * - * @return string[] A list of fully-qualified implementations provided by the service provider. - */ - public function provides(): array; - - /** - * Binds and sets up implementations at boot time. - */ - public function boot(): void; } diff --git a/src/Container/Contracts/Provider.php b/src/Container/Contracts/Provider.php index 576aa03a..90fc694c 100644 --- a/src/Container/Contracts/Provider.php +++ b/src/Container/Contracts/Provider.php @@ -2,45 +2,30 @@ namespace StellarWP\Foundation\Container\Contracts; -use Adbar\Dot; -use StellarWP\Foundation\Container\ContainerAdapter; +use StellarWP\Foundation\Container\Exceptions\ContainerException; +use StellarWP\Foundation\Container\Exceptions\NotFoundException; /** - * Providers should extend this abstract in order to have - * access to the container instance to register their bindings. + * Provides feature registration access to the shared container and configuration. */ abstract class Provider implements Providable { - /** - * Whether this service provider will be a deferred one or not. - */ - protected bool $deferred = false; - - public function __construct( - /** @var Container|ContainerAdapter $container */ - protected readonly Container $container, - /** @var Dot */ - protected readonly Dot $config - ) { - } + protected readonly Configuration $config; /** - * {@inheritDoc} + * Provide the shared container and resolve the application configuration used during registration. + * + * @throws ContainerException When the configuration service cannot be resolved. + * @throws NotFoundException When the configuration service has not been registered. */ - public function isDeferred(): bool { - return $this->deferred; - } - - /** - * {@inheritDoc} - */ - public function provides(): array { - return []; + final public function __construct( + protected readonly Container $container + ) { + $this->config = $this->container->get(Configuration::class); } /** - * {@inheritDoc} + * Register this feature's bindings and application hooks. */ - public function boot(): void { - } + abstract public function register(): void; } diff --git a/src/Container/Contracts/Resolver.php b/src/Container/Contracts/Resolver.php new file mode 100644 index 00000000..395f2ed6 --- /dev/null +++ b/src/Container/Contracts/Resolver.php @@ -0,0 +1,34 @@ +|string $id + * + * @throws ContainerException When the entry cannot be resolved. + * @throws NotFoundException When the entry does not exist. + * + * @return ($id is class-string ? T : mixed) + */ + public function get(string $id); + + /** + * Determine whether the container can resolve an identifier. + * + * @return bool + */ + public function has(string $id); +} diff --git a/src/Container/Exceptions/ContainerException.php b/src/Container/Exceptions/ContainerException.php new file mode 100644 index 00000000..a744c83d --- /dev/null +++ b/src/Container/Exceptions/ContainerException.php @@ -0,0 +1,13 @@ + [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -The DI Container configuration and Service Provider implementation, utilizing -[di52](https://github.com/lucatume/di52). +Foundation Container supplies autowiring, contextual bindings, lazy callbacks and decorator chains behind Foundation-owned contracts. Requires PHP 8.3 or later. -## Installation - -```shell -composer require stellarwp/foundation-container +```sh +composer require stellarwp/foundation-container:^2.0 ``` -## Container Configuration - -Create a new ContainerAdapter, by passing in an instance of di52: +## Create the application container ```php -load(); -} - -// This implements the Contracts/Container.php interface. -$container = new ContainerAdapter(new Container()); - -// Bind the concrete to the interface, so anytime we ask for a container we get this one. -$container->bind(Container::class, $container); - -// Register our project's configuration. See "Making a config.php" below for more detail. -$container->bind(Dot::class, new Dot(require_once dirname(__FILE__) . '/config.php')); - -// Register any service providers in the container. -$providers = [ - StellarWP\YourProject\ServiceProvider::class, - // as many as you have made... -]; - -foreach ( $providers as $provider ) { - $container->register($provider); -} +use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; +use StellarWP\Foundation\Container\ContainerFactory; + +$configuration = new ArrayConfiguration([ + 'catalog' => [ + 'endpoint' => 'https://example.com/catalog', + ], +]); +$factory = new ContainerFactory(); +$container = $factory->create($configuration); ``` -Here is an example Service Provider: +`ContainerFactory` registers the container, resolver and configuration contracts. Configuration is a read-only snapshot for the container lifetime. Missing keys return the supplied default; an explicitly configured `null` remains `null`. -```php -container` and `$this->config`; put service dependencies in the services you register. -use lucatume\DI52\ContainerException; +```php use StellarWP\Foundation\Container\Contracts\Provider; -use StellarWP\Foundation\Storage\Contracts\Storage; -use StellarWP\Foundation\Storage\Drivers\LocalStorage; -final class ServiceProvider extends Provider +final class CatalogProvider extends Provider { - /** - * @throws ContainerException - */ - public function register(): void { - $this->container->bind(Storage::class, LocalStorage::class); - $this->container->when(LocalStorage::class) - ->needs('$storagePath') - ->give($this->config->get('storage_path')); - } -} -``` - -## Environment Variable Configuration - -This library uses the [Dot](https://github.com/adbario/php-dot-notation) package to set and fetch configuration -values, which are initially provided via Environment Variables, either manually set or via an `.env` file -utilizing [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) to read them. + public function register(): void { + $this->container->when(CatalogClient::class) + ->needs('$endpoint') + ->give($this->config->get('catalog.endpoint')); -Each Service Provider will have access to Dot via the `$this->config` property, it is best practice to only -access configuration variables from a Service Provider and never in your concrete classes. - -### Making a config.php - -A sample config.php for a project. Note: we fall back to sane defaults if the environment variable isn't available. + $this->container->singleton(CatalogClient::class); + } +} -```php - $_ENV['SOME_KEY'] ?? '', - 'log' => [ - 'level' => $_ENV['LOG_LEVEL'] ?? 'debug', - 'channel' => $_ENV['LOG_CHANNEL'] ?? 'null', - 'channels' => [ - 'errorlog' => [], - 'console' => [ - 'with' => [ - 'stream' => 'php://stdout', - ], - ], - ], - ], -]; +$container->register(CatalogProvider::class); ``` -Inside a Provider, we can then access deep variables with dot notation, e.g. - -```php -// Get the console log stream type from config.php. -$stream = $this->config->get('log.channels.console.with.stream'); +`CatalogClient` represents the application's own class. Register providers once, in dependency order, before resolving services. Registration is eager; service bindings remain lazy. Repeating registration can repeat hooks and contributions. -// Get the log level. -$level = $this->config->get('log.level'); -``` +Applications with an existing registration abstraction may implement `Contracts\Providable` instead. It requires only `register(): void` and imposes no constructor. The application owns that implementation's injected dependencies. The supplied `Provider` also implements this interface. -> 💡 If using a `config.php` in a WordPress plugin, simply add your configured $_ENV vars in your wp-config.php. +Factory closures receive Foundation's `Contracts\Resolver`, not DI52. Use `get()` and `has()` inside factories. Inject resolved services into application code rather than passing the container into business services. -```php -// Inside wp-config.php - -// App configuration. -$_ENV['SOME_KEY'] = 'abcd-1234'; -$_ENV['LOG_LEVEL'] = 'info'; -$_ENV['LOG_CHANNEL'] = 'errorlog'; -``` +`callback(Service::class, 'method')` creates a lazy callable with stable identity, suitable for WordPress hooks. `mergeArrayVar()` collects contributions from multiple providers. `singletonDecorators()` and `bindDecorators()` compose registered implementations. +Container failures use `Exceptions\ContainerException` and `Exceptions\NotFoundException`. The underlying DI52 container and its undocumented methods are not part of Foundation's public API. diff --git a/src/Container/composer.json b/src/Container/composer.json index d6c66b03..1708aed4 100644 --- a/src/Container/composer.json +++ b/src/Container/composer.json @@ -11,6 +11,7 @@ "php": ">=8.3", "adbario/php-dot-notation": ">=2.5", "lucatume/di52": ">=4.1", + "psr/container": ">=1.1", "stellarwp/container-contract": "^1.1", "vlucas/phpdotenv": ">=4.3" }, diff --git a/src/Log/.github/workflows/close-pull-request.yml b/src/Log/.github/workflows/close-pull-request.yml deleted file mode 100644 index 7c34d2eb..00000000 --- a/src/Log/.github/workflows/close-pull-request.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Close Pull Request - -on: - pull_request_target: - types: [opened] - -jobs: - run: - runs-on: ubuntu-latest - steps: - - uses: superbrothers/close-pull-request@v3 - with: - comment: "This is a read-only repository. Please submit your PR on the https://github.com/stellarwp/prophecy-monorepo repository.

Thanks!" diff --git a/src/Log/Formatters/ColoredLineFormatter.php b/src/Log/Formatters/ColoredLineFormatter.php index d66811a2..b7f8a890 100644 --- a/src/Log/Formatters/ColoredLineFormatter.php +++ b/src/Log/Formatters/ColoredLineFormatter.php @@ -68,11 +68,13 @@ public function __construct( /** * Formats a log record, with color. * - * @param mixed[] $record A log record to format. + * Accept the installed Monolog version's record and preserve it for the parent formatter. + * + * @param mixed $record Monolog 2's record array or Monolog 3's LogRecord, supplied by the installed logger. * * @return string The formatted and colored record */ - public function format(array $record): string { + public function format($record): string { $formatted = parent::format($record); $formatted = str_replace('%color_start%', $this->colorScheme[\StellarWP\Foundation\Log\LogLevel::toPsrLogLevel($record['level'])], $formatted); diff --git a/src/Log/Handlers/NullHandler.php b/src/Log/Handlers/NullHandler.php index 57c9ef71..df135b83 100644 --- a/src/Log/Handlers/NullHandler.php +++ b/src/Log/Handlers/NullHandler.php @@ -11,7 +11,12 @@ */ final class NullHandler extends AbstractHandler { - public function handle(array $record): bool { - return $record['level'] >= $this->level; + /** + * Discard matching records and stop their delivery to subsequent handlers. + * + * Accept the installed Monolog version's record; the parent owns level comparison. + */ + public function handle($record): bool { + return $this->isHandling($record); } } diff --git a/src/Log/LogLevel.php b/src/Log/LogLevel.php index 6e80855d..231d0307 100644 --- a/src/Log/LogLevel.php +++ b/src/Log/LogLevel.php @@ -67,7 +67,7 @@ final class LogLevel * * @throws UnhandledMatchError * - * @return int The Monolog level code. + * @return self::* The Monolog level code. */ public static function fromName(string $level): int { return match ($level) { diff --git a/src/Log/LogProvider.php b/src/Log/LogProvider.php index c587bf68..ecc6cabb 100644 --- a/src/Log/LogProvider.php +++ b/src/Log/LogProvider.php @@ -2,134 +2,134 @@ namespace StellarWP\Foundation\Log; -use lucatume\DI52\Container; +use InvalidArgumentException; use Monolog\Formatter\LineFormatter; use Monolog\Handler\AbstractHandler; use Monolog\Handler\ErrorLogHandler; use Monolog\Handler\FormattableHandlerInterface; use Monolog\Handler\StreamHandler; use Monolog\Logger; +use Monolog\Processor\PsrLogMessageProcessor; use Psr\Log\LoggerInterface; use RuntimeException; use StellarWP\Foundation\Container\Contracts\Provider; +use StellarWP\Foundation\Container\Contracts\Resolver as C; +use StellarWP\Foundation\Container\Exceptions\ContainerException; use StellarWP\Foundation\Log\Formatters\ColoredLineFormatter; use StellarWP\Foundation\Log\Handlers\NullHandler; +use UnhandledMatchError; /** - * Default logging provider for consumers that want Foundation to wire logging for them. - * - * This provider is intentionally conservative: if the configured logging transport is - * unavailable, the application should keep running. Consumers that need different - * channels, handlers, or failure behavior can register their own provider instead. + * Registers the configured PSR-3 logger with built-in or application-defined channels. */ final class LogProvider extends Provider { - public const string LOG_LEVEL = 'foundation.log.log_level'; - public const string CHANNEL_ERRORLOG = 'errorlog'; - private const string CHANNEL_CONSOLE = 'console'; - private const string CHANNEL_NULL = 'null'; - private const string CHANNEL_STACK = 'stack'; - public const array CHANNELS = [ + private const string CHANNEL_ERRORLOG = 'errorlog'; + private const string CHANNEL_CONSOLE = 'console'; + private const string CHANNEL_NULL = 'null'; + private const string CHANNEL_STACK = 'stack'; + private const array CHANNELS = [ self::CHANNEL_CONSOLE => [ - 'class' => StreamHandler::class, + 'handler' => StreamHandler::class, 'formatter' => ColoredLineFormatter::class, ], self::CHANNEL_ERRORLOG => [ - 'class' => ErrorLogHandler::class, + 'handler' => ErrorLogHandler::class, 'formatter' => LineFormatter::class, ], self::CHANNEL_STACK => [ - self::CHANNEL_CONSOLE, - self::CHANNEL_ERRORLOG, + 'channels' => [self::CHANNEL_CONSOLE, self::CHANNEL_ERRORLOG], ], self::CHANNEL_NULL => [ - 'class' => NullHandler::class, + 'handler' => NullHandler::class, ], ]; /** - * {@inheritDoc} + * Register the application logger with its configured channel and level. + * + * @throws ContainerException When service bindings cannot be registered. + * @throws UnhandledMatchError When the configured log level is unsupported. */ public function register(): void { - $this->container->singleton(self::LOG_LEVEL, LogLevel::fromName($this->config->get('log.level', 'debug'))); + $level = LogLevel::fromName($this->config->get('log.level', 'debug')); $this->container->when(ColoredLineFormatter::class) ->needs('$dateFormat') ->give('Y-m-d H:i:s.v e'); - $channel = $this->config->get('log.channel'); - $this->container->singleton( - StreamHandler::class, - fn ($c) => new StreamHandler( - $this->config->get("log.channels.$channel.with.stream", 'php://stdout'), - $c->get(self::LOG_LEVEL) - ) + LoggerInterface::class, + fn (C $c): LoggerInterface => $this->createLogger($c, $level) ); + } - $this->container->bind( - LoggerInterface::class, - static function (Container $c) use ($channel): LoggerInterface { - $handler = self::CHANNELS[$channel] ?? false; - - if (! $handler) { - throw new RuntimeException( - sprintf( - 'Invalid log channel. Valid options are: %s', - implode(',', array_keys(self::CHANNELS)) - ) - ); - } + /** + * Build the selected logger from its channels' destinations and formatting. + * + * @param LogLevel::* $level + * + * @throws InvalidArgumentException When a configured stream is neither a path nor a resource. + * @throws RuntimeException When a channel is invalid or channels share a handler instance. + * @throws ContainerException When a configured handler or formatter cannot be resolved. + */ + private function createLogger(C $c, int $level): Logger { + $channel = $this->config->get('log.channel'); + $channels = self::CHANNELS; - $logger = new Logger($channel); - - /** - * @var array $handlers - */ - $handlers = []; - - // Single handler channel. - if (! empty($handler['class'])) { - if ($channel === self::CHANNEL_ERRORLOG && ! self::isErrorLogAvailable()) { - $handler = self::CHANNELS[self::CHANNEL_NULL]; - } - - $handlers[] = [ - 'handler' => $c->get($handler['class']), - 'formatter' => $handler['formatter'] ?? '', - ]; - } else { - // We are on a stack channel, which uses multiple existing handlers. - foreach ($handler as $stackChannel) { - if ($stackChannel === self::CHANNEL_ERRORLOG && ! self::isErrorLogAvailable()) { - continue; - } - - $handlers[] = [ - 'handler' => $c->get(self::CHANNELS[$stackChannel]['class']), - 'formatter' => self::CHANNELS[$stackChannel]['formatter'], - ]; - } - } + foreach ($this->config->get('log.channels', []) as $name => $definition) { + $channels[$name] = array_replace($channels[$name] ?? [], $definition); + } + + $selected = $channels[$channel] ?? null; + + if ($selected === null) { + throw new RuntimeException(sprintf( + 'Invalid log channel. Valid options are: %s', + implode(',', array_keys($channels)) + )); + } + + $logger = new Logger($channel); + $logger->pushProcessor($c->get(PsrLogMessageProcessor::class)); - /** @var array{handler: AbstractHandler, formatter: string|class-string} $registeredHandler */ - foreach ($handlers as $registeredHandler) { - if (! empty($registeredHandler['formatter']) && $registeredHandler['handler'] instanceof FormattableHandlerInterface) { - $registeredHandler['handler']->setFormatter($c->get($registeredHandler['formatter'])); - } + foreach ($selected['channels'] ?? [$channel] as $name) { + $definition = $channels[$name] ?? []; - // Set the configured log level for each handler. - $registeredHandler['handler']->setLevel($c->get(self::LOG_LEVEL)); + if (! isset($definition['handler'])) { + throw new RuntimeException(sprintf('Log channel "%s" must define a handler.', $name)); + } - $logger->pushHandler($registeredHandler['handler']); + if ($definition['handler'] === ErrorLogHandler::class && ! function_exists('error_log')) { + if (isset($selected['channels'])) { + continue; } - return $logger; + $definition = self::CHANNELS[self::CHANNEL_NULL]; } - ); - } - private static function isErrorLogAvailable(): bool { - return function_exists('error_log'); + $handler = $definition['handler'] === StreamHandler::class + ? new StreamHandler($definition['with']['stream'] ?? 'php://stdout', $level) + : $c->get($definition['handler']); + + if (in_array($handler, $logger->getHandlers(), true)) { + throw new RuntimeException(sprintf( + 'Log channel "%s" shares a handler instance with another stack entry. Use separate handler bindings or a single shared channel.', + $name + )); + } + + if (isset($definition['formatter']) && $handler instanceof FormattableHandlerInterface) { + $handler->setFormatter($c->get($definition['formatter'])); + } + + if ($handler instanceof AbstractHandler) { + $handler->setLevel($level); + } + + $logger->pushHandler($handler); + } + + return $logger; } } diff --git a/src/Log/README.md b/src/Log/README.md index dd4baa06..ae9fd6c8 100644 --- a/src/Log/README.md +++ b/src/Log/README.md @@ -3,48 +3,62 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -A logging library using [Monolog](https://github.com/Seldaek/monolog) that implements the `Psr\Log\LoggerInterface` interface. +Foundation Log registers one shared PSR-3 logger per container using Monolog 2.11+ or 3.10+. Requires PHP 8.3 or later. -## Installation - - -```shell -composer require stellarwp/foundation-log +```sh +composer require stellarwp/foundation-log:^2.0 ``` -If using [stellarwp/foundation-container](https://github.com/stellarwp/foundation-container), create a `config.php` and register -it in the container with: +## Configure the logger ```php -$this->container->bind(Dot::class, new Dot(require_once dirname(__FILE__) . '/config.php')); +use Psr\Log\LoggerInterface; +use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; +use StellarWP\Foundation\Container\ContainerFactory; +use StellarWP\Foundation\Log\LogProvider; + +$configuration = new ArrayConfiguration([ + 'log' => [ + 'channel' => 'errorlog', + 'level' => 'info', + ], +]); +$factory = new ContainerFactory(); +$container = $factory->create($configuration); +$container->register(LogProvider::class); + +$logger = $container->get(LoggerInterface::class); +$logger->info('Order {order_id} paid.', [ + 'order_id' => 42, +]); ``` -The config.php file maps environment variables, either from an `.env` file if you configured [phpdotenv](https://github.com/vlucas/phpdotenv), or manually set, e.g. +Inject `Psr\Log\LoggerInterface` into application services. The logger is shared, so handler and processor changes remain in effect for that container's lifetime. + +Built-in channels are `errorlog`, `console`, `null`, and `stack` (console plus error log). The level defaults to `debug`; select a channel explicitly. PSR-3 placeholders are interpolated while structured context is retained. + +## Custom destinations and stacks + +Add channel definitions under `log.channels`. Each destination selects a registered Monolog handler; an optional `formatter` selects a registered formatter. For example, with your `BufferedAxiomHandler` already bound in the container: ```php - [ - 'level' => $_ENV['APP_LOG_LEVEL'] ?? 'debug', - 'channel' => $_ENV['APP_LOG_CHANNEL'] ?? 'null', // console, errorlog, stack (both console and errorlog) or null - 'channels' => [ - 'errorlog' => [], - 'console' => [ - 'with' => [ - 'stream' => 'php://stdout', - ], - ], - 'stack' => [ - 'with' => [ - 'stream' => 'php://stdout', - ], - ], - ], - ], -]; +'log' => [ + 'channel' => 'application', + 'level' => 'info', + 'channels' => [ + 'axiom' => [ + 'handler' => BufferedAxiomHandler::class, + ], + 'application' => [ + 'channels' => [ + 'errorlog', + 'axiom', + ], + ], + ], +], ``` -Then, include the [LogProvider.php](./LogProvider.php) in your -application and call the `register` method. Anytime you inject a `Psr\Log\LoggerInterface` instance into another class, it will use -your provided configuration. +A custom stream channel can use `Monolog\Handler\StreamHandler` with `with.stream` set to a path or open stream. Stack entries must identify concrete handler channels, not nested stacks. Separate entries must not resolve to the same handler instance. Monolog invokes handlers in reverse insertion order; handler bubbling controls further delivery. + +Foundation does not include an Axiom transport or automatically buffer records. The application supplies credentials, transport failure handling, buffer limits and flushing. [Foundation Shutdown](https://github.com/stellarwp/foundation-shutdown) provides an explicit end-of-request flush boundary. Long-running workers should flush between jobs rather than waiting for process termination. diff --git a/src/Log/composer.json b/src/Log/composer.json index 8ac9d8d7..b42af7f1 100644 --- a/src/Log/composer.json +++ b/src/Log/composer.json @@ -9,7 +9,7 @@ }, "require": { "php": ">=8.3", - "monolog/monolog": "^2.11", + "monolog/monolog": "^2.11 || ^3.10", "stellarwp/foundation-container": "^2.0", "psr/log": ">=1.0" }, diff --git a/src/Pipeline/.github/workflows/close-pull-request.yml b/src/Pipeline/.github/workflows/close-pull-request.yml deleted file mode 100644 index 7c34d2eb..00000000 --- a/src/Pipeline/.github/workflows/close-pull-request.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Close Pull Request - -on: - pull_request_target: - types: [opened] - -jobs: - run: - runs-on: ubuntu-latest - steps: - - uses: superbrothers/close-pull-request@v3 - with: - comment: "This is a read-only repository. Please submit your PR on the https://github.com/stellarwp/prophecy-monorepo repository.

Thanks!" diff --git a/src/Shutdown/.gitattributes b/src/Shutdown/.gitattributes new file mode 100644 index 00000000..e82014a9 --- /dev/null +++ b/src/Shutdown/.gitattributes @@ -0,0 +1,7 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore paths when git creates an archive of this package +.gitattributes export-ignore +.gitignore export-ignore +.github export-ignore diff --git a/src/Shutdown/.gitignore b/src/Shutdown/.gitignore new file mode 100644 index 00000000..d1502b08 --- /dev/null +++ b/src/Shutdown/.gitignore @@ -0,0 +1,2 @@ +vendor/ +composer.lock diff --git a/src/Shutdown/Contracts/ShutdownRunner.php b/src/Shutdown/Contracts/ShutdownRunner.php new file mode 100644 index 00000000..d222d02c --- /dev/null +++ b/src/Shutdown/Contracts/ShutdownRunner.php @@ -0,0 +1,10 @@ + [!WARNING] +> **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). + +Foundation Shutdown runs contributed tasks once, in ascending priority order. Tasks with equal priorities retain contribution order. Requires PHP 8.3 or later. + +```sh +composer require stellarwp/foundation-shutdown:^2.0 +``` + +## Flush an application's logging buffer + +Implement `Terminable` for the work performed at shutdown. For a shared Monolog buffer: + +```php +use Monolog\Handler\BufferHandler; +use StellarWP\Foundation\Shutdown\Contracts\Terminable; + +final readonly class FlushLogs implements Terminable +{ + public function __construct(private BufferHandler $buffer) { + } + + public function terminate(): void { + $this->buffer->flush(); + } +} +``` + +After creating the Foundation container and binding the same `BufferHandler` used by the application logger, register the shutdown provider during WordPress bootstrap and contribute the task: + +```php +use StellarWP\Foundation\Container\Contracts\Resolver; +use StellarWP\Foundation\Shutdown\ShutdownProvider; +use StellarWP\Foundation\Shutdown\Task; + +$container->register(ShutdownProvider::class); +$container->mergeArrayVar( + ShutdownProvider::TASKS, + static function (Resolver $resolver): array { + $flush = $resolver->get(FlushLogs::class); + + return [ + new Task($flush, 100), + ]; + } +); +``` + +Contribute tasks before the runner is first resolved. Register the provider once. It attaches to WordPress `shutdown` at `PHP_INT_MAX`, skipping installation and plugin-uninstallation requests before resolving tasks. It attempts FastCGI or LiteSpeed response finishing when available, then runs the tasks. + +An optional registered PSR-3 logger receives diagnostics. A task failure or logging failure does not prevent remaining tasks from running. Termination is attempted once, including when a task fails; it is not a retry queue. + +Outside WordPress, construct `Runner` with `Task` objects and call `terminate()` at the application's shutdown boundary. Do not register the WordPress provider in a standalone CLI process. The runner is synchronous and does not enforce timeouts or guarantee delivery after a process crash. Each task must bound its own work; put durable delivery in a queue when required. + +For logging, schedule the flush after other tasks that may emit records. A long-running worker needs separate per-job flushes because this runner intentionally terminates only once. diff --git a/src/Shutdown/ResponseFinishingRunner.php b/src/Shutdown/ResponseFinishingRunner.php new file mode 100644 index 00000000..49a6b396 --- /dev/null +++ b/src/Shutdown/ResponseFinishingRunner.php @@ -0,0 +1,43 @@ +terminated) { + return; + } + + $this->terminated = true; + + foreach (['fastcgi_finish_request', 'litespeed_finish_request'] as $finishRequest) { + if (! function_exists($finishRequest)) { + continue; + } + + try { + if ($finishRequest()) { + break; + } + } catch (Throwable) { + // Response finishing is best-effort and must not block termination work. + } + } + + $this->runner->terminate(); + } +} diff --git a/src/Shutdown/Runner.php b/src/Shutdown/Runner.php new file mode 100644 index 00000000..d629819e --- /dev/null +++ b/src/Shutdown/Runner.php @@ -0,0 +1,117 @@ + + */ + private array $tasks; + + private bool $terminated = false; + + /** + * Validate and retain the contributed shutdown tasks and optional logger. + * + * @param array $tasks + */ + public function __construct( + array $tasks = [], + private readonly ?LoggerInterface $logger = null + ) { + foreach ($tasks as $task) { + if (! $task instanceof Task) { + throw new InvalidArgumentException('Shutdown tasks must be instances of Task.'); + } + } + + $this->tasks = array_values($tasks); + } + + /** + * {@inheritDoc} + */ + public function terminate(): void { + if ($this->terminated) { + return; + } + + $this->terminated = true; + + $tasks = $this->orderedTasks(); + + $this->log(LogLevel::DEBUG, 'Running shutdown tasks.', [ + 'task_count' => count($tasks), + ]); + + foreach ($tasks as $task) { + $context = [ + 'task' => $task->terminable::class, + 'priority' => $task->priority, + ]; + + $this->log(LogLevel::DEBUG, 'Running shutdown task.', $context); + + try { + $task->terminable->terminate(); + } catch (Throwable $exception) { + $this->log(LogLevel::ERROR, 'Shutdown task failed.', $context + [ + 'exception' => $exception, + ]); + } + } + } + + /** + * Logging must not interrupt application termination. + * + * @param array $context + */ + private function log(string $level, string $message, array $context = []): void { + try { + $this->logger?->log($level, $message, $context); + } catch (Throwable) { + // The remaining termination work is more important than diagnostics. + } + } + + /** + * Return tasks in stable priority order. + * + * @return list + */ + private function orderedTasks(): array { + /** + * @var list $indexedTasks + */ + $indexedTasks = []; + + foreach ($this->tasks as $index => $task) { + $indexedTasks[] = [ + 'index' => $index, + 'task' => $task, + ]; + } + + usort( + $indexedTasks, + static fn (array $left, array $right): int => ($left['task']->priority <=> $right['task']->priority) + ?: ($left['index'] <=> $right['index']) + ); + + return array_map( + static fn (array $entry): Task => $entry['task'], + $indexedTasks + ); + } +} diff --git a/src/Shutdown/ShutdownProvider.php b/src/Shutdown/ShutdownProvider.php new file mode 100644 index 00000000..19e2f7a8 --- /dev/null +++ b/src/Shutdown/ShutdownProvider.php @@ -0,0 +1,44 @@ +container->mergeArrayVar(self::TASKS, []); + + $this->container->when(Runner::class) + ->needs('$tasks') + ->give(static fn (C $c): array => $c->get(self::TASKS)); + + $this->container->singletonDecorators(ShutdownRunner::class, [ + ResponseFinishingRunner::class, + Runner::class, + ]); + + add_action( + 'shutdown', + function (): void { + // Request state can change after registration; skip before resolving tasks or finishing the response. + if (defined('WP_UNINSTALL_PLUGIN') || wp_installing()) { + return; + } + + $this->container->get(ShutdownRunner::class)->terminate(); + }, + PHP_INT_MAX + ); + } +} diff --git a/src/Shutdown/Task.php b/src/Shutdown/Task.php new file mode 100644 index 00000000..80a3e0e3 --- /dev/null +++ b/src/Shutdown/Task.php @@ -0,0 +1,17 @@ +=8.3", + "psr/log": ">=1.0", + "stellarwp/foundation-container": "^2.0" + }, + "autoload": { + "psr-4": { + "StellarWP\\Foundation\\Shutdown\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-main": "2.0.x-dev" + } + } +} diff --git a/src/View/.gitattributes b/src/View/.gitattributes new file mode 100644 index 00000000..e82014a9 --- /dev/null +++ b/src/View/.gitattributes @@ -0,0 +1,7 @@ +# Path-based git attributes +# https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html + +# Ignore paths when git creates an archive of this package +.gitattributes export-ignore +.gitignore export-ignore +.github export-ignore diff --git a/src/View/.gitignore b/src/View/.gitignore new file mode 100644 index 00000000..d1502b08 --- /dev/null +++ b/src/View/.gitignore @@ -0,0 +1,2 @@ +vendor/ +composer.lock diff --git a/src/View/Contracts/DirectoryAwareView.php b/src/View/Contracts/DirectoryAwareView.php new file mode 100644 index 00000000..cdd2ddb3 --- /dev/null +++ b/src/View/Contracts/DirectoryAwareView.php @@ -0,0 +1,18 @@ + $data Values made available to the renderer. + * + * @throws Throwable When rendering fails. + */ + public function render(string $name, array $data = []): string; +} diff --git a/src/View/Exceptions/ViewNotFoundException.php b/src/View/Exceptions/ViewNotFoundException.php new file mode 100644 index 00000000..2d03e866 --- /dev/null +++ b/src/View/Exceptions/ViewNotFoundException.php @@ -0,0 +1,12 @@ +directory = $resolved; + } + + /** + * {@inheritDoc} + */ + public function withDirectory(string $directory): static { + return new self($directory); + } + + /** + * {@inheritDoc} + * + * @throws InvalidArgumentException When the view name is invalid or the data contains a reserved key. + * @throws RuntimeException When the view leaves output buffering in an invalid state. + * @throws ViewNotFoundException When the view does not exist, is unreadable, or resolves outside the configured directory. + * @throws \Throwable When the view itself throws. + */ + public function render(string $name, array $data = []): string { + foreach (self::RESERVED_DATA_KEYS as $reservedKey) { + if (array_key_exists($reservedKey, $data)) { + throw new InvalidArgumentException(sprintf('View data key "%s" is reserved by PhpView.', $reservedKey)); + } + } + + $path = $this->resolve($name); + $bufferLevel = ob_get_level(); + $renderBufferLevel = $bufferLevel + 1; + $renderBufferTouched = false; + + ob_start(static function () use (&$renderBufferTouched): string { + $renderBufferTouched = true; + + return ''; + }); + + try { + self::renderFile($path, $data); + + if ($renderBufferTouched || ob_get_level() !== $renderBufferLevel) { + throw new RuntimeException(sprintf('The view "%s" must leave output buffering unchanged.', $name)); + } + + $output = ob_get_clean(); + + if ($output === false) { + throw new RuntimeException(sprintf('The output buffer for view "%s" could not be read.', $name)); + } + + return $output; + } finally { + self::discardBuffersAbove($bufferLevel); + } + } + + /** + * Render a PHP file in an isolated static scope with the supplied view data. + * + * @param array $foundationViewData + */ + private static function renderFile(string $foundationViewPath, array $foundationViewData): void { + extract($foundationViewData, EXTR_SKIP); + + require $foundationViewPath; + } + + /** + * Remove buffers opened while rendering without closing a caller-owned buffer. + * + * PHP cannot remove a buffer created without PHP_OUTPUT_HANDLER_REMOVABLE. + */ + private static function discardBuffersAbove(int $bufferLevel): void { + while (ob_get_level() > $bufferLevel) { + $status = ob_get_status(); + + if (($status['flags'] & PHP_OUTPUT_HANDLER_REMOVABLE) === 0 || ! ob_end_clean()) { + return; + } + } + } + + /** + * Resolve a relative view name to a readable PHP file inside the configured directory. + * + * @throws InvalidArgumentException When the view name is empty, absolute, or traverses parent directories. + * @throws ViewNotFoundException When the view cannot be safely resolved and read. + */ + private function resolve(string $name): string { + $this->validateName($name); + + $relative = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $name) . '.php'; + $path = realpath($this->directory . DIRECTORY_SEPARATOR . $relative); + + if ($path === false || ! is_file($path) || ! is_readable($path) || ! $this->contains($path)) { + throw new ViewNotFoundException(sprintf('The view "%s" could not be found in "%s".', $name, $this->directory)); + } + + return $path; + } + + /** + * Reject names that could select files outside the configured directory. + * + * @throws InvalidArgumentException When the name is empty, absolute, or contains a parent-directory segment. + */ + private function validateName(string $name): void { + if ( + trim($name) === '' + || str_contains($name, "\0") + || str_starts_with($name, '/') + || str_starts_with($name, '\\') + || preg_match('/^[A-Za-z]:[\\\\\/]/', $name) === 1 + ) { + throw new InvalidArgumentException('View names must be non-empty relative paths.'); + } + + $segments = preg_split('#[\\\\/]#', $name); + + if ($segments === false || in_array('..', $segments, true)) { + throw new InvalidArgumentException('View names cannot traverse parent directories.'); + } + } + + /** + * Determine whether a canonical file path remains inside the canonical view directory. + */ + private function contains(string $path): bool { + $directory = rtrim($this->directory, '/\\') . DIRECTORY_SEPARATOR; + + if (DIRECTORY_SEPARATOR === '\\') { + return str_starts_with(strtolower($path), strtolower($directory)); + } + + return str_starts_with($path, $directory); + } +} diff --git a/src/View/README.md b/src/View/README.md new file mode 100644 index 00000000..43b3e100 --- /dev/null +++ b/src/View/README.md @@ -0,0 +1,42 @@ +# Foundation View + +> [!WARNING] +> **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). + +Foundation View renders trusted PHP templates to strings. It confines template selection to a configured directory and supports immutable directory changes. Requires PHP 8.3 or later. + +```sh +composer require stellarwp/foundation-view:^2.0 +``` + +## Render a template + +```php +use StellarWP\Foundation\View\PhpView; + +$view = new PhpView(__DIR__ . '/views'); +$html = $view->render('account/summary', [ + 'name' => 'Alex', +]); +``` + +This renders `views/account/summary.php` with `$name` available to the template. Supply names without the `.php` extension. Templates are executable PHP, so only use trusted application templates and escape values for their output context, e.g. `esc_html($name)` in WordPress HTML. + +## Container registration + +Set `view.directory` to an existing readable directory, then register `StellarWP\Foundation\View\ViewProvider`. Inject `Contracts\View` for rendering or `Contracts\DirectoryAwareView` when a consumer needs directory selection. Both resolve to the same configured `PhpView` instance by default. + +```php +$otherView = $view->withDirectory(__DIR__ . '/email-views'); +$html = $otherView->render('receipt', [ + 'name' => 'Alex', +]); +``` + +`withDirectory()` returns a new renderer and leaves the original unchanged. + +## Template boundaries + +Absolute names, parent-directory traversal and null bytes are rejected. Resolved files must stay inside the configured directory, including through symlinks. Missing or inaccessible templates throw `Exceptions\ViewNotFoundException`. + +Rendering captures output and cleans up removable buffers opened by the template when it fails. Templates must leave the renderer's output buffer intact and must not close, flush or replace it. This is not a sandbox for untrusted PHP; templates can still perform arbitrary PHP operations. diff --git a/src/View/ViewProvider.php b/src/View/ViewProvider.php new file mode 100644 index 00000000..7432ff3f --- /dev/null +++ b/src/View/ViewProvider.php @@ -0,0 +1,45 @@ +registerView(); + } + + /** + * Validate the view directory and register the shared renderer instance. + * + * @throws InvalidArgumentException When view.directory is not a non-empty string. + */ + private function registerView(): void { + $directory = $this->config->get('view.directory'); + + if (! is_string($directory) || trim($directory) === '') { + throw new InvalidArgumentException('The view.directory configuration value must be a non-empty string.'); + } + + $this->container->when(PhpView::class) + ->needs('$directory') + ->give($directory); + + $this->container->singleton(PhpView::class); + $this->container->singleton(View::class, static fn (C $c): PhpView => $c->get(PhpView::class)); + $this->container->singleton(DirectoryAwareView::class, static fn (C $c): PhpView => $c->get(PhpView::class)); + } +} diff --git a/src/View/composer.json b/src/View/composer.json new file mode 100644 index 00000000..14cc05c6 --- /dev/null +++ b/src/View/composer.json @@ -0,0 +1,24 @@ +{ + "name": "stellarwp/foundation-view", + "type": "library", + "description": "Render scoped PHP views to strings with immutable runtime directory selection.", + "license": "GPL-2.0-or-later", + "config": { + "vendor-dir": "vendor", + "preferred-install": "dist" + }, + "require": { + "php": ">=8.3", + "stellarwp/foundation-container": "^2.0" + }, + "autoload": { + "psr-4": { + "StellarWP\\Foundation\\View\\": "" + } + }, + "extra": { + "branch-alias": { + "dev-main": "2.0.x-dev" + } + } +} diff --git a/src/WPCli/.github/workflows/close-pull-request.yml b/src/WPCli/.github/workflows/close-pull-request.yml deleted file mode 100644 index 6bfbabee..00000000 --- a/src/WPCli/.github/workflows/close-pull-request.yml +++ /dev/null @@ -1,13 +0,0 @@ -name: Close Pull Request - -on: - pull_request_target: - types: [opened] - -jobs: - run: - runs-on: ubuntu-latest - steps: - - uses: superbrothers/close-pull-request@v3 - with: - comment: "This is a read-only repository. Please submit your PR on the https://github.com/stellarwp/foundation repository.

Thanks!" diff --git a/tests/Feature/Log/ConfiguredLoggerTest.php b/tests/Feature/Log/ConfiguredLoggerTest.php new file mode 100644 index 00000000..de9d98e4 --- /dev/null +++ b/tests/Feature/Log/ConfiguredLoggerTest.php @@ -0,0 +1,333 @@ +configureLogger([ + 'channel' => 'stack', + 'channels' => [ + 'stack' => ['channels' => ['errorlog', 'audit']], + 'audit' => ['handler' => TestHandler::class], + ], + ]); + $audit = new TestHandler(); + $errorlog = new TestHandler(); + $this->container->singleton(TestHandler::class, $audit); + $this->container->singleton(ErrorLogHandler::class, $errorlog); + $context = [ + 'site_id' => 42, + 'exception' => new RuntimeException('Remote catalog unavailable.'), + ]; + + $this->container->get(LoggerInterface::class)->error( + 'Catalog import for site {site_id} failed: {unknown}.', + $context + ); + + foreach ([$audit, $errorlog] as $handler) { + $this->assertTrue($handler->hasError([ + 'message' => 'Catalog import for site 42 failed: {unknown}.', + 'context' => $context, + ])); + } + } + + public function test_a_stack_combines_builtin_and_custom_handlers(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'level' => 'warning', + 'channels' => [ + 'stack' => [ + 'channels' => ['console', 'errorlog', 'audit'], + ], + 'console' => ['with' => ['stream' => 'php://memory']], + 'audit' => ['handler' => TestHandler::class, 'formatter' => JsonFormatter::class], + ], + ]); + $audit = new TestHandler(); + $errorlog = new TestHandler(); + $this->container->singleton(TestHandler::class, $audit); + $this->container->singleton(ErrorLogHandler::class, $errorlog); + + $logger = $this->container->get(LoggerInterface::class); + $this->assertInstanceOf(Logger::class, $logger); + $logger->info('Below threshold.'); + $logger->warning('Catalog import failed.', ['site_id' => 42]); + + $this->assertSame($logger, $this->container->get(LoggerInterface::class)); + $this->assertCount(1, $audit->getRecords()); + $this->assertCount(1, $errorlog->getRecords()); + $this->assertTrue($errorlog->hasWarning('Catalog import failed.')); + $this->assertSame(['site_id' => 42], $errorlog->getRecords()[0]['context']); + $this->assertInstanceOf(JsonFormatter::class, $audit->getFormatter()); + $console = $logger->getHandlers()[2]; + $this->assertInstanceOf(StreamHandler::class, $console); + $this->assertSame([$audit, $errorlog, $console], $logger->getHandlers()); + $stream = $console->getStream(); + $this->assertIsResource($stream); + rewind($stream); + $this->assertStringContainsString('Catalog import failed.', stream_get_contents($stream)); + } + + public function test_configured_stack_members_replace_the_default_list(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'channels' => [ + 'stack' => ['channels' => ['audit']], + 'audit' => ['handler' => TestHandler::class], + ], + ]); + $audit = new TestHandler(); + $this->container->singleton(TestHandler::class, $audit); + + $logger = $this->container->get(LoggerInterface::class); + $this->assertInstanceOf(Logger::class, $logger); + $logger->debug('Uses the existing default level.'); + + $this->assertSame([$audit], $logger->getHandlers()); + $this->assertTrue($audit->hasDebugRecords()); + } + + public function test_a_custom_channel_resolves_handler_dependencies_through_the_container(): void { + $this->configureLogger([ + 'channel' => 'audit', + 'channels' => ['audit' => ['handler' => GroupHandler::class]], + ]); + $audit = new TestHandler(); + $this->container->when(GroupHandler::class)->needs('$handlers')->give([$audit]); + + $this->container->get(LoggerInterface::class)->info('Custom handler dependency.'); + + $this->assertTrue($audit->hasInfo('Custom handler dependency.')); + } + + public function test_an_application_can_define_a_named_stack(): void { + $this->configureLogger([ + 'channel' => 'background', + 'channels' => [ + 'background' => ['channels' => ['audit']], + 'audit' => ['handler' => TestHandler::class], + ], + ]); + $audit = new TestHandler(); + $this->container->singleton(TestHandler::class, $audit); + + $this->container->get(LoggerInterface::class)->info('Background work.'); + + $this->assertSame('background', $audit->getRecords()[0]['channel']); + } + + public function test_an_unknown_stack_member_fails_when_the_logger_is_resolved(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'channels' => ['stack' => ['channels' => ['missing']]], + ]); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('log channel missing must define a handler.'); + + $this->container->get(LoggerInterface::class); + } + + public function test_an_empty_stack_discards_records(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'channels' => ['stack' => ['channels' => []]], + ]); + + $logger = $this->container->get(LoggerInterface::class); + $this->assertInstanceOf(Logger::class, $logger); + $logger->warning('No destinations configured.'); + + $this->assertSame([], $logger->getHandlers()); + } + + /** + * @dataProvider selectedChannels + */ + #[DataProvider('selectedChannels')] + public function test_a_console_destination_is_preserved_when_selected_through_a_stack(string $channel): void { + $path = $this->prepare_temp_dir('log-channels') . '/console.log'; + $this->configureLogger([ + 'channel' => $channel, + 'channels' => [ + 'console' => ['with' => ['stream' => $path]], + 'stack' => ['channels' => ['console']], + 'background' => ['channels' => ['console']], + ], + ]); + + $logger = $this->container->get(LoggerInterface::class); + $this->assertInstanceOf(Logger::class, $logger); + $handler = $logger->getHandlers()[0]; + $this->assertInstanceOf(StreamHandler::class, $handler); + $this->assertSame($path, $handler->getUrl()); + + $logger->info('Catalog imported.'); + + $this->assertStringContainsString('Catalog imported.', (string) file_get_contents($path)); + } + + /** + * @return iterable + */ + public static function selectedChannels(): iterable { + yield 'direct' => ['console']; + + yield 'default stack' => ['stack']; + + yield 'custom stack' => ['background']; + } + + public function test_stream_channels_keep_independent_destinations_and_formatters(): void { + $directory = $this->prepare_temp_dir('log-channels'); + $this->configureLogger([ + 'channel' => 'stack', + 'level' => 'warning', + 'channels' => [ + 'stack' => ['channels' => ['plain', 'json']], + 'plain' => [ + 'handler' => StreamHandler::class, + 'formatter' => LineFormatter::class, + 'with' => ['stream' => $directory . '/plain.log'], + ], + 'json' => [ + 'handler' => StreamHandler::class, + 'formatter' => JsonFormatter::class, + 'with' => ['stream' => $directory . '/json.log'], + ], + ], + ]); + $this->container->singleton(LineFormatter::class, new LineFormatter("%message%\n")); + + $logger = $this->container->get(LoggerInterface::class); + $this->assertInstanceOf(Logger::class, $logger); + [$json, $plain] = $logger->getHandlers(); + $this->assertNotSame($plain, $json); + + $logger->info('Below threshold.'); + $logger->warning('Catalog import failed.', ['site_id' => 42]); + + $this->assertSame("Catalog import failed.\n", file_get_contents($directory . '/plain.log')); + $record = json_decode((string) file_get_contents($directory . '/json.log'), true, 512, JSON_THROW_ON_ERROR); + $this->assertSame('Catalog import failed.', $record['message']); + $this->assertSame(['site_id' => 42], $record['context']); + } + + public function test_transient_custom_handlers_keep_independent_channel_formatters(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'channels' => [ + 'stack' => ['channels' => ['plain', 'json']], + 'plain' => ['handler' => TestHandler::class, 'formatter' => LineFormatter::class], + 'json' => ['handler' => TestHandler::class, 'formatter' => JsonFormatter::class], + ], + ]); + + $logger = $this->container->get(LoggerInterface::class); + $this->assertInstanceOf(Logger::class, $logger); + [$json, $plain] = $logger->getHandlers(); + $this->assertInstanceOf(TestHandler::class, $json); + $this->assertInstanceOf(TestHandler::class, $plain); + $this->assertNotSame($plain, $json); + $this->assertInstanceOf(LineFormatter::class, $plain->getFormatter()); + $this->assertInstanceOf(JsonFormatter::class, $json->getFormatter()); + + $logger->info('Both custom channels receive this.'); + + $this->assertCount(1, $plain->getRecords()); + $this->assertCount(1, $json->getRecords()); + } + + public function test_a_shared_custom_handler_cannot_be_reconfigured_as_two_stack_channels(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'channels' => [ + 'stack' => ['channels' => ['plain', 'json']], + 'plain' => ['handler' => TestHandler::class, 'formatter' => LineFormatter::class], + 'json' => ['handler' => TestHandler::class, 'formatter' => JsonFormatter::class], + ], + ]); + $this->container->singleton(TestHandler::class, new TestHandler()); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('shares a handler instance'); + + $this->container->get(LoggerInterface::class); + } + + public function test_a_single_custom_channel_can_keep_its_shared_handlers_formatter(): void { + $this->configureLogger([ + 'channel' => 'console', + 'channels' => [ + 'console' => ['handler' => TestHandler::class, 'formatter' => null], + ], + ]); + $handler = new TestHandler(); + $formatter = new JsonFormatter(); + $handler->setFormatter($formatter); + $this->container->singleton(TestHandler::class, $handler); + + $this->container->get(LoggerInterface::class)->info('Use the configured handler.'); + + $this->assertSame($formatter, $handler->getFormatter()); + $this->assertTrue($handler->hasInfo('Use the configured handler.')); + } + + public function test_a_non_bubbling_handler_stops_delivery_to_earlier_stack_entries(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'channels' => [ + 'stack' => ['channels' => ['audit', 'stop']], + 'audit' => ['handler' => TestHandler::class], + 'stop' => ['handler' => GroupHandler::class], + ], + ]); + $audit = new TestHandler(); + $last = new TestHandler(); + $this->container->singleton(TestHandler::class, $audit); + $this->container->singleton(GroupHandler::class, new GroupHandler([$last], false)); + + $this->container->get(LoggerInterface::class)->warning('Handled by the last entry.'); + + $this->assertTrue($last->hasWarning('Handled by the last entry.')); + $this->assertSame([], $audit->getRecords()); + } + + public function test_an_application_can_replace_the_logger_before_it_resolves(): void { + $this->configureLogger(['channel' => 'invalid']); + $logger = new NullLogger(); + $this->container->singleton(LoggerInterface::class, $logger); + + $this->assertSame($logger, $this->container->get(LoggerInterface::class)); + } + + /** + * @param array $configuration + */ + private function configureLogger(array $configuration): void { + $dataDirectory = $this->data_dir(); + $this->container = (new ContainerFactory())->create(new ArrayConfiguration(['log' => $configuration])); + $this->container->singleton(TestCase::DATA_DIR, $dataDirectory); + $this->container->register(LogProvider::class); + } +} diff --git a/tests/Feature/Log/Handlers/NullHandlerTest.php b/tests/Feature/Log/Handlers/NullHandlerTest.php index 251450e0..2f5f4bef 100644 --- a/tests/Feature/Log/Handlers/NullHandlerTest.php +++ b/tests/Feature/Log/Handlers/NullHandlerTest.php @@ -2,6 +2,8 @@ namespace StellarWP\Foundation\Tests\Feature\Log\Handlers; +use Monolog\Handler\TestHandler; +use Monolog\Logger; use PHPUnit\Framework\Attributes\DataProvider; use StellarWP\Foundation\Log\Handlers\NullHandler; use StellarWP\Foundation\Log\LogLevel; @@ -9,63 +11,45 @@ final class NullHandlerTest extends TestCase { - private NullHandler $handler; - - protected function setUp(): void { - parent::setUp(); - - $this->handler = $this->container->get(NullHandler::class); - } - /** - * @param array{level: int, result: bool} $input + * @param array{level: LogLevel::*, result: bool} $input * * @dataProvider logProvider */ #[DataProvider('logProvider')] - public function test_it_null_logs_valid_levels(array $input): void { - $this->assertSame( - $input['result'], - // @phpstan-ignore-next-line - $this->handler->handle([ - 'level' => $input['level'], - ]) - ); + public function test_it_discards_matching_records_and_leaves_lower_levels_for_other_handlers(array $input): void { + $captured = new TestHandler(); + $logger = new Logger('tests', [ + new NullHandler(LogLevel::WARNING), + $captured, + ]); + + $logger->log(LogLevel::toPsrLogLevel($input['level']), 'A record subject to the null threshold.'); + + $this->assertCount($input['result'] ? 0 : 1, $captured->getRecords()); } /** - * @return array> + * @return array> */ public static function logProvider(): array { return [ - [ - [ - 'level' => 1, - 'result' => false, - ], - ], - [ - [ - 'level' => 50, - 'result' => false, - ], - ], [ [ 'level' => LogLevel::DEBUG, - 'result' => true, + 'result' => false, ], ], [ [ 'level' => LogLevel::INFO, - 'result' => true, + 'result' => false, ], ], [ [ 'level' => LogLevel::NOTICE, - 'result' => true, + 'result' => false, ], ], [ diff --git a/tests/Feature/Log/InvalidLoggerTest.php b/tests/Feature/Log/InvalidLoggerTest.php index b112377c..80d324fe 100644 --- a/tests/Feature/Log/InvalidLoggerTest.php +++ b/tests/Feature/Log/InvalidLoggerTest.php @@ -2,10 +2,10 @@ namespace StellarWP\Foundation\Tests\Feature\Log; -use lucatume\DI52\ContainerException; use PHPUnit\Framework\Attributes\PreserveGlobalState; use PHPUnit\Framework\Attributes\RunInSeparateProcess; use Psr\Log\LoggerInterface; +use StellarWP\Foundation\Container\Exceptions\ContainerException; use StellarWP\Foundation\Tests\TestCase; final class InvalidLoggerTest extends TestCase diff --git a/tests/Feature/Log/NullLoggerTest.php b/tests/Feature/Log/NullLoggerTest.php index 5a3d01f6..74becf25 100644 --- a/tests/Feature/Log/NullLoggerTest.php +++ b/tests/Feature/Log/NullLoggerTest.php @@ -22,6 +22,7 @@ protected function setUp(): void { public function test_it_can_change_log_channels(): void { $logger = $this->container->get(LoggerInterface::class); $this->assertInstanceOf(Logger::class, $logger); + $this->assertSame($logger, $this->container->get(LoggerInterface::class)); $handler = $logger->getHandlers()[0]; $this->assertInstanceOf(NullHandler::class, $handler); } diff --git a/tests/Feature/Log/StackLoggerTest.php b/tests/Feature/Log/StackLoggerTest.php index 7ae55e67..9416dd5c 100644 --- a/tests/Feature/Log/StackLoggerTest.php +++ b/tests/Feature/Log/StackLoggerTest.php @@ -27,10 +27,12 @@ public function test_it_has_the_correct_logger_handlers_when_running_tests(): vo $this->assertSame('debug', $_ENV['TEST_LOG_LEVEL']); - /** @var AbstractProcessingHandler $handler */ + /** + * @var AbstractProcessingHandler $handler + */ foreach ($logger->getHandlers() as $handler) { // https://github.com/Seldaek/monolog/blob/main/doc/01-usage.md#log-levels - $this->assertSame(100, $handler->getLevel()); + $this->assertSame(Logger::toMonologLevel('debug'), $handler->getLevel()); $this->assertThat($handler, $this->logicalOr( $this->isInstanceOf(ErrorLogHandler::class), diff --git a/tests/Feature/Log/UnavailableErrorLogLoggerTest.php b/tests/Feature/Log/UnavailableErrorLogLoggerTest.php index 58e3317f..f04d53d8 100644 --- a/tests/Feature/Log/UnavailableErrorLogLoggerTest.php +++ b/tests/Feature/Log/UnavailableErrorLogLoggerTest.php @@ -9,7 +9,6 @@ use PHPUnit\Framework\Attributes\RunInSeparateProcess; use Psr\Log\LoggerInterface; use StellarWP\Foundation\Log\Handlers\NullHandler; -use StellarWP\Foundation\Log\LogProvider; use StellarWP\Foundation\Tests\TestCase; final class UnavailableErrorLogLoggerTest extends TestCase @@ -20,7 +19,7 @@ protected function setUp(): void { #[RunInSeparateProcess] #[PreserveGlobalState(false)] public function test_it_falls_back_to_the_null_handler_when_error_log_is_unavailable(): void { - $_ENV['TEST_LOG_CHANNEL'] = LogProvider::CHANNEL_ERRORLOG; + $_ENV['TEST_LOG_CHANNEL'] = 'errorlog'; parent::setUp(); diff --git a/tests/Support/Fixtures/Container/CallbackListener.php b/tests/Support/Fixtures/Container/CallbackListener.php new file mode 100644 index 00000000..41e4580d --- /dev/null +++ b/tests/Support/Fixtures/Container/CallbackListener.php @@ -0,0 +1,18 @@ +calls++; + } + + public function fail(): void { + throw new RuntimeException('Callback failed.'); + } +} diff --git a/tests/Support/Fixtures/Container/ConfigurationReadingProvider.php b/tests/Support/Fixtures/Container/ConfigurationReadingProvider.php new file mode 100644 index 00000000..28b9ae0f --- /dev/null +++ b/tests/Support/Fixtures/Container/ConfigurationReadingProvider.php @@ -0,0 +1,14 @@ +container->singleton(self::VALUE, $this->config->get('fixture.value')); + } +} diff --git a/tests/Support/Fixtures/Container/FixedConfiguration.php b/tests/Support/Fixtures/Container/FixedConfiguration.php new file mode 100644 index 00000000..6131f43c --- /dev/null +++ b/tests/Support/Fixtures/Container/FixedConfiguration.php @@ -0,0 +1,71 @@ + $values + */ + public function __construct( + private array $values + ) { + } + + /** + * {@inheritDoc} + */ + public function all(): array { + return $this->values; + } + + /** + * {@inheritDoc} + */ + public function has(string $key): bool { + return $this->find($key)['exists']; + } + + /** + * {@inheritDoc} + */ + public function get(string $key, mixed $default = null): mixed { + $result = $this->find($key); + + return $result['exists'] ? $result['value'] : $default; + } + + /** + * Find an exact key or traverse its dotted path through the fixed values. + * + * @return array{exists: bool, value: mixed} + */ + private function find(string $key): array { + if (array_key_exists($key, $this->values)) { + return [ + 'exists' => true, + 'value' => $this->values[$key], + ]; + } + + $value = $this->values; + + foreach (explode('.', $key) as $segment) { + if (! is_array($value) || ! array_key_exists($segment, $value)) { + return [ + 'exists' => false, + 'value' => null, + ]; + } + + $value = $value[$segment]; + } + + return [ + 'exists' => true, + 'value' => $value, + ]; + } +} diff --git a/tests/Support/Fixtures/Container/IndependentProvider.php b/tests/Support/Fixtures/Container/IndependentProvider.php new file mode 100644 index 00000000..729dfc90 --- /dev/null +++ b/tests/Support/Fixtures/Container/IndependentProvider.php @@ -0,0 +1,23 @@ +listener->listen(); + $this->container->singleton('application.listener', $this->listener); + } +} diff --git a/tests/Support/Fixtures/Container/TestProvider.php b/tests/Support/Fixtures/Container/TestProvider.php index 24020fda..e296624c 100644 --- a/tests/Support/Fixtures/Container/TestProvider.php +++ b/tests/Support/Fixtures/Container/TestProvider.php @@ -2,16 +2,13 @@ namespace StellarWP\Foundation\Tests\Support\Fixtures\Container; -use Adbar\Dot; -use StellarWP\Foundation\Container\Contracts\Container; use StellarWP\Foundation\Container\Contracts\Provider; final class TestProvider extends Provider { - public function __construct(Container $container) { - parent::__construct($container, new Dot()); - } + public static int $registrationCount = 0; public function register(): void { + self::$registrationCount++; } } diff --git a/tests/Support/Fixtures/Container/ThrowingContainerService.php b/tests/Support/Fixtures/Container/ThrowingContainerService.php new file mode 100644 index 00000000..9149e038 --- /dev/null +++ b/tests/Support/Fixtures/Container/ThrowingContainerService.php @@ -0,0 +1,15 @@ +buffer->flush(); + } +} diff --git a/tests/Support/Fixtures/Shutdown/CallbackTerminable.php b/tests/Support/Fixtures/Shutdown/CallbackTerminable.php new file mode 100644 index 00000000..5ea7b66b --- /dev/null +++ b/tests/Support/Fixtures/Shutdown/CallbackTerminable.php @@ -0,0 +1,18 @@ +callback)(); + } +} diff --git a/tests/Support/Fixtures/Shutdown/finish-request-functions.php b/tests/Support/Fixtures/Shutdown/finish-request-functions.php new file mode 100644 index 00000000..9ef3f06a --- /dev/null +++ b/tests/Support/Fixtures/Shutdown/finish-request-functions.php @@ -0,0 +1,21 @@ +create(new ArrayConfiguration([])); +$container->register(ShutdownProvider::class); +$container->singleton(ShutdownRunner::class, static function (): ShutdownRunner { + throw new RuntimeException('Shutdown must not resolve the runner during uninstall.'); +}); + +if ($arguments[2] === 'after') { + define('WP_UNINSTALL_PLUGIN', 'example/example.php'); +} + +do_action('shutdown'); +echo 'skipped'; diff --git a/tests/Support/Fixtures/View/DelegatingDirectoryView.php b/tests/Support/Fixtures/View/DelegatingDirectoryView.php new file mode 100644 index 00000000..dc1cbe0e --- /dev/null +++ b/tests/Support/Fixtures/View/DelegatingDirectoryView.php @@ -0,0 +1,24 @@ +view->withDirectory($directory); + } + + public function render(string $name, array $data = []): string { + return $this->view->render($name, $data); + } +} diff --git a/tests/Support/Fixtures/View/JsonView.php b/tests/Support/Fixtures/View/JsonView.php new file mode 100644 index 00000000..83edfc48 --- /dev/null +++ b/tests/Support/Fixtures/View/JsonView.php @@ -0,0 +1,22 @@ + $name, + 'data' => $data, + ], JSON_THROW_ON_ERROR); + } +} diff --git a/tests/TestCase.php b/tests/TestCase.php index 6584059d..a3c4b08b 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -2,13 +2,12 @@ namespace StellarWP\Foundation\Tests; -use Adbar\Dot; use Mockery; use ReflectionObject; -use StellarWP\ContainerContract\ContainerInterface; -use StellarWP\Foundation\Container\ContainerAdapter; +use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; +use StellarWP\Foundation\Container\ContainerFactory; use StellarWP\Foundation\Container\Contracts\Container; -use StellarWP\Foundation\Container\Contracts\Providable; +use StellarWP\Foundation\Container\Contracts\Provider; use StellarWP\Foundation\Log\LogProvider; use StellarWP\Foundation\Tests\Support\Traits\WithDataDir; @@ -24,7 +23,7 @@ class TestCase extends \PHPUnit\Framework\TestCase protected Container $container; /** - * @var array> + * @var array> */ private array $providers = [ LogProvider::class, @@ -52,10 +51,9 @@ protected function tearDown(): void { protected function setUp(): void { parent::setUp(); - $this->container = new ContainerAdapter(new \lucatume\DI52\Container()); - $this->container->bind(Container::class, $this->container); - $this->container->bind(ContainerInterface::class, $this->container); - $this->container->singleton(Dot::class, new Dot(require __DIR__ . '/config.php')); + $this->container = (new ContainerFactory())->create( + new ArrayConfiguration(require __DIR__ . '/config.php') + ); $this->container->singleton(self::TEST_DIR, __DIR__); $this->container->singleton(self::DATA_DIR, __DIR__ . '/_data/'); $this->container->singleton(self::FIXTURE_DIR, fn (): string => dirname((string) (new ReflectionObject($this))->getFileName()) . '/fixtures'); diff --git a/tests/Unit/Cli/CliProviderTest.php b/tests/Unit/Cli/CliProviderTest.php index a802d903..a061ce42 100644 --- a/tests/Unit/Cli/CliProviderTest.php +++ b/tests/Unit/Cli/CliProviderTest.php @@ -2,9 +2,6 @@ namespace StellarWP\Foundation\Tests\Unit\Cli; -use Adbar\Dot; -use lucatume\DI52\Container as DI52Container; -use StellarWP\ContainerContract\ContainerInterface; use StellarWP\Foundation\Cli\Application; use StellarWP\Foundation\Cli\CliProvider; use StellarWP\Foundation\Cli\Commands\Make\WPCliCommand; @@ -18,17 +15,16 @@ use StellarWP\Foundation\Cli\Generation\StubRenderer; use StellarWP\Foundation\Cli\Generation\StubResolver; use StellarWP\Foundation\Cli\Generation\WordPressClassNameResolver; -use StellarWP\Foundation\Container\ContainerAdapter; -use StellarWP\Foundation\Container\Contracts\Container; +use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; +use StellarWP\Foundation\Container\ContainerFactory; use StellarWP\Foundation\Tests\TestCase; final class CliProviderTest extends TestCase { public function test_it_registers_cli_services(): void { - $container = new ContainerAdapter(new DI52Container()); - $container->bind(Container::class, $container); - $container->bind(ContainerInterface::class, $container); - $container->singleton(Dot::class, new Dot()); + $configuration = new ArrayConfiguration(); + $factory = new ContainerFactory(); + $container = $factory->create($configuration); $container->register(CliProvider::class); $this->assertInstanceOf(Application::class, $container->get(Application::class)); diff --git a/tests/Unit/Cli/Commands/Package/CreateCommandTest.php b/tests/Unit/Cli/Commands/Package/CreateCommandTest.php index a8928a7e..7a10154c 100644 --- a/tests/Unit/Cli/Commands/Package/CreateCommandTest.php +++ b/tests/Unit/Cli/Commands/Package/CreateCommandTest.php @@ -132,7 +132,6 @@ public function test_it_prompts_to_scaffold_a_missing_package_before_creating_th ['composer', 'monorepo', 'merge'], ], $processRunner->commands); $this->assertFileExists($rootPath . '/src/WPCli/composer.json'); - $this->assertFileExists($rootPath . '/src/WPCli/.github/workflows/close-pull-request.yml'); $this->assertStringContainsString('"name": "stellarwp/foundation-wpcli"', (string) file_get_contents($rootPath . '/src/WPCli/composer.json')); } diff --git a/tests/Unit/Cli/Commands/Package/PackageFilesValidatorTest.php b/tests/Unit/Cli/Commands/Package/PackageFilesValidatorTest.php index 8637c72a..2d9d7b87 100644 --- a/tests/Unit/Cli/Commands/Package/PackageFilesValidatorTest.php +++ b/tests/Unit/Cli/Commands/Package/PackageFilesValidatorTest.php @@ -23,7 +23,6 @@ public function test_it_reports_missing_required_package_files(): void { 'README.md', '.gitattributes', '.gitignore', - '.github/workflows/close-pull-request.yml', ], $missingFiles); } } diff --git a/tests/Unit/Cli/Commands/Package/PackageScaffolderTest.php b/tests/Unit/Cli/Commands/Package/PackageScaffolderTest.php index c15bf995..e22dc1b6 100644 --- a/tests/Unit/Cli/Commands/Package/PackageScaffolderTest.php +++ b/tests/Unit/Cli/Commands/Package/PackageScaffolderTest.php @@ -43,7 +43,6 @@ public function test_it_creates_a_package_scaffold_with_the_default_package_name 'README.md', '.gitattributes', '.gitignore', - '.github/workflows/close-pull-request.yml', ], $scaffold->createdFiles); $this->assertFileExists($rootPath . '/src/WPCli/composer.json'); diff --git a/tests/Unit/Container/Configuration/ArrayConfigurationTest.php b/tests/Unit/Container/Configuration/ArrayConfigurationTest.php new file mode 100644 index 00000000..e925b0e7 --- /dev/null +++ b/tests/Unit/Container/Configuration/ArrayConfigurationTest.php @@ -0,0 +1,61 @@ + [ + 'enabled' => true, + 'value' => null, + ], + ]); + + $this->assertInstanceOf(Configuration::class, $configuration); + $this->assertTrue($configuration->get('feature.enabled')); + $this->assertNull($configuration->get('feature.value', 'fallback')); + $this->assertSame('fallback', $configuration->get('feature.missing', 'fallback')); + } + + public function test_it_determines_whether_nested_values_exist(): void { + $configuration = new ArrayConfiguration([ + 'feature' => [ + 'enabled' => true, + 'value' => null, + ], + ]); + + $this->assertTrue($configuration->has('feature.enabled')); + $this->assertTrue($configuration->has('feature.value')); + $this->assertFalse($configuration->has('feature.missing')); + } + + public function test_it_returns_every_configuration_value(): void { + $values = [ + 'feature' => [ + 'enabled' => true, + ], + ]; + + $configuration = new ArrayConfiguration($values); + + $this->assertSame($values, $configuration->all()); + } + + public function test_an_exact_key_takes_priority_over_its_dotted_path(): void { + $configuration = new ArrayConfiguration([ + 'feature.value' => 'exact', + 'feature' => [ + 'value' => 'nested', + ], + ]); + + $this->assertTrue($configuration->has('feature.value')); + $this->assertSame('exact', $configuration->get('feature.value')); + } +} diff --git a/tests/Unit/Container/ContainerAdapterTest.php b/tests/Unit/Container/ContainerAdapterTest.php index 6876066f..14f048cf 100644 --- a/tests/Unit/Container/ContainerAdapterTest.php +++ b/tests/Unit/Container/ContainerAdapterTest.php @@ -3,9 +3,18 @@ namespace StellarWP\Foundation\Tests\Unit\Container; use lucatume\DI52\Container as DI52Container; -use lucatume\DI52\ContainerException; +use RuntimeException; +use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; use StellarWP\Foundation\Container\ContainerAdapter; +use StellarWP\Foundation\Container\Contracts\Configuration; +use StellarWP\Foundation\Container\Contracts\Container; +use StellarWP\Foundation\Container\Contracts\Resolver; +use StellarWP\Foundation\Container\Exceptions\ContainerException; +use StellarWP\Foundation\Container\Exceptions\NotFoundException; +use StellarWP\Foundation\Tests\Support\Fixtures\Container\CallbackListener; use StellarWP\Foundation\Tests\Support\Fixtures\Container\ContainerAdapterSample; +use StellarWP\Foundation\Tests\Support\Fixtures\Container\TestProvider; +use StellarWP\Foundation\Tests\Support\Fixtures\Container\ThrowingContainerService; use StellarWP\Foundation\Tests\TestCase; final class ContainerAdapterTest extends TestCase @@ -25,10 +34,98 @@ public function test_it_returns_callbacks_from_the_wrapped_container(): void { $this->assertSame('value', $callback()); } - public function test_it_forwards_unknown_method_calls_to_the_wrapped_container(): void { + public function test_it_preserves_cached_callback_identity_from_the_wrapped_container(): void { $adapter = new ContainerAdapter(new DI52Container()); - $this->assertSame('fallback', $adapter->getVar('missing', 'fallback')); + $adapter->singleton(ContainerAdapterSample::class, new ContainerAdapterSample('value')); + + $this->assertSame( + $adapter->callback(ContainerAdapterSample::class, 'read'), + $adapter->callback(ContainerAdapterSample::class, 'read') + ); + } + + public function test_it_preserves_callback_identity_for_transient_services(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + $adapter->bind(ContainerAdapterSample::class, static fn (): ContainerAdapterSample => new ContainerAdapterSample('value')); + + $this->assertSame( + $adapter->callback(ContainerAdapterSample::class, 'read'), + $adapter->callback(ContainerAdapterSample::class, 'read') + ); + } + + public function test_it_preserves_callback_identity_for_an_object(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $listener = new CallbackListener(); + + $this->assertSame( + $adapter->callback($listener, 'listen'), + $adapter->callback($listener, 'listen') + ); + } + + public function test_it_registers_foundation_providers_without_using_the_backend_provider_lifecycle(): void { + $adapter = new ContainerAdapter(new DI52Container()); + TestProvider::$registrationCount = 0; + $adapter->bind(Container::class, $adapter); + $adapter->bind(Configuration::class, new ArrayConfiguration()); + + $adapter->register(TestProvider::class, 'test-provider'); + + $this->assertSame(1, TestProvider::$registrationCount); + $this->assertSame($adapter->get(TestProvider::class), $adapter->get('test-provider')); + } + + public function test_it_rejects_classes_that_do_not_implement_the_provider_contract(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('must implement'); + + $adapter->register(CallbackListener::class); + } + + public function test_it_merges_array_bindings_on_the_wrapped_container(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + $adapter->bind('second', static fn (): string => 'second'); + $adapter->mergeArrayVar('values', ['first']); + $adapter->mergeArrayVar('values', static fn (Resolver $resolver): array => [$resolver->get('second')]); + + $this->assertSame(['first', 'second'], $adapter->get('values')); + } + + public function test_it_supplies_the_foundation_resolver_to_binding_factories(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + $adapter->bind('dependency', static fn (): string => 'resolved'); + $adapter->bind('service', static fn (Resolver $resolver): mixed => $resolver->has('dependency') + ? $resolver->get('dependency') + : null); + + $this->assertSame('resolved', $adapter->get('service')); + } + + public function test_it_supplies_the_foundation_resolver_to_singleton_factories(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + $adapter->singleton('service', static fn (Resolver $resolver): Resolver => $resolver); + + $this->assertSame($adapter, $adapter->get('service')); + $this->assertSame($adapter->get('service'), $adapter->get('service')); + } + + public function test_it_supplies_the_foundation_resolver_to_contextual_factories(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + $adapter->bind('dependency', static fn (): string => 'resolved'); + $adapter->when(ContainerAdapterSample::class) + ->needs('$value') + ->give(static fn (Resolver $resolver): string => $resolver->get('dependency')); + + $this->assertSame('resolved', $adapter->get(ContainerAdapterSample::class)->value); } public function test_it_merges_array_values_across_multiple_calls(): void { @@ -37,7 +134,7 @@ public function test_it_merges_array_values_across_multiple_calls(): void { $adapter->mergeArrayVar('list', ['a']); $adapter->mergeArrayVar('list', ['b', 'c']); - $this->assertSame(['a', 'b', 'c'], $adapter->getVar('list')); + $this->assertSame(['a', 'b', 'c'], $adapter->get('list')); } public function test_it_merges_associative_array_values_without_replacing_previous_ones(): void { @@ -46,7 +143,7 @@ public function test_it_merges_associative_array_values_without_replacing_previo $adapter->mergeArrayVar('config', ['x' => 1]); $adapter->mergeArrayVar('config', ['y' => 2]); - $this->assertSame(['x' => 1, 'y' => 2], $adapter->getVar('config')); + $this->assertSame(['x' => 1, 'y' => 2], $adapter->get('config')); } public function test_it_throws_when_merging_into_an_already_resolved_singleton(): void { @@ -60,25 +157,141 @@ public function test_it_throws_when_merging_into_an_already_resolved_singleton() $adapter->mergeArrayVar('resolved', ['second']); } + public function test_it_translates_missing_entries_to_the_foundation_exception(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + try { + $adapter->get('missing-entry'); + $this->fail('Expected a missing container entry to throw.'); + } catch (NotFoundException $exception) { + $this->assertNull($exception->getPrevious()); + } + } + + public function test_it_preserves_application_failures_without_leaking_backend_exceptions(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + try { + $adapter->get(ThrowingContainerService::class); + $this->fail('Expected service construction to throw.'); + } catch (ContainerException $exception) { + $this->assertInstanceOf(RuntimeException::class, $exception->getPrevious()); + $this->assertSame('Service construction failed.', $exception->getPrevious()->getMessage()); + } + } + + public function test_instance_factories_translate_deferred_container_failures(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $factory = $adapter->instance(ThrowingContainerService::class); + + try { + $factory(); + $this->fail('Expected deferred service construction to throw.'); + } catch (ContainerException $exception) { + $this->assertInstanceOf(RuntimeException::class, $exception->getPrevious()); + $this->assertSame('Service construction failed.', $exception->getPrevious()->getMessage()); + } + } + + public function test_instance_factories_preserve_translated_missing_entry_failures(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $factory = $adapter->instance('missing-entry'); + + try { + $factory(); + $this->fail('Expected the missing deferred service to throw.'); + } catch (ContainerException $exception) { + $this->assertNull($exception->getPrevious()); + } + } + + public function test_callbacks_translate_deferred_container_failures(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $callback = $adapter->callback(ThrowingContainerService::class, 'run'); + + $this->expectException(ContainerException::class); + + $callback(); + } + + public function test_callback_method_failures_remain_application_exceptions(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $callback = $adapter->callback(new CallbackListener(), 'fail'); + + $this->expectException(RuntimeException::class); + $this->expectExceptionMessage('Callback failed.'); + + $callback(); + } + + public function test_it_rejects_non_callable_container_callbacks(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $callback = $adapter->callback(new CallbackListener(), 'missing'); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('is not a callable container callback'); + + $callback(); + } + + public function test_it_supplies_the_foundation_resolver_to_decorator_closures(): void { + $adapter = new ContainerAdapter(new DI52Container()); + + $adapter->bindDecorators('service', [ + static fn (Resolver $resolver): ContainerAdapterSample => new ContainerAdapterSample( + $resolver === $adapter ? 'resolved' : 'unexpected' + ), + ]); + + $service = $adapter->get('service'); + + $this->assertInstanceOf(ContainerAdapterSample::class, $service); + $this->assertSame('resolved', $service->value); + } + public function test_it_forwards_singleton_decorator_bindings(): void { - $container = $this->createMock(DI52Container::class); - $decorators = [ContainerAdapterSample::class]; + $container = $this->createMock(DI52Container::class); + $adapter = new ContainerAdapter($container); + $decorator = static fn (Resolver $resolver): Resolver => $resolver; $container->expects($this->once()) ->method('singletonDecorators') - ->with('service', $decorators, ['read'], true); + ->with( + 'service', + $this->callback(function (array $decorators) use ($adapter): bool { + $this->assertCount(2, $decorators); + $this->assertSame($adapter, $decorators[0]()); + $this->assertSame(ContainerAdapterSample::class, $decorators[1]); - (new ContainerAdapter($container))->singletonDecorators('service', $decorators, ['read'], true); + return true; + }), + ['read'], + true + ); + + $adapter->singletonDecorators('service', [$decorator, ContainerAdapterSample::class], ['read'], true); } public function test_it_forwards_decorator_bindings(): void { - $container = $this->createMock(DI52Container::class); - $decorators = [ContainerAdapterSample::class]; + $container = $this->createMock(DI52Container::class); + $adapter = new ContainerAdapter($container); + $decorator = static fn (Resolver $resolver): Resolver => $resolver; $container->expects($this->once()) ->method('bindDecorators') - ->with('service', $decorators, ['read'], true); + ->with( + 'service', + $this->callback(function (array $decorators) use ($adapter): bool { + $this->assertCount(2, $decorators); + $this->assertSame($adapter, $decorators[0]()); + $this->assertSame(ContainerAdapterSample::class, $decorators[1]); + + return true; + }), + ['read'], + true + ); - (new ContainerAdapter($container))->bindDecorators('service', $decorators, ['read'], true); + $adapter->bindDecorators('service', [$decorator, ContainerAdapterSample::class], ['read'], true); } } diff --git a/tests/Unit/Container/ContainerFactoryTest.php b/tests/Unit/Container/ContainerFactoryTest.php new file mode 100644 index 00000000..89a6a7e5 --- /dev/null +++ b/tests/Unit/Container/ContainerFactoryTest.php @@ -0,0 +1,24 @@ + ['enabled' => true]]); + $container = (new ContainerFactory())->create($configuration); + + $this->assertSame($container, $container->get(Container::class)); + $this->assertSame($container, $container->get(Resolver::class)); + $this->assertSame($container, $container->get(ContainerInterface::class)); + $this->assertSame($configuration, $container->get(Configuration::class)); + } +} diff --git a/tests/Unit/Container/ProvidableTest.php b/tests/Unit/Container/ProvidableTest.php new file mode 100644 index 00000000..9c8cc27a --- /dev/null +++ b/tests/Unit/Container/ProvidableTest.php @@ -0,0 +1,57 @@ +getMethods(); + + $this->assertCount(1, $methods); + $this->assertSame('register', $methods[0]->getName()); + $base = new ReflectionClass(Provider::class); + + $this->assertTrue($base->implementsInterface(Providable::class)); + } + + public function test_application_provider_resolves_its_dependencies_without_foundation_configuration(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $listener = new CallbackListener(); + $adapter->singleton(Container::class, $adapter); + $adapter->singleton(CallbackListener::class, $listener); + + $adapter->register(IndependentProvider::class, 'application.provider'); + + $this->assertSame(1, $listener->calls); + $this->assertSame($listener, $adapter->get('application.listener')); + $this->assertSame($adapter->get(IndependentProvider::class), $adapter->get('application.provider')); + } + + public function test_invalid_resolved_binding_cannot_execute_or_publish_a_provider_alias(): void { + $adapter = new ContainerAdapter(new DI52Container()); + $listener = new CallbackListener(); + $adapter->singleton(IndependentProvider::class, $listener); + + try { + $adapter->register(IndependentProvider::class, 'invalid.provider'); + $this->fail('A non-provider binding must be rejected.'); + } catch (ContainerException $exception) { + $this->assertStringContainsString('must resolve to', $exception->getMessage()); + } + + $this->assertFalse($adapter->has('invalid.provider')); + $this->assertSame(0, $listener->calls); + } +} diff --git a/tests/Unit/Container/ProviderTest.php b/tests/Unit/Container/ProviderTest.php index d3c2acc6..04dd15fd 100644 --- a/tests/Unit/Container/ProviderTest.php +++ b/tests/Unit/Container/ProviderTest.php @@ -2,18 +2,22 @@ namespace StellarWP\Foundation\Tests\Unit\Container; -use StellarWP\Foundation\Tests\Support\Fixtures\Container\TestProvider; +use StellarWP\Foundation\Container\Contracts\Configuration; +use StellarWP\Foundation\Tests\Support\Fixtures\Container\ConfigurationReadingProvider; +use StellarWP\Foundation\Tests\Support\Fixtures\Container\FixedConfiguration; use StellarWP\Foundation\Tests\TestCase; final class ProviderTest extends TestCase { - public function test_it_uses_default_provider_behavior(): void { - $provider = new TestProvider($this->container); + public function test_it_makes_configuration_available_to_providers(): void { + $this->container->singleton(Configuration::class, new FixedConfiguration([ + 'fixture' => [ + 'value' => 'configured', + ], + ])); - $this->assertFalse($provider->isDeferred()); - $this->assertSame([], $provider->provides()); + $this->container->register(ConfigurationReadingProvider::class); - $provider->boot(); - $this->addToAssertionCount(1); + $this->assertSame('configured', $this->container->get(ConfigurationReadingProvider::VALUE)); } } diff --git a/tests/Unit/Log/Formatters/ColoredLineFormatterTest.php b/tests/Unit/Log/Formatters/ColoredLineFormatterTest.php index 6aab9342..1f77e540 100644 --- a/tests/Unit/Log/Formatters/ColoredLineFormatterTest.php +++ b/tests/Unit/Log/Formatters/ColoredLineFormatterTest.php @@ -2,33 +2,63 @@ namespace StellarWP\Foundation\Tests\Unit\Log\Formatters; -use DateTimeImmutable; +use Monolog\Handler\StreamHandler; +use Monolog\Logger; +use PHPUnit\Framework\Attributes\DataProvider; use Psr\Log\LogLevel as PsrLogLevel; use StellarWP\Foundation\Log\Formatters\ColoredLineFormatter; -use StellarWP\Foundation\Log\LogLevel; use StellarWP\Foundation\Tests\TestCase; final class ColoredLineFormatterTest extends TestCase { - public function test_it_formats_records_with_a_custom_color_scheme(): void { + /** + * @dataProvider coloredFormats + */ + #[DataProvider('coloredFormats')] + public function test_it_formats_records_with_a_custom_color_scheme(string $format, int $mode, string $expected): void { $formatter = new ColoredLineFormatter( - '%color_start%%level_name%%color_end% %message%', + $format, colorScheme: [ PsrLogLevel::ERROR => '[error]', - ] + ], + colorMode: $mode, ); + $handler = new StreamHandler('php://memory'); + $handler->setFormatter($formatter); + $logger = new Logger('tests', [ + $handler, + ]); + $logger->error('Something happened'); + $stream = $handler->getStream(); + $this->assertIsResource($stream); + rewind($stream); $this->assertSame( - '[error]ERROR' . "\033[0m" . ' Something happened', - $formatter->format([ - 'message' => 'Something happened', - 'context' => [], - 'level' => LogLevel::ERROR, - 'level_name' => 'ERROR', - 'channel' => 'tests', - 'datetime' => new DateTimeImmutable(), - 'extra' => [], - ]) + $expected, + stream_get_contents($stream), ); } + + /** + * @return iterable + */ + public static function coloredFormats(): iterable { + yield 'explicit color markers' => [ + '%color_start%%level_name%%color_end% %message%', + ColoredLineFormatter::MODE_COLOR_LEVEL_ALL, + "[error]ERROR\033[0m Something happened", + ]; + + yield 'color every level marker' => [ + '%level_name% %level_name% %message%', + ColoredLineFormatter::MODE_COLOR_LEVEL_ALL, + "[error]ERROR\033[0m [error]ERROR\033[0m Something happened", + ]; + + yield 'color only the first level marker' => [ + '%level_name% %level_name% %message%', + ColoredLineFormatter::MODE_COLOR_LEVEL_FIRST, + "[error]ERROR\033[0m ERROR Something happened", + ]; + } } diff --git a/tests/Unit/Shutdown/ResponseFinishingRunnerTest.php b/tests/Unit/Shutdown/ResponseFinishingRunnerTest.php new file mode 100644 index 00000000..f5926104 --- /dev/null +++ b/tests/Unit/Shutdown/ResponseFinishingRunnerTest.php @@ -0,0 +1,92 @@ +markTestSkipped('Native response-finishing functions cannot be replaced by test fixtures.'); + } + } + + #[RunInSeparateProcess] + public function test_it_finishes_the_response_and_runs_shutdown_tasks_once(): void { + require dirname(__DIR__, 2) . '/Support/Fixtures/Shutdown/litespeed-finish-request.php'; + + $GLOBALS['foundation_shutdown_calls'] = []; + + $runner = $this->runner(); + + $runner->terminate(); + $runner->terminate(); + + $this->assertSame(['litespeed', 'task'], $GLOBALS['foundation_shutdown_calls']); + + unset($GLOBALS['foundation_shutdown_calls']); + } + + #[RunInSeparateProcess] + public function test_it_prefers_fastcgi_response_finishing(): void { + require dirname(__DIR__, 2) . '/Support/Fixtures/Shutdown/finish-request-functions.php'; + + $GLOBALS['foundation_shutdown_calls'] = []; + + $this->runner()->terminate(); + + $this->assertSame(['fastcgi', 'task'], $GLOBALS['foundation_shutdown_calls']); + + unset($GLOBALS['foundation_shutdown_calls']); + } + + #[RunInSeparateProcess] + public function test_a_response_finishing_failure_does_not_prevent_shutdown_tasks(): void { + require dirname(__DIR__, 2) . '/Support/Fixtures/Shutdown/finish-request-functions.php'; + + $GLOBALS['foundation_shutdown_calls'] = []; + $GLOBALS['foundation_shutdown_fastcgi_failure'] = true; + + $this->runner()->terminate(); + + $this->assertSame(['fastcgi', 'litespeed', 'task'], $GLOBALS['foundation_shutdown_calls']); + + unset( + $GLOBALS['foundation_shutdown_calls'], + $GLOBALS['foundation_shutdown_fastcgi_failure'] + ); + } + + #[RunInSeparateProcess] + public function test_it_falls_back_when_fastcgi_does_not_finish_the_response(): void { + require dirname(__DIR__, 2) . '/Support/Fixtures/Shutdown/finish-request-functions.php'; + + $GLOBALS['foundation_shutdown_calls'] = []; + $GLOBALS['foundation_shutdown_fastcgi_false'] = true; + + $this->runner()->terminate(); + + $this->assertSame(['fastcgi', 'litespeed', 'task'], $GLOBALS['foundation_shutdown_calls']); + + unset( + $GLOBALS['foundation_shutdown_calls'], + $GLOBALS['foundation_shutdown_fastcgi_false'] + ); + } + + private function runner(): ResponseFinishingRunner { + return new ResponseFinishingRunner(new Runner([ + new Task(new CallbackTerminable(static function (): void { + $GLOBALS['foundation_shutdown_calls'][] = 'task'; + })), + ])); + } +} diff --git a/tests/Unit/Shutdown/RunnerTest.php b/tests/Unit/Shutdown/RunnerTest.php new file mode 100644 index 00000000..80080a6d --- /dev/null +++ b/tests/Unit/Shutdown/RunnerTest.php @@ -0,0 +1,154 @@ +recordingTask($calls, 'last', 100), + $this->recordingTask($calls, 'second', 10), + $this->recordingTask($calls, 'third', 10), + $this->recordingTask($calls, 'first', 0), + ]); + + $runner->terminate(); + + $this->assertSame(['first', 'second', 'third', 'last'], $calls); + } + + public function test_it_runs_each_task_only_once(): void { + $calls = []; + $runner = new Runner([$this->recordingTask($calls, 'task')]); + + $runner->terminate(); + $runner->terminate(); + + $this->assertSame(['task'], $calls); + } + + public function test_it_is_safe_to_invoke_recursively(): void { + $calls = []; + $runner = new Runner(); + + $recursive = new CallbackTerminable(static function () use (&$calls, &$runner): void { + $calls[] = 'recursive'; + $runner->terminate(); + }); + + $runner = new Runner([ + new Task($recursive), + $this->recordingTask($calls, 'next'), + ]); + + $runner->terminate(); + + $this->assertSame(['recursive', 'next'], $calls); + } + + public function test_a_failed_task_does_not_prevent_later_tasks(): void { + $calls = []; + + $failing = new CallbackTerminable(static function () use (&$calls): void { + $calls[] = 'failed'; + + throw new Error('Expected test failure.'); + }); + + $runner = new Runner([ + new Task($failing), + $this->recordingTask($calls, 'completed'), + ]); + + $runner->terminate(); + + $this->assertSame(['failed', 'completed'], $calls); + } + + public function test_it_logs_task_execution_and_failures_when_a_logger_is_available(): void { + $handler = new TestHandler(); + $logger = new Logger('shutdown', [$handler]); + $failure = new Error('Expected test failure.', 42); + $failing = new CallbackTerminable(static function () use ($failure): void { + throw $failure; + }); + + $runner = new Runner([ + new Task($failing, 10), + ], $logger); + + $runner->terminate(); + + $records = $handler->getRecords(); + + $this->assertCount(3, $records); + $this->assertSame('Running shutdown tasks.', $records[0]['message']); + $this->assertSame(['task_count' => 1], $records[0]['context']); + $this->assertSame('Running shutdown task.', $records[1]['message']); + $this->assertSame([ + 'task' => CallbackTerminable::class, + 'priority' => 10, + ], $records[1]['context']); + $this->assertSame('Shutdown task failed.', $records[2]['message']); + $this->assertSame([ + 'task' => CallbackTerminable::class, + 'priority' => 10, + 'exception' => $failure, + ], $records[2]['context']); + } + + public function test_a_failed_logger_does_not_prevent_termination_work(): void { + $calls = []; + $logger = $this->createMock(LoggerInterface::class); + + $logger->method('log')->willThrowException(new Error('Expected logger failure.')); + + $runner = new Runner([ + $this->recordingTask($calls, 'completed'), + ], $logger); + + $runner->terminate(); + + $this->assertSame(['completed'], $calls); + } + + public function test_it_accepts_an_empty_task_list(): void { + $runner = new Runner(); + + $runner->terminate(); + $runner->terminate(); + + $this->addToAssertionCount(1); + } + + public function test_it_rejects_invalid_task_contributions(): void { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('Shutdown tasks must be instances of Task.'); + + $runner = new Runner(['invalid']); + } + + /** + * @param list $calls + */ + private function recordingTask(array &$calls, string $name, int $priority = 0): Task { + return new Task( + new CallbackTerminable(static function () use (&$calls, $name): void { + $calls[] = $name; + }), + $priority + ); + } +} diff --git a/tests/Unit/View/PhpViewTest.php b/tests/Unit/View/PhpViewTest.php new file mode 100644 index 00000000..bf5aefa3 --- /dev/null +++ b/tests/Unit/View/PhpViewTest.php @@ -0,0 +1,229 @@ +data_dir('View/default')); + + $this->assertSame( + '

Hello, Foundation

' . PHP_EOL, + $view->render('greeting', [ + 'greeting' => 'Hello', + 'name' => 'Foundation', + ]) + ); + } + + public function test_it_escapes_template_data_in_the_template(): void { + $view = new PhpView($this->data_dir('View/default')); + + $this->assertSame( + '

<strong>Hello</strong>, Foundation

' . PHP_EOL, + $view->render('greeting', [ + 'greeting' => 'Hello', + 'name' => 'Foundation', + ]) + ); + } + + public function test_it_renders_a_view_from_a_nested_directory(): void { + $view = new PhpView($this->data_dir('View/default')); + + $this->assertSame('

Product summary

' . PHP_EOL, $view->render('admin/product-summary')); + } + + public function test_it_returns_a_new_renderer_for_a_runtime_directory_without_mutating_the_original(): void { + $view = new PhpView($this->data_dir('View/default')); + $runtimeView = $view->withDirectory($this->data_dir('View/runtime')); + + $this->assertNotSame($view, $runtimeView); + $this->assertSame('

Runtime directory

' . PHP_EOL, $runtimeView->render('greeting')); + $this->assertSame( + '

Hello, Foundation

' . PHP_EOL, + $view->render('greeting', ['greeting' => 'Hello', 'name' => 'Foundation']) + ); + } + + /** + * @dataProvider reserved_view_data_keys + */ + #[DataProvider('reserved_view_data_keys')] + public function test_it_rejects_reserved_view_data_keys(string $key): void { + $view = new PhpView($this->data_dir('View/default')); + + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage(sprintf('View data key "%s" is reserved by PhpView.', $key)); + + $view->render('greeting', [$key => null]); + } + + /** + * @return array + */ + public static function reserved_view_data_keys(): array { + return [ + 'view path' => ['key' => 'foundationViewPath'], + 'view data' => ['key' => 'foundationViewData'], + ]; + } + + public function test_it_restores_the_output_buffer_when_a_view_throws(): void { + $view = new PhpView($this->data_dir('View/default')); + $bufferLevel = ob_get_level(); + + try { + $view->render('throws'); + $this->fail('Expected the view exception to be propagated.'); + } catch (RuntimeException $exception) { + $this->assertSame('View rendering failed.', $exception->getMessage()); + } + + $this->assertSame($bufferLevel, ob_get_level()); + } + + public function test_it_rejects_and_cleans_up_an_unclosed_view_buffer(): void { + $view = new PhpView($this->data_dir('View/default')); + $bufferLevel = ob_get_level(); + + try { + $view->render('unclosed-buffer'); + $this->fail('Expected unbalanced output buffering to be rejected.'); + } catch (RuntimeException $exception) { + $this->assertSame('The view "unclosed-buffer" must leave output buffering unchanged.', $exception->getMessage()); + } + + $this->assertSame($bufferLevel, ob_get_level()); + } + + public function test_it_allows_balanced_buffers_owned_by_the_view(): void { + $view = new PhpView($this->data_dir('View/default')); + + $this->assertSame('Balanced view output.', $view->render('balanced-buffer')); + } + + public function test_it_does_not_close_a_caller_buffer_when_the_view_closes_its_rendering_buffer(): void { + $view = new PhpView($this->data_dir('View/default')); + $bufferLevel = ob_get_level(); + + ob_start(); + + try { + $view->render('closes-buffer'); + $this->fail('Expected an unexpectedly closed rendering buffer to be rejected.'); + } catch (RuntimeException $exception) { + $this->assertSame('The view "closes-buffer" must leave output buffering unchanged.', $exception->getMessage()); + $this->assertSame($bufferLevel + 1, ob_get_level()); + } finally { + while (ob_get_level() > $bufferLevel) { + ob_end_clean(); + } + } + + $this->assertSame($bufferLevel, ob_get_level()); + } + + public function test_it_rejects_a_same_depth_replacement_for_its_rendering_buffer(): void { + $view = new PhpView($this->data_dir('View/default')); + $bufferLevel = ob_get_level(); + + try { + $view->render('replaces-buffer'); + $this->fail('Expected a replaced rendering buffer to be rejected.'); + } catch (RuntimeException $exception) { + $this->assertSame('The view "replaces-buffer" must leave output buffering unchanged.', $exception->getMessage()); + } + + $this->assertSame($bufferLevel, ob_get_level()); + } + + public function test_it_rejects_flushing_its_rendering_buffer_without_leaking_output(): void { + $view = new PhpView($this->data_dir('View/default')); + $bufferLevel = ob_get_level(); + + ob_start(); + + try { + $view->render('flushes-buffer'); + $this->fail('Expected a flushed rendering buffer to be rejected.'); + } catch (RuntimeException $exception) { + $this->assertSame('The view "flushes-buffer" must leave output buffering unchanged.', $exception->getMessage()); + $this->assertSame('', ob_get_contents()); + } finally { + while (ob_get_level() > $bufferLevel) { + ob_end_clean(); + } + } + + $this->assertSame($bufferLevel, ob_get_level()); + } + + public function test_it_rejects_an_invalid_view_directory(): void { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('must exist and be readable'); + + new PhpView($this->data_dir('View/missing')); + } + + public function test_it_reports_a_missing_view(): void { + $view = new PhpView($this->data_dir('View/default')); + + $this->expectException(ViewNotFoundException::class); + $this->expectExceptionMessage('The view "missing" could not be found'); + + $view->render('missing'); + } + + /** + * @dataProvider invalid_view_names + */ + #[\PHPUnit\Framework\Attributes\DataProvider('invalid_view_names')] + public function test_it_rejects_unsafe_view_names(string $name): void { + $view = new PhpView($this->data_dir('View/default')); + + $this->expectException(InvalidArgumentException::class); + + $view->render($name); + } + + /** + * @return array + */ + public static function invalid_view_names(): array { + return [ + 'empty' => ['name' => ''], + 'null byte' => ['name' => "greeting\0ignored"], + 'absolute Unix' => ['name' => '/tmp/view'], + 'absolute Windows' => ['name' => 'C:\\tmp\\view'], + 'parent traversal' => ['name' => '../outside'], + 'nested traversal' => ['name' => 'nested/../../outside'], + ]; + } + + public function test_it_rejects_a_symlink_that_resolves_outside_the_view_directory(): void { + $directory = $this->prepare_temp_dir('view'); + $root = $directory . '/root'; + $outside = $directory . '/outside.php'; + + mkdir($root); + file_put_contents($outside, 'Outside'); + + if (! symlink($outside, $root . '/linked.php')) { + $this->markTestSkipped('The test environment cannot create symbolic links.'); + } + + $view = new PhpView($root); + + $this->expectException(ViewNotFoundException::class); + + $view->render('linked'); + } +} diff --git a/tests/Unit/View/ViewContractTest.php b/tests/Unit/View/ViewContractTest.php new file mode 100644 index 00000000..317fd387 --- /dev/null +++ b/tests/Unit/View/ViewContractTest.php @@ -0,0 +1,30 @@ +assertSame( + '{"view":"product-summary","data":{"count":3}}', + $view->render('product-summary', ['count' => 3]) + ); + } + + public function test_a_directory_aware_adapter_may_return_another_implementation(): void { + $view = new PhpView($this->data_dir('View/default')); + $adapter = new DelegatingDirectoryView($view); + $runtimeView = $adapter->withDirectory($this->data_dir('View/runtime')); + + $this->assertInstanceOf(PhpView::class, $runtimeView); + $this->assertNotSame($view, $runtimeView); + $this->assertSame('

Runtime directory

' . PHP_EOL, $runtimeView->render('greeting')); + } +} diff --git a/tests/Unit/View/ViewProviderTest.php b/tests/Unit/View/ViewProviderTest.php new file mode 100644 index 00000000..d8d7db5e --- /dev/null +++ b/tests/Unit/View/ViewProviderTest.php @@ -0,0 +1,40 @@ +container->singleton(Configuration::class, new ArrayConfiguration([ + 'view' => ['directory' => $this->data_dir('View/default')], + ])); + $this->container->register(ViewProvider::class); + + $view = $this->container->get(View::class); + + $this->assertInstanceOf(PhpView::class, $view); + $this->assertSame($view, $this->container->get(View::class)); + $this->assertSame($view, $this->container->get(DirectoryAwareView::class)); + $this->assertSame($view, $this->container->get(PhpView::class)); + $this->assertSame( + '

Hello, Foundation

' . PHP_EOL, + $view->render('greeting', ['greeting' => 'Hello', 'name' => 'Foundation']) + ); + } + + public function test_it_rejects_missing_view_configuration(): void { + $this->expectException(InvalidArgumentException::class); + $this->expectExceptionMessage('view.directory configuration value must be a non-empty string'); + + $this->container->register(ViewProvider::class); + } +} diff --git a/tests/WPUnitSupport/WPTestCase.php b/tests/WPUnitSupport/WPTestCase.php index 910d8065..37c0ac8a 100644 --- a/tests/WPUnitSupport/WPTestCase.php +++ b/tests/WPUnitSupport/WPTestCase.php @@ -3,6 +3,9 @@ namespace StellarWP\Foundation\Tests\WPUnitSupport; use lucatume\WPBrowser\TestCase\WPTestCase as CodeceptionWPTestCase; +use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; +use StellarWP\Foundation\Container\ContainerFactory; +use StellarWP\Foundation\Container\Contracts\Container; /** * Base test case for WordPress integration tests. @@ -12,4 +15,13 @@ */ abstract class WPTestCase extends CodeceptionWPTestCase { + protected Container $container; + + protected function setUp(): void { + parent::setUp(); + + $this->container = (new ContainerFactory())->create( + new ArrayConfiguration(require dirname(__DIR__) . '/config.php') + ); + } } diff --git a/tests/_data/View/default/admin/product-summary.php b/tests/_data/View/default/admin/product-summary.php new file mode 100644 index 00000000..ce78839e --- /dev/null +++ b/tests/_data/View/default/admin/product-summary.php @@ -0,0 +1 @@ +

Product summary

diff --git a/tests/_data/View/default/balanced-buffer.php b/tests/_data/View/default/balanced-buffer.php new file mode 100644 index 00000000..1f2e0656 --- /dev/null +++ b/tests/_data/View/default/balanced-buffer.php @@ -0,0 +1,7 @@ +

,

diff --git a/tests/_data/View/default/replaces-buffer.php b/tests/_data/View/default/replaces-buffer.php new file mode 100644 index 00000000..28d36650 --- /dev/null +++ b/tests/_data/View/default/replaces-buffer.php @@ -0,0 +1,5 @@ +Runtime directory

diff --git a/tests/_data/cli/package/valid-root/src/Log/.github/workflows/close-pull-request.yml b/tests/_data/cli/package/valid-root/src/Log/.github/workflows/close-pull-request.yml deleted file mode 100644 index e51ed73c..00000000 --- a/tests/_data/cli/package/valid-root/src/Log/.github/workflows/close-pull-request.yml +++ /dev/null @@ -1,5 +0,0 @@ -name: Close Pull Request - -on: - pull_request_target: - types: [opened] diff --git a/tests/wpunit/Shutdown/BufferedLoggingTest.php b/tests/wpunit/Shutdown/BufferedLoggingTest.php new file mode 100644 index 00000000..7c4d5207 --- /dev/null +++ b/tests/wpunit/Shutdown/BufferedLoggingTest.php @@ -0,0 +1,61 @@ + [ + 'channel' => 'buffered', + 'level' => 'info', + 'channels' => [ + 'buffered' => [ + 'handler' => BufferHandler::class, + ], + ], + ], + ]); + $factory = new ContainerFactory(); + $container = $factory->create($configuration); + $sink = new TestHandler(); + $buffer = new BufferHandler($sink, 100); + $flush = new BufferedLogFlush($buffer); + + $container->singleton(BufferHandler::class, $buffer); + $container->register(LogProvider::class); + $container->register(ShutdownProvider::class); + $container->mergeArrayVar(ShutdownProvider::TASKS, [ + new Task($flush, 100), + ]); + + $logger = $container->get(LoggerInterface::class); + $logger->info('Order {order_id} paid.', [ + 'order_id' => 42, + ]); + $logger->warning('Delivery delayed.'); + + $this->assertSame($logger, $container->get(LoggerInterface::class)); + $this->assertSame([], $sink->getRecords()); + + do_action('shutdown'); + do_action('shutdown'); + + $this->assertCount(2, $sink->getRecords()); + $this->assertTrue($sink->hasInfo('Order 42 paid.')); + $this->assertTrue($sink->hasWarning('Delivery delayed.')); + } +} diff --git a/tests/wpunit/Shutdown/ShutdownProviderTest.php b/tests/wpunit/Shutdown/ShutdownProviderTest.php new file mode 100644 index 00000000..8813edce --- /dev/null +++ b/tests/wpunit/Shutdown/ShutdownProviderTest.php @@ -0,0 +1,146 @@ +container->register(ShutdownProvider::class); + $this->container->mergeArrayVar(ShutdownProvider::TASKS, [ + new Task(new CallbackTerminable(static function () use (&$calls): void { + $calls[] = 'terminated'; + })), + ]); + + $runner = $this->container->get(ShutdownRunner::class); + + $this->assertInstanceOf(ResponseFinishingRunner::class, $runner); + $this->assertSame($runner, $this->container->get(ShutdownRunner::class)); + + $runner->terminate(); + + $this->assertSame(['terminated'], $calls); + } + + public function test_it_injects_a_registered_psr_logger(): void { + $handler = new TestHandler(); + + $this->container->singleton(LoggerInterface::class, new Logger('shutdown', [$handler])); + $this->container->register(ShutdownProvider::class); + + $this->container->get(ShutdownRunner::class)->terminate(); + + $this->assertTrue($handler->hasDebugThatMatches('/Running shutdown tasks\./')); + } + + public function test_it_runs_contributed_tasks_on_wordpress_shutdown(): void { + $calls = []; + + $this->container->register(ShutdownProvider::class); + + $this->container->mergeArrayVar(ShutdownProvider::TASKS, [ + new Task(new CallbackTerminable(static function () use (&$calls): void { + $calls[] = 'terminated'; + })), + ]); + + $this->assertSame([], $calls); + do_action('shutdown'); + do_action('shutdown'); + + $this->assertSame(['terminated'], $calls); + } + + public function test_it_does_not_resolve_the_runner_while_wordpress_is_installing(): void { + $wasInstalling = wp_installing(true); + + try { + $this->container->register(ShutdownProvider::class); + $this->assertShutdownSkipsRunner(); + } finally { + wp_installing($wasInstalling); + } + } + + public function test_it_checks_installation_state_after_provider_registration(): void { + $this->container->register(ShutdownProvider::class); + $wasInstalling = wp_installing(true); + + try { + $this->assertShutdownSkipsRunner(); + } finally { + wp_installing($wasInstalling); + } + } + + public function test_it_runs_when_installation_has_finished_before_shutdown(): void { + $wasInstalling = wp_installing(true); + $calls = []; + + try { + $this->container->register(ShutdownProvider::class); + $this->container->mergeArrayVar(ShutdownProvider::TASKS, [ + new Task(new CallbackTerminable(static function () use (&$calls): void { + $calls[] = 'terminated'; + })), + ]); + wp_installing(false); + do_action('shutdown'); + + $this->assertSame(['terminated'], $calls); + } finally { + wp_installing($wasInstalling); + } + } + + public function test_uninstall_state_is_checked_before_resolving_the_runner(): void { + foreach (['before', 'after'] as $when) { + $process = new Process([ + PHP_BINARY, + dirname(__DIR__, 2) . '/Support/Fixtures/Shutdown/uninstall-request.php', + constant('ABSPATH'), + $when, + ]); + $process->mustRun(); + + $this->assertSame('skipped', $process->getOutput(), 'Uninstall started ' . $when . ' provider registration.'); + } + } + + /** + * Excluded requests must not build tasks or attempt response finishing. + */ + private function assertShutdownSkipsRunner(): void { + $resolutions = 0; + $runner = $this->createMock(ShutdownRunner::class); + $runner->expects($this->never())->method('terminate'); + $this->container->singleton(ShutdownRunner::class, static function () use (&$resolutions, $runner): ShutdownRunner { + $resolutions++; + + return $runner; + }); + + do_action('shutdown'); + $this->assertSame(0, $resolutions); + } +} From 37a23afdd1885343fe0c66450694b678e7ad751c Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 10:42:19 -0600 Subject: [PATCH 02/18] Allow SLIC coverage reporting to publish PR status and comments --- .github/workflows/tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index cc715e2a..df4b7da3 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -74,6 +74,11 @@ jobs: runs-on: ubuntu-latest name: SLIC Tests + permissions: + contents: read + pull-requests: write + statuses: write + env: COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{ github.token }}"}}' From 73429ebd88b031a75cb848084378f1230df7d025 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 10:48:14 -0600 Subject: [PATCH 03/18] Document config-file bootstrap and shared configuration migration --- UPGRADING-2.0.md | 2 +- src/Container/README.md | 29 ++++++++++++++++++++++------- src/Log/README.md | 29 +++++++++++++++++++++-------- 3 files changed, 44 insertions(+), 16 deletions(-) diff --git a/UPGRADING-2.0.md b/UPGRADING-2.0.md index 87b42cf0..37409683 100644 --- a/UPGRADING-2.0.md +++ b/UPGRADING-2.0.md @@ -14,7 +14,7 @@ The former `foundation-container-wordpress` package is removed. Register WordPre Factory callbacks receive `Contracts\Resolver`, not DI52. Change callback parameter types and use its `get()` and `has()` methods. Raw-container access through `getContainer()` and magic forwarding of undocumented DI52 operations are removed. Use the declared Foundation container operations. Catch Foundation's `Exceptions\ContainerException` or `Exceptions\NotFoundException` instead of DI52 exceptions. -Configuration is a read-only application-lifetime snapshot. Assemble plugin settings before registering their providers. Replacing configuration after providers have been constructed does not update their stored snapshot. +Configuration is a read-only application-lifetime snapshot. Load application settings with `$values = require __DIR__ . '/config.php';` and pass the returned array to `ArrayConfiguration`. Combine settings from plugins sharing a container before creating that snapshot; replace late calls to `Dot::merge()` with this bootstrap-time assembly. Replacing configuration after providers have been constructed does not update their stored snapshot. ## Logging diff --git a/src/Container/README.md b/src/Container/README.md index 2ce49824..614a9e9b 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -11,19 +11,34 @@ composer require stellarwp/foundation-container:^2.0 ## Create the application container +Keep application settings in a `config.php` file that returns an array: + ```php -use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; -use StellarWP\Foundation\Container\ContainerFactory; + [ - 'endpoint' => 'https://example.com/catalog', + 'endpoint' => $_ENV['CATALOG_ENDPOINT'] ?? 'https://example.com/catalog', ], -]); -$factory = new ContainerFactory(); -$container = $factory->create($configuration); +]; +``` + +Load that file during application bootstrap, after the Composer autoloader and any environment setup: + +```php +use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; +use StellarWP\Foundation\Container\ContainerFactory; + +$values = require __DIR__ . '/config.php'; +$configuration = new ArrayConfiguration($values); +$factory = new ContainerFactory(); +$container = $factory->create($configuration); ``` +Use `require`, not `require_once`, when capturing the returned array: a repeated `require_once` returns `true`. `ArrayConfiguration` uses Dot internally for dotted-key lookups such as `catalog.endpoint`. + +If several plugins contribute to one application's configuration, load and combine their values before constructing `ArrayConfiguration`. Providers read the completed configuration; they do not merge settings into a mutable Dot instance. Load any `.env` values before requiring the configuration file. + `ContainerFactory` registers the container, resolver and configuration contracts. Configuration is a read-only snapshot for the container lifetime. Missing keys return the supplied default; an explicitly configured `null` remains `null`. ## Register features diff --git a/src/Log/README.md b/src/Log/README.md index ae9fd6c8..234a1129 100644 --- a/src/Log/README.md +++ b/src/Log/README.md @@ -11,20 +11,31 @@ composer require stellarwp/foundation-log:^2.0 ## Configure the logger +Add the logging settings to the application's `config.php`: + +```php + [ + 'channel' => 'errorlog', + 'level' => $_ENV['LOG_LEVEL'] ?? 'info', + ], +]; +``` + +Load the configuration when bootstrapping the application container, then register the logging provider: + ```php use Psr\Log\LoggerInterface; use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; use StellarWP\Foundation\Container\ContainerFactory; use StellarWP\Foundation\Log\LogProvider; -$configuration = new ArrayConfiguration([ - 'log' => [ - 'channel' => 'errorlog', - 'level' => 'info', - ], -]); -$factory = new ContainerFactory(); -$container = $factory->create($configuration); +$values = require __DIR__ . '/config.php'; +$configuration = new ArrayConfiguration($values); +$factory = new ContainerFactory(); +$container = $factory->create($configuration); $container->register(LogProvider::class); $logger = $container->get(LoggerInterface::class); @@ -33,6 +44,8 @@ $logger->info('Order {order_id} paid.', [ ]); ``` +If the application already has a Foundation container, include these settings in its configuration and register `LogProvider` on that existing container. + Inject `Psr\Log\LoggerInterface` into application services. The logger is shared, so handler and processor changes remain in effect for that container's lifetime. Built-in channels are `errorlog`, `console`, `null`, and `stack` (console plus error log). The level defaults to `debug`; select a channel explicitly. PSR-3 placeholders are interpolated while structured context is retained. From 3a756549318a7d024258b532bc41b4b81e5a7444 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:02:46 -0600 Subject: [PATCH 04/18] Restore package introductions and remove redundant PHP requirements --- src/Container/README.md | 7 ++++++- src/Log/README.md | 2 +- src/Shutdown/README.md | 2 +- src/View/README.md | 2 +- 4 files changed, 9 insertions(+), 4 deletions(-) diff --git a/src/Container/README.md b/src/Container/README.md index 614a9e9b..b5ba2aa8 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -3,7 +3,12 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation Container supplies autowiring, contextual bindings, lazy callbacks and decorator chains behind Foundation-owned contracts. Requires PHP 8.3 or later. +Foundation Container provides a shared container contract and service provider +base class. + +It supports autowiring, contextual bindings, lazy WordPress callbacks, +cross-provider collections, and decorator chains without exposing the underlying +container implementation to application code. ```sh composer require stellarwp/foundation-container:^2.0 diff --git a/src/Log/README.md b/src/Log/README.md index 234a1129..ec51f00d 100644 --- a/src/Log/README.md +++ b/src/Log/README.md @@ -3,7 +3,7 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation Log registers one shared PSR-3 logger per container using Monolog 2.11+ or 3.10+. Requires PHP 8.3 or later. +Foundation Log registers one shared PSR-3 logger per container using Monolog 2.11+ or 3.10+. ```sh composer require stellarwp/foundation-log:^2.0 diff --git a/src/Shutdown/README.md b/src/Shutdown/README.md index 141852db..502d712e 100644 --- a/src/Shutdown/README.md +++ b/src/Shutdown/README.md @@ -3,7 +3,7 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation Shutdown runs contributed tasks once, in ascending priority order. Tasks with equal priorities retain contribution order. Requires PHP 8.3 or later. +Foundation Shutdown runs contributed tasks once, in ascending priority order. Tasks with equal priorities retain contribution order. ```sh composer require stellarwp/foundation-shutdown:^2.0 diff --git a/src/View/README.md b/src/View/README.md index 43b3e100..c05fc9d1 100644 --- a/src/View/README.md +++ b/src/View/README.md @@ -3,7 +3,7 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation View renders trusted PHP templates to strings. It confines template selection to a configured directory and supports immutable directory changes. Requires PHP 8.3 or later. +Foundation View renders trusted PHP templates to strings. It confines template selection to a configured directory and supports immutable directory changes. ```sh composer require stellarwp/foundation-view:^2.0 From 74032d026abfe4de7ed93c00034e93a07399fbe6 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:03:20 -0600 Subject: [PATCH 05/18] Align package README installation and introduction format --- src/Container/README.md | 6 ++++-- src/Log/README.md | 10 +++++++--- src/Shutdown/README.md | 10 +++++++--- src/View/README.md | 8 +++++--- 4 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/Container/README.md b/src/Container/README.md index b5ba2aa8..03c2ba6f 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -10,8 +10,10 @@ It supports autowiring, contextual bindings, lazy WordPress callbacks, cross-provider collections, and decorator chains without exposing the underlying container implementation to application code. -```sh -composer require stellarwp/foundation-container:^2.0 +## Installation + +```shell +composer require stellarwp/foundation-container ``` ## Create the application container diff --git a/src/Log/README.md b/src/Log/README.md index ec51f00d..3cecbbb1 100644 --- a/src/Log/README.md +++ b/src/Log/README.md @@ -3,12 +3,16 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation Log registers one shared PSR-3 logger per container using Monolog 2.11+ or 3.10+. +Foundation Log provides a shared PSR-3 logger using Monolog and the Foundation container. -```sh -composer require stellarwp/foundation-log:^2.0 +## Installation + +```shell +composer require stellarwp/foundation-log ``` +Supports Monolog `^2.11 || ^3.10`. + ## Configure the logger Add the logging settings to the application's `config.php`: diff --git a/src/Shutdown/README.md b/src/Shutdown/README.md index 502d712e..75a5ba66 100644 --- a/src/Shutdown/README.md +++ b/src/Shutdown/README.md @@ -3,14 +3,18 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation Shutdown runs contributed tasks once, in ascending priority order. Tasks with equal priorities retain contribution order. +Foundation Shutdown runs application tasks at the end of a request. -```sh -composer require stellarwp/foundation-shutdown:^2.0 +## Installation + +```shell +composer require stellarwp/foundation-shutdown ``` ## Flush an application's logging buffer +Tasks run once, in ascending priority order. Tasks with equal priorities retain contribution order. + Implement `Terminable` for the work performed at shutdown. For a shared Monolog buffer: ```php diff --git a/src/View/README.md b/src/View/README.md index c05fc9d1..d54f60b2 100644 --- a/src/View/README.md +++ b/src/View/README.md @@ -3,10 +3,12 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation View renders trusted PHP templates to strings. It confines template selection to a configured directory and supports immutable directory changes. +Foundation View renders trusted PHP templates to strings. -```sh -composer require stellarwp/foundation-view:^2.0 +## Installation + +```shell +composer require stellarwp/foundation-view ``` ## Render a template From 58e4393b2cbb565baf27e5f23e7356650e78d248 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:06:23 -0600 Subject: [PATCH 06/18] Restore complete Container setup and configuration examples --- src/Container/README.md | 191 ++++++++++++++++++++++++++++++++++------ 1 file changed, 162 insertions(+), 29 deletions(-) diff --git a/src/Container/README.md b/src/Container/README.md index 03c2ba6f..cddad6b4 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -4,11 +4,12 @@ > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). Foundation Container provides a shared container contract and service provider -base class. +base class, backed by [DI52](https://github.com/lucatume/di52) out of the box. +`ContainerFactory` creates and configures DI52 automatically; applications use +Foundation's contracts to register and resolve their services. It supports autowiring, contextual bindings, lazy WordPress callbacks, -cross-provider collections, and decorator chains without exposing the underlying -container implementation to application code. +cross-provider collections, and decorator chains. ## Installation @@ -16,65 +17,197 @@ container implementation to application code. composer require stellarwp/foundation-container ``` -## Create the application container +## Container Configuration -Keep application settings in a `config.php` file that returns an array: +Create a `config.php` in the application root that returns its settings as an +array. The [configuration example below](#making-a-configphp) includes catalog +and logging settings. + +In the application's bootstrap file, load the Composer autoloader, load any +optional `.env` file, and create the container before registering providers: ```php [ - 'endpoint' => $_ENV['CATALOG_ENDPOINT'] ?? 'https://example.com/catalog', - ], -]; -``` - -Load that file during application bootstrap, after the Composer autoloader and any environment setup: +namespace My\App; -```php +use Dotenv\Dotenv; +use My\App\Catalog\CatalogProvider; use StellarWP\Foundation\Container\Configuration\ArrayConfiguration; use StellarWP\Foundation\Container\ContainerFactory; -$values = require __DIR__ . '/config.php'; +require_once __DIR__ . '/vendor/autoload.php'; + +$path = __DIR__; + +if (is_file($path . '/.env')) { + $dotenv = Dotenv::createImmutable($path); + $dotenv->load(); +} + +$values = require $path . '/config.php'; $configuration = new ArrayConfiguration($values); $factory = new ContainerFactory(); $container = $factory->create($configuration); + +$providers = [ + CatalogProvider::class, +]; + +foreach ($providers as $provider) { + $container->register($provider); +} ``` -Use `require`, not `require_once`, when capturing the returned array: a repeated `require_once` returns `true`. `ArrayConfiguration` uses Dot internally for dotted-key lookups such as `catalog.endpoint`. +This assumes the application autoloads its `My\App` classes through Composer. +`ContainerFactory` registers the shared container under Foundation's `Container` +and `Resolver` contracts and the StellarWP `ContainerInterface`. It also registers +the supplied `Configuration`; applications do not need to bind these manually. + +Use `require` when capturing the configuration array. A repeated `require_once` +returns `true` instead of evaluating the file and returning its settings again. -If several plugins contribute to one application's configuration, load and combine their values before constructing `ArrayConfiguration`. Providers read the completed configuration; they do not merge settings into a mutable Dot instance. Load any `.env` values before requiring the configuration file. +Register providers once, in dependency order, before resolving their services. +Provider registration runs immediately; service bindings remain lazy. Foundation +has no separate provider `boot()` phase. Repeating registration can repeat hooks +and contributions. -`ContainerFactory` registers the container, resolver and configuration contracts. Configuration is a read-only snapshot for the container lifetime. Missing keys return the supplied default; an explicitly configured `null` remains `null`. +## Service Providers -## Register features +Extend `StellarWP\Foundation\Container\Contracts\Provider` for ordinary providers. +Its final constructor supplies `$this->container` and `$this->config`. Put service +dependencies in the services you register rather than overriding that constructor. -Extend `StellarWP\Foundation\Container\Contracts\Provider` for ordinary providers. Its final constructor supplies `$this->container` and `$this->config`; put service dependencies in the services you register. +For example, suppose the application owns a `Catalog` interface and an +`HttpCatalog` implementation whose constructor accepts `string $endpoint`. +The provider binds the implementation and supplies its endpoint from configuration: ```php +container->when(CatalogClient::class) + $endpoint = $this->config->get('catalog.endpoint'); + + $this->container->when(HttpCatalog::class) ->needs('$endpoint') - ->give($this->config->get('catalog.endpoint')); + ->give($endpoint); - $this->container->singleton(CatalogClient::class); + $this->container->singleton(Catalog::class, HttpCatalog::class); } } +``` + +Application services can now receive `Catalog` through constructor injection. +`HttpCatalog` receives the configured endpoint without depending on Dot, +Foundation configuration, or the container itself. + +Applications with an existing registration base class may implement +`Contracts\Providable` instead. Its only method is `register(): void`, and the +application owns the constructor. The supplied `Provider` implements this same +interface. + +## Environment Variable Configuration + +`ArrayConfiguration` uses [Dot](https://github.com/adbario/php-dot-notation) +internally for dotted-key lookups. Providers access the Foundation `Configuration` +contract through `$this->config`, rather than receiving Dot directly. + +The included [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) can populate +`$_ENV` from an application's `.env` file. Load environment values before requiring +`config.php`, because that file evaluates them when it runs. -$container->register(CatalogProvider::class); +### Making a config.php + +Provide defaults for environment values that have not been set: + +```php + [ + 'endpoint' => $_ENV['CATALOG_ENDPOINT'] ?? 'https://example.com/catalog', + ], + 'log' => [ + 'level' => $_ENV['LOG_LEVEL'] ?? 'info', + 'channel' => $_ENV['LOG_CHANNEL'] ?? 'errorlog', + 'channels' => [ + 'console' => [ + 'with' => [ + 'stream' => 'php://stdout', + ], + ], + ], + ], +]; +``` + +The `log` settings are consumed by +[Foundation Log](https://github.com/stellarwp/foundation-log) when that package is +installed and its `LogProvider` is registered. Foundation Container does not +register a logger itself. + +An optional `.env` file for these settings could contain: + +```dotenv +CATALOG_ENDPOINT=https://example.com/catalog +LOG_LEVEL=info +LOG_CHANNEL=errorlog +``` + +In WordPress, the application can set these values in `wp-config.php` before +WordPress loads the plugins: + +```php +$_ENV['CATALOG_ENDPOINT'] = 'https://example.com/catalog'; +$_ENV['LOG_LEVEL'] = 'info'; +$_ENV['LOG_CHANNEL'] = 'errorlog'; +``` + +### Reading configuration + +Inside a provider, use dotted keys to read nested values: + +```php +$stream = $this->config->get('log.channels.console.with.stream'); +$level = $this->config->get('log.level', 'info'); ``` -`CatalogClient` represents the application's own class. Register providers once, in dependency order, before resolving services. Registration is eager; service bindings remain lazy. Repeating registration can repeat hooks and contributions. +`get()` uses the supplied default only when the key is absent. A configured `null` +remains `null`. `has()` checks whether a key exists, including keys with null values; +`all()` returns the complete configuration array. + +### Configuration lifetime + +Configuration exposes read methods only. Assemble shared defaults and overrides +before constructing `ArrayConfiguration` and registering providers that read it. +Providers do not merge settings into a mutable Dot instance. + +Changing environment values afterward does not update the configuration. Replacing +the configuration binding also does not rebuild existing providers, service +bindings, or singletons. Tests needing different settings should load their values +and create a fresh configuration and container for each scenario. + +Plugin-specific settings can remain in a dedicated settings service instead of +being added to shared application configuration. -Applications with an existing registration abstraction may implement `Contracts\Providable` instead. It requires only `register(): void` and imposes no constructor. The application owns that implementation's injected dependencies. The supplied `Provider` also implements this interface. +## Container Contracts -Factory closures receive Foundation's `Contracts\Resolver`, not DI52. Use `get()` and `has()` inside factories. Inject resolved services into application code rather than passing the container into business services. +Factory closures receive Foundation's `Contracts\Resolver`, not DI52. Use `get()` +and `has()` inside factories; inject resolved dependencies into application +services rather than passing them the container. -`callback(Service::class, 'method')` creates a lazy callable with stable identity, suitable for WordPress hooks. `mergeArrayVar()` collects contributions from multiple providers. `singletonDecorators()` and `bindDecorators()` compose registered implementations. +`callback(Service::class, 'method')` creates a lazy callable with stable identity, +suitable for WordPress hooks. `mergeArrayVar()` collects contributions from +multiple providers. `singletonDecorators()` and `bindDecorators()` compose +registered implementations. -Container failures use `Exceptions\ContainerException` and `Exceptions\NotFoundException`. The underlying DI52 container and its undocumented methods are not part of Foundation's public API. +Container failures use `Exceptions\ContainerException` and +`Exceptions\NotFoundException`. DI52 is supplied as the default backend, but its +undocumented methods are not part of Foundation's public API. From 9d7962b9820b68de5fe8c1c57032acdc6ea5b01f Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:08:30 -0600 Subject: [PATCH 07/18] Focus Container README on setup and usage examples --- src/Container/README.md | 85 ++++++----------------------------------- 1 file changed, 12 insertions(+), 73 deletions(-) diff --git a/src/Container/README.md b/src/Container/README.md index cddad6b4..01698098 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -5,11 +5,6 @@ Foundation Container provides a shared container contract and service provider base class, backed by [DI52](https://github.com/lucatume/di52) out of the box. -`ContainerFactory` creates and configures DI52 automatically; applications use -Foundation's contracts to register and resolve their services. - -It supports autowiring, contextual bindings, lazy WordPress callbacks, -cross-provider collections, and decorator chains. ## Installation @@ -23,8 +18,8 @@ Create a `config.php` in the application root that returns its settings as an array. The [configuration example below](#making-a-configphp) includes catalog and logging settings. -In the application's bootstrap file, load the Composer autoloader, load any -optional `.env` file, and create the container before registering providers: +Use `ContainerFactory` to create the container with your configuration and register +the application's providers. It creates the DI52 instance automatically: ```php container` and `$this->config`. Put service -dependencies in the services you register rather than overriding that constructor. +Extend `Provider` to register services using `$this->container` and read +configuration through `$this->config`. For example, suppose the application owns a `Catalog` interface and an `HttpCatalog` implementation whose constructor accepts `string $endpoint`. @@ -105,23 +88,11 @@ final class CatalogProvider extends Provider ``` Application services can now receive `Catalog` through constructor injection. -`HttpCatalog` receives the configured endpoint without depending on Dot, -Foundation configuration, or the container itself. - -Applications with an existing registration base class may implement -`Contracts\Providable` instead. Its only method is `register(): void`, and the -application owns the constructor. The supplied `Provider` implements this same -interface. ## Environment Variable Configuration -`ArrayConfiguration` uses [Dot](https://github.com/adbario/php-dot-notation) -internally for dotted-key lookups. Providers access the Foundation `Configuration` -contract through `$this->config`, rather than receiving Dot directly. - -The included [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) can populate -`$_ENV` from an application's `.env` file. Load environment values before requiring -`config.php`, because that file evaluates them when it runs. +Use the included [vlucas/phpdotenv](https://github.com/vlucas/phpdotenv) to load +`.env` values before requiring `config.php`, as shown in the bootstrap example. ### Making a config.php @@ -148,10 +119,8 @@ return [ ]; ``` -The `log` settings are consumed by -[Foundation Log](https://github.com/stellarwp/foundation-log) when that package is -installed and its `LogProvider` is registered. Foundation Container does not -register a logger itself. +The `log` settings apply when using +[Foundation Log](https://github.com/stellarwp/foundation-log). An optional `.env` file for these settings could contain: @@ -172,42 +141,12 @@ $_ENV['LOG_CHANNEL'] = 'errorlog'; ### Reading configuration -Inside a provider, use dotted keys to read nested values: +`ArrayConfiguration` uses [Dot](https://github.com/adbario/php-dot-notation) for +nested lookups. Inside a provider: ```php $stream = $this->config->get('log.channels.console.with.stream'); $level = $this->config->get('log.level', 'info'); ``` -`get()` uses the supplied default only when the key is absent. A configured `null` -remains `null`. `has()` checks whether a key exists, including keys with null values; -`all()` returns the complete configuration array. - -### Configuration lifetime - -Configuration exposes read methods only. Assemble shared defaults and overrides -before constructing `ArrayConfiguration` and registering providers that read it. -Providers do not merge settings into a mutable Dot instance. - -Changing environment values afterward does not update the configuration. Replacing -the configuration binding also does not rebuild existing providers, service -bindings, or singletons. Tests needing different settings should load their values -and create a fresh configuration and container for each scenario. - -Plugin-specific settings can remain in a dedicated settings service instead of -being added to shared application configuration. - -## Container Contracts - -Factory closures receive Foundation's `Contracts\Resolver`, not DI52. Use `get()` -and `has()` inside factories; inject resolved dependencies into application -services rather than passing them the container. - -`callback(Service::class, 'method')` creates a lazy callable with stable identity, -suitable for WordPress hooks. `mergeArrayVar()` collects contributions from -multiple providers. `singletonDecorators()` and `bindDecorators()` compose -registered implementations. - -Container failures use `Exceptions\ContainerException` and -`Exceptions\NotFoundException`. DI52 is supplied as the default backend, but its -undocumented methods are not part of Foundation's public API. +`has()` checks whether a key exists; `all()` returns the complete configuration array. From 40dbf5f5ac0cdf579ded05d0010cb3d89bf6e81d Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:09:18 -0600 Subject: [PATCH 08/18] Follow the original Container README structure and example flow --- src/Container/README.md | 69 ++++++++++++++++------------------------- 1 file changed, 27 insertions(+), 42 deletions(-) diff --git a/src/Container/README.md b/src/Container/README.md index 01698098..285c6071 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -3,8 +3,8 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -Foundation Container provides a shared container contract and service provider -base class, backed by [DI52](https://github.com/lucatume/di52) out of the box. +The DI container configuration and service provider implementation, using +[DI52](https://github.com/lucatume/di52) out of the box. ## Installation @@ -14,12 +14,8 @@ composer require stellarwp/foundation-container ## Container Configuration -Create a `config.php` in the application root that returns its settings as an -array. The [configuration example below](#making-a-configphp) includes catalog -and logging settings. - -Use `ContainerFactory` to create the container with your configuration and register -the application's providers. It creates the DI52 instance automatically: +Create the container with `ContainerFactory`, which sets up DI52 and registers +your configuration: ```php load(); } +// Load the project's configuration. See "Making a config.php" below. $values = require $path . '/config.php'; $configuration = new ArrayConfiguration($values); $factory = new ContainerFactory(); $container = $factory->create($configuration); +// Register the application providers in dependency order. $providers = [ CatalogProvider::class, ]; @@ -54,16 +53,8 @@ foreach ($providers as $provider) { } ``` -Register providers in dependency order. - -## Service Providers - -Extend `Provider` to register services using `$this->container` and read -configuration through `$this->config`. - -For example, suppose the application owns a `Catalog` interface and an -`HttpCatalog` implementation whose constructor accepts `string $endpoint`. -The provider binds the implementation and supplies its endpoint from configuration: +Here is an example service provider. The application's `HttpCatalog` implements +`Catalog` and accepts an `$endpoint` constructor argument: ```php config`. Read settings +in the provider and inject the values into your services, as shown above. ### Making a config.php -Provide defaults for environment values that have not been set: +A sample `config.php` for a project, with defaults when environment values are not set: ```php config->get('log.channels.console.with.stream'); -```dotenv -CATALOG_ENDPOINT=https://example.com/catalog -LOG_LEVEL=info -LOG_CHANNEL=errorlog +// Get the log level. +$level = $this->config->get('log.level'); ``` -In WordPress, the application can set these values in `wp-config.php` before -WordPress loads the plugins: +If using `config.php` in a WordPress plugin, set the environment values in +`wp-config.php` before WordPress loads the plugins: ```php +// Inside wp-config.php. $_ENV['CATALOG_ENDPOINT'] = 'https://example.com/catalog'; $_ENV['LOG_LEVEL'] = 'info'; $_ENV['LOG_CHANNEL'] = 'errorlog'; ``` - -### Reading configuration - -`ArrayConfiguration` uses [Dot](https://github.com/adbario/php-dot-notation) for -nested lookups. Inside a provider: - -```php -$stream = $this->config->get('log.channels.console.with.stream'); -$level = $this->config->get('log.level', 'info'); -``` - -`has()` checks whether a key exists; `all()` returns the complete configuration array. From 8b0b046ab4da76671e4a331ea1d1c496cf2f5e2e Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:11:01 -0600 Subject: [PATCH 09/18] Highlight provider registration order with a GitHub alert --- src/Container/README.md | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/Container/README.md b/src/Container/README.md index 285c6071..38046628 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -43,7 +43,7 @@ $configuration = new ArrayConfiguration($values); $factory = new ContainerFactory(); $container = $factory->create($configuration); -// Register the application providers in dependency order. +// Register the application providers. $providers = [ CatalogProvider::class, ]; @@ -53,6 +53,9 @@ foreach ($providers as $provider) { } ``` +> [!WARNING] +> Register providers in dependency order. Providers that supply dependencies must be registered before providers that use them. + Here is an example service provider. The application's `HttpCatalog` implements `Catalog` and accepts an `$endpoint` constructor argument: From 4beb651ded424d6a437e3b0dd4fff2f1bbcac9fc Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:13:07 -0600 Subject: [PATCH 10/18] Restore service provider heading and optional environment example --- src/Container/README.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/Container/README.md b/src/Container/README.md index 38046628..753566aa 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -56,6 +56,8 @@ foreach ($providers as $provider) { > [!WARNING] > Register providers in dependency order. Providers that supply dependencies must be registered before providers that use them. +## Service Providers + Here is an example service provider. The application's `HttpCatalog` implements `Catalog` and accepts an `$endpoint` constructor argument: @@ -129,6 +131,14 @@ $stream = $this->config->get('log.channels.console.with.stream'); $level = $this->config->get('log.level'); ``` +An optional `.env` file for these settings could contain: + +```dotenv +CATALOG_ENDPOINT=https://example.com/catalog +LOG_LEVEL=info +LOG_CHANNEL=errorlog +``` + If using `config.php` in a WordPress plugin, set the environment values in `wp-config.php` before WordPress loads the plugins: From 835130a4b6badd32b79295db47901cc33a1a4a18 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:14:09 -0600 Subject: [PATCH 11/18] Restore Container capabilities introduction --- src/Container/README.md | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/Container/README.md b/src/Container/README.md index 753566aa..cda47dfc 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -3,8 +3,11 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -The DI container configuration and service provider implementation, using -[DI52](https://github.com/lucatume/di52) out of the box. +Foundation Container provides a shared container contract and service provider +base class, backed by [DI52](https://github.com/lucatume/di52) out of the box. + +It supports autowiring, contextual bindings, lazy WordPress callbacks, +cross-provider collections, and decorator chains. ## Installation From 0660f067f4e870f5491239c9780fed7d82e7e544 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:17:59 -0600 Subject: [PATCH 12/18] Add configuration assembly tip to Container README --- src/Container/README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/Container/README.md b/src/Container/README.md index cda47dfc..86a727c2 100644 --- a/src/Container/README.md +++ b/src/Container/README.md @@ -17,6 +17,9 @@ composer require stellarwp/foundation-container ## Container Configuration +> [!TIP] +> Combine shared defaults and overrides ***before*** creating `ArrayConfiguration`. Providers receive read-only configuration. + Create the container with `ContainerFactory`, which sets up DI52 and registers your configuration: From 45ac1253225ce2a00dfb63d5bfe61d2bf932faa4 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:21:41 -0600 Subject: [PATCH 13/18] Declare read-only CI defaults and clarify stack logging destinations --- .github/workflows/tests.yml | 3 +++ src/Log/README.md | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index df4b7da3..2e81d3db 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -5,6 +5,9 @@ on: branches: - main +permissions: + contents: read + jobs: ci: runs-on: ${{ matrix.os }} diff --git a/src/Log/README.md b/src/Log/README.md index 3cecbbb1..aa644f42 100644 --- a/src/Log/README.md +++ b/src/Log/README.md @@ -52,7 +52,7 @@ If the application already has a Foundation container, include these settings in Inject `Psr\Log\LoggerInterface` into application services. The logger is shared, so handler and processor changes remain in effect for that container's lifetime. -Built-in channels are `errorlog`, `console`, `null`, and `stack` (console plus error log). The level defaults to `debug`; select a channel explicitly. PSR-3 placeholders are interpolated while structured context is retained. +Built-in channels are `errorlog`, `console`, `null`, and `stack` (console plus PHP error log when available). The level defaults to `debug`; select a channel explicitly. PSR-3 placeholders are interpolated while structured context is retained. ## Custom destinations and stacks From 3c4116004362513e29d9ee42c0f18b53ecca97bf Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:26:03 -0600 Subject: [PATCH 14/18] Restore package creation guidance after workflow removal --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index 6aaa3c0e..4eb3ed6d 100644 --- a/README.md +++ b/README.md @@ -141,6 +141,7 @@ composer run foundation -- package:create The package argument can be a new package component such as `WPCli`, an existing package directory, short package name, or Composer package name, for example `Log`, `foundation-log`, or `stellarwp/foundation-log`. +If the package does not exist yet, the command asks whether to create the local scaffold in `src/` and asks for the Composer package name with a default such as `stellarwp/foundation-wpcli`. The scaffold includes the required `composer.json`, `README.md`, `.gitattributes`, and `.gitignore` files. After scaffolding, the command runs `composer monorepo merge` so the root `composer.json` includes the new package. The command runs as a dry run by default. It validates the required split package files, prints the target repository name and description, and shows the GitHub CLI commands it will run. @@ -154,6 +155,7 @@ The command runs as a dry run by default. It validates the required split packag composer run foundation -- package:create --apply ``` +The command creates the `stellarwp/foundation-` repository with the standard `[READ ONLY]` description and disables issues, wiki, projects, and pull requests. #### Generating WP-CLI Commands From 78cad3689b5f3f0dbb046f0424096d191a2af464 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:36:35 -0600 Subject: [PATCH 15/18] Fix deferred resolver factories and custom logging thresholds --- src/Container/ContainerAdapter.php | 4 +- src/Log/Handlers/MinimumLevelHandler.php | 60 ++++++++++ src/Log/LogProvider.php | 8 +- src/Log/README.md | 2 + tests/Feature/Log/ConfiguredLoggerTest.php | 44 +++++++ .../Log/Handlers/MinimumLevelHandlerTest.php | 108 ++++++++++++++++++ tests/Unit/Container/ContainerAdapterTest.php | 8 ++ 7 files changed, 232 insertions(+), 2 deletions(-) create mode 100644 src/Log/Handlers/MinimumLevelHandler.php create mode 100644 tests/Feature/Log/Handlers/MinimumLevelHandlerTest.php diff --git a/src/Container/ContainerAdapter.php b/src/Container/ContainerAdapter.php index e6f11234..533cc82c 100644 --- a/src/Container/ContainerAdapter.php +++ b/src/Container/ContainerAdapter.php @@ -153,12 +153,14 @@ public function mergeArrayVar(string $id, mixed $implementation): void { * {@inheritDoc} */ public function instance(mixed $id, array $buildArgs = [], ?array $afterBuildMethods = null): Closure { + $implementation = $this->adaptImplementation($id); + /** * @var Closure $factory */ $factory = $this->call( // @phpstan-ignore-next-line invalid DocBlock comments in DI52 - fn (): Closure => $this->container->instance($id, $buildArgs, $afterBuildMethods) + fn (): Closure => $this->container->instance($implementation, $buildArgs, $afterBuildMethods) ); return fn (): mixed => $this->resolveDeferred(static fn (): mixed => $factory()); diff --git a/src/Log/Handlers/MinimumLevelHandler.php b/src/Log/Handlers/MinimumLevelHandler.php new file mode 100644 index 00000000..a8f8773a --- /dev/null +++ b/src/Log/Handlers/MinimumLevelHandler.php @@ -0,0 +1,60 @@ += $this->minimumLevel && parent::isHandling($record); + } + + /** + * Preserve the wrapped handler's bubbling decision for accepted records. + * + * @param mixed $record The installed Monolog version's record representation. + */ + public function handle($record): bool { + if ($record['level'] < $this->minimumLevel) { + return false; + } + + return parent::handle($record); + } + + /** + * Preserve batch delivery while excluding records below the application threshold. + */ + public function handleBatch(array $records): void { + $accepted = []; + + foreach ($records as $record) { + if ($record['level'] >= $this->minimumLevel) { + $accepted[] = $record; + } + } + + if ($accepted === []) { + return; + } + + parent::handleBatch($accepted); + } +} diff --git a/src/Log/LogProvider.php b/src/Log/LogProvider.php index ecc6cabb..13c3226c 100644 --- a/src/Log/LogProvider.php +++ b/src/Log/LogProvider.php @@ -16,6 +16,7 @@ use StellarWP\Foundation\Container\Contracts\Resolver as C; use StellarWP\Foundation\Container\Exceptions\ContainerException; use StellarWP\Foundation\Log\Formatters\ColoredLineFormatter; +use StellarWP\Foundation\Log\Handlers\MinimumLevelHandler; use StellarWP\Foundation\Log\Handlers\NullHandler; use UnhandledMatchError; @@ -92,6 +93,7 @@ private function createLogger(C $c, int $level): Logger { $logger = new Logger($channel); $logger->pushProcessor($c->get(PsrLogMessageProcessor::class)); + $resolvedHandlers = []; foreach ($selected['channels'] ?? [$channel] as $name) { $definition = $channels[$name] ?? []; @@ -112,19 +114,23 @@ private function createLogger(C $c, int $level): Logger { ? new StreamHandler($definition['with']['stream'] ?? 'php://stdout', $level) : $c->get($definition['handler']); - if (in_array($handler, $logger->getHandlers(), true)) { + if (in_array($handler, $resolvedHandlers, true)) { throw new RuntimeException(sprintf( 'Log channel "%s" shares a handler instance with another stack entry. Use separate handler bindings or a single shared channel.', $name )); } + $resolvedHandlers[] = $handler; + if (isset($definition['formatter']) && $handler instanceof FormattableHandlerInterface) { $handler->setFormatter($c->get($definition['formatter'])); } if ($handler instanceof AbstractHandler) { $handler->setLevel($level); + } else { + $handler = new MinimumLevelHandler($handler, $level); } $logger->pushHandler($handler); diff --git a/src/Log/README.md b/src/Log/README.md index aa644f42..dce76449 100644 --- a/src/Log/README.md +++ b/src/Log/README.md @@ -76,6 +76,8 @@ Add channel definitions under `log.channels`. Each destination selects a registe ], ``` +The configured level is the minimum for every destination, including composite handlers. Their own filtering may be stricter. + A custom stream channel can use `Monolog\Handler\StreamHandler` with `with.stream` set to a path or open stream. Stack entries must identify concrete handler channels, not nested stacks. Separate entries must not resolve to the same handler instance. Monolog invokes handlers in reverse insertion order; handler bubbling controls further delivery. Foundation does not include an Axiom transport or automatically buffer records. The application supplies credentials, transport failure handling, buffer limits and flushing. [Foundation Shutdown](https://github.com/stellarwp/foundation-shutdown) provides an explicit end-of-request flush boundary. Long-running workers should flush between jobs rather than waiting for process termination. diff --git a/tests/Feature/Log/ConfiguredLoggerTest.php b/tests/Feature/Log/ConfiguredLoggerTest.php index de9d98e4..2839b886 100644 --- a/tests/Feature/Log/ConfiguredLoggerTest.php +++ b/tests/Feature/Log/ConfiguredLoggerTest.php @@ -120,6 +120,50 @@ public function test_a_custom_channel_resolves_handler_dependencies_through_the_ $this->assertTrue($audit->hasInfo('Custom handler dependency.')); } + public function test_the_configured_level_filters_composite_handlers(): void { + $this->configureLogger([ + 'channel' => 'audit', + 'level' => 'error', + 'channels' => [ + 'audit' => [ + 'handler' => GroupHandler::class, + ], + ], + ]); + $audit = new TestHandler(); + $this->container->when(GroupHandler::class)->needs('$handlers')->give([$audit]); + + $logger = $this->container->get(LoggerInterface::class); + $logger->debug('Below the configured threshold.'); + $logger->error('At the configured threshold.'); + + $this->assertCount(1, $audit->getRecords()); + $this->assertTrue($audit->hasError('At the configured threshold.')); + } + + public function test_a_shared_composite_handler_cannot_appear_twice_in_a_stack(): void { + $this->configureLogger([ + 'channel' => 'stack', + 'channels' => [ + 'stack' => [ + 'channels' => ['first', 'second'], + ], + 'first' => [ + 'handler' => GroupHandler::class, + ], + 'second' => [ + 'handler' => GroupHandler::class, + ], + ], + ]); + $this->container->singleton(GroupHandler::class, new GroupHandler([new TestHandler()])); + + $this->expectException(ContainerException::class); + $this->expectExceptionMessage('shares a handler instance'); + + $this->container->get(LoggerInterface::class); + } + public function test_an_application_can_define_a_named_stack(): void { $this->configureLogger([ 'channel' => 'background', diff --git a/tests/Feature/Log/Handlers/MinimumLevelHandlerTest.php b/tests/Feature/Log/Handlers/MinimumLevelHandlerTest.php new file mode 100644 index 00000000..dd6f7811 --- /dev/null +++ b/tests/Feature/Log/Handlers/MinimumLevelHandlerTest.php @@ -0,0 +1,108 @@ +debug('Debug.'); + $logger->warning('Warning.'); + $logger->error('Error.'); + $records = $collector->getRecords(); + + $handler = new MinimumLevelHandler(new TestHandler(LogLevel::ERROR), LogLevel::WARNING); + + $this->assertFalse($handler->isHandling($records[0])); + $this->assertFalse($handler->isHandling($records[1])); + $this->assertTrue($handler->isHandling($records[2])); + } + + public function test_direct_delivery_preserves_bubbling_and_excludes_lower_levels(): void { + $collector = new TestHandler(); + $logger = new Logger('records', [$collector]); + $logger->debug('Debug.'); + $logger->error('Error.'); + $records = $collector->getRecords(); + $sink = new TestHandler(LogLevel::DEBUG, false); + $handler = new MinimumLevelHandler($sink, LogLevel::ERROR); + + $this->assertFalse($handler->handle($records[0])); + $this->assertTrue($handler->handle($records[1])); + $this->assertCount(1, $sink->getRecords()); + } + + public function test_batch_delivery_filters_records_without_replaying_them(): void { + $collector = new TestHandler(); + $logger = new Logger('records', [$collector]); + $logger->debug('Debug.'); + $logger->error('Error.'); + $records = $collector->getRecords(); + $sink = new TestHandler(); + $handler = new MinimumLevelHandler($sink, LogLevel::ERROR); + + $handler->handleBatch($records); + $handler->handleBatch([$records[0]]); + $handler->handleBatch([]); + + $this->assertCount(1, $sink->getRecords()); + $this->assertTrue($sink->hasError('Error.')); + } + + public function test_closing_a_wrapped_composite_flushes_its_buffer(): void { + $sink = new TestHandler(); + $buffer = new BufferHandler($sink); + $handler = new MinimumLevelHandler(new GroupHandler([$buffer]), LogLevel::ERROR); + $logger = new Logger('buffered', [$handler]); + $logger->debug('Debug.'); + $logger->error('Error.'); + + $this->assertSame([], $sink->getRecords()); + + $logger->close(); + $logger->close(); + + $this->assertCount(1, $sink->getRecords()); + $this->assertTrue($sink->hasError('Error.')); + } + + public function test_reset_reaches_the_wrapped_handler(): void { + $sink = new TestHandler(); + $handler = new MinimumLevelHandler(new GroupHandler([$sink]), LogLevel::ERROR); + $logger = new Logger('resettable', [$handler]); + $logger->error('Error.'); + + $this->assertCount(1, $sink->getRecords()); + + $logger->reset(); + + $this->assertSame([], $sink->getRecords()); + } + + public function test_formatter_and_processors_reach_the_wrapped_handler(): void { + $sink = new TestHandler(); + $handler = new MinimumLevelHandler($sink, LogLevel::INFO); + $formatter = new JsonFormatter(); + $processor = new PsrLogMessageProcessor(); + $handler->setFormatter($formatter); + $handler->pushProcessor($processor); + $logger = new Logger('formatted', [$handler]); + $logger->info('Order {id}.', ['id' => 42]); + + $this->assertSame($formatter, $handler->getFormatter()); + $this->assertSame($formatter, $sink->getFormatter()); + $this->assertSame($processor, $handler->popProcessor()); + $this->assertTrue($sink->hasInfo('Order 42.')); + } +} diff --git a/tests/Unit/Container/ContainerAdapterTest.php b/tests/Unit/Container/ContainerAdapterTest.php index 14f048cf..266c1eff 100644 --- a/tests/Unit/Container/ContainerAdapterTest.php +++ b/tests/Unit/Container/ContainerAdapterTest.php @@ -27,6 +27,14 @@ public function test_it_returns_instance_builders_from_the_wrapped_container(): $this->assertSame('value', $factory()->value); } + public function test_deferred_closure_factories_receive_the_foundation_resolver(): void { + $backend = new DI52Container(); + $adapter = new ContainerAdapter($backend); + $factory = $adapter->instance(static fn (Resolver $resolver): Resolver => $resolver); + + $this->assertSame($adapter, $factory()); + } + public function test_it_returns_callbacks_from_the_wrapped_container(): void { $adapter = new ContainerAdapter(new DI52Container()); $callback = $adapter->callback(new ContainerAdapterSample('value'), 'read'); From 86e9dffef9a15a7b8e672ef5f287815b973d0f2d Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:36:36 -0600 Subject: [PATCH 16/18] Run Foundation workflows on Blacksmith with explicit Composer setup --- .../workflows/check-for-required-files.yml | 2 +- .github/workflows/monorepo-split.yml | 7 +- .github/workflows/quality.yml | 3 +- .github/workflows/tests.yml | 71 +++++++++++++++---- 4 files changed, 65 insertions(+), 18 deletions(-) diff --git a/.github/workflows/check-for-required-files.yml b/.github/workflows/check-for-required-files.yml index 04fa5128..5036c580 100644 --- a/.github/workflows/check-for-required-files.yml +++ b/.github/workflows/check-for-required-files.yml @@ -8,7 +8,7 @@ on: jobs: check-workflows: - runs-on: ubuntu-latest + runs-on: blacksmith-2vcpu-ubuntu-2404 steps: - name: Check out repository diff --git a/.github/workflows/monorepo-split.yml b/.github/workflows/monorepo-split.yml index 96908971..c286d5b0 100644 --- a/.github/workflows/monorepo-split.yml +++ b/.github/workflows/monorepo-split.yml @@ -13,7 +13,7 @@ env: jobs: list-repos: - runs-on: ubuntu-latest + runs-on: blacksmith-2vcpu-ubuntu-2404 outputs: matrix: ${{ steps.set-matrix.outputs.matrix }} @@ -28,7 +28,7 @@ jobs: split: needs: list-repos - runs-on: ubuntu-latest + runs-on: blacksmith-2vcpu-ubuntu-2404 strategy: fail-fast: false @@ -70,7 +70,7 @@ jobs: bump-next-development-line: needs: split if: ${{ startsWith(github.ref, 'refs/tags/') }} - runs-on: ubuntu-latest + runs-on: blacksmith-2vcpu-ubuntu-2404 steps: - name: Determine next development line @@ -107,6 +107,7 @@ jobs: with: php-version: '8.3' coverage: none + tools: composer:v2 - name: Install Composer dependencies if: ${{ steps.version.outputs.should_bump == 'true' }} diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 28614770..8dd235f4 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -7,7 +7,7 @@ on: jobs: ci: - runs-on: ubuntu-latest + runs-on: blacksmith-2vcpu-ubuntu-2404 name: Code Quality steps: @@ -19,6 +19,7 @@ jobs: with: php-version: '8.3' coverage: pcov + tools: composer:v2 - name: Detect File Changes uses: dorny/paths-filter@v4 diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 2e81d3db..7351ee59 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -10,13 +10,13 @@ permissions: jobs: ci: - runs-on: ${{ matrix.os }} + runs-on: blacksmith-2vcpu-ubuntu-2404 strategy: fail-fast: true matrix: - os: [ ubuntu-latest ] php: [ '8.3', '8.4', '8.5' ] - name: Tests PHP${{ matrix.php }} - ${{ matrix.os }} + # Preserve existing required-check names when changing runner providers. + name: Tests PHP${{ matrix.php }} - ubuntu-latest steps: - name: Checkout code @@ -27,6 +27,7 @@ jobs: with: php-version: ${{ matrix.php }} coverage: none + tools: composer:v2 - name: Install Composer dependencies uses: ramsey/composer-install@v4 @@ -40,7 +41,7 @@ jobs: run: vendor/bin/phpunit --configuration ./phpunit.xml.dist --colors=always --testsuite Feature monolog: - runs-on: ubuntu-latest + runs-on: blacksmith-2vcpu-ubuntu-2404 name: Monolog ${{ matrix.monolog }} compatibility strategy: fail-fast: false @@ -56,6 +57,7 @@ jobs: with: php-version: '8.3' coverage: none + tools: composer:v2 - name: Install Composer dependencies uses: ramsey/composer-install@v4 @@ -74,14 +76,9 @@ jobs: vendor/bin/phpunit --configuration phpunit.xml.dist tests/Feature/Log slic: - runs-on: ubuntu-latest + runs-on: blacksmith-2vcpu-ubuntu-2404 name: SLIC Tests - permissions: - contents: read - pull-requests: write - statuses: write - env: COMPOSER_AUTH: '{"github-oauth": {"github.com": "${{ github.token }}"}}' @@ -97,6 +94,27 @@ jobs: path: slic fetch-depth: 1 + - name: Set up host PHP and Composer + uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + coverage: none + tools: composer:v2 + + - name: Get Composer cache directory + id: composer-cache-directory + run: | + cache_directory=$(composer config cache-dir --absolute) + echo "path=$cache_directory" >> "$GITHUB_OUTPUT" + + - name: Restore Composer cache + uses: actions/cache@v6 + with: + path: ${{ steps.composer-cache-directory.outputs.path }} + key: ${{ runner.os }}-composer-slic-php8.3-v1-${{ hashFiles('composer.lock', 'composer.json', 'src/*/composer.json') }} + restore-keys: | + ${{ runner.os }}-composer-slic-php8.3-v1- + - name: Set SLIC environment variables run: | echo "SLIC_BIN=${GITHUB_WORKSPACE}/slic/slic" >> $GITHUB_ENV @@ -112,6 +130,8 @@ jobs: echo "SSH_AUTH_SOCK=/tmp/ssh_agent.sock" >> $GITHUB_ENV - name: Configure SLIC + env: + COMPOSER_CACHE_PATH: ${{ steps.composer-cache-directory.outputs.path }} run: | cd "${GITHUB_WORKSPACE}/.." "${SLIC_BIN}" here @@ -121,13 +141,13 @@ jobs: "${SLIC_BIN}" xdebug off "${SLIC_BIN}" debug on "${SLIC_BIN}" php-version set 8.3 --skip-rebuild + "${SLIC_BIN}" composer-cache set "$COMPOSER_CACHE_PATH" "${SLIC_BIN}" info "${SLIC_BIN}" config - name: Install dependencies run: | "${SLIC_BIN}" use foundation - "${SLIC_BIN}" composer set-version 2 "${SLIC_BIN}" composer install - name: Update WordPress @@ -163,14 +183,39 @@ jobs: run: | "${SLIC_BIN}" run --coverage --coverage-xml clover.xml --disable-coverage-php --ext DotReporter - - name: Monitor coverage + - name: Upload coverage report if: github.event_name == 'pull_request' + uses: actions/upload-artifact@v7 + with: + name: coverage-report + path: tests/_output/clover.xml + if-no-files-found: error + retention-days: 1 + + coverage: + if: github.event_name == 'pull_request' + needs: slic + runs-on: blacksmith-2vcpu-ubuntu-2404 + name: Monitor coverage + + permissions: + contents: read + pull-requests: write + statuses: write + + steps: + - name: Download coverage report + uses: actions/download-artifact@v8 + with: + name: coverage-report + + - name: Monitor coverage uses: slavcodev/coverage-monitor-action@v1 with: github_token: ${{ secrets.GITHUB_TOKEN }} comment_footer: false coverage_format: clover - coverage_path: tests/_output/clover.xml + coverage_path: clover.xml threshold_alert: 90 threshold_warning: 95 threshold_metric: "lines" From 46444c5d72a0b1f629232eb0ce430788efd415db Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 11:42:39 -0600 Subject: [PATCH 17/18] Include Pipeline execution contract and lifecycle fixes from PR 6 --- UPGRADING-2.0.md | 8 + src/Pipeline/Contracts/Pipeline.php | 36 ++++ .../Exceptions/PipelineNotStarted.php | 12 ++ src/Pipeline/Pipeline.php | 189 ++++++------------ src/Pipeline/README.md | 92 ++++++++- .../Fixtures/Pipeline/MultipleMethodsPipe.php | 32 +++ tests/Unit/Pipeline/PipelineTest.php | 135 +++++++++++-- 7 files changed, 357 insertions(+), 147 deletions(-) create mode 100644 src/Pipeline/Contracts/Pipeline.php create mode 100644 src/Pipeline/Exceptions/PipelineNotStarted.php create mode 100644 tests/Support/Fixtures/Pipeline/MultipleMethodsPipe.php diff --git a/UPGRADING-2.0.md b/UPGRADING-2.0.md index 37409683..d9096629 100644 --- a/UPGRADING-2.0.md +++ b/UPGRADING-2.0.md @@ -26,6 +26,14 @@ The former public `LogProvider::LOG_LEVEL`, `CHANNEL_ERRORLOG` and `CHANNELS` im Custom channels and stacks can resolve application-defined handlers. Built-in channel names remain `errorlog`, `console`, `null` and `stack`; use those strings in configuration. Duplicate handler instances in a stack are rejected to prevent conflicting destination setup. +## Pipelines + +Construct pipelines with Foundation's `Contracts\Resolver`, or resolve the concrete `Pipeline` through the container. The optional/null constructor argument and `setContainer()` are removed. Consumers can depend on `Pipeline\Contracts\Pipeline` for `send()`, `then()`, and `thenReturn()`; configure the concrete implementation in a provider. See the [Pipeline examples](src/Pipeline/README.md). + +Call `send()` before execution. Missing input now throws `PipelineNotStarted` instead of an uninitialized-property error; `send(null)` remains valid. + +Execution state and helpers are private. Subclasses using `carry()`, `prepareDestination()`, `parsePipeString()`, `pipes()`, `getContainer()`, `handleCarry()`, or `handleException()` must move that behavior into pipes or implement the execution contract. Wrap `$next()` inside a pipe to transform its result or catch a downstream exception. The fluent `send()` return type is now `static`; overrides must use a compatible return type. + ## New packages - [Shutdown](src/Shutdown/README.md) runs application-owned termination tasks with failure isolation and deterministic ordering. It does not add an Axiom transport, retry queue or automatic log buffering. diff --git a/src/Pipeline/Contracts/Pipeline.php b/src/Pipeline/Contracts/Pipeline.php new file mode 100644 index 00000000..4873030b --- /dev/null +++ b/src/Pipeline/Contracts/Pipeline.php @@ -0,0 +1,36 @@ +container = $container; + public function __construct( + private readonly Resolver $container + ) { } /** - * Set the container instance. + * Supply the value for this execution, including an explicit null. * * @return $this */ - public function setContainer(Container $container): self { - $this->container = $container; - - return $this; - } - - /** - * Set the object being sent through the pipeline. - * - * @return $this - */ - public function send(mixed $passable): self { + public function send(mixed $passable): static { $this->passable = $passable; + $this->started = true; return $this; } /** - * Set the array of pipes. - * - * @param array|mixed $pipes + * Replace the configured pipes without changing the current value. * * @return $this */ @@ -79,8 +63,6 @@ public function through(mixed $pipes): self { /** * Push additional pipes onto the pipeline. * - * @param array|mixed $pipes - * * @return $this */ public function pipe(mixed $pipes): self { @@ -100,71 +82,54 @@ public function via(string $method): self { /** * Run the pipeline with a final destination callback. + * + * @throws PipelineNotStarted When no value has been supplied through {@see self::send()}. + * @throws Throwable When a pipe, container resolution, or the destination fails. */ public function then(Closure $destination): mixed { - $pipeline = array_reduce( - array_reverse($this->pipes()), $this->carry(), $this->prepareDestination($destination) - ); + if (! $this->started) { + throw new PipelineNotStarted('Call send() before executing the pipeline.'); + } + + $pipes = array_reverse($this->pipes); + $reducer = $this->carry(); + $pipeline = array_reduce($pipes, $reducer, $destination); return $pipeline($this->passable); } /** * Run the pipeline and return the result. + * + * @throws PipelineNotStarted When no value has been supplied through {@see self::send()}. + * @throws Throwable When a pipe or container resolution fails. */ public function thenReturn(): mixed { return $this->then(static fn ($passable) => $passable); } /** - * Get the final piece of the Closure onion. + * Build the reducer that wraps each pipe around the next stage. */ - protected function prepareDestination(Closure $destination): Closure { - return function ($passable) use ($destination) { - try { - return $destination($passable); - } catch (Throwable $e) { - return $this->handleException($passable, $e); - } - }; - } + private function carry(): Closure { + return function (Closure $next, mixed $pipe): Closure { + return function (mixed $passable) use ($next, $pipe): mixed { + if (is_callable($pipe)) { + return $pipe($passable, $next); + } - /** - * Get a Closure that represents a slice of the application onion. - */ - protected function carry(): Closure { - return function ($stack, $pipe) { - return function ($passable) use ($stack, $pipe) { - try { - if (is_callable($pipe)) { - // If the pipe is a callable, then we will call it directly, but otherwise we - // will resolve the pipes out of the dependency container and call it with - // the appropriate method and arguments, returning the results back out. - return $pipe($passable, $stack); - } elseif (! is_object($pipe)) { - [$name, $parameters] = $this->parsePipeString($pipe); - - // If the pipe is a string we will parse the string and resolve the class out - // of the dependency injection container. We can then build a callable and - // execute the pipe function giving in the parameters that are required. - $pipe = $this->getContainer()->get($name); - - $parameters = array_merge([$passable, $stack], $parameters); - } else { - // If the pipe is already an object we'll just make a callable and pass it to - // the pipe as-is. There is no need to do any extra parsing and formatting - // since the object we're given was already a fully instantiated object. - $parameters = [$passable, $stack]; - } - - $carry = method_exists($pipe, $this->method) - ? $pipe->{$this->method}(...$parameters) - : $pipe(...$parameters); - - return $this->handleCarry($carry); - } catch (Throwable $e) { - return $this->handleException($passable, $e); + if (is_object($pipe)) { + $parameters = [$passable, $next]; + } else { + [$name, $arguments] = $this->parsePipeString($pipe); + + $pipe = $this->container->get($name); + $parameters = array_merge([$passable, $next], $arguments); } + + return method_exists($pipe, $this->method) + ? $pipe->{$this->method}(...$parameters) + : $pipe(...$parameters); }; }; } @@ -172,53 +137,13 @@ protected function carry(): Closure { /** * Parse full pipe string to get name and parameters. * - * @return array + * @return array{string, list} */ - protected function parsePipeString(string $pipe): array { - [$name, $parameters] = array_pad(explode(':', $pipe, 2), 2, []); - - if (is_string($parameters)) { - $parameters = explode(',', $parameters); - } + private function parsePipeString(string $pipe): array { + $segments = explode(':', $pipe, 2); + $name = $segments[0]; + $parameters = isset($segments[1]) ? explode(',', $segments[1]) : []; return [$name, $parameters]; } - - /** - * Get the array of configured pipes. - * - * @return mixed[] - */ - protected function pipes(): array { - return $this->pipes; - } - - /** - * Get the container instance. - * - * @throws \RuntimeException - */ - protected function getContainer(): Container { - if (! $this->container) { - throw new RuntimeException('A container instance has not been passed to the Pipeline.'); - } - - return $this->container; - } - - /** - * Handle the value returned from each pipe before passing it to the next. - */ - protected function handleCarry(mixed $carry): mixed { - return $carry; - } - - /** - * Handle the given exception. - * - * @throws Throwable - */ - protected function handleException(mixed $passable, Throwable $e): mixed { - throw $e; - } } diff --git a/src/Pipeline/README.md b/src/Pipeline/README.md index 1f20a672..9788a775 100644 --- a/src/Pipeline/README.md +++ b/src/Pipeline/README.md @@ -3,10 +3,100 @@ > [!WARNING] > **This is a read-only repository!** For pull requests or issues, see [stellarwp/foundation](https://github.com/stellarwp/foundation). -A Pipeline / Command Design Pattern implementation based on [Laravel's Pipeline implementation](https://github.com/illuminate/pipeline/blob/master/Pipeline.php). +Foundation Pipeline passes values through ordered, container-resolved pipes. Each pipe can transform the value, stop execution, or continue to the next pipe. It is based on [Laravel's Pipeline implementation](https://github.com/illuminate/pipeline/blob/master/Pipeline.php). ## Installation ```shell composer require stellarwp/foundation-pipeline ``` + +## Define a pipe + +A pipe receives the current value and a `$next` closure. Pass the transformed value to `$next` to continue: + +```php +get(Pipeline::class); +$result = $pipeline + ->through(TrimTitle::class) + ->send(' New product ') + ->thenReturn(); + +// $result is 'New product'. +``` + +Use `then()` when a final callback should consume the processed value: + +```php +$result = $pipeline + ->send(' New product ') + ->then(static fn (string $title): string => strtoupper($title)); + +// $result is 'NEW PRODUCT'. +``` + +Call `send()` before execution. Executing without a value throws `PipelineNotStarted`; `null` is a valid value. A pipe can stop execution by returning without calling `$next`. Exceptions from pipes and the destination propagate unchanged, so a pipe can catch failures from `$next` when it owns recovery. + +## Configure a pipeline for a service + +Configure the concrete pipeline in a provider. Consumers can request the smaller `Contracts\Pipeline` interface, which exposes `send()`, `then()`, and `thenReturn()`. + +For an application service named `TitleImporter` that receives that interface, register this contextual binding in its provider: + +```php +use My\App\Titles\TitleImporter; +use My\App\Titles\TrimTitle; +use StellarWP\Foundation\Container\Contracts\Resolver; +use StellarWP\Foundation\Pipeline\Contracts\Pipeline as PipelineContract; +use StellarWP\Foundation\Pipeline\Pipeline; + +$this->container->when(TitleImporter::class) + ->needs(PipelineContract::class) + ->give(static function (Resolver $resolver): PipelineContract { + $pipeline = $resolver->get(Pipeline::class); + + return $pipeline->through(TrimTitle::class); + }); +``` + +> [!WARNING] +> Keep configured pipelines transient with `bind()` rather than `singleton()`. Sending values and configuring pipes changes the instance, so sharing it between consumers can carry state from one operation into another. + +## Pipe forms + +| Form | Behavior | +| --- | --- | +| Class name | Resolved through the container, then its `handle()` method is called, falling back to `__invoke()`. | +| Non-invokable object | Used directly through its `handle()` method. | +| Callable or invokable object | Called directly with the value and `$next`. | +| `ClassName:first,second` | Resolved through the container; extra string arguments follow the value and `$next`. | + +`through()` replaces the pipe list and `pipe()` appends to it. Both accept an array of pipes or separate arguments. Pipes run in the configured order. + +Use `via('process')` to choose another method for class-name or non-invokable object pipes. Callables and directly supplied invokable objects are still invoked directly. + +For different execution behavior, implement `Contracts\Pipeline`. To transform a downstream result or catch a downstream exception, wrap the `$next()` call inside a pipe. diff --git a/tests/Support/Fixtures/Pipeline/MultipleMethodsPipe.php b/tests/Support/Fixtures/Pipeline/MultipleMethodsPipe.php new file mode 100644 index 00000000..855e388f --- /dev/null +++ b/tests/Support/Fixtures/Pipeline/MultipleMethodsPipe.php @@ -0,0 +1,32 @@ +assertSame('A Sample String That Is Passed Through To All The Pipes.', $result); } - public function test_it_sets_the_container_after_construction(): void { - $result = (new Pipeline())->setContainer($this->container) - ->send('a sample string that is passed through to all pipes.') - ->through([ - PipelineStageOne::class, - PipelineStageTwo::class, - ])->thenReturn(); + public function test_it_exposes_a_minimal_execution_contract(): void { + $pipeline = $this->pipeline->through([ + PipelineStageOne::class, + PipelineStageTwo::class, + ]); + + $this->assertInstanceOf(PipelineContract::class, $pipeline); + $this->assertSame( + 'A Sample String That Is Passed Through To All The Pipes.', + $pipeline->send('a sample string that is passed through to all pipes.')->thenReturn() + ); + } - $this->assertSame('A Sample String That Is Passed Through To All The Pipes.', $result); + public function test_it_resolves_with_its_required_container_dependency(): void { + $pipeline = $this->container->get(Pipeline::class); + + $result = $pipeline->send('a sample string that is passed through to all pipes.') + ->through(PipelineStageOne::class) + ->thenReturn(); + + $this->assertSame('A Sample String That Is Passed Through To All Pipes.', $result); + } + + public function test_it_resolves_class_pipes_through_the_resolver_contract(): void { + $resolver = $this->createMock(Resolver::class); + $stage = new PipelineStageOne(); + + $resolver->expects($this->once()) + ->method('get') + ->with(PipelineStageOne::class) + ->willReturn($stage); + + $pipeline = new Pipeline($resolver); + $pipeline->through(PipelineStageOne::class); + + $result = $pipeline->send('sample value')->thenReturn(); + + $this->assertSame('Sample Value', $result); + } + + public function test_container_resolution_failures_propagate_unchanged(): void { + $resolver = $this->createMock(Resolver::class); + $failure = new ContainerException('Pipe dependency is unavailable.'); + + $resolver->expects($this->once()) + ->method('get') + ->with(PipelineStageOne::class) + ->willThrowException($failure); + + $pipeline = new Pipeline($resolver); + $pipeline->through(PipelineStageOne::class)->send('value'); + + try { + $pipeline->thenReturn(); + $this->fail('Expected the pipe resolution failure.'); + } catch (ContainerException $exception) { + $this->assertSame($failure, $exception); + } } public function test_it_pushes_additional_pipes(): void { @@ -146,6 +200,18 @@ public function __invoke(string $passable, Closure $next): string { $this->assertSame('A Sample String', $result); } + public function test_invokable_objects_take_precedence_over_default_and_configured_methods(): void { + $pipe = new MultipleMethodsPipe(); + + $this->assertSame('value:invoke', $this->pipeline->through($pipe)->send('value')->thenReturn()); + $this->assertSame('value:handle', $this->pipeline->through(MultipleMethodsPipe::class)->send('value')->thenReturn()); + + $this->pipeline->via('process'); + + $this->assertSame('value:invoke', $this->pipeline->through($pipe)->send('value')->thenReturn()); + $this->assertSame('value:process', $this->pipeline->through(MultipleMethodsPipe::class)->send('value')->thenReturn()); + } + public function test_it_rethrows_when_an_object_pipe_has_no_callable_handler(): void { $this->expectException(Error::class); @@ -172,12 +238,53 @@ public function test_it_rethrows_pipe_exceptions(): void { ->thenReturn(); } - public function test_it_requires_a_container_for_class_string_pipes(): void { - $this->expectException(RuntimeException::class); - $this->expectExceptionMessage('A container instance has not been passed to the Pipeline.'); + public function test_a_pipe_can_skip_later_pipes_and_the_destination(): void { + $result = $this->pipeline->send('input') + ->through( + static fn (): string => 'skipped', + static fn (): never => throw new RuntimeException('Later pipe must not run.') + ) + ->then(static fn (): never => throw new RuntimeException('Destination must not run.')); - (new Pipeline())->send('passable') - ->through(PipelineStageOne::class) - ->thenReturn(); + $this->assertSame('skipped', $result); + } + + public function test_a_pipe_can_transform_the_destination_result(): void { + $result = $this->pipeline->send('input') + ->through(static fn (string $value, Closure $next): string => '[' . $next($value) . ']') + ->then(static fn (string $value): string => strtoupper($value)); + + $this->assertSame('[INPUT]', $result); + } + + public function test_a_pipe_can_handle_a_downstream_failure(): void { + $failure = new RuntimeException('Destination failed.'); + $caught = null; + + $result = $this->pipeline->send('input') + ->through(static function (string $value, Closure $next) use (&$caught): string { + try { + return $next($value); + } catch (RuntimeException $exception) { + $caught = $exception; + + return 'fallback'; + } + }) + ->then(static fn (): never => throw $failure); + + $this->assertSame($failure, $caught); + $this->assertSame('fallback', $result); + } + + public function test_it_rejects_execution_before_a_value_is_sent(): void { + $this->expectException(PipelineNotStarted::class); + $this->expectExceptionMessage('Call send() before executing the pipeline.'); + + $this->pipeline->thenReturn(); + } + + public function test_it_accepts_null_as_an_explicit_passable_value(): void { + $this->assertNull($this->pipeline->send(null)->thenReturn()); } } From 9dca5d227b024a08b2a4cd81795124073a2950e8 Mon Sep 17 00:00:00 2001 From: Justin Frydman Date: Fri, 30 Oct 2026 19:18:43 -0600 Subject: [PATCH 18/18] Preserve handler thresholds and verify split publication --- .../workflows/check-for-required-files.yml | 3 ++ .github/workflows/monorepo-split.yml | 34 +++++++++++++++++- .github/workflows/quality.yml | 4 +++ AGENTS.md | 3 +- README.md | 4 ++- src/Log/LogProvider.php | 5 ++- tests/Feature/Log/ConfiguredLoggerTest.php | 35 +++++++++++++++++++ 7 files changed, 84 insertions(+), 4 deletions(-) diff --git a/.github/workflows/check-for-required-files.yml b/.github/workflows/check-for-required-files.yml index 5036c580..2dc9b230 100644 --- a/.github/workflows/check-for-required-files.yml +++ b/.github/workflows/check-for-required-files.yml @@ -6,6 +6,9 @@ on: branches: - main +permissions: + contents: read + jobs: check-workflows: runs-on: blacksmith-2vcpu-ubuntu-2404 diff --git a/.github/workflows/monorepo-split.yml b/.github/workflows/monorepo-split.yml index c286d5b0..f4565227 100644 --- a/.github/workflows/monorepo-split.yml +++ b/.github/workflows/monorepo-split.yml @@ -8,6 +8,14 @@ on: tags: - '*' +permissions: + contents: read + +# The action updates the same split branches for main and tags; serialize publication. +concurrency: + group: foundation-package-publication + cancel-in-progress: false + env: GITHUB_TOKEN: ${{ secrets.GH_BOT_TOKEN }} @@ -39,6 +47,9 @@ jobs: - name: Checkout uses: actions/checkout@v6 + - name: Check split credentials + run: test -n "$GITHUB_TOKEN" + # no tag - name: Split with no tag if: ${{ ! startsWith(github.ref, 'refs/tags/') }} @@ -57,7 +68,7 @@ jobs: if: ${{ startsWith(github.ref, 'refs/tags/')}} uses: moderntribe/monorepo-split-github-action@4.0.2 with: - tag: "${GITHUB_REF#refs/tags/}" + tag: ${{ github.ref_name }} package_directory: 'src/${{ matrix.package.directory }}' repository_organization: 'stellarwp' @@ -67,6 +78,27 @@ jobs: user_name: "StellarWP GitHub Action" user_email: "action@github.com" + # The upstream split action does not consistently fail on unsuccessful git pushes. + - name: Verify published package tree + env: + GH_TOKEN: ${{ secrets.GH_BOT_TOKEN }} + PACKAGE_REPOSITORY: ${{ matrix.package.name }} + PACKAGE_DIRECTORY: ${{ matrix.package.directory }} + shell: bash + run: | + set -euo pipefail + published_ref=main + if [[ "$GITHUB_REF" == refs/tags/* ]]; then + published_ref="$GITHUB_REF_NAME" + fi + expected_tree=$(git rev-parse "${GITHUB_SHA}:src/${PACKAGE_DIRECTORY}") + actual_tree=$(gh api "repos/stellarwp/${PACKAGE_REPOSITORY}/commits/${published_ref}" --jq '.commit.tree.sha') + if [[ "$actual_tree" != "$expected_tree" ]]; then + echo "Published ${PACKAGE_REPOSITORY}@${published_ref} does not match the release source." + exit 1 + fi + echo "Verified ${PACKAGE_REPOSITORY}@${published_ref}." + bump-next-development-line: needs: split if: ${{ startsWith(github.ref, 'refs/tags/') }} diff --git a/.github/workflows/quality.yml b/.github/workflows/quality.yml index 8dd235f4..f03211bf 100644 --- a/.github/workflows/quality.yml +++ b/.github/workflows/quality.yml @@ -5,6 +5,10 @@ on: branches: - main +permissions: + contents: read + pull-requests: read + jobs: ci: runs-on: blacksmith-2vcpu-ubuntu-2404 diff --git a/AGENTS.md b/AGENTS.md index 954a42c2..ae4766a3 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -171,7 +171,8 @@ After completing a feature, run `composer test:coverage`, review `clover.xml` fo - Adding a new split package is usually a minor SemVer release because it introduces new functionality without breaking existing packages. Use a major release only if the change also breaks an existing public API or package contract. - Run `composer monorepo bump-interdependency ` when planning a major version release so Foundation packages that depend on each other require the new major line, for example `^3.0`. It may also be useful for a minor release when one package must require APIs added in that new minor, for example `^1.1`. - Before publishing a release, verify the intended release-line package constraints are already committed. For a minor release such as `1.2.0`, internal Foundation package dependencies should already require the released line, for example `^1.2`. -- Publishing a GitHub release creates the release tag and triggers the tagged monorepo split. Wait for the tagged `Split Monorepo Packages and Release` workflow to succeed before considering the release complete. +- Verify all target split repositories exist and their packages are registered on Packagist before publication. `GH_BOT_TOKEN` must be available to the workflow, have contents and workflow write access to those repositories, and belong to an actor allowed to push the post-release bump to protected `main`. The workflow token cannot supply cross-repository write access. +- Publishing a GitHub release creates the release tag and triggers the tagged monorepo split. Wait for the tagged `Split Monorepo Packages and Release` workflow, including package-tree verification, to succeed. Verify Composer installation of the aggregate and split releases afterward. - After a successful tagged split for a minor or major `.0` release, the split workflow automatically bumps internal package constraints and branch aliases to the next development line on `main`, for example from `^1.2` and `1.2.x-dev` to `^1.3` and `1.3.x-dev`. - The post-release automation intentionally skips patch tags such as `1.2.1`, because patch releases should not move `dev-main` to a new minor development line. - If the post-release automation fails, fetch the release tag and manually run `composer monorepo bump-interdependency `, `composer monorepo package-alias`, and `composer monorepo merge`, then commit and push the updated package `composer.json` files. diff --git a/README.md b/README.md index 4eb3ed6d..82978e37 100644 --- a/README.md +++ b/README.md @@ -116,9 +116,11 @@ Before drafting the release, run only the monorepo maintenance commands that pre | You are planning a major version release, for example `2.0` to `3.0`. You should run this so any Foundation packages that depend on each other require the new major line, such as `^3.0`. You may also run it for a minor release if one package must require APIs added in that new minor version. | `composer monorepo bump-interdependency `, then `composer monorepo merge` | Updates package-to-package dependency constraints for the release being published. Use the release's minimum Composer constraint, such as `^3.0` or `^1.2`. | | Internal package constraints already match the release line. | No pre-release monorepo maintenance command is needed. | Continue to drafting the release. | +Before publishing, confirm every repository listed above exists with its read-only settings, each package is registered on [Packagist](https://packagist.org/packages/submit), and the release checks pass. The `GH_BOT_TOKEN` organization secret must be available to this repository, with contents and workflow write access to every split repository and permission to push the post-release bump to protected `main` (an allowed bypass actor). Workflow `GITHUB_TOKEN` permissions do not grant access to other repositories. + After any needed command, commit the updated `composer.json` files. Then draft a new release on [GitHub](https://github.com/stellarwp/foundation/releases/new), following [semver](https://semver.org/) closely. -The [monorepo split GitHub workflow](./.github/workflows/monorepo-split.yml) deploys each project's code to its sub-repository on pushes to `main` and when release tags are pushed. Publishing a GitHub release creates the release tag and triggers the tagged split. +The [monorepo split GitHub workflow](./.github/workflows/monorepo-split.yml) deploys each project's code to its sub-repository on pushes to `main` and when release tags are pushed. Publishing a GitHub release creates the release tag and triggers the tagged split. Wait for the tagged workflow to succeed: it verifies that every published package tree matches the tagged source. Then verify Composer can install the released aggregate and split packages. After a successful tagged split for a minor or major `.0` release, the workflow automatically moves `dev-main` to the next development line. For example, publishing `1.2.0` causes the workflow to bump internal constraints to `^1.3` and branch aliases to `1.3.x-dev`. Patch releases such as `1.2.1` intentionally skip this step. diff --git a/src/Log/LogProvider.php b/src/Log/LogProvider.php index 13c3226c..4d04aca9 100644 --- a/src/Log/LogProvider.php +++ b/src/Log/LogProvider.php @@ -128,7 +128,10 @@ private function createLogger(C $c, int $level): Logger { } if ($handler instanceof AbstractHandler) { - $handler->setLevel($level); + // A destination may intentionally reject more than the application's minimum. + $handlerLevelName = Logger::getLevelName($handler->getLevel()); + $handlerLevel = LogLevel::fromName(strtolower($handlerLevelName)); + $handler->setLevel(max($level, $handlerLevel)); } else { $handler = new MinimumLevelHandler($handler, $level); } diff --git a/tests/Feature/Log/ConfiguredLoggerTest.php b/tests/Feature/Log/ConfiguredLoggerTest.php index 2839b886..f345cba6 100644 --- a/tests/Feature/Log/ConfiguredLoggerTest.php +++ b/tests/Feature/Log/ConfiguredLoggerTest.php @@ -141,6 +141,41 @@ public function test_the_configured_level_filters_composite_handlers(): void { $this->assertTrue($audit->hasError('At the configured threshold.')); } + /** + * @param Logger::DEBUG|Logger::ERROR $handlerLevel + * + * @dataProvider handlerThresholds + */ + #[DataProvider('handlerThresholds')] + public function test_custom_handlers_keep_the_stricter_threshold(string $applicationLevel, int $handlerLevel): void { + $this->configureLogger([ + 'channel' => 'audit', + 'level' => $applicationLevel, + 'channels' => [ + 'audit' => ['handler' => TestHandler::class], + ], + ]); + $audit = new TestHandler($handlerLevel); + $this->container->singleton(TestHandler::class, $audit); + $logger = $this->container->get(LoggerInterface::class); + + $logger->debug('Below both thresholds.'); + $logger->warning('Below the stricter threshold.'); + $logger->error('At the stricter threshold.'); + + $this->assertCount(1, $audit->getRecords()); + $this->assertTrue($audit->hasError('At the stricter threshold.')); + } + + /** + * @return iterable + */ + public static function handlerThresholds(): iterable { + yield 'handler is stricter' => ['debug', Logger::ERROR]; + + yield 'application is stricter' => ['error', Logger::DEBUG]; + } + public function test_a_shared_composite_handler_cannot_appear_twice_in_a_stack(): void { $this->configureLogger([ 'channel' => 'stack',