Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Added

- **`Pollora\Testing\IsolatesWordPressHooks`: the hooks of one test no longer reach the next one** ([#741](https://github.com/Pollora/framework/issues/741)). A test process loads WordPress once and creates one application per test, so the callbacks of a flushed application stayed in `$wp_filter` and failed, or ran twice, when a later test fired them. Add the trait to the base test case of the project (`use IsolatesWordPressHooks;`); nothing changes without it. After each test, `$wp_filter`, `$wp_actions` and `$wp_filters` go back to what loading WordPress left: what the application or the test hooked is removed, what the core, plugins, must-use plugins and `functions.php` hooked is kept, as are the static methods hooked while the application booted and what `pollora/roles` and `pollora/schedule` hook once per process. It restores hooks only: other statics and WordPress globals still outlive a test, and, as before, a theme or plugin that registers from a file WordPress includes once is registered in the first application of the process only. A callback hooked by a file first included during a test is removed with the rest and does not come back. Requires `APP_ENV=testing` for the load to be recorded; without it, each test only gets back the hooks it started with.
- **`Pollora\Testing\IsolatesWordPressHooks`: the hooks of one test no longer reach the next one** ([#741](https://github.com/Pollora/framework/issues/741)). A test process loads WordPress once and creates one application per test, so the callbacks of a flushed application stayed in `$wp_filter` and failed, or ran twice, when a later test fired them. Add the trait to the base test case of the project (`use IsolatesWordPressHooks;`); nothing changes without it. After each test, `$wp_filter`, `$wp_actions` and `$wp_filters` go back to what loading WordPress left: what the application or the test hooked is removed, what the core, plugins, must-use plugins and `functions.php` hooked is kept, as are the static methods hooked while the application booted and what `pollora/roles` and `pollora/schedule` hook once per process. It restores hooks only: other statics and WordPress globals still outlive a test. A callback hooked by a file first included during a test is removed with the rest and does not come back. Requires `APP_ENV=testing` for the load to be recorded; without it, each test only gets back the hooks it started with.

### Changed

Expand All @@ -18,6 +18,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

### Fixed

- **In a test process, every application has the theme and plugins that register with Pollora, not only the first** ([#749](https://github.com/Pollora/framework/issues/749)). WordPress includes `functions.php` and plugin files once per process, so from the second test on `pollora_register()` was never called again: no theme views, configuration or providers, and no plugin ones. The calls made while WordPress loads are now remembered and repeated for each later application, and what they hook into `plugins_loaded`, `setup_theme`, `after_setup_theme`, `widgets_init`, `init` and `wp_loaded` runs again, without counting those actions twice; the callbacks of the earlier application they replace are unhooked, with or without `IsolatesWordPressHooks`. Only under unit tests (`APP_ENV=testing`): nothing is repeated elsewhere. Only `pollora_register()` is repeated: other code of `functions.php`, of a plugin file or of `app/inc` still runs once per process, as does a direct call to a registrar.
- **The files of a module's `app/inc` are included once per process.** A module registered a second time, as when a child theme and its parent both call `pollora_register(ModuleType::Theme)`, included them again, which is fatal when one declares a function.
- **`pollora:make:theme`, `pollora:make:plugin` and `pollora:make:module` can authenticate their requests to the GitHub API** ([#747](https://github.com/Pollora/framework/issues/747)). Since 13.45.1 nothing is downloaded when the list of tags cannot be read, and the anonymous limit of 60 requests an hour for each IP address is easily reached from a shared address such as a CI runner. Set `MODULES_GITHUB_TOKEN` (`modules.versions.github_token`, so far only used by the update checks of private modules) and those requests are authenticated. The token goes to `https://api.github.com` only: not to the archive or checksum downloads of github.com, and not along a redirect that leaves the API. It therefore does not make the archive of a private repository downloadable. `GITHUB_TOKEN` is not read: map it to `MODULES_GITHUB_TOKEN` where that is wanted. A refusal for a `403` or `429` now says how to configure the token. **If you already set `MODULES_GITHUB_TOKEN`**, these commands now send it too: a token that is expired or revoked makes them fail with a `401` where the anonymous request would have worked. Without a token nothing changes.

## [v13.45.1](https://github.com/Pollora/framework/compare/v13.45.0...v13.45.1) - 2026-12-03
Expand Down
12 changes: 5 additions & 7 deletions rector.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@
declare(strict_types=1);

use Rector\Config\RectorConfig;
use Rector\Php83\Rector\ClassMethod\AddOverrideAttributeToOverriddenMethodsRector;
use Rector\TypeDeclaration\Rector\ClassMethod\ScalarParamTypeByMethodCallTypeRector;
use Rector\DeadCode\Rector\ClassMethod\RemoveEmptyClassMethodRector;
use RectorLaravel\Rector\ArrayDimFetch\ServerVariableToRequestFacadeRector;
use RectorLaravel\Rector\FuncCall\UnlinkFuncCallToFileFacadeDeleteRector;
use RectorLaravel\Rector\MethodCall\ContainerBindConcreteWithClosureOnlyRector;
Expand All @@ -17,11 +16,10 @@
__DIR__.'/tests',
])
->withSkip([
AddOverrideAttributeToOverriddenMethodsRector::class,
// getAttribute($key) and setAttribute($key) override Eloquent's untyped
// signatures: typing $key would be a fatal incompatible declaration.
ScalarParamTypeByMethodCallTypeRector::class => [
__DIR__.'/src/Models/Concerns/HasTypedMeta.php',
// An empty method of a test double is there to be called or reflected:
// Rector 2.9.2 removes them.
RemoveEmptyClassMethodRector::class => [
__DIR__.'/tests',
],
// rector-laravel 2.7 turns every unlink() into File::delete(). The
// cleanup of temp files, caches and test fixtures runs where the
Expand Down
11 changes: 9 additions & 2 deletions src/Modules/Infrastructure/Services/ModuleAssetManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
use Pollora\Asset\Application\Services\AssetManager;
use Pollora\Foundation\Support\IncludesFiles;
use Psr\Log\LoggerInterface;
use Symfony\Component\Finder\Finder;

/**
* Generic module asset manager.
Expand Down Expand Up @@ -144,8 +145,14 @@ public function loadModuleIncludes(string $modulePath): void
{
$includeDirectory = $modulePath.'/app/inc';

if (is_dir($includeDirectory)) {
$this->includes($includeDirectory);
if (! is_dir($includeDirectory)) {
return;
}

// Once per process: a module registered again (a later application of a test process, a parent and a child
// theme) must not declare its functions twice
foreach (Finder::create()->files()->name('*.php')->in($includeDirectory)->sortByName() as $file) {
@include_once $file->getRealPath();
}
}

Expand Down
111 changes: 111 additions & 0 deletions src/Testing/ModuleRegistrations.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
<?php

declare(strict_types=1);

namespace Pollora\Testing;

use Pollora\Modules\Domain\Enums\ModuleType;

/**
* Registers again, in each later application of a test process, what `pollora_register()` was given while WordPress
* loaded.
*
* A theme registers from its `functions.php` and a plugin from its main file: WordPress includes them once, so only the
* application that loaded it would have them. {@see WordPressLoadRecorder} drives this, in unit tests only.
*
* @internal
*/
final class ModuleRegistrations
{
/**
* The actions of the load a registration hooks into. They take no argument, and are not fired again: only what the
* new registrations hooked into them runs. `widgets_init` comes first because WordPress fires it early in `init`.
*/
private const array LOAD_ACTIONS = [
'plugins_loaded',
'setup_theme',
'after_setup_theme',
'widgets_init',
'init',
'wp_loaded',
];

private static bool $recording = false;

/** @var array<string, array{ModuleType, ?string, ?string}> */
private static array $registrations = [];

/** What the load hooked, the framework's own callbacks included */
private static ?WordPressHookState $hookedByLoad = null;

private static ?WordPressHookState $hookedByLastReplay = null;

public static function startRecording(): void
{
self::$recording = true;
}

public static function stopRecording(): void
{
self::$recording = false;
}

public static function keepHooksOfLoad(WordPressHookState $hooks): void
{
if (self::$registrations !== []) {
self::$hookedByLoad = $hooks;
}
}

/**
* Remembers a call of `pollora_register()`. Does nothing outside of a recorded load.
*/
public static function record(ModuleType $type, ?string $name, ?string $path): void
{
if (! self::$recording) {
return;
}

// A parent and a child theme both register the theme: once is enough
self::$registrations[$type->value.':'.$name] ??= [$type, $name, $path];
}

/**
* Registers the recorded modules in the current application, then runs what they hooked into the actions the load
* already fired.
*/
public static function replay(): void
{
if (self::$registrations === []) {
return;
}

$before = WordPressHookState::capture();

foreach (self::$registrations as [$type, $name, $path]) {
pollora_register($type, $name, $path);
}

foreach (self::LOAD_ACTIONS as $action) {
if (($GLOBALS['wp_actions'][$action] ?? 0) > 0) {
$before->runCallbacksAddedTo($action);
}
}

// The callbacks of the registrations replaced here: bound to an application that is gone, or about to run the
// same code twice
$added = WordPressHookState::capture()->addedSince($before);

self::$hookedByLoad?->removeRegisteredAgain($before);
self::$hookedByLastReplay?->removeRegisteredAgain($before);
self::$hookedByLastReplay = $added;
}

public static function forget(): void
{
self::$recording = false;
self::$registrations = [];
self::$hookedByLoad = null;
self::$hookedByLastReplay = null;
}
}
97 changes: 97 additions & 0 deletions src/Testing/WordPressHookState.php
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,78 @@ public function with(self $other, \Closure $accepts): self
return new self($hooks, $this->actions, $this->filters);
}

/**
* Runs the callbacks an action gained since this state, and those only, in the order of their priorities.
* The others stay hooked, and the action is not counted as fired once more.
*/
public function runCallbacksAddedTo(string $action): void
{
$hook = $GLOBALS['wp_filter'][$action] ?? null;

if (! $hook instanceof \WP_Hook) {
return;
}

$added = clone $hook;

foreach (isset($this->hooks[$action]) ? $this->hooks[$action]->callbacks : [] as $priority => $callbacks) {
foreach ($callbacks as $callback) {
$added->remove_filter($action, $callback['function'], $priority);
}
}

if ($added->callbacks === []) {
return;
}

$GLOBALS['wp_filter'][$action] = $added;
$GLOBALS['wp_current_filter'][] = $action;

try {
$added->do_action(['']);
} finally {
array_pop($GLOBALS['wp_current_filter']);

// What the callbacks hooked into the action they were running in
foreach ($added->callbacks as $priority => $callbacks) {
foreach ($callbacks as $id => $callback) {
if (! isset($hook->callbacks[$priority][$id])) {
$hook->add_filter($action, $callback['function'], $priority, $callback['accepted_args']);
}
}
}

$GLOBALS['wp_filter'][$action] = $hook;
}
}

/**
* Unhooks the callbacks of this state that WordPress was given again since another one: the same code, at the same
* priority, from a new object. A theme class hooked during the load would otherwise run once for the application
* that loaded WordPress and once for the current one.
*/
public function removeRegisteredAgain(self $since): void
{
foreach ($this->hooks as $name => $hook) {
$current = $GLOBALS['wp_filter'][$name] ?? null;

if (! $current instanceof \WP_Hook) {
continue;
}

foreach ($hook->callbacks as $priority => $callbacks) {
$added = array_diff_key($current->callbacks[$priority] ?? [], ($since->hooks[$name] ?? null)?->callbacks[$priority] ?? []);
$code = array_filter(array_map(fn (array $callback): ?string => $this->code($callback['function']), $added));

foreach (array_diff_key($callbacks, $added) as $callback) {
if (\in_array($this->code($callback['function']), $code, true)) {
$current->remove_filter($name, $callback['function'], $priority);
}
}
}
}
}

/**
* Put WordPress back in this state. Callbacks removed since are back, in their order; the others are gone.
*/
Expand Down Expand Up @@ -138,6 +210,31 @@ private function objectCallbackFile(mixed $callback): ?string
return (new \ReflectionMethod($callback[0], $callback[1]))->getFileName() ?: null;
}

/**
* What tells that two callbacks of different objects are the same code, null for a callback without an object:
* WordPress already keys those by name.
*/
private function code(mixed $callback): ?string
{
if ($callback instanceof \Closure) {
$function = new \ReflectionFunction($callback);
$object = $function->getClosureThis();

return implode(':', [
$object === null ? '' : $object::class,
(string) $function->getFileName(),
(string) $function->getStartLine(),
$function->getName(),
]);
}

if (\is_object($callback)) {
return $callback::class.'::__invoke';
}

return \is_array($callback) && \is_object($callback[0] ?? null) ? $callback[0]::class.'::'.$callback[1] : null;
}

/**
* A `WP_Hook` is changed in place, so a state keeps and gives copies.
*
Expand Down
25 changes: 20 additions & 5 deletions src/Testing/WordPressLoadRecorder.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
* must-use plugins, the theme's `functions.php`) is never added again, so it has to outlive every test; what an
* application hooked before or after the load has not.
*
* The modules registered during that load are registered again in each later application ({@see ModuleRegistrations}).
*
* It only brackets the load: the caller includes `wp-settings.php` itself, so the variables of that file keep the
* scope they had.
*
Expand All @@ -28,19 +30,30 @@ final class WordPressLoadRecorder
public static function start(): void
{
self::$before = WordPressHookState::capture();
ModuleRegistrations::startRecording();
}

/**
* Call right after the load. Only the first load of the process counts.
* Call right after the load. Only the first load of the process counts; a later one, which included nothing,
* registers the modules of the first again.
*
* @param bool $alreadyLoaded WordPress was loaded before start(): all that was hooked then is kept
*/
public static function finish(bool $alreadyLoaded = false): void
{
$before = self::$before;
self::$before = null;
ModuleRegistrations::stopRecording();

if (! $before instanceof WordPressHookState) {
return;
}

if (! $before instanceof WordPressHookState || self::$loaded instanceof WordPressHookState) {
if ($alreadyLoaded) {
ModuleRegistrations::replay();
}

if (self::$loaded instanceof WordPressHookState) {
return;
}

Expand All @@ -52,9 +65,10 @@ public static function finish(bool $alreadyLoaded = false): void

// The theme and the plugins register with Pollora from files the load includes: what the framework hooks
// then belongs to this application, like the hooks it adds before or after the load
self::$loaded = WordPressHookState::capture()
->addedSince($before)
->withoutObjectCallbacksFrom(\dirname(__DIR__));
$added = WordPressHookState::capture()->addedSince($before);
ModuleRegistrations::keepHooksOfLoad($added);

self::$loaded = $added->withoutObjectCallbacksFrom(\dirname(__DIR__));
}

/**
Expand All @@ -69,5 +83,6 @@ public static function forget(): void
{
self::$before = null;
self::$loaded = null;
ModuleRegistrations::forget();
}
}
4 changes: 4 additions & 0 deletions src/helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
use Pollora\Modules\Domain\Enums\ModuleType;
use Pollora\Plugin\Application\Services\PluginRegistrar;
use Pollora\Support\RecursiveMenuIterator;
use Pollora\Testing\ModuleRegistrations;
use Pollora\Theme\Domain\Contracts\ThemeRegistrarInterface;

if (! function_exists('pollora_register')) {
Expand Down Expand Up @@ -45,6 +46,9 @@ function pollora_register(ModuleType $type, ?string $name = null, ?string $path
return;
}

// Only records while a test process loads WordPress, which includes the calling file once
ModuleRegistrations::record($type, $name, $path);

try {
match ($type) {
ModuleType::Theme => resolve(ThemeRegistrarInterface::class)->register(),
Expand Down
11 changes: 11 additions & 0 deletions tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,17 @@ public function log($level, string|Stringable $message, array $context = []): vo
unset($GLOBALS['pollora_inc_order']);
});

it('includes a file once, however often its module is registered', function (): void {
File::ensureDirectoryExists($this->module.'/app/inc');
$function = 'pollora_inc_'.str_replace('.', '', uniqid('', true));
file_put_contents($this->module.'/app/inc/helpers.php', "<?php function {$function}(): string { return 'declared'; }");

(new ModuleAssetManager($this->app))->loadModuleIncludes($this->module);
(new ModuleAssetManager($this->app))->loadModuleIncludes($this->module);

expect($function())->toBe('declared');
});

it('has no include to load when app/inc does not exist', function (): void {
(new ModuleAssetManager($this->app))->loadModuleIncludes($this->module);

Expand Down
Loading
Loading