diff --git a/CHANGELOG.md b/CHANGELOG.md index 6992704d..a134fbd8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 @@ -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 diff --git a/rector.php b/rector.php index 561beb55..b4fd2cd0 100644 --- a/rector.php +++ b/rector.php @@ -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; @@ -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 diff --git a/src/Modules/Infrastructure/Services/ModuleAssetManager.php b/src/Modules/Infrastructure/Services/ModuleAssetManager.php index d98ded73..e33f9fc0 100644 --- a/src/Modules/Infrastructure/Services/ModuleAssetManager.php +++ b/src/Modules/Infrastructure/Services/ModuleAssetManager.php @@ -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. @@ -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(); } } diff --git a/src/Testing/ModuleRegistrations.php b/src/Testing/ModuleRegistrations.php new file mode 100644 index 00000000..d23eae24 --- /dev/null +++ b/src/Testing/ModuleRegistrations.php @@ -0,0 +1,111 @@ + */ + 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; + } +} diff --git a/src/Testing/WordPressHookState.php b/src/Testing/WordPressHookState.php index 4704de20..0ab0a258 100644 --- a/src/Testing/WordPressHookState.php +++ b/src/Testing/WordPressHookState.php @@ -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. */ @@ -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. * diff --git a/src/Testing/WordPressLoadRecorder.php b/src/Testing/WordPressLoadRecorder.php index 8414b429..287649df 100644 --- a/src/Testing/WordPressLoadRecorder.php +++ b/src/Testing/WordPressLoadRecorder.php @@ -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. * @@ -28,10 +30,12 @@ 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 */ @@ -39,8 +43,17 @@ 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; } @@ -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__)); } /** @@ -69,5 +83,6 @@ public static function forget(): void { self::$before = null; self::$loaded = null; + ModuleRegistrations::forget(); } } diff --git a/src/helpers.php b/src/helpers.php index 95e49030..8b40daaf 100755 --- a/src/helpers.php +++ b/src/helpers.php @@ -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')) { @@ -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(), diff --git a/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php b/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php index 6a507221..864c1bab 100644 --- a/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php +++ b/tests/Feature/ModuleScaffold/ModuleAssetManagerTest.php @@ -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', "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); diff --git a/tests/Feature/Testing/ModuleRegistrationsTest.php b/tests/Feature/Testing/ModuleRegistrationsTest.php new file mode 100644 index 00000000..0a402bfd --- /dev/null +++ b/tests/Feature/Testing/ModuleRegistrationsTest.php @@ -0,0 +1,94 @@ +app); +}); + +afterEach(function (): void { + afterLoadingModules(); +}); + +/** + * @param Closure(): void $files what the load includes, nothing for a later one + */ +function loadWordPress(?Closure $files = null): void +{ + WordPressLoadRecorder::start(); + + if ($files instanceof Closure) { + $files(); + } + + WordPressLoadRecorder::finish(! $files instanceof Closure); +} + +it('repeats each registration of the load once, with its arguments, in their order', function (): void { + loadWordPress(function (): void { + pollora_register(ModuleType::Plugin, 'one', '/plugins/one'); + pollora_register(ModuleType::Theme); + pollora_register(ModuleType::Plugin, 'two', '/plugins/two'); + pollora_register(ModuleType::Theme); + pollora_register(ModuleType::Plugin, 'one', '/elsewhere/one'); + }); + takeModuleLog(); + + loadWordPress(); + + expect(takeModuleLog())->toBe([ + 'plugin one registered from /plugins/one', + 'theme registered', + 'plugin two registered from /plugins/two', + ]); +}); + +it('unhooks what the load, then each replay, had hooked and the next registration hooks again', function (): void { + loadWordPress(function (): void { + pollora_register(ModuleType::Theme); + }); + + foreach (['second', 'third'] as $ignored) { + loadWordPress(); + takeModuleLog(); + + fireHook('probe_content'); + + expect(takeModuleLog())->toHaveCount(1); + } +}); + +it('repeats nothing that was registered outside of a load', function (): void { + loadWordPress(static function (): void {}); + pollora_register(ModuleType::Theme); + takeModuleLog(); + + loadWordPress(); + + expect(takeModuleLog())->toBe([]) + ->and(hookedCallbacks()['probe_content'])->toBe(1); +}); + +it('forgets the registrations with the load', function (): void { + WordPressLoadRecorder::start(); + pollora_register(ModuleType::Theme); + WordPressLoadRecorder::forget(); + // No longer recording either + pollora_register(ModuleType::Theme); + takeModuleLog(); + + loadWordPress(); + + expect(takeModuleLog())->toBe([]); +}); diff --git a/tests/Feature/Testing/ReplaysModuleRegistrationsTest.php b/tests/Feature/Testing/ReplaysModuleRegistrationsTest.php new file mode 100644 index 00000000..37235335 --- /dev/null +++ b/tests/Feature/Testing/ReplaysModuleRegistrationsTest.php @@ -0,0 +1,64 @@ +toContain('theme registered', 'core init', 'theme init') + ->and(config('theme.menus'))->toBe(['primary']); +}); + +it('registers them again in the next one, and runs only what they hooked into the actions of the load', function (): void { + expect(takeModuleLog())->toBe(REPLAYED) + ->and(config('theme.menus'))->toBe(['primary']) + ->and(config('theme.templates'))->toBe(['wide']) + ->and($GLOBALS['wp_actions']['init'])->toBe(1) + ->and($GLOBALS['wp_filter']['init']->callbacks)->toHaveKeys([10, 20, 50]); + + $GLOBALS['probe_counts'] = hookedCallbacks(); + + // The theme class hooked by the first application is replaced, not joined + fireHook('probe_content'); + + expect(takeModuleLog())->toBe(['content of application '.spl_object_id(app())]); + + // Outside of the load: nothing to repeat + pollora_register(ModuleType::Plugin, 'from-a-test', '/plugins/from-a-test'); + takeModuleLog(); +}); + +it('gives every later application the same theme and as many callbacks', function (): void { + expect(takeModuleLog())->toBe(REPLAYED) + ->and(config('theme.menus'))->toBe(['primary']) + ->and(hookedCallbacks())->toBe($GLOBALS['probe_counts']); + + fireHook('probe_content'); + + expect(takeModuleLog())->toBe(['content of application '.spl_object_id(app())]); + + unset($GLOBALS['probe_counts']); +}); diff --git a/tests/Feature/Testing/ReplaysModuleRegistrationsWithoutIsolationTest.php b/tests/Feature/Testing/ReplaysModuleRegistrationsWithoutIsolationTest.php new file mode 100644 index 00000000..46d1c112 --- /dev/null +++ b/tests/Feature/Testing/ReplaysModuleRegistrationsWithoutIsolationTest.php @@ -0,0 +1,42 @@ +toContain('theme registered'); +}); + +it('replaces the callbacks of the earlier registration without the isolation trait', function (): void { + expect(takeModuleLog())->toContain('theme registered', 'theme init')->not->toContain('core init'); + + $GLOBALS['probe_counts'] = hookedCallbacks(); +}); + +it('does not pile them up application after application', function (): void { + takeModuleLog(); + + // Each earlier `init` callback of the theme hooked one more into `init` and `wp_loaded`, and none came back twice + expect(hookedCallbacks()['probe_content'])->toBe($GLOBALS['probe_counts']['probe_content']) + ->and(hookedCallbacks()['after_setup_theme'])->toBe($GLOBALS['probe_counts']['after_setup_theme']) + ->and(hookedCallbacks()['init'])->toBe($GLOBALS['probe_counts']['init']); + + fireHook('probe_content'); + + expect(takeModuleLog())->toBe(['content of application '.spl_object_id(app())]); + + unset($GLOBALS['probe_counts']); +}); diff --git a/tests/Support/Testing/IsolatedModuleLoadingTestCase.php b/tests/Support/Testing/IsolatedModuleLoadingTestCase.php new file mode 100644 index 00000000..2045cd1c --- /dev/null +++ b/tests/Support/Testing/IsolatedModuleLoadingTestCase.php @@ -0,0 +1,12 @@ + */ + public static array $log = []; + + public function register(): void + { + self::bindRegistrars($this->app); + } + + /** + * Binds registrars that log what they are asked to register. + */ + public static function bindRegistrars(Application $app): void + { + $app->instance(ThemeRegistrarInterface::class, new ProbeThemeRegistrar($app)); + + $plugins = Mockery::mock(PluginRegistrar::class); + $plugins->shouldReceive('register')->andReturnUsing(function (string $name, string $path): PluginModuleInterface { + self::$log[] = "plugin {$name} registered from {$path}"; + + hookInto('plugins_loaded', static function (): void { + self::$log[] = 'plugin plugins_loaded'; + }); + + return Mockery::mock(PluginModuleInterface::class); + }); + $app->instance(PluginRegistrar::class, $plugins); + } + + public function boot(): void + { + $alreadyLoaded = self::$loaded; + + WordPressLoadRecorder::start(); + + if (! $alreadyLoaded) { + hookInto('init', ModuleLoadingServiceProvider::class.'::coreInit'); + + pollora_register(ModuleType::Plugin, 'probe-plugin', '/plugins/probe-plugin'); + // A child theme and its parent both register the theme + pollora_register(ModuleType::Theme); + pollora_register(ModuleType::Theme); + + foreach (['plugins_loaded', 'after_setup_theme', 'init', 'widgets_init', 'wp_loaded'] as $action) { + fireHook($action); + } + + self::$loaded = true; + } + + WordPressLoadRecorder::finish($alreadyLoaded); + } + + public static function coreInit(): void + { + self::$log[] = 'core init'; + } + + public static function reset(): void + { + self::$loaded = false; + self::$log = []; + } +} diff --git a/tests/Support/Testing/ModuleLoadingTestCase.php b/tests/Support/Testing/ModuleLoadingTestCase.php new file mode 100644 index 00000000..7ab849ae --- /dev/null +++ b/tests/Support/Testing/ModuleLoadingTestCase.php @@ -0,0 +1,15 @@ +application; + } +} diff --git a/tests/Support/Testing/ProbeThemeRegistrar.php b/tests/Support/Testing/ProbeThemeRegistrar.php new file mode 100644 index 00000000..dcf88904 --- /dev/null +++ b/tests/Support/Testing/ProbeThemeRegistrar.php @@ -0,0 +1,64 @@ +app; + $name = 'application '.spl_object_id($app); + + ModuleLoadingServiceProvider::$log[] = 'theme registered'; + + hookInto('probe_content', [new ProbeThemeHooks($name), 'filterContent']); + + hookInto('init', static function () use ($app): void { + ModuleLoadingServiceProvider::$log[] = 'theme init'; + $app->make('config')->set('theme.templates', ['wide']); + + hookInto('init', static fn (): null => null, 50); + hookInto('wp_loaded', static function (): void { + ModuleLoadingServiceProvider::$log[] = 'theme wp_loaded'; + }); + }, 20); + + hookInto('widgets_init', static function (): void { + ModuleLoadingServiceProvider::$log[] = 'theme widgets_init'; + }); + + hookInto('after_setup_theme', static function () use ($app): void { + ModuleLoadingServiceProvider::$log[] = 'theme after_setup_theme'; + $app->make('config')->set('theme.menus', ['primary']); + }, 1); + + hookInto('rest_api_init', static function (): void { + ModuleLoadingServiceProvider::$log[] = 'theme rest_api_init'; + }); + + return \Mockery::mock(ThemeModuleInterface::class); + } + + public function getActiveTheme(): ?ThemeModuleInterface + { + return null; + } + + public function isThemeActive(string $themeName): bool + { + return false; + } + + public function resetActiveTheme(): void {} +} diff --git a/tests/Support/Testing/module-loading.php b/tests/Support/Testing/module-loading.php new file mode 100644 index 00000000..f8ccff70 --- /dev/null +++ b/tests/Support/Testing/module-loading.php @@ -0,0 +1,38 @@ + what was registered and run since the last call + */ +function takeModuleLog(): array +{ + $log = ModuleLoadingServiceProvider::$log; + ModuleLoadingServiceProvider::$log = []; + + return $log; +} diff --git a/tests/Support/Testing/wordpress-hooks.php b/tests/Support/Testing/wordpress-hooks.php index 3ee98905..68994dbd 100644 --- a/tests/Support/Testing/wordpress-hooks.php +++ b/tests/Support/Testing/wordpress-hooks.php @@ -36,6 +36,16 @@ public function remove_filter(string $hook, mixed $callback, int $priority): boo return true; } + /** @param array $args */ + public function do_action(array $args): void + { + foreach ($this->callbacks as $callbacks) { + foreach ($callbacks as $callback) { + ($callback['function'])(...$args); + } + } + } + public static function id(mixed $callback): string { if (is_string($callback)) {