diff --git a/.gitattributes b/.gitattributes index a32205b..c6e073e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -30,4 +30,6 @@ /CLAUDE.md linguist-documentation export-ignore /CHANGELOG.md linguist-documentation export-ignore -# Ship on purpose: README.md and LICENSE.md, inc/, plus ai/ and bin/sync-ai-instructions.js, which consumers run from vendor/ via `npm run sync-ai`. +# These are intentionally shipped. +/LICENSE.md linguist-documentation +/README.md linguist-documentation diff --git a/.github/ISSUE_TEMPLATE/feature.yml b/.github/ISSUE_TEMPLATE/feature.yml index c48eca1..e540047 100644 --- a/.github/ISSUE_TEMPLATE/feature.yml +++ b/.github/ISSUE_TEMPLATE/feature.yml @@ -7,17 +7,8 @@ body: - type: markdown attributes: value: >- - Thanks for the suggestion. Please search - [existing issues](https://github.com/rtCamp/wp-primitives/issues?q=is%3Aissue) - first. - - type: markdown - attributes: - value: >- - `inc/Contracts/` is public API: every rtCamp plugin and theme consumes - it, so changing a signature there is a breaking change. The package also - keeps zero Composer runtime dependencies. - [CONTRIBUTING.md](https://github.com/rtCamp/wp-primitives/blob/main/.github/CONTRIBUTING.md) - explains how to build it yourself. + Thanks for the suggestion. Please search [existing issues](https://github.com/rtCamp/wp-primitives/issues?q=is%3Aissue) first. + See [CONTRIBUTING.md](https://github.com/rtCamp/wp-primitives/blob/main/.github/CONTRIBUTING.md) for contribution guidelines. - type: dropdown id: area attributes: diff --git a/.github/SECURITY.md b/.github/SECURITY.md index 16374c6..b43e984 100644 --- a/.github/SECURITY.md +++ b/.github/SECURITY.md @@ -9,11 +9,11 @@ ## Reporting a vulnerability -Please do not report security issues in public issues, pull requests or discussions. +In the interest of responsible disclosure, please **do not** report security issues in public issues, pull requests or discussions. -Report them privately through GitHub instead: open the repository's **Security** tab and choose **Report a vulnerability**, or go straight to . The report stays visible only to you and the maintainers, and the fix, the release and the advisory are coordinated in that same thread. +Instead, report security issues privately through GitHub: open the repository's **Security** tab and choose **Report a vulnerability**, or go to . -Include what you can of: +Make sure to include as much as you can of: - the affected class or method and the package version; - the impact, and the conditions an attacker needs; diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 43ce74e..b6943f5 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -21,7 +21,7 @@ Detailed rules: `.github/instructions/php.instructions.md`. ## Review conduct -- **One comment per distinct issue** Distinct problems get separate comments, even on the same line. A single root cause spanning lines → posted once at the clearest line. +- **One comment per distinct issue.** Distinct problems get separate comments, even on the same line. Post a single root cause spanning lines once, at the clearest line. - **Always post the missing-tests finding** when a new/changed class ships without a matching test in `tests/phpunit/Integration/`. Mandatory; exempt from dedupe/trim/comment-budget. - **Order by impact:** backward-compatibility/contract break → correctness → security → style. - **On a correct, deliberate implementation, don't manufacture findings.** Prefer zero comments over low-value ones. A clean PR comes back clean. diff --git a/.github/instructions/php.instructions.md b/.github/instructions/php.instructions.md index e95ccd6..b7ccb1f 100644 --- a/.github/instructions/php.instructions.md +++ b/.github/instructions/php.instructions.md @@ -23,9 +23,9 @@ Everything under `inc/Contracts/` is a **consumed contract**. New abstracts/inte ## Flag on review (priority order) -1. 🚩 **MANDATORY: always post, exempt from dedupe/trim/budget:** a new or changed class/trait/interface shipped without a matching test in `tests/phpunit/Integration/`. -2. 🚩 Backward-incompatible change to anything under `inc/Contracts/` (renamed/removed/retyped public method, changed abstract signature) without a documented migration. This breaks every consumer. -3. 🚩 A new dependency added to `composer.json` `require` (must stay `php`-only; dev tools go in `require-dev`). -4. 🚩 Missing `strict_types`/types/docblocks; PSR-4 mismatch; `self::` where `static::` is required. -5. 🚩 Missing escape/sanitize where the utility touches WordPress output/input; raw `$wpdb` without `prepare()`. -6. 🚩 New abstract/interface that doesn't follow the existing contract shape (e.g. an `Abstract*` not implementing `Registrable`, or duplicating a capability the `Loader`/`Container` already provides). +1. **MANDATORY: always post, exempt from dedupe/trim/budget:** a new or changed class/trait/interface shipped without a matching test in `tests/phpunit/Integration/`. +2. Backward-incompatible change to anything under `inc/Contracts/` (renamed/removed/retyped public method, changed abstract signature) without a documented migration. This breaks every consumer. +3. A new dependency added to `composer.json` `require` (must stay `php`-only; dev tools go in `require-dev`). +4. Missing `strict_types`/types/docblocks; PSR-4 mismatch; `self::` where `static::` is required. +5. Missing escape/sanitize where the utility touches WordPress output/input; raw `$wpdb` without `prepare()`. +6. New abstract/interface that doesn't follow the existing contract shape (e.g. an `Abstract*` not implementing `Registrable`, or duplicating a capability the `Loader`/`Container` already provides). diff --git a/.github/labels.yml b/.github/labels.yml index 772850a..ae794e2 100644 --- a/.github/labels.yml +++ b/.github/labels.yml @@ -1,16 +1,15 @@ # Labels for rtCamp/wp-primitives. # -# Labels are repository settings, not files, so adding an entry here does not -# create the label. A maintainer applies this list by running +# To apply these labels to the repository, run # `gh label create --color --description --force` -# for each entry: missing labels are created and existing ones updated. That -# never deletes a label, so removing an entry here does not remove it on GitHub. +# for each entry, which creates missing labels and updates existing ones. +# +# To remove an existing label, you must delete it manually on GitHub or use +# `gh label delete ` # # The "Shared" sections are the same in all five rtCamp framework repositories # (wp-shared-workflows, wp-primitives, wp-tooling, theme-elementary and -# plugin-elementary), apart from the wording of the BC descriptions; change them -# in all five together. The sections after them belong to this repository. -# .github/release.yml groups release notes by these labels. +# plugin-elementary), and should be changed together across all repositories. # --- Shared: type ------------------------------------------------------------ - name: 'Type: Bug' @@ -104,7 +103,7 @@ description: 'Shared traits (Singleton)' - name: 'Scope: Quality Config' color: '0075CA' - description: 'phpcs.xml.dist + phpstan.neon.dist' + description: 'phpcs.xml.dist and phpstan.neon.dist' - name: 'Scope: Tests' color: 'BFDADC' description: 'PHPUnit test suite' @@ -112,7 +111,7 @@ color: 'FEF2C0' description: 'Documentation' -# --- Legacy: keep until relabelled ------------------------------------------- +# --- wp-devtools: keep until relabelled -------------------------------------- # These describe wp-devtools code that is not in this package. They are still on # closed issues, so they stay until those are relabelled; don't use them on new # issues. diff --git a/.github/release.yml b/.github/release.yml deleted file mode 100644 index 0357637..0000000 --- a/.github/release.yml +++ /dev/null @@ -1,31 +0,0 @@ -# Groups GitHub's automatically generated release notes by the shared labels -# in .github/labels.yml. A pull request goes under the first category whose -# labels it carries; an unlabelled one goes under "Other". -changelog: - exclude: - # Dependabot's routine bumps are noise in release notes. A dependency - # change a person makes still shows under "Dependencies". - authors: - - dependabot - - dependabot[bot] - - dependabot-preview - categories: - - title: Breaking changes - labels: - - 'BC: Breaking' - - title: Features - labels: - - 'Type: Feature' - - 'BC: Additive' - - title: Fixes - labels: - - 'Type: Bug' - - title: Docs - labels: - - 'Type: Docs' - - title: Dependencies - labels: - - dependencies - - title: Other - labels: - - '*' diff --git a/.github/workflows/auto-merge.yml b/.github/workflows/auto-merge.yml index b4a508d..dd81af2 100644 --- a/.github/workflows/auto-merge.yml +++ b/.github/workflows/auto-merge.yml @@ -1,13 +1,10 @@ name: Dependabot auto-merge -# GitHub's documented pattern: run on the Dependabot pull request itself (no -# workflow_run, no checkout), read the update type from Dependabot's metadata and -# enable auto-merge for minor and patch updates. Auto-merge then waits for every -# ruleset requirement, so the "Test and Measure" jobs must be required status -# checks for a red run to block the merge. +# Enables auto-merge for Dependabot minor and patch updates. # -# Repository prerequisites (Settings): "Allow auto-merge" enabled, and the main -# ruleset's required reviews satisfiable for Dependabot pull requests. +# Requires "Allow auto-merge" in the repository settings, and the "Test and Measure" jobs as required +# status checks so a failing run blocks the merge. +# @see https://docs.github.com/en/code-security/dependabot/working-with-dependabot/automating-dependabot-with-github-actions on: pull_request diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index d67d755..65e1d4a 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -43,9 +43,8 @@ jobs: - name: Build documentation id: docs - # Pinned to a commit: the action's code only lives on the unmerged - # codex/documentation-workflow branch (rtCamp/action-docusaurus-build#1). - # Move to a release tag once that PR merges and is tagged. + # @todo Switch to a release tag commit once the Action is merged and tagged. + # @see https://github.com/rtCamp/action-docusaurus-build#1. uses: rtCamp/action-docusaurus-build@b671d6800c68a74da8913edb9321422fe8afaedc # codex/documentation-workflow, 2026-09-17 with: site-title: ${{ vars.DOCS_SITE_TITLE }} diff --git a/.github/workflows/pr-title.yml b/.github/workflows/pr-title.yml index 0481c81..4a04cf6 100644 --- a/.github/workflows/pr-title.yml +++ b/.github/workflows/pr-title.yml @@ -1,11 +1,6 @@ name: PR Title Validation -# Pull requests are squash-merged and the PR title becomes the commit on main. release-please -# reads those subjects to pick the next version and write CHANGELOG.md, so the title has to be a -# Conventional Commit: feat -> minor, fix -> patch, a "!" after the type -> major. -# -# Not a required status check: the release pull request is opened with GITHUB_TOKEN, which -# starts no workflow runs, so this check never reports on it. +# Ensures PR titles follow the Conventional Commit format, so they can be used during release notes generation. on: pull_request: diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 82fdbd7..9bd876c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,14 +1,7 @@ name: Release -# release-please reads the Conventional Commit subjects squash-merged to main and keeps one -# release pull request open that bumps the version and writes CHANGELOG.md. Merging that pull -# request tags vX.Y.Z on main and publishes the GitHub release with the changelog entry as notes. -# -# The release pull request is opened with GITHUB_TOKEN, so GitHub starts no workflow runs on it -# (no tests, no PR title check). Keep the PR title check out of the required checks. If the Test -# and Measure jobs become required, as auto-merge.yml expects for Dependabot, a release pull -# request waits on checks that never start: switch the token below to a GitHub App token, which -# starts them, or have a maintainer push an empty commit to the release branch, which does too. +# Opens the release pull request and publishes releases with release-please. +# @see docs/maintainers.md#releasing on: push: diff --git a/.gitignore b/.gitignore index 3199f6d..4ec1777 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,7 @@ /vendor/ /node_modules/ -# macOS/IDE +# OS and editor files .DS_Store Thumbs.db .idea/ @@ -16,7 +16,7 @@ Thumbs.db tests/_output/* !tests/_output/.gitkeep -# Local Configs +# Local config overrides /phpcs.xml /phpunit.xml /phpstan.neon diff --git a/CLAUDE.md b/CLAUDE.md index e6cd04b..43c994c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,7 +1 @@ -# CLAUDE.md - -Read **[AGENTS.md](AGENTS.md)**: it is the source of truth for this repo's conventions, shared across all AI tools (Claude Code, Copilot, Codex). The detailed rules it points to live in `.github/`. - -Claude-specific notes: - -- _(none currently; keep Claude overrides here if they ever diverge from AGENTS.md)_ +@AGENTS.md diff --git a/README.md b/README.md index 6afaf89..5b98122 100644 --- a/README.md +++ b/README.md @@ -7,128 +7,36 @@

- A shared PHP base for WordPress projects, distributed as a Composer package - (rtcamp/wp-primitives). It ships the contracts, loaders, and - utilities that plugins and themes boot through — so you write intent instead - of registration boilerplate. + Shared bases classes, loaders, and utilities for WordPress plugins and themes, distributed as the Composer package rtcamp/wp-primitives.

--- -`wp-primitives` is a **library, not a plugin**. It ships contracts (interfaces, abstracts, traits) plus concrete loaders and utilities; consuming plugins and themes build their features on top. It has **zero Composer runtime dependencies**. +`wp-primitives` is a zero-dependency **Composer library** meant to be consumed by WordPress plugins and themes. It requires PHP 8.2+ and WordPress 6.5+, and has no Composer runtime dependencies. -Requirements: +The library provides: -- PHP 8.2+ -- WordPress 6.5+ -- Composer -- The OpenSSL PHP extension when using `Encryptor` +- Shared base classes for WordPress objects like post types, blocks, and settings pages. +- Loaders to manage the lifecycle of these objects. +- Utility functions and traits to simplify common tasks in WordPress development. -## Install +## Quick Start ```bash -composer require rtcamp/wp-primitives:^2.0 +composer require rtcamp/wp-primitives ``` -The package is published on [Packagist](https://packagist.org/packages/rtcamp/wp-primitives), so no extra configuration is needed. To install straight from GitHub instead (a branch, a fork, or a project that does not use Packagist), add a VCS repository before requiring it: +For more details on requirements, installation, and usage, see [Getting started](docs/getting-started.md). -```json -{ - "repositories": [ - { "type": "vcs", "url": "https://github.com/rtCamp/wp-primitives" } - ] -} -``` - -PSR-4 autoloading: `rtCamp\WPPrimitives\` → `inc/`. - -## Quick look - -```php -use rtCamp\WPPrimitives\Contracts\Abstracts\AbstractPostType; -use rtCamp\WPPrimitives\Contracts\Traits\Loader; -use rtCamp\WPPrimitives\Contracts\Traits\Singleton; - -final class ArticlePostType extends AbstractPostType { - public static function get_slug(): string { return 'article'; } - public function get_singular_label(): string { return __( 'Article', 'acme' ); } - public function get_plural_label(): string { return __( 'Articles', 'acme' ); } - public function get_menu_icon(): string { return 'dashicons-media-document'; } -} - -final class Main { - use Loader; - use Singleton; - - protected function __construct() { - static::$instance = $this; // before loading classes that can re-enter - $this->load( [ ArticlePostType::class ] ); // instantiates + registers hooks - } -} - -Main::get_instance(); -``` - -A registered, REST-enabled post type with no `register_post_type()` call and no `init` hook written by hand. Full walkthrough in [docs/getting-started.md](docs/getting-started.md). - -## What's inside +## Usage -- **Registration core** — the spine every consumer boots through: - - `Registrable`, `ConditionallyRegistrable`, `Shareable`, `CLICommand` interfaces - - the `Loader` trait (instantiate a list of classes, register their hooks, cache the shared ones) and the `Container` it stores instances in -- **Twelve `Abstract*` base classes** — one per WordPress registration chore, so a consumer writes intent instead of boilerplate: `AbstractModule`, `AbstractPostType`, `AbstractTaxonomy`, `AbstractBlock`, `AbstractShortcode`, `AbstractRESTController`, `AbstractSettingsPage`, `AbstractAdminPage`, `AbstractUserRole`, `AbstractFeature`, `AbstractAbility`, `AbstractAbilityRegistrar` -- **Asset & render loaders** — `AssetLoader` (scripts/styles/modules + `*.asset.php` manifests), `ComponentLoader` and `TemplateLoader` (resolve components/templates across the child-theme → parent-theme → package hierarchy) -- **`Singleton` trait** — standard `get_instance()` with clone/wakeup guards -- **Utilities & services** (`inc/Utils/`) — context-scoped helpers: - - `Encryptor` — authenticated AES-256-GCM encryption for values stored in the DB - - `Cache` — typed wrapper over the WP object cache, group-namespaced, optional SWR - - `FeatureSelector` + `FeatureSelectorSettingsPage` — a fail-closed feature-flag registry and its admin toggle page - - `Logger` — context-prefixed, `WP_DEBUG`-gated logging - - `Timer` — named request-scoped timers and laps - - `Transients` — prefix-namespaced transient storage - -The contract surface (`inc/Contracts/`) is the public API: every interface, abstract, and signature there is consumed by dependents, so changes to it are treated as breaking. - -## What's NOT here (intentional) - -- **No bootstrap / `Main` class.** The framework gives you the `Loader` trait and the contracts; each consumer writes its own entry class that kicks off the first `load()`. The framework is the spine, not the application. -- **No project scaffolding engine.** Scaffold/init tooling lives in a separate package (`@rtcamp/wp-tooling`), not here. +See [docs/index.md](docs/index.md) for detailed usage instructions. ## Documentation -Start with [docs/index.md](docs/index.md), then: - -| Doc | What it covers | -| ----------------------------------------------- | ---------------------------------------------------------------------------------------------- | -| [getting-started.md](docs/getting-started.md) | Install, bootstrap a plugin or theme, load a module, and share a service. | -| [architecture.md](docs/architecture.md) | How a class becomes a live hook — the `Registrable` → `Loader` → `Container` flow. Read first. | -| [contracts.md](docs/contracts.md) | The interfaces and traits in detail. | -| [abstracts.md](docs/abstracts.md) | Cookbook for the `Abstract*` base classes. | -| [loaders.md](docs/loaders.md) | `AssetLoader`, `ComponentLoader`, `TemplateLoader` and the theme-override hierarchy. | -| [utilities.md](docs/utilities.md) | `Encryptor`, `Cache`, feature flags, logging, transients, timers, and `Container`. | -| [upgrading.md](docs/upgrading.md) | What changes between releases and what a consumer has to do about it. | -| [troubleshooting.md](docs/troubleshooting.md) | Symptom → cause for the errors and silent no-ops the framework emits. | -| [ai-review-system.md](docs/ai-review-system.md) | How the AI review instructions are authored here and synced into the skeletons. | -| [maintainers.md](docs/maintainers.md) | Development environment, tests, change checklist, and documentation maintenance. | - -## Development - -```bash -composer install -npm ci -npm run wp-env start -composer lint -composer analyse -npm run lint:js -npm run format -npm run test:php -``` - -Tests run against real WordPress via [`@wordpress/env`](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-env/). Use `npm run test:php`, which runs PHPUnit inside the wp-env test container; `composer test` only works directly when a host WordPress test suite has been configured. See [docs/maintainers.md](docs/maintainers.md) for the complete workflow. - ## Contributing -See [CONTRIBUTING.md](.github/CONTRIBUTING.md). +This repository is maintained by rtCamp. Contributions are welcome and encouraged. See [CONTRIBUTING.md](.github/CONTRIBUTING.md). ## License diff --git a/ai/primitives-php.instructions.md b/ai/primitives-php.instructions.md index 33ae8bf..6993c92 100644 --- a/ai/primitives-php.instructions.md +++ b/ai/primitives-php.instructions.md @@ -5,7 +5,7 @@ description: 'Framework + WordPress rules for PHP. Canonical source, shipped by # PHP rules: framework, WordPress, security, tests -`rtcamp/wp-primitives` (`rtCamp\WPPrimitives`) is in gitignored `vendor/` (invisible at review). These rules ARE its contract. +`rtcamp/wp-primitives` (`rtCamp\WPPrimitives`) is in gitignored `vendor/` (invisible at review). These rules are its contract. ## Architecture @@ -19,7 +19,7 @@ Decision order for a new class, **do NOT default to Singleton**: Extend the framework abstracts; never hand-roll their job: `AbstractModule`, `AbstractFeature`, and `Abstract{PostType,Taxonomy,Block,Shortcode,RESTController,SettingsPage,AdminPage,UserRole,Ability,AbilityRegistrar}`. -Flag genuine contract/security violations, not style. Allow any correct implementation. +Flag real contract/security violations, not style. Allow any correct implementation. ## Mandatory @@ -45,11 +45,11 @@ Flag genuine contract/security violations, not style. Allow any correct implemen ## Flag on review (priority order) -1. 🚩 **MANDATORY: always post, exempt from dedupe/trim/budget:** a new/changed `Abstract*` subclass or `Registrable` (post type, taxonomy, block, shortcode, REST, settings, role, cron) shipped without a matching test in `tests/php/`. Flag on EVERY such PR, even amid higher-severity issues. -2. 🚩 `Singleton`/`::get_instance()` outside `Main` → `Loader`+`Registrable` (or `Shareable`+`get_shared()` if retrieval is genuinely needed). Never a service locator. -3. 🚩 `Shareable` with no real later-retrieval need → plain `Registrable`. -4. 🚩 WP-hooking class not implementing `Registrable` / not loaded via the `Loader`. -5. 🚩 A class calling `register_post_type`/`register_taxonomy`/`register_rest_route`/`add_menu_page`/`add_shortcode`/`register_block_type`/`wp_register_ability` directly instead of extending the matching `Abstract*` (`AbstractPostType`, `AbstractRESTController`, `AbstractAdminPage`, …). Name the abstract to extend. -6. 🚩 Missing `strict_types`/types/docblocks; PSR-4 mismatch; `self::` for LSB. -7. 🚩 Missing escape/sanitize/nonce/capability; raw `$wpdb` without `prepare()`; REST without a real `permission_callback`; inline assets; wrong/absent text domain. -8. 🚩 Edit under `vendor/rtcamp/wp-primitives` or WordPress core. +1. **MANDATORY: always post, exempt from dedupe/trim/budget:** a new/changed `Abstract*` subclass or `Registrable` (post type, taxonomy, block, shortcode, REST, settings, role, cron) shipped without a matching test in `tests/php/`. Flag on EVERY such PR, even amid higher-severity issues. +2. `Singleton`/`::get_instance()` outside `Main`. Use `Loader`+`Registrable` (or `Shareable`+`get_shared()` if retrieval is needed). Never a service locator. +3. `Shareable` with no real later-retrieval need. Use plain `Registrable`. +4. WP-hooking class not implementing `Registrable` / not loaded via the `Loader`. +5. A class calling `register_post_type`/`register_taxonomy`/`register_rest_route`/`add_menu_page`/`add_shortcode`/`register_block_type`/`wp_register_ability` directly instead of extending the matching `Abstract*` (`AbstractPostType`, `AbstractRESTController`, `AbstractAdminPage`, …). Name the abstract to extend. +6. Missing `strict_types`/types/docblocks; PSR-4 mismatch; `self::` for LSB. +7. Missing escape/sanitize/nonce/capability; raw `$wpdb` without `prepare()`; REST without a real `permission_callback`; inline assets; wrong/absent text domain. +8. Edit under `vendor/rtcamp/wp-primitives` or WordPress core. diff --git a/bin/sync-ai-instructions.js b/bin/sync-ai-instructions.js index c1fbd71..21eac23 100644 --- a/bin/sync-ai-instructions.js +++ b/bin/sync-ai-instructions.js @@ -3,26 +3,22 @@ /* eslint no-console: 0 */ /** - * Sync AI / Copilot instructions for rtCamp WordPress projects. + * Sync AI and Copilot instructions for rtCamp WordPress projects. * - * Shipped by rtcamp/wp-primitives; run from a consuming package via `npm run sync-ai` - * (chained from `npm run init`). Does two jobs in one pass: + * Run from a package that requires rtcamp/wp-primitives with `npm run sync-ai` (also called by `npm run init`). * - * 1. Refresh: copy the canonical framework rules from each package's - * vendor/rtcamp/wp-primitives/ai/primitives-php.instructions.md into that - * package's .github/instructions/primitives-php.instructions.md. - * 2. Project: if the package sits inside a wp-content root (an ancestor - * containing plugins/), write every package's instructions to that root's - * .github/instructions/ with applyTo globs re-scoped to the root, so GitHub - * Copilot code review (which only reads the repo-root .github/) picks them up. + * 1. Refresh: copy vendor/rtcamp/wp-primitives/ai/primitives-php.instructions.md into the + * package's .github/instructions/. + * 2. Project: if the package is inside a wp-content root (an ancestor containing plugins/), + * write every package's instructions to the root's .github/instructions/, with applyTo + * globs rewritten relative to the root. Rules shared by several packages go to one file. * - * Run from a standalone plugin/theme repo (no wp-content root above): step 1 only. - * Run from inside an assembled project: steps 1 and 2 for every package. + * A standalone plugin or theme repository runs step 1 only. * - * Rules identical across packages (the framework copy) project to a single file - * with a combined applyTo; per-package files (structure) stay separate as - * -. Pass --check for a CI gate (exit 1 on drift), --root DIR to - * force the wp-content root. + * --check: write nothing, and exit 1 if any file is out of date. + * --root DIR: search for the wp-content root from DIR instead of the working directory. + * + * @see docs/ai-review-system.md */ const fs = require( 'fs' ); @@ -34,14 +30,12 @@ const FRAMEWORK_SRC = const MARKER = ''; -// Pre-2.0 this package was rtcamp/wp-framework and shipped framework-php.instructions.md. -// Consumers upgrading across the rename still have the old file committed; recognise it so -// refreshPackage() can delete it and the root prune step can sweep any projected copies. +// Delete the legacy instruction file generated by rtcamp/wp-framework. const LEGACY_INSTRUCTION_FILE = 'framework-php.instructions.md'; const LEGACY_MARKER = ''; -// Copilot code review reads only the first ~4000 chars of an instruction file. +// Copilot code review reads only the first 4000 characters of an instruction file. const COPILOT_CHAR_LIMIT = 4000; const argv = process.argv.slice( 2 ); @@ -94,10 +88,9 @@ const discoverPackages = ( root ) => { fs.readdirSync( container ).forEach( ( slug ) => { const base = path.join( container, slug ); const dir = path.join( base, '.github', 'instructions' ); - // A package qualifies when it already carries instructions or when it vendors - // the framework, because refreshPackage() creates its .github/instructions/ on - // the first run. Site repos often commit only the root projection, so a fresh - // checkout has no per-package directory and would otherwise be skipped forever. + // Include a package that vendors rtcamp/wp-primitives even without .github/instructions/, because + // refreshPackage() creates that directory. + // Site repositories often commit only the root copies, so a fresh checkout has no per-package directory. if ( fs.existsSync( dir ) || fs.existsSync( path.join( base, FRAMEWORK_SRC ) ) @@ -160,7 +153,7 @@ const prefixGlobs = ( applyTo, prefix ) => .map( ( g ) => `${ prefix }/${ g.trim().replace( /^\.?\//, '' ) }` ); /** - * Append the GENERATED marker at the END so it never eats the first ~4000 chars. + * Append the GENERATED marker after the rules, outside the first COPILOT_CHAR_LIMIT characters. * * @param {string} content Instruction content. * @return {string} Content with marker appended. @@ -181,7 +174,7 @@ const writeIfChanged = ( outPath, content, relRoot, verb ) => { if ( rulesLen > COPILOT_CHAR_LIMIT ) { console.error( color.yellow( - ` WARNING ${ path.relative( relRoot, outPath ) } rules are ${ rulesLen } chars (>${ COPILOT_CHAR_LIMIT }); Copilot only reads the first ~4000. Trim the source.` + ` WARNING ${ path.relative( relRoot, outPath ) } rules are ${ rulesLen } chars (>${ COPILOT_CHAR_LIMIT }); Copilot reads only the first ${ COPILOT_CHAR_LIMIT }. Trim the source.` ) ); } @@ -204,7 +197,7 @@ const writeIfChanged = ( outPath, content, relRoot, verb ) => { }; /** - * Step 1 — refresh a package's primitives-php copy from its vendored package. + * Refresh a package's primitives-php.instructions.md from its vendored copy (step 1). * * @param {string} base Package root. * @param {string} relRoot Root for log labels. @@ -228,10 +221,7 @@ const refreshPackage = ( base, relRoot ) => { 'refresh' ); - // Migration from <2.0: drop the superseded filename so it is not projected to the root - // and so Copilot does not read two copies of the same rules. Only a copy the old - // sync generated (it carries LEGACY_MARKER) is removed; a hand-written file that - // happens to share the name is left alone, matching the root prune below. + // Delete the rtcamp/wp-framework copy so Copilot does not read the same rules twice. const legacy = path.join( base, '.github', @@ -255,7 +245,7 @@ const refreshPackage = ( base, relRoot ) => { }; /** - * Step 2 — project every package's instructions to the wp-content root. + * Project every package's instructions to the wp-content root (step 2). * * @param {string} root wp-content root. * @param {Array} packages Discovered packages. @@ -263,8 +253,8 @@ const refreshPackage = ( base, relRoot ) => { const projectToRoot = ( root, packages ) => { const groups = new Map(); packages.forEach( ( { type, slug, dir } ) => { - // Under --check a package discovered through its vendored framework has no - // directory yet; refreshPackage() has already reported that as drift. + // Under --check, a package found through its vendored rtcamp/wp-primitives may + // have no directory yet. refreshPackage() has already reported that as drift. if ( ! fs.existsSync( dir ) ) { return; } @@ -332,11 +322,11 @@ const main = () => { const root = findRoot( start ); if ( ! root ) { - // Standalone package: refresh this package's framework copy only. + // Standalone package: refresh this package's copy only. if ( ! refreshPackage( start, start ) ) { console.log( color.yellow( - 'No wp-content root and no vendored framework found. Nothing to do.' + 'No wp-content root and no vendored rtcamp/wp-primitives found. Nothing to do.' ) ); process.exit( 0 ); diff --git a/composer.json b/composer.json index 65260c3..4828486 100644 --- a/composer.json +++ b/composer.json @@ -1,6 +1,6 @@ { "name": "rtcamp/wp-primitives", - "description": "Contracts, loaders and utilities for building WordPress plugins and themes on a shared, tested base.", + "description": "Contracts, loaders and utilities for building WordPress plugins and themes.", "keywords": [ "wordpress", "wordpress-plugin", @@ -75,7 +75,7 @@ "lint:fix": "Auto-fix fixable PHPCS violations.", "analyse": "Run PHPStan static analysis.", "test": "Run the PHPUnit test suite.", - "check": "Run lint + analyse + test in sequence. Exit code 0 if all green." + "check": "Run lint, analyse and test in order. Exits 0 if all pass." }, "require": { "php": ">=8.2" diff --git a/eslint.config.mjs b/eslint.config.mjs index 421e470..9005931 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -1,9 +1,8 @@ /** - * rtCamp shared ESLint flat config. + * ESLint flat config. * - * Extends `@rtcamp/eslint-config` (which bundles `@wordpress/eslint-plugin`, - * eslint-comments, and the jest config for test files). Only the - * project-specific ignores are layered on top. + * Extends `@rtcamp/eslint-config`. + * @see https://github.com/rtCamp/wp-tooling/tree/main/node-packages/eslint-config */ import rtCampConfig from '@rtcamp/eslint-config'; diff --git a/inc/AssetLoader.php b/inc/AssetLoader.php index efa3cfd..1434e75 100644 --- a/inc/AssetLoader.php +++ b/inc/AssetLoader.php @@ -2,14 +2,12 @@ /** * Asset loader. * - * Concrete, injectable asset loader for WordPress scripts, styles, script - * modules and block manifests. A plain class (not a trait) so the loading - * behaviour has an instance identity that can be passed around and shared — - * consumers either extend it or, when their base-class slot is taken, hold one. + * Registers WordPress scripts, styles, script modules and block manifests. + * Consumers extend it or hold an instance. * - * Registers an asset by name relative to the instance's assets directory, set at - * construction: the source URL is built from the base URL and the dependency + - * version metadata is read from the sibling `*.asset.php` manifest on disk. + * Assets are registered by name relative to the assets directory passed to the + * constructor. The source URL is built from the base URL, and the dependencies + * and version are read from the sibling `*.asset.php` manifest. * * @package rtCamp\WPPrimitives * @@ -27,14 +25,14 @@ */ class AssetLoader { /** - * Default asset handle prefix. Subclasses override this constant to namespace - * their handles; handle() reads it via late static binding. + * Asset handle prefix used by handle(). + * + * Subclasses override it to namespace their handles. */ public const HANDLE_PREFIX = 'wp-primitives-'; /** - * Base directory path (plugin or theme root). Readable by subclasses that - * need to resolve their own paths (e.g. a block build directory). + * Base directory path (plugin or theme root). * * @var string */ @@ -77,10 +75,7 @@ public function get_assets_dir(): string { } /** - * Prefix a short name with HANDLE_PREFIX to form an asset handle. With the - * default prefix, handle( 'frontend' ) returns 'wp-primitives-frontend'. - * Subclasses namespace their handles by overriding the HANDLE_PREFIX - * constant; uniqueness is the caller's responsibility (pass distinct names). + * Prefix a short name with HANDLE_PREFIX to form an asset handle. * * @param string $name Short handle name. * @@ -108,8 +103,6 @@ public function get_base_dir(): string { * @return bool True if the asset file exists. */ public function has_asset( string $filename, string $extension ): bool { - // Mirror get_asset_meta()'s traversal guard: this is public API and may be - // called directly with consumer-supplied values. if ( ! $this->is_safe_asset_path( $filename, $extension ) ) { return false; } @@ -122,11 +115,11 @@ public function has_asset( string $filename, string $extension ): bool { /** * Whether a filename/extension pair is safe to interpolate into a path. * - * Both parts matter. The extension is joined after a literal dot, so a - * leading-dot extension forms `..` out of two values that each look clean: - * `has_asset( '/', './outside' )` would otherwise build `//../outside` - * and probe outside the assets directory. An extension is a bare suffix, so - * path separators in it are always wrong. + * The extension is joined after a literal dot, so a leading-dot extension + * forms `..` from two values that pass the `..` check on their own. + * + * For example, `has_asset( '/', './outside' )` would build `//../outside`. + * Path separators are rejected in the extension. * * @param string $filename Asset path relative to the assets directory, excluding the extension. * @param string $extension Asset file extension (e.g. 'js', 'css'). @@ -165,10 +158,6 @@ private function asset_src( string $filename, string $extension ): string { /** * Resolve the effective dependencies and version for a registration. * - * Explicit arguments win; otherwise values are inherited from $meta. The - * version is normalised to `string|false` so it passes straight to the - * wp_register_* functions (which read `false` as "no version"). - * * @param array{version: string, dependencies?: array} $meta Resolved asset metadata. * @param array $deps Caller dependencies (empty to inherit). * @param ?string $ver Caller version (null to inherit). @@ -188,12 +177,6 @@ private function resolve_deps_and_version( array $meta, array $deps, ?string $ve /** * Register a block collection from its manifest file. * - * Uses the block metadata-collection API (`wp_register_block_types_from_metadata_collection()`) - * when available — WordPress 6.8+ — which registers every block from a single - * manifest without reading each block.json. On the supported 6.5–6.7 range - * that function does not exist, so each block is registered from its own - * block.json on disk instead: slower, but functionally equivalent. - * * @param string $block_path Relative path to the block collection. E.g. `build/blocks`. * @param string $manifest_file Path to the manifest file, relative to the base directory. E.g. `build/blocks-manifest.php`. */ @@ -216,9 +199,7 @@ public function register_block_manifest( string $block_path, string $manifest_fi return; } - // Fallback for WordPress 6.5–6.7: register each block from disk. The - // manifest is keyed by block directory name; the block.json lives in the - // built block directory under $blocks_dir. + // Fallback for WordPress 6.5 to 6.7: register each block from its own block.json. // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.UsingVariable -- Existence checked above. $manifest = require $manifest_path; @@ -294,11 +275,11 @@ public function register_style( string $handle, string $filename, array $deps = * * @param string $handle Name of the script module. Should be unique. * @param string $filename Path of the module relative to the assets directory, excluding the .js extension. - * @param array $deps Optional. Module dependencies — each a module-ID string or an [id, import] array. Inherited from the asset file if empty. + * @param array $deps Optional. Module dependencies, each a module ID string or an [id, import] array. Inherited from the asset file if empty. * @param ?string $ver Optional. Version string. Inherited from the asset file (or filemtime) if null. * - * @return bool False if the asset file is missing; otherwise true. (wp_register_script_module() - * returns void, so success past the file check cannot be reported.) + * @return bool False if the asset file is missing, otherwise true. wp_register_script_module() + * returns void, so a failure after the file check is not reported. */ public function register_script_module( string $handle, string $filename, array $deps = [], ?string $ver = null ): bool { $meta = $this->get_asset_meta( $filename, 'js' ); @@ -309,8 +290,7 @@ public function register_script_module( string $handle, string $filename, array $module_deps = empty( $deps ) ? ( $meta['dependencies'] ?? [] ) : $deps; - // wp_register_script_module() expects each dependency in id/import form; - // normalise plain module-ID strings while leaving array entries intact. + // wp_register_script_module() expects each dependency as an [id, import] array. $module_deps = array_map( static fn ( string|array $dep ): array => is_array( $dep ) ? $dep : [ 'id' => $dep ], $module_deps @@ -331,9 +311,8 @@ public function register_script_module( string $handle, string $filename, array /** * Resolve asset metadata for an asset by name (relative path + extension). * - * Returns null if the filename is rejected for path traversal, or — with a - * warning — if the asset file itself is missing. The `.asset.php` manifest is - * optional, and an invalid one is ignored with a warning (see read_asset_manifest()). + * Triggers a _doing_it_wrong() notice when the asset file is missing. The + * `.asset.php` manifest is optional; see {@see AssetLoader::read_asset_manifest()}. * * @param string $filename Asset path relative to the assets directory, excluding the extension. * @param string $extension Asset file extension (e.g. 'js', 'css'). @@ -341,10 +320,7 @@ public function register_script_module( string $handle, string $filename, array * @return array{version: string, dependencies?: array}|null Metadata, or null if the filename is rejected (path traversal) or the asset file is missing. */ private function get_asset_meta( string $filename, string $extension ): ?array { - // $filename feeds a require() in read_asset_manifest(); reject traversal - // in either part up front. The in-tree callers pre-sanitise and pass a - // literal extension, but this class is public API and may be called - // directly, so the guard covers both values. + // $filename feeds a require() in read_asset_manifest(). if ( ! $this->is_safe_asset_path( $filename, $extension ) ) { return null; } @@ -353,7 +329,7 @@ private function get_asset_meta( string $filename, string $extension ): ?array { $manifest_file = sprintf( '%s/%s.asset.php', $base, $filename ); $asset_file = sprintf( '%s/%s.%s', $base, $filename, $extension ); - // The actual asset file is required — if it's missing, there is nothing to register. + // Without an asset file, there's nothing to register. if ( ! file_exists( $asset_file ) ) { _doing_it_wrong( static::class, @@ -374,6 +350,8 @@ private function get_asset_meta( string $filename, string $extension ): ?array { /** * Read an optional `.asset.php` manifest, falling back to the asset's filemtime. * + * An invalid manifest triggers a _doing_it_wrong() notice and is ignored. + * * @param string $manifest_file Absolute path to the `.asset.php` manifest. * @param string $asset_file Absolute path to the asset file the version falls back to. * diff --git a/inc/ComponentLoader.php b/inc/ComponentLoader.php index 40d91a6..43a7a03 100644 --- a/inc/ComponentLoader.php +++ b/inc/ComponentLoader.php @@ -2,13 +2,13 @@ /** * Component loader for resolving and rendering PHP component partials. * - * A component is a self-contained, render-only package (PHP + built CSS/JS). - * The loader resolves it following the WordPress theme hierarchy — child theme - * overrides parent theme overrides plugin — renders the PHP in an isolated - * scope, and (by default) registers + enqueues its CSS/JS. + * A component is a PHP partial with optional built CSS and JS. The loader + * resolves it in theme hierarchy order (child theme, then parent theme, then + * plugin), renders the PHP in an isolated scope, and by default registers and + * enqueues its CSS and JS. * - * Each consuming package (a theme, a plugin) loads its own subclass with a - * distinct context, so their components and asset handles never collide. + * Each theme or plugin uses its own subclass with a distinct context, which + * namespaces its hooks and asset handles. * * @package rtCamp\WPPrimitives * @since 1.0.0 @@ -27,8 +27,8 @@ class ComponentLoader { /** * Component PHP directory, relative to each source root in the hierarchy. * - * A component resolves to `/src/components/{Name}/{Name}.php`, searched - * across get_asset_loaders() (child theme → parent theme → package). + * A component resolves to `/src/components/{Name}/{Name}.php`. The roots + * come from {@see ComponentLoader::get_asset_loaders()}. * * @var string */ @@ -68,14 +68,14 @@ class ComponentLoader { private array $component_data_cache = []; /** - * Asset loader for the package's own base — the owning theme or plugin root. + * Asset loader for the owning theme or plugin root. * * @var AssetLoader|null */ private ?AssetLoader $asset_loader; /** - * Memoised asset loaders to search for component assets, override-precedence first. + * Memoised result of get_asset_loaders(). * * @var array|null */ @@ -84,24 +84,17 @@ class ComponentLoader { /** * Constructor. * - * @param AssetLoader|null $asset_loader Asset loader for the package's own - * base (its theme or plugin root) — - * typically the shared instance. - * Optional: a subclass loaded - * via the framework Loader instead - * overrides get_asset_loader() to resolve - * a shared instance lazily. + * @param AssetLoader|null $asset_loader Asset loader for the parent theme or plugin root. */ public function __construct( ?AssetLoader $asset_loader = null ) { $this->asset_loader = $asset_loader; } /** - * Get the context slug identifying the package that owns this loader. + * Get the context slug (prefix) identifying the package that owns this loader. * - * Used to namespace asset handles and to target the component filters. - * Subclasses override this to return their own slug (e.g. a theme/plugin - * slug); the default keeps the framework's own namespace. + * Prefixes asset handles and component hook names. Subclasses override it + * with their theme or plugin slug. * * @return string Context slug. */ @@ -110,12 +103,7 @@ protected function get_context(): string { } /** - * Build a context-namespaced hook name so one package's component filters - * don't fire for another's. - * - * The context is prefixed into the hook name (e.g. `my-plugin/component_before_render`), - * mirroring TemplateLoader's prefixed hooks — the loader context slug is still - * passed as an argument for handlers that want it. + * Build a hook name prefixed with the context, e.g. `my-plugin/component_before_render`. * * @param non-empty-string $event Hook suffix (e.g. 'before_render'). * @@ -126,10 +114,9 @@ private function component_hook( string $event ): string { } /** - * Get the package's own asset loader — the owning theme or plugin. + * Get the asset loader for the parent theme or plugin. * - * Returns the injected loader. A subclass loaded without constructor - * injection must override this to supply one (e.g. a shared instance). + * Returns the loader passed to the constructor. * * @return AssetLoader Asset loader instance. * @@ -148,16 +135,14 @@ protected function get_asset_loader(): AssetLoader { /** * Asset loaders to search for a component asset, in override precedence. * - * Follows the WordPress template hierarchy (child theme > parent theme > - * plugin), but only includes the override layers that sit *above* the - * package's own loader and that actually exist — so no redundant loaders are - * spawned: + * Follows the WordPress template hierarchy and includes only the layers that + * take precedence over the owning package: * - * - self is the parent theme → [ child?, self ] - * - self is the child theme → [ self ] - * - self is a plugin → [ child?, parent, self ] + * - Owner is the parent theme: [ child?, owner ] + * - Owner is the child theme: [ owner ] + * - Owner is a plugin: [ child?, parent, owner ] * - * where `child?` is present only when a distinct child theme is active. + * `child?` is included only when a child theme is active. * * @return array Asset loaders, override-precedence first. */ @@ -175,17 +160,17 @@ protected function get_asset_loaders(): array { $loaders = []; - // Child theme override layer: a distinct child theme exists and self isn't it. + // A child theme is active and is not the owner. if ( $has_child && $self_dir !== $stylesheet ) { $loaders[] = new AssetLoader( $stylesheet, get_stylesheet_directory_uri(), $assets_dir ); } - // Parent theme override layer: self is neither the parent nor the child theme. + // The owner is neither the parent nor the child theme. if ( $self_dir !== $template && $self_dir !== $stylesheet ) { $loaders[] = new AssetLoader( $template, get_template_directory_uri(), $assets_dir ); } - // The package's own loader is lowest precedence — overrides above win. + // The package's own loader has the lowest precedence. $loaders[] = $self; $this->asset_loaders = $loaders; @@ -194,8 +179,9 @@ protected function get_asset_loaders(): array { } /** - * Clear request-level lookup caches: resolved component metadata and the - * memoised asset-loader hierarchy (so a mid-request theme change is picked up). + * Clear the resolved component metadata and the memoised asset loaders. + * + * Useful after switch_theme() or switch_to_blog() on a long-lived instance. */ public function clear_cache(): void { $this->component_data_cache = []; @@ -205,9 +191,6 @@ public function clear_cache(): void { /** * Render a component by name. * - * Resolves the component file from child theme, parent theme, or plugin paths, - * then includes it with the provided arguments available in scope. - * * @param string $name Component name (e.g. 'Button', 'Card'). * @param array $args Arguments to pass to the component. * @param array $options { @@ -226,9 +209,6 @@ public function render( string $name, array $args = [], array $options = [] ): v /** * Get the rendered HTML of a component as a string. * - * Uses output buffering to capture the component output instead of - * sending it directly to the browser. - * * @param string $name Component name (e.g. 'Button', 'Card'). * @param array $args Arguments to pass to the component. * @param array $options Optional. Resolution options. See render(). @@ -251,8 +231,7 @@ public function get( string $name, array $args = [], array $options = [] ): stri } /** - * Shared render pipeline backing render() and get(): resolve the component, - * include its file, then register + enqueue its assets. + * Resolve a component, include its file, then register and enqueue its assets. * * @param string $name Component name (e.g. 'Button', 'Card'). * @param array $args Arguments to pass to the component. @@ -289,9 +268,7 @@ protected function render_component( string $name, array $args = [], array $opti */ do_action( $this->component_hook( 'before_render' ), $name, $args, $context ); - // Delegate to a private static method so the component file loads in an - // isolated scope with no access to $this. self:: (not static::) is - // deliberate — the loader must not late-bind to a subclass here. + // Load in an isolated scope. self::load_template( (string) $component['file'], $args, $name, $options ); $this->enqueue_component_assets( $component, $options ); @@ -333,10 +310,7 @@ private function get_render_options( array $options ): array { } /** - * Resolve a component's metadata (resolved file path + asset info). - * - * The component PHP is located across the source hierarchy (child theme → - * parent theme → package), at `/{php_dir}/{Name}/{Name}.php`. + * Resolve a component's file path and asset names across the resolution hierarchy. * * @param string $name Component name. * @param array $options Resolution options. @@ -387,8 +361,7 @@ private function get_component_data( string $name, array $options = [] ): array| /** * Locate a component's PHP file across the resolution hierarchy. * - * Searches each loader's base directory for `/{php_dir}/{Name}/{Name}.php`, - * first hit wins. + * Returns the first readable `/{php_dir}/{Name}/{Name}.php`. * * @param string $component_name Component name. * @param bool $allow_override Whether theme/child overrides may win, or only the package's own dir. @@ -412,9 +385,6 @@ private function locate_component_file( string $component_name, bool $allow_over /** * Loaders to search when resolving a component, in override precedence. * - * The full override hierarchy when overrides are allowed, otherwise only the - * package's own loader — so the component resolves from its own directory. - * * @param bool $allow_override Whether theme/child overrides may win. * * @return array Loaders to search, override-precedence first. @@ -426,9 +396,7 @@ private function resolution_loaders( bool $allow_override ): array { /** * Resolve the asset filenames a component requests. * - * Returns the asset name (relative to the assets directory, no extension) - * for each requested type; existence and the override base are resolved at - * registration time across get_asset_loaders(). + * Asset names are relative to the assets directory, without an extension. * * @param string $component_name Component name. * @param array $options Component render options. @@ -540,8 +508,7 @@ private function component_asset_handle( string $name, string $asset_type ): str /** * Ensure a component asset is registered. * - * Searches the asset loaders in override precedence and registers via the - * first one that holds the file. + * Resolves the asset through the first loader that has the file. * * @param non-empty-string $asset_type 'style' or 'script'. * @param non-empty-string $handle Asset handle. Should be unique. @@ -575,10 +542,6 @@ private function ensure_component_asset_registered( string $asset_type, string $ /** * Normalize and validate a component name before using it in filesystem paths. * - * Trims whitespace, bounds the length, and allows only alphanumeric - * characters, underscores and dashes — which inherently blocks empty names, - * path separators and traversal sequences. - * * @param string $name Component name to normalize and validate. * * @return string|false Normalized component name, or false when invalid. @@ -594,11 +557,7 @@ private function normalize_component_name( string $name ): string|false { } /** - * Isolate the scope for the required component file. - * - * The component receives $args, $name and the resolved $options in scope - * (and no access to $this), so it can render and forward options to nested - * components. + * Require a component file in a static scope. * * @param string $__file Component file path. * @param array $args Component arguments. diff --git a/inc/Contracts/Abstracts/AbstractAbility.php b/inc/Contracts/Abstracts/AbstractAbility.php index d821380..f9bd2c4 100644 --- a/inc/Contracts/Abstracts/AbstractAbility.php +++ b/inc/Contracts/Abstracts/AbstractAbility.php @@ -1,6 +1,9 @@ /`. * * @return lowercase-string&non-falsy-string Ability name. */ @@ -47,8 +38,8 @@ abstract protected function label(): string; /** * Return the description of what the ability does. * - * Written for the caller deciding whether to invoke the ability — for an - * MCP-exposed ability that caller is an AI agent choosing a tool. + * Written for the caller deciding whether to invoke the ability. For an ability exposed over MCP, that caller is + * the AI agent choosing a tool. * * @return string Description. */ @@ -58,28 +49,23 @@ abstract protected function description(): string; * Return the slug of the category this ability belongs to. * * The Abilities API requires every ability to name a registered category. - * The {@see AbstractAbilityRegistrar} that registers this ability - * registers the category first, so the two normally return the same slug. + * The {@see AbstractAbilityRegistrar} that registers this ability registers the category first, so the two normally return the same slug. * * @return string Category slug. */ abstract protected function category(): string; /** - * Return the JSON Schema describing the ability input. + * The JSON Schema describing the ability input. * - * Return an empty array for an ability that takes no input; args() then - * omits the key entirely. + * Return an empty array for an ability that takes no input. * * @return array Input schema. */ abstract protected function input_schema(): array; /** - * Return the JSON Schema describing the ability output. - * - * Return an empty array to leave the output unspecified; args() then - * omits the key entirely. + * The JSON Schema describing the ability output. * * @return array Output schema. */ @@ -95,25 +81,21 @@ abstract protected function output_schema(): array; abstract public function execute( mixed $input ): mixed; /** - * Decide whether the current user may execute the ability. - * - * Defaults to `manage_options` — fail-closed, administrators only. - * Override to gate on a different capability or on the input. + * Whether the current user may execute the ability. * * @param mixed $input Input the ability is being called with. * * @return bool|\WP_Error True to allow; false or a WP_Error to deny. */ - protected function permission( mixed $input = null ): bool|\WP_Error { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found, VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- $input is the override seam; the default gate ignores it. + protected function permission( mixed $input = null ): bool|\WP_Error { // phpcs:ignore Generic.CodeAnalysis.UnusedFunctionParameter.Found, VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Available for overrides that use $input. return current_user_can( 'manage_options' ); } /** * Return the ability meta. * - * Defaults to empty, which keeps the Abilities API defaults — not exposed - * over REST, no MCP flag. Override to opt in, e.g. - * `[ 'show_in_rest' => true ]`. + * Leave empty to keep the Abilities API defaults. Override to change them, e.g. + * `[ 'show_in_rest' => true ]` * * @return array Meta. */ @@ -122,14 +104,7 @@ protected function meta(): array { } /** - * Build the registration arguments for wp_register_ability(). - * - * The schema and meta keys are included only when non-empty, so the - * Abilities API applies its own defaults otherwise. Both callbacks are - * wrapped in closures with a defaulted parameter: when an ability - * declares no input schema, core invokes its callbacks with no arguments - * at all, and the wrappers keep that call safe for the required - * execute() signature (and keep permission() protected). + * Builds the registration arguments for wp_register_ability(). * * @return array Registration args. */ diff --git a/inc/Contracts/Abstracts/AbstractAbilityRegistrar.php b/inc/Contracts/Abstracts/AbstractAbilityRegistrar.php index 0adb229..4adb80b 100644 --- a/inc/Contracts/Abstracts/AbstractAbilityRegistrar.php +++ b/inc/Contracts/Abstracts/AbstractAbilityRegistrar.php @@ -2,6 +2,9 @@ /** * Abstract Ability Registrar. * + * Registers a group of {@see AbstractAbility} instances with the WordPress Abilities API (WordPress 6.9+). + * The category is registered on `wp_abilities_api_categories_init` and each ability on `wp_abilities_api_init`. + * * @package rtCamp\WPPrimitives\Contracts\Abstracts * @since 1.0.0 */ @@ -15,20 +18,6 @@ /** * Class AbstractAbilityRegistrar * - * Registers a group of {@see AbstractAbility} services with the WordPress - * Abilities API (WordPress 6.9+): the shared category on - * `wp_abilities_api_categories_init`, then each ability on - * `wp_abilities_api_init` — the only hooks those registrations are legal on. - * Core fires both lazily, the first time the abilities registry is accessed. - * - * On cores older than 6.9 the hooks never fire, so the registrar is inert and - * the package's WordPress floor is unchanged. The function_exists guards - * inside the callbacks are belt-and-braces for partial backports. - * - * Category registration is idempotent: the wp_register_ability_category() - * call is skipped when the slug is already registered, so several registrars - * can share one category and load in any order. - * * @since 1.0.0 */ abstract class AbstractAbilityRegistrar implements Registrable { @@ -92,10 +81,7 @@ abstract protected function abilities(): array; /** * Return the category description. - * - * The Abilities API rejects a category without a non-empty description, - * so there is no default. Written for the caller browsing the category — - * for MCP-exposed abilities that caller is an AI agent. + * Written for the caller browsing the category. For abilities exposed over MCP, that caller is an AI agent. * * @return string Category description. */ @@ -104,8 +90,7 @@ abstract protected function category_description(): string; /** * Return the human-readable category label. * - * Defaults to a title-cased version of the slug ("my-plugin" → "My Plugin"). - * Override to provide a more descriptive name. + * Defaults to the slug in title case, so "my-plugin" becomes "My Plugin". * * @return string Category label. */ @@ -116,8 +101,7 @@ protected function category_label(): string { /** * Runs immediately before the abilities are registered. * - * Empty by default. Override for one-time preparation the abilities - * depend on — ensuring storage exists, priming options, and so on. + * Empty by default. Override for setup the abilities depend on, such as creating storage or priming options. */ protected function before_register(): void {} } diff --git a/inc/Contracts/Abstracts/AbstractBlock.php b/inc/Contracts/Abstracts/AbstractBlock.php index 3639a1f..be8d12e 100644 --- a/inc/Contracts/Abstracts/AbstractBlock.php +++ b/inc/Contracts/Abstracts/AbstractBlock.php @@ -2,9 +2,9 @@ /** * Abstract Block class. * - * Provides a clean interface for registering dynamic WordPress blocks. - * For static blocks (JSON-only, no server-side render), use the AssetLoader - * class with `register_block_manifest()` directly. + * Base class for a dynamic WordPress block. + * + * For a static block with no server-side render, use {@see \rtCamp\WPPrimitives\AssetLoader::register_block_manifest()}. * * @package rtCamp\WPPrimitives\Contracts\Abstracts * @since 1.0.0 @@ -32,8 +32,7 @@ abstract public static function get_name(): string; /** * Render the block on the server side. * - * Public because WordPress calls it directly as the block's render_callback - * (wired in register_block()); a protected method would fatal when core invokes it. + * @internal Called by WordPress as the block's render_callback. * * @param array $attributes Block attributes. * @param string $content Block inner content. @@ -53,12 +52,8 @@ public function register_hooks(): void { /** * Register the block type with WordPress. * - * Registers from get_block_dir() when that directory holds a block.json, and - * by name otherwise. A configured directory without a block.json (a fresh - * clone or a CI run before `npm run build`, or a deploy that lost its build) - * falls back to registering by name: the server-side render still works, and - * WordPress no longer receives the directory path as a block name, which it - * rejected with a "must contain a namespace prefix" notice on every request. + * Registers from get_block_dir() when that directory contains a block.json, and by name otherwise, + * so the server-side render still works before `npm run build`. */ public function register_block(): void { $args = $this->get_block_args(); diff --git a/inc/Contracts/Abstracts/AbstractFeature.php b/inc/Contracts/Abstracts/AbstractFeature.php index 847b070..a2b9fee 100644 --- a/inc/Contracts/Abstracts/AbstractFeature.php +++ b/inc/Contracts/Abstracts/AbstractFeature.php @@ -2,6 +2,11 @@ /** * Abstract Feature. * + * Base class for a service that runs only when its feature flag is enabled. + * Each feature extends a consumer-defined intermediate class whose get_feature_registry() returns the shared FeatureSelector. + * + * The constructor adds the feature to the registry, which the settings page reads. + * * @package rtCamp\WPPrimitives\Contracts\Abstracts * @since 1.0.0 */ @@ -16,15 +21,6 @@ /** * Class AbstractFeature * - * Base class for feature-flag-gated services. Each concrete feature extends a - * consumer-defined intermediate that supplies the shared FeatureSelector - * registry via get_feature_registry(). - * - * On construction the feature self-registers its slug, display name, and - * description into the registry so the admin settings page discovers it - * automatically. can_register() reads the same registry to decide whether - * register_hooks() should run. - * * @since 1.0.0 */ abstract class AbstractFeature implements ConditionallyRegistrable { @@ -45,8 +41,7 @@ abstract protected function get_feature_registry(): FeatureSelector; /** * Return the human-readable label shown on the settings page. * - * Defaults to a title-cased version of the slug ("author-bio" → "Author Bio"). - * Override to provide a more descriptive name. + * Defaults to the slug in title case, so "author-bio" becomes "Author Bio". * * @return string Display name. */ diff --git a/inc/Contracts/Abstracts/AbstractModule.php b/inc/Contracts/Abstracts/AbstractModule.php index 5e367be..4a549e0 100644 --- a/inc/Contracts/Abstracts/AbstractModule.php +++ b/inc/Contracts/Abstracts/AbstractModule.php @@ -2,8 +2,8 @@ /** * Abstract Module class. * - * A module groups related Registrable classes together, acting as an - * intermediary between the plugin's Main class and individual services. + * A module groups related Registrable classes together, acting as an intermediary between the plugin's Main class and + * individual services. * * @package rtCamp\WPPrimitives\Contracts\Abstracts * @since 1.0.0 diff --git a/inc/Contracts/Abstracts/AbstractPostType.php b/inc/Contracts/Abstracts/AbstractPostType.php index 215dab8..6b608cf 100644 --- a/inc/Contracts/Abstracts/AbstractPostType.php +++ b/inc/Contracts/Abstracts/AbstractPostType.php @@ -3,9 +3,6 @@ * Abstract Post Type class. * * Provides a rich base for registering WordPress custom post types. - * Subclasses declare the slug, labels and icon; the base class builds - * the full options array and handles registration, including optional - * taxonomy association and a post-registration hook. * * Usage: * @@ -69,10 +66,7 @@ public function register_hooks(): void { } /** - * Register the post type and its taxonomies. - * - * Calls after_register() when done — override that for any - * additional setup that must run after the post type exists. + * Register the post type. */ public function register(): void { $this->register_post_type(); @@ -88,10 +82,7 @@ public function register_post_type(): void { } /** - * Associate supported taxonomies with this post type. - * - * Called after register_post_type(). Uses the slugs returned by - * get_supported_taxonomies() to call register_taxonomy_for_object_type(). + * Associate the taxonomies from get_supported_taxonomies() with this post type. */ public function register_taxonomies(): void { foreach ( $this->get_supported_taxonomies() as $taxonomy ) { @@ -102,16 +93,15 @@ public function register_taxonomies(): void { /** * Runs after the post type has been registered. * - * Override to add any additional setup (e.g. flushing rewrite rules on - * first activation) without touching the registration logic. + * Override to add any additional setup (e.g. flushing rewrite rules on first activation) without touching the registration logic. */ public function after_register(): void {} /** * Get the full args array passed to register_post_type(). * - * Override to customise any option; or override the individual - * helper methods (get_editor_supports, is_hierarchical, …) instead. + * To change a single option, override its helper method, such as get_editor_supports() or is_hierarchical(), + * or use get_custom_options(). * * @return array */ @@ -140,7 +130,7 @@ public function get_options(): array { } /** - * Get any additional options to merge into the post type args. + * Get extra options to merge into the register_post_type() args. * * Override to add or override any options not covered by the other * helper methods. @@ -153,6 +143,7 @@ protected function get_custom_options(): array { /** * Get the post type labels. + * * Override to add more labels or customise as needed. * * @return array diff --git a/inc/Contracts/Abstracts/AbstractRESTController.php b/inc/Contracts/Abstracts/AbstractRESTController.php index 2e4b2c4..de6eb40 100644 --- a/inc/Contracts/Abstracts/AbstractRESTController.php +++ b/inc/Contracts/Abstracts/AbstractRESTController.php @@ -46,9 +46,7 @@ public function register_hooks(): void { /** * Register the controller's REST routes. * - * The base throws to force a subclass override. A missing implementation is a - * programming error, so this raises `\LogicException` (was a bare `\Exception`). - * Implement it with `register_rest_route()` calls under `$this->namespace`. + * Subclasses must override this with `register_rest_route()` calls under `$this->namespace`. * * @throws \LogicException Always, unless a subclass overrides it. * diff --git a/inc/Contracts/Abstracts/AbstractSettingsPage.php b/inc/Contracts/Abstracts/AbstractSettingsPage.php index 0d9378b..e3e25c8 100644 --- a/inc/Contracts/Abstracts/AbstractSettingsPage.php +++ b/inc/Contracts/Abstracts/AbstractSettingsPage.php @@ -2,9 +2,7 @@ /** * Abstract Settings Page class. * - * Provides a clean interface for registering a WordPress settings page - * with the Settings API. Handles menu registration, settings registration, - * and rendering in a single class. + * Base class for a WordPress settings page. It adds the menu page and registers its options with the Settings API. * * @package rtCamp\WPPrimitives\Contracts\Abstracts * @since 1.0.0 @@ -60,10 +58,7 @@ public function register_hooks(): void { add_action( 'admin_init', [ $this, 'register_settings' ] ); add_action( 'rest_api_init', [ $this, 'register_settings' ] ); - // The menu and render() are gated by get_capability(), but options.php gates - // the *save* on option_page_capability_{group}, which defaults to - // manage_options. Align them so a lowered get_capability() can actually save, - // instead of rendering a page that silently fails to persist. + // Use ::get_capability() for the option page capability checks. add_filter( 'option_page_capability_' . $this->get_option_group(), fn (): string => $this->get_capability() diff --git a/inc/Contracts/Abstracts/AbstractShortcode.php b/inc/Contracts/Abstracts/AbstractShortcode.php index 8bb7433..373f840 100644 --- a/inc/Contracts/Abstracts/AbstractShortcode.php +++ b/inc/Contracts/Abstracts/AbstractShortcode.php @@ -2,8 +2,6 @@ /** * Abstract Shortcode class. * - * Class to be extended by all shortcodes. Handles registration and provides a clean render interface. - * * @package rtCamp\WPPrimitives\Contracts\Abstracts * @since 1.0.0 */ @@ -40,10 +38,12 @@ public function register_shortcode(): void { } /** - * Shortcode callback wrapper. Parses attributes and delegates to render(). + * Shortcode callback wrapper. + * + * Parses attributes and delegates to render(). * - * @param array|string $atts Shortcode attributes. WordPress passes an empty string when the tag has none. - * @param string|null $content Enclosed content (if any). + * @param array|'' $atts Shortcode attributes. Empty string if no attributes are provided. + * @param string|null $content Enclosed content, or null. * * @return string Rendered shortcode output. */ diff --git a/inc/Contracts/Abstracts/AbstractTaxonomy.php b/inc/Contracts/Abstracts/AbstractTaxonomy.php index 0e80f6b..3e3cdef 100644 --- a/inc/Contracts/Abstracts/AbstractTaxonomy.php +++ b/inc/Contracts/Abstracts/AbstractTaxonomy.php @@ -3,8 +3,6 @@ * Abstract Taxonomy class. * * Provides a rich base for registering WordPress custom taxonomies. - * Subclasses declare the slug, object types and labels; the base class - * builds the full options array and handles registration. * * Usage: * @@ -68,9 +66,6 @@ public function register_hooks(): void { /** * Register the taxonomy. - * - * Calls after_register() when done — override that for any - * additional setup that must run after the taxonomy exists. */ public function register(): void { $this->register_taxonomy(); @@ -94,8 +89,8 @@ public function after_register(): void {} /** * Get the full args array passed to register_taxonomy(). * - * Override to customise any option; or override the individual - * helper methods (is_hierarchical, get_labels, …) instead. + * To change a single option, override its helper method, such as + * is_hierarchical() or get_labels(), or use get_custom_options(). * * @return array */ @@ -115,7 +110,7 @@ public function get_options(): array { } /** - * Get any additional options to merge into the taxonomy args. + * Get extra options to merge into the register_taxonomy() args. * * Override to add or override any options not covered by the other * helper methods. diff --git a/inc/Contracts/Interfaces/ConditionallyRegistrable.php b/inc/Contracts/Interfaces/ConditionallyRegistrable.php index 7384ce3..899de8f 100644 --- a/inc/Contracts/Interfaces/ConditionallyRegistrable.php +++ b/inc/Contracts/Interfaces/ConditionallyRegistrable.php @@ -2,13 +2,8 @@ /** * Interface for Registrable classes whose registration is conditional. * - * Implement this when a class should only register its hooks under certain - * runtime conditions — e.g. behind a feature flag, when WP-CLI is active, - * or only in admin requests. The Loader skips register_hooks() entirely - * when can_register() returns false. - * - * Classes that always register can keep implementing the plain Registrable - * interface instead; this one is strictly opt-in. + * Implement this when a class should only register its hooks under certain runtime conditions, such as feature flags, + * when WP-CLI is active, or an admin request. * * @package rtCamp\WPPrimitives\Contracts\Interfaces * @since 1.0.0 diff --git a/inc/Contracts/Interfaces/Registrable.php b/inc/Contracts/Interfaces/Registrable.php index ec40a0b..4750381 100644 --- a/inc/Contracts/Interfaces/Registrable.php +++ b/inc/Contracts/Interfaces/Registrable.php @@ -2,7 +2,7 @@ /** * Interface for Registrable classes. * - * Registrable classes are those that register hooks (actions/filters) with WordPress. + * A Registrable class adds WordPress actions and filters in register_hooks(). * * @package rtCamp\WPPrimitives\Contracts\Interfaces * @since 1.0.0 diff --git a/inc/Contracts/Interfaces/Shareable.php b/inc/Contracts/Interfaces/Shareable.php index 005cd30..a879eff 100644 --- a/inc/Contracts/Interfaces/Shareable.php +++ b/inc/Contracts/Interfaces/Shareable.php @@ -2,17 +2,10 @@ /** * Interface for Shareable classes. * - * Shareable is a SOFT ANTI-PATTERN. It introduces hidden shared state similar - * to a Singleton. Use only when a hooked class genuinely must be retrieved - * later. + * Classes with this interface are cached by {@see rtCamp\WPPrimitives\Contracts\Traits\Loader} and can be retrieved + * for reuse with ::get_shared(). * - * Shareable classes are those whose instance should be reused. When the Loader - * meets a Shareable, it caches the instance in a Container for later retrieval - * via get_shared(). Absence of this interface means a fresh, non-shared - * instance — the default. It is a marker: implement it, nothing more. - * - * Implemented alongside Registrable when a hooked class must also be shared, - * or on its own for a plain shared service. + * Shareable is an ANTI-PATTERN that adds hidden shared state, like Singleton. It should only be used when code needs to retrieve the same instance after loading. * * @package rtCamp\WPPrimitives\Contracts\Interfaces * @since 1.0.0 diff --git a/inc/Contracts/Traits/Loader.php b/inc/Contracts/Traits/Loader.php index d58b70d..77dcb87 100644 --- a/inc/Contracts/Traits/Loader.php +++ b/inc/Contracts/Traits/Loader.php @@ -2,10 +2,6 @@ /** * Loader trait. * - * Loads a list of classes: instantiates each, registers hooks for any - * Registrable, and caches any Shareable instance in a per-host Container. - * Plain classes (neither Registrable nor Shareable) are just instantiated. - * * @package rtCamp\WPPrimitives\Contracts\Traits * @since 1.0.0 */ @@ -31,10 +27,9 @@ trait Loader { private ?Container $container = null; /** - * Instantiate each class; register hooks if Registrable; cache if Shareable. + * Instantiate each class. * - * The Registrable and Shareable checks are independent — a class may be - * both, in which case its hooks are registered and its instance is cached. + * Creates a new instance of each class, registers hooks for each Registrable, and caches each Shareable instance in a per-host Container. * * @param class-string[] $classes Classes to load. */ @@ -51,12 +46,14 @@ protected function load( array $classes ): void { $instance = new $class_name(); + // Register hooks if the instance is Registrable. if ( $instance instanceof Registrable ) { if ( ! $instance instanceof ConditionallyRegistrable || $instance->can_register() ) { $instance->register_hooks(); } } + // Cache the instance if it is Shareable. if ( $instance instanceof Shareable ) { $this->container->set( $class_name, $instance ); } diff --git a/inc/Contracts/Traits/Singleton.php b/inc/Contracts/Traits/Singleton.php index 9ff4053..a770d6f 100644 --- a/inc/Contracts/Traits/Singleton.php +++ b/inc/Contracts/Traits/Singleton.php @@ -5,6 +5,8 @@ * Singletons are an ANTI-PATTERN. Use with caution and only when necessary. * In most cases, it's better to use dependency injection. * + * Avoid using this trait in a class meant to be extended by multiple subclasses, as the static instance will be shared across them. + * * @package rtCamp\WPPrimitives\Contracts\Traits * @since 1.0.0 */ @@ -20,25 +22,14 @@ trait Singleton { /** * The single instance of the class using this trait. * - * Protected on purpose: it is part of the trait's contract. A singleton whose - * constructor does real work (a plugin/theme `Main` running a Loader) should - * assign `static::$instance = $this;` as its first statement, so anything - * built during that work can call `get_instance()` re-entrantly and receive - * this same object instead of triggering a second construction. - * - * Limitation: a trait `static` property is one storage slot shared by a class - * and its subclasses. Do not extend a class that uses this trait and call - * `get_instance()` on the child — whichever side is resolved first occupies - * the shared slot for both. - * * @var ?static */ protected static $instance; /** - * The single constructor. + * Protected to prevent direct instantiation. * - * It's protected to prevent direct instantiation. + * When overloading, assign `static::$instance = $this;` as the first statement in the constructor to ensure `get_instance()` returns the correct object during construction. */ protected function __construct() { // To be implemented by the class using the trait. @@ -47,11 +38,8 @@ protected function __construct() { /** * Get the instance of the class. * - * The instance is stored once the constructor returns. If the constructor - * does work that can call back into `get_instance()`, assign - * `static::$instance = $this;` as its first statement (see the property - * docblock) — otherwise the re-entrant call finds nothing stored yet and - * constructs a second instance, recursing until the stack blows. + * Before calling `get_instance()` within the constructor, ensure that `static::$instance` has been assigned. + * Do not call in a child class, to prevent the static $instance from being shared across different subclasses. */ public static function get_instance(): static { if ( ! isset( static::$instance ) ) { diff --git a/inc/TemplateLoader.php b/inc/TemplateLoader.php index ccb97d3..b8fbed5 100644 --- a/inc/TemplateLoader.php +++ b/inc/TemplateLoader.php @@ -1,29 +1,19 @@ parent theme > package. - * Unlike a render-only component, a template part is loaded via WordPress' - * load_template(), so the global query/post are in scope. + * Allows plugins or child themes to override templates. * - * Works for both plugin and theme packages. A plugin's own templates live - * outside the theme, so all three layers apply. A theme's own templates already - * sit inside the (parent) theme, so the package layer collapses into the theme - * override layer automatically — self-aware, like ComponentLoader. + * Usage: * - * Consumers extend this class with their own config and share it through the - * container (implements Shareable), mirroring the AssetLoader / ComponentLoader - * pattern. Render wrappers typically live in the consumer's helper class. - * - * // Plugin: own templates in the plugin, theme overrides at theme/my-plugin/. + * // Plugin: templates in the plugin, theme overrides at theme/my-plugin/. * final class Templates extends TemplateLoader implements Shareable { * public function __construct() { * parent::__construct( 'my_plugin', MY_PLUGIN_PATH . 'templates', 'my-plugin' ); * } * } * - * // Theme: own templates in the theme, child theme overrides at the same path. + * // Theme: templates in the theme, child theme overrides at the same path. * final class Templates extends TemplateLoader implements Shareable { * public function __construct() { * parent::__construct( 'my_theme', get_template_directory() . '/templates', 'templates' ); @@ -101,9 +91,8 @@ public function __construct( string $hook_prefix, string $template_dir, string $ /** * Render a template part, echoing its output. * - * Resolves the highest-priority template across child theme, parent theme, - * then the package, and loads it via load_template() with the (filtered) - * arguments in scope. No-op when no template is found. + * Resolves the template from the child theme, parent theme or package, and loads it with load_template() + * and the filtered arguments. Does nothing when no template is found. * * @param non-empty-string $slug Template slug. * @param string|null $name Optional. Template variation name. @@ -165,9 +154,6 @@ public function get( string $slug, ?string $name = null, array $args = [] ): str /** * Locate a template part's file without rendering it. * - * The low-level escape hatch for callers that only need to know whether a - * template exists, or want its path. Most callers want render() or get(). - * * @param non-empty-string $slug Template slug. * @param string|null $name Optional. Template variation name. * @@ -260,10 +246,7 @@ static function ( string $template ): string { private function find_template( array $templates ): string|false { $paths = $this->get_template_paths(); - // Key on the resolved paths as well as the candidate names: the paths depend - // on the active theme (get_stylesheet_directory()/get_template_directory()), - // so a Shareable loader reused across a switch_theme()/switch_to_blog() in - // one request must not serve the previous theme's cached hit. + // Use the active theme paths to prevent a cross-theme cache collision. $cache_key = md5( implode( '|', $paths ) . "\0" . implode( '|', $templates ) ); if ( array_key_exists( $cache_key, $this->location_cache ) ) { @@ -272,9 +255,7 @@ private function find_template( array $templates ): string|false { $found = false; - // Template names are the outer loop so a more specific name (e.g. the - // {slug}-{name} variant) wins across layers, matching WordPress' - // locate_template() precedence — name dominates location. + // Per locate_template(), a `{slug}-{name}.php` in any path beats `{slug}.php` in a higher-precedence path. foreach ( $templates as $template ) { $template = ltrim( $template, '/\\' ); @@ -296,10 +277,9 @@ private function find_template( array $templates ): string|false { /** * Get the ordered, trailing-slashed search paths (child > parent > package). * - * Works for both plugin and theme packages. Only the theme layers that sit - * ABOVE the package can override it: a package inside the parent theme is - * overridden only by the child theme, and a package inside the child theme - * has no override layer at all. Mirrors ComponentLoader's hierarchy. + * Only the theme layers above the package are included. Templates inside the + * parent theme are overridden only by the child theme, and templates inside + * the child theme have no override layer. * * @return array Paths in resolution order, most specific first. */ @@ -309,25 +289,23 @@ private function get_template_paths(): array { $package = trailingslashit( $this->template_dir ); $has_child = $stylesheet !== $template; - // Where the package's own templates live decides which theme layers sit - // above it (and can therefore override it). + // Where the package's own templates live decides which theme layers can override them. $in_child = str_starts_with( $package, $stylesheet ); $in_parent = str_starts_with( $package, $template ); $paths = []; - // Child theme override layer: a distinct child theme exists and the - // package isn't itself in it. + // A child theme is active and the package is not in it. if ( $has_child && ! $in_child ) { $paths[1] = $stylesheet . $this->template_theme_dir; } - // Parent theme override layer: the package is in neither theme. + // The package is in neither theme. if ( ! $in_parent && ! $in_child ) { $paths[10] = $template . $this->template_theme_dir; } - // The package's own templates — lowest precedence. + // The package's own templates have the lowest precedence. $paths[100] = $this->template_dir; /** diff --git a/inc/Utils/Cache.php b/inc/Utils/Cache.php index 30cca1f..3d223e4 100644 --- a/inc/Utils/Cache.php +++ b/inc/Utils/Cache.php @@ -13,51 +13,25 @@ /** * Class - Cache * - * Typed wrapper over WordPress's object-cache functions with per-consumer - * group namespacing and optional stale-while-revalidate (SWR) stampede - * prevention. - * - * Instance-based, configured with a context slug at construction — so each - * consumer's cache groups are namespaced and cannot collide with another - * plugin or theme using the same group name through a shared object cache: + * Typed wrapper over the WordPress object-cache functions. Each cache group is + * prefixed with the instance's context slug, and {@see Cache::remember_swr()} + * adds stale-while-revalidate (SWR) regeneration. * * $cache = new Cache( 'my-plugin' ); * $nav = $cache->remember( 'nav_items', fn() => build_nav(), 'theme', 300 ); * - * Designed to be a service: construct it with the package's slug, register an - * instance as Shareable in a consumer's container, or extend it to change the - * namespacing by overriding the {@see Cache::resolve_group()} seam (the same - * pattern as {@see \rtCamp\WPPrimitives\ComponentLoader::get_context()}). - * - * Centralises calls to `wp_cache_get`, `wp_cache_set`, `wp_cache_delete`, and - * `wp_cache_flush_group` so consumers have a single typed API and one place to - * layer cross-cutting behaviour (logging, telemetry, fallbacks). It adds no - * cache layer of its own: WordPress's object cache already keeps an - * in-process, per-request store (and persistent drop-ins keep a local cache in - * front of the network), so every read and write goes straight through. - * - * Miss detection uses `wp_cache_get()`'s `$found` out-parameter, so falsy - * values such as `false` or `0` are cached and served like any other value — - * a callback returning `false` is not regenerated on every call. - * - * Two get-or-set flavours: - * - {@see Cache::remember()} — plain get-or-set; one key, no extra writes. - * - {@see Cache::remember_swr()} — adds stale-while-revalidate stampede - * prevention for expensive regenerations: on expiry, one caller regenerates - * in the foreground while the rest are served the stale copy. - * - * `wp_cache_flush_group()` was added in WordPress 6.1; `flush_group()` checks - * `wp_cache_supports( 'flush_group' )` so it gracefully returns `false` when - * the persistent cache backend does not support group flushing. + * Reads and writes go straight to the object cache. Misses are detected with + * the `$found` argument of `wp_cache_get()`, so falsy values such as `false` + * and `0` are cached like any other value. See docs/utilities.md. * * @since 1.0.0 */ class Cache { /** - * TTL (seconds) for the SWR regeneration lock key. + * TTL in seconds for the SWR regeneration lock key. * - * Dead-man switch: if the regenerating process crashes before releasing the - * lock, it auto-expires so subsequent requests are not permanently blocked. + * If the regenerating process dies before releasing the lock, the lock + * expires after this many seconds. */ protected const LOCK_TTL = 30; @@ -72,20 +46,16 @@ class Cache { protected const LOCK_RETRIES = 2; /** - * Multiplier applied to `$expiration` when storing the stale entry. - * Stale data must outlive the fresh entry long enough for at least one - * regeneration cycle to complete. + * Multiplier applied to `$expiration` when storing the stale entry, so the + * stale entry outlives the fresh entry by at least one regeneration. */ protected const STALE_MULTIPLIER = 2; /** * Constructor. * - * @param string $context Context slug identifying the package that owns this - * instance (e.g. a theme/plugin slug). Prefixed onto - * every cache group so consumers sharing an object - * cache cannot collide. Empty string means no - * namespacing — groups are passed through verbatim. + * @param string $context Theme or plugin slug prefixed onto every cache group. + * An empty string leaves groups unchanged. */ public function __construct( protected string $context = '', @@ -97,8 +67,7 @@ public function __construct( * * With a context of `my-plugin`, group `posts` resolves to * `my-plugin:posts` and the default (empty) group resolves to `my-plugin`. - * Without a context, groups pass through verbatim. Override this seam to - * change the namespacing scheme. + * Without a context, groups are returned unchanged. * * @param string $group Caller-supplied cache group. * @@ -115,15 +84,11 @@ protected function resolve_group( string $group ): string { /** * Get a value from cache. * - * Returns `mixed` because object-cache entries can hold any serialisable - * value (mirrors WordPress's own `wp_cache_get()` signature). - * * @param string $key Cache key. * @param string $group Cache group. Defaults to the global group. - * @param bool $force Re-fetch from the persistent backend, bypassing the - * drop-in's local in-process cache. - * @param bool|null $found Set to `true` if the key was found, `false` if not. - * Disambiguates a stored falsy value from a miss. + * @param bool $force Whether to bypass the drop-in's in-process cache and read from the persistent backend. + * @param bool|null $found Set to `true` if the key was found, `false` if not. Tells a stored falsy value apart from + * a miss. * * @return mixed Stored value, or `false` if missing or expired. */ @@ -142,16 +107,15 @@ public function get( string $key, string $group = '', bool $force = false, ?bool * @return bool True on success, false on failure. */ public function set( string $key, mixed $value, string $group = '', int $expiration = 0 ): bool { - // phpcs:ignore WordPressVIPMinimum.Performance.LowExpiryCacheTime.CacheTimeUndetermined -- expiry originates with the caller; enforced at call sites, not inside the wrapper. + // phpcs:ignore WordPressVIPMinimum.Performance.LowExpiryCacheTime.CacheTimeUndetermined -- The caller sets the expiry. return wp_cache_set( $key, $value, $this->resolve_group( $group ), $expiration ); } /** * Delete a single key from cache. * - * Deletes only `$key`. It does not remove the companion `{key}_stale` / - * `{key}_lock` entries written by {@see Cache::remember_swr()} — to fully - * invalidate an SWR-remembered value, flush its group instead. + * Does not remove the `{key}_stale` and `{key}_lock` entries written by {@see Cache::remember_swr()}. + * To invalidate those as well, flush the group. * * @param string $key Cache key. * @param string $group Cache group. Defaults to the global group. @@ -165,16 +129,7 @@ public function delete( string $key, string $group = '' ): bool { /** * Flush an entire cache group. Requires WordPress 6.1+. * - * Gates on `wp_cache_supports( 'flush_group' )` rather than a bare - * `function_exists()` check: `wp_cache_flush_group()` exists on every WP 6.1+ - * core, but the active object-cache drop-in may not implement group flushing - * (e.g. some Memcached or Redis configurations). Calling it there would - * report success while flushing nothing. - * - * Both functions are guarded with `function_exists()`: `wp_cache_supports` - * keeps this safe on pre-6.1 cores (where neither exists), and the explicit - * `wp_cache_flush_group` guard protects against an inconsistent drop-in that - * advertises support without defining the function. + * Returns false when the object-cache drop-in does not support group flushing. * * @param string $group Cache group to flush. * @@ -196,13 +151,10 @@ public function flush_group( string $group ): bool { /** * Return a cached value, generating and storing it if absent. * - * Plain get-or-set: one key, no companion entries, no locking. For - * expensive regenerations that need stampede protection, use - * {@see Cache::remember_swr()} instead. + * Stores one key and takes no lock. For expensive regenerations, use {@see Cache::remember_swr()}. * - * `$callback` takes no arguments: to regenerate with specific parameters, - * capture them in a closure and encode the same parameters in `$key` so each - * variant caches under its own entry: + * `$callback` takes no arguments. Capture any parameters in a closure and include them in `$key`, so each variant + * its own entry: * * $id = 42; * $posts = $cache->remember( @@ -212,24 +164,16 @@ public function flush_group( string $group ): bool { * 300 * ); * - * Hits are detected via `wp_cache_get()`'s `$found` out-parameter, so a - * callback that returns a falsy value (`false`, `0`, `''`) is cached - * normally and not re-invoked on every call. - * - * If `$callback` throws, the exception propagates to the caller and nothing - * is cached. - * - * Returns `mixed` because the stored value can be any serialisable type - * (mirrors WordPress's own `wp_cache_get()` return type). + * A falsy return value from `$callback` is cached like any other value. If + * `$callback` throws, the exception propagates and nothing is cached. * * @param string $key Cache key. - * @param callable $callback Invoked (with no arguments) when the entry is - * absent; its return value is stored and - * returned. Capture any inputs via a closure. + * @param callable $callback Called with no arguments on a miss. Its return + * value is stored and returned. * @param string $group Cache group. Defaults to the global group. * @param int $expiration TTL in seconds. `0` means no expiry. * - * @return mixed The cached or freshly-generated value. + * @return mixed The cached or generated value. */ public function remember( string $key, callable $callback, string $group = '', int $expiration = 0 ): mixed { $found = false; @@ -245,62 +189,36 @@ public function remember( string $key, callable $callback, string $group = '', i } /** - * Return a cached value with stale-while-revalidate stampede prevention, - * generating and storing it if absent. - * - * Use this instead of {@see Cache::remember()} when regeneration is - * expensive enough that a thundering herd on expiry matters. On expiry, - * exactly one caller wins the regeneration lock and runs `$callback` - * synchronously, paying the regeneration cost in the foreground; every - * other caller returns the stale copy (stored at `{key}_stale` with a 2× - * TTL) without waiting. All callers — including the lock winner — are - * served the stale value for the current request; the fresh value lands in - * cache for subsequent requests. - * - * Reserved suffixes: companion entries are stored at `{key}_stale` and - * `{key}_lock`. Avoid passing a `$key` that already ends in `_stale` or - * `_lock`, as it would collide with another remembered value's companions. + * Return a cached value, regenerating it under a lock and serving a stale copy while one caller regenerates. + * + * The stale copy is stored at `{key}_stale` and the lock at `{key}_lock`, so `$key` must not end in `_stale` + * or `_lock`. + * + * Use this instead of {@see Cache::remember()} when regeneration is expensive enough that a thundering herd on expiry matters. * * Flow: - * - Fresh hit → return immediately. - * - Fresh miss + stale → if lock acquired, regenerate synchronously, write - * both keys, release lock; return stale either way. - * - Both absent → cold start (first-ever load or full flush); acquire - * lock, regenerate, write both keys; if lock not - * acquired, spin-wait up to {@see Cache::LOCK_RETRIES} × - * {@see Cache::LOCK_WAIT_US} µs, then call `$callback` - * directly as a last resort without releasing the - * other process's lock. - * - * As with {@see Cache::remember()}, hits are detected via the `$found` - * out-parameter (falsy values cache normally) and `$callback` takes no - * arguments — capture inputs via a closure and encode them in `$key`. - * - * If `$callback` throws, the exception propagates to the caller and the - * regeneration lock is released immediately (no value is cached), so the - * next request can retry without waiting out {@see Cache::LOCK_TTL}. - * - * **Requires a persistent object cache (Redis, Memcached) for effective - * cross-process stampede prevention.** On the default WordPress in-memory - * cache each PHP-FPM worker has its own isolated cache, so locks and stale - * entries are not shared across processes. The method remains useful as an - * ergonomic get-or-set helper regardless. - * - * Returns `mixed` because the stored value can be any serialisable type - * (mirrors WordPress's own `wp_cache_get()` return type). - * - * @param string $key Cache key (avoid endings `_stale` / `_lock`). - * @param callable $callback Invoked (with no arguments) when the fresh - * entry is absent; its return value is stored and - * returned. Capture any inputs via a closure. + * - Fresh hit: return it. + * - Fresh miss with a stale copy: the caller that acquires the lock + * regenerates and writes both keys. Every caller, including that one, + * returns the stale copy. + * - Both absent: the caller that acquires the lock regenerates and returns + * the new value. Other callers retry the fresh key up to + * {@see Cache::LOCK_RETRIES} times, {@see Cache::LOCK_WAIT_US} + * microseconds apart, then call `$callback` themselves. + * + * If `$callback` throws, the exception propagates, nothing is cached and the lock is released. + * + * Locks and stale copies are shared across PHP workers only with a persistent object cache such as Redis + * or Memcached. + * + * @param string $key Cache key. Must not end in `_stale` or `_lock`. + * @param callable $callback Called with no arguments on a fresh miss. Its + * return value is stored and returned. * @param string $group Cache group. Defaults to the global group. * @param int $expiration TTL in seconds for the fresh entry. `0` means - * no expiry: no stale companion is written (a - * never-expiring entry has nothing to - * revalidate), though cold-start lock - * protection still applies. + * no expiry, and no stale copy is written. * - * @return mixed The cached or freshly-generated value. + * @return mixed The cached, stale or generated value. */ public function remember_swr( string $key, callable $callback, string $group = '', int $expiration = 0 ): mixed { $found = false; @@ -339,9 +257,8 @@ public function remember_swr( string $key, callable $callback, string $group = ' /** * Atomically acquire the SWR regeneration lock. * - * Relies on `wp_cache_add()` failing when the key already exists, so only - * one process wins the lock. The {@see Cache::LOCK_TTL} expiry is a - * dead-man switch in case the winner crashes before releasing it. + * `wp_cache_add()` fails when the key already exists, so only one process acquires the lock. + * The lock expires after {@see Cache::LOCK_TTL} seconds. * * @param string $lock_key Lock cache key. * @param string $group Caller-supplied cache group. @@ -349,32 +266,23 @@ public function remember_swr( string $key, callable $callback, string $group = ' * @return bool True if this process acquired the lock. */ protected function acquire_lock( string $lock_key, string $group ): bool { - // phpcs:ignore WordPressVIPMinimum.Performance.LowExpiryCacheTime.CacheTimeUndetermined -- LOCK_TTL is a dead-man-switch for the lock entry, not a data TTL. + // phpcs:ignore WordPressVIPMinimum.Performance.LowExpiryCacheTime.CacheTimeUndetermined -- LOCK_TTL is the lock expiry, not a data TTL. return wp_cache_add( $lock_key, 1, $this->resolve_group( $group ), static::LOCK_TTL ); } /** - * Invoke `$callback`, write the cache entries, optionally release the lock, and return the value. - * - * The stale companion is only written for expiring entries - * (`$expiration > 0`): a never-expiring fresh entry has nothing to - * revalidate, so duplicating it at `{key}_stale` would only waste backend - * memory. - * - * When this process acquired the lock, it is released in a `finally` block so - * a throwing callback cannot leave it held for the remainder of - * {@see Cache::LOCK_TTL}. + * Call `$callback`, write the cache entries, release the lock if given, and return the value. * - * Returns `mixed` because the callback can return any serialisable type. + * The stale copy is written only when `$expiration > 0`. The lock is released even when `$callback` throws. * * @param string $key Fresh cache key. - * @param string $stale_key Stale cache key (grace-period copy). + * @param string $stale_key Stale cache key. * @param callable $callback Invoked to produce the fresh value. * @param string $group Cache group. - * @param int $expiration TTL for the fresh entry; stale TTL = expiration × {@see Cache::STALE_MULTIPLIER}. + * @param int $expiration TTL for the fresh entry. The stale TTL is this times {@see Cache::STALE_MULTIPLIER}. * @param string $lock_key Optional lock key to delete after regeneration. * - * @return mixed The freshly-generated value. + * @return mixed The generated value. */ protected function store_with_stale( string $key, string $stale_key, callable $callback, string $group, int $expiration, string $lock_key = '' ): mixed { try { diff --git a/inc/Utils/Encryptor.php b/inc/Utils/Encryptor.php index 1b5b1df..f863243 100644 --- a/inc/Utils/Encryptor.php +++ b/inc/Utils/Encryptor.php @@ -15,12 +15,8 @@ /** * Class - Encryptor * - * Instance-based, configured with a key (and optional cipher) at construction — - * so different domains can use different keys, and it is trivially testable. - * - * Designed to be a service: construct it with a key, register an instance as - * Shareable in a consumer's container, or extend it to change the cipher or the - * key source (e.g. KMS) by overriding the {@see Encryptor::key()} seam. + * Each instance has its own key and cipher. To read the key from another source such as a KMS, + * override {@see Encryptor::key()}. * * @since 1.0.0 */ @@ -149,9 +145,7 @@ public function decrypt( string $raw_value ): string|false { /** * Whether the OpenSSL extension is available. * - * A seam rather than an inline extension_loaded() call so the "no OpenSSL" - * path, which makes encrypt() and decrypt() fail closed, can be exercised by - * a subclass in tests. + * Tests override this to cover the path where encrypt() and decrypt() return false. * * @return bool True when OpenSSL can be used. */ @@ -162,13 +156,10 @@ protected function is_openssl_available(): bool { /** * Resolve the raw secret. * - * Override seam: a subclass can source the secret from elsewhere (KMS, a - * rotated secret, an env var) without touching the crypto. Must never return - * an empty secret — encryption must not proceed with a weak/missing key. + * Subclasses override this to read the secret from another source, such as a KMS or an environment variable. + * Overrides must throw rather than return an empty string. * - * The return value is a *secret of any length*, not a cipher key: the - * derivation in {@see Encryptor::cipher_key()} turns it into one, so an - * override cannot accidentally hand OpenSSL a wrong-length key. + * The secret can be any length. {@see Encryptor::cipher_key()} derives the cipher key from it. * * @return string The raw secret. * @@ -185,20 +176,15 @@ protected function key(): string { } /** - * Derive the cipher key actually handed to OpenSSL. - * - * Deliberately private and not part of the override seam: the derivation is - * a correctness guarantee for every key source, including subclasses that - * override {@see Encryptor::key()}. Were this folded into that seam, a KMS- - * or env-backed override would bypass it and fall back to OpenSSL's silent - * handling of a wrong-length key. - * - * OpenSSL NUL-pads a too-short key and truncates a too-long one, which would - * quietly weaken the cipher (a 16-byte secret becomes 16 real bytes + 16 zero - * bytes for AES-256) and make rotating only the tail of a long secret a no-op. - * Hashing maps any-length secret to a full-strength, fixed-length key - * deterministically. Only reached from encrypt()/decrypt(), which have already - * confirmed the OpenSSL extension is loaded. + * Derive the cipher key passed to OpenSSL. + * + * OpenSSL NUL-pads a short key and truncates a long one. For AES-256, a + * 16-byte secret would become 16 secret bytes and 16 zero bytes, and + * changing only the tail of a long secret would have no effect. Hashing + * turns a secret of any length into a key of the cipher's length. + * + * This method is private so that overrides of {@see Encryptor::key()} still + * go through the derivation. * * @return string Key of exactly the cipher's key length. * diff --git a/inc/Utils/FeatureSelector.php b/inc/Utils/FeatureSelector.php index f560bef..102a665 100644 --- a/inc/Utils/FeatureSelector.php +++ b/inc/Utils/FeatureSelector.php @@ -13,36 +13,21 @@ /** * Feature-flag registry for a single package. * - * Each instance is scoped to one context slug (a theme or plugin slug). All - * flag states live together in a single WP option as a serialised associative - * array, rather than one option row per flag. This keeps the options table clean - * and makes it trivial to read, export, or reset all flags at once. + * Each instance belongs to one theme or plugin slug, its context. All flag + * states are stored in one option as an associative array. * - * Flag resolution order in is_enabled(): - * 0. Registered? — unregistered slugs are always off; nothing below runs - * 1. PHP constant — define in wp-config.php to lock a flag hard - * 2. Stored array — value from the shared option for this flag's key - * 3. default true — a registered flag is on unless explicitly turned off + * For the context "my-plugin" and the flag "dark-mode": * - * Storage scheme (context "my-plugin"): - * option name → my_plugin_features (one row; value is an associative array) - * array key → dark-mode (flag slug, dashes preserved) - * constant name → MY_PLUGIN_FEATURE_DARK_MODE - * - * Context slugs are normalized with underscores (my_plugin_features). Flag - * keys preserve dashes — only spaces and other non-[a-z0-9-] characters are - * collapsed to a single dash. Constant names always use underscores (derived - * independently via the underscore normalizer). + * option name: my_plugin_features + * array key: dark-mode + * constant name: MY_PLUGIN_FEATURE_DARK_MODE * * Usage: * $flags = new FeatureSelector( 'my-plugin' ); * $flags->register( [ 'dark-mode', 'beta-search' => [ 'name' => 'Beta search' ] ] ); * $flags->is_enabled( 'dark-mode' ); * - * Extend and implement as Shareable to share a single registry instance across - * the framework container. Override shared_option_key() to change where flags - * are stored; flag_key() and constant_name() are independent and must be - * overridden separately if needed. + * Override shared_option_key() to store flags in another option. * * @since 1.0.0 */ @@ -56,7 +41,7 @@ class FeatureSelector { protected array $registered = []; /** - * Normalized flag key → original slug map for O(1) collision checks. + * Original slugs keyed by normalized flag key, for collision checks. * * @var array */ @@ -65,10 +50,8 @@ class FeatureSelector { /** * Constructor. * - * @param string $context Package slug — namespaces the shared option key - * and override constants so flags from different - * packages never collide. Omit only if you're certain - * nothing else uses the bare `features` option name. + * @param string $context Theme or plugin slug. Prefixes the option name and the override constants. When empty, the + * option is named `features`. */ public function __construct( protected string $context = '', @@ -84,15 +67,14 @@ public function get_context(): string { /** * Register one or more flags. * - * Accepts a single slug string, a list of slugs, or a slug => metadata map — - * or any mix of the three. Valid metadata keys: name (defaults to the slug), - * description. Either may be a closure returning the string, so translated - * text is only built when get_features() reads it, not at registration. - * Malformed entries are silently skipped. + * Accepts a slug, a list of slugs, a slug => metadata map, or a mix of + * these. Metadata keys are `name`, which defaults to the slug, and + * `description`. Either can be a closure that returns the string, which + * get_features() calls. Malformed entries are skipped without a notice. * - * First registration wins. Collision is checked on the normalized flag key - * so two slugs that normalize identically ("beta-search" and "beta search") - * are treated as duplicates and the second is rejected via _doing_it_wrong(). + * Slugs with the same {@see FeatureSelector::flag_key()}, such as + * "beta-search" and "beta search", collide. The first registration is kept + * and later ones trigger _doing_it_wrong(). * * @param array|string $features Flags to register. */ @@ -138,14 +120,17 @@ public function register( array|string $features ): void { /** * Check whether a flag is enabled. * - * Resolves in order: registry check → PHP constant → stored array value → default true. - * Unregistered slugs always return false (silently — no _doing_it_wrong()). - * String 'false' constants (a common wp-config mistake) are treated as false. + * Returns false for an unregistered slug, without a notice. Otherwise + * returns the first of: + * + * 1. The override constant from constant_name(). A string 'false' counts as false. + * 2. The stored value for the flag. + * 3. True. * * @param string $flag Flag slug as passed to register(). */ public function is_enabled( string $flag ): bool { - // Registry is authoritative: unregistered flags are always off. + // Unregistered flags are always off. if ( ! isset( $this->flag_keys[ $this->flag_key( $flag ) ] ) ) { return false; } @@ -169,7 +154,8 @@ public function is_enabled( string $flag ): bool { * * @param string $flag Flag slug. * - * @return bool True if the change was persisted; false if the flag is not registered. + * @return bool True if the option was updated. False if the flag is not registered or the stored value was already + * true. */ public function enable( string $flag ): bool { if ( ! isset( $this->flag_keys[ $this->flag_key( $flag ) ] ) ) { @@ -192,15 +178,12 @@ public function enable( string $flag ): bool { /** * Disable a flag and persist the change to the database. * - * Unlike the old per-flag approach there's no update_option() no-op edge - * case: we're always writing a changed array (the key is added or toggled), - * and update_option() calls add_option() internally when the row is absent. - * - * A PHP constant override still wins at read time regardless of what's stored. + * An override constant from constant_name() takes precedence over the stored value. * * @param string $flag Flag slug. * - * @return bool True if the change was persisted; false if the flag is not registered. + * @return bool True if the option was updated. False if the flag isn't registered or the stored value was already + * false. */ public function disable( string $flag ): bool { if ( ! isset( $this->flag_keys[ $this->flag_key( $flag ) ] ) ) { @@ -248,10 +231,9 @@ public function get_features(): array { } /** - * The single WP option name that stores all flag states for this context. + * Name of the option that stores all flag states for this context. * - * Format: {context}_features (e.g. my_plugin_features). - * Override this to change where flags are stored. + * Format: {context}_features, e.g. my_plugin_features. */ public function shared_option_key(): string { $context = $this->normalize( $this->context ); @@ -262,11 +244,8 @@ public function shared_option_key(): string { /** * Normalized array key for a flag within the stored option. * - * Lowercases the slug and collapses any run of characters outside [a-z0-9-] - * to a single dash, preserving existing dashes. This keeps stored keys - * human-readable (e.g. dark-mode, beta-search) and consistent with typical - * WP slug conventions. Contrast with normalize(), which uses underscores for - * PHP option-name and constant-name contexts. + * Lowercases the slug and replaces each run of characters outside [a-z0-9-] + * with a single dash. Leading and trailing dashes are trimmed. * * @param string $flag Flag slug. */ @@ -275,9 +254,9 @@ public function flag_key( string $flag ): string { } /** - * PHP constant name for a flag — define in wp-config.php to hard-lock it. + * Name of the constant that overrides a flag's stored state. * - * Format: {CONTEXT}_FEATURE_{FLAG} (e.g. MY_PLUGIN_FEATURE_DARK_MODE). + * Format: {CONTEXT}_FEATURE_{FLAG}, e.g. MY_PLUGIN_FEATURE_DARK_MODE. * * @param string $flag Flag slug. */ @@ -285,19 +264,14 @@ public function constant_name( string $flag ): string { $context = $this->normalize( $this->context ); $prefix = '' === $context ? 'FEATURE_' : strtoupper( $context ) . '_FEATURE_'; - // Derive the constant from flag_key() — the same partition used for storage - // — so two slugs that get distinct storage keys can't collapse to one - // constant. (normalize() collapses runs of dashes, so `beta-search` and - // `beta--search` would otherwise share MY_PLUGIN_FEATURE_BETA_SEARCH and one - // define() would lock both.) Unchanged for ordinary single-dash slugs. + // Built from flag_key() rather than normalize() which collapses multiple dashes into one. return $prefix . strtoupper( str_replace( '-', '_', $this->flag_key( $flag ) ) ); } /** - * Lowercase + collapse anything outside [a-z0-9_] to a single underscore. + * Lowercase and replace each run of characters outside [a-z0-9_] with a single underscore. * - * Not sanitize_key() — that drops invalid characters instead of replacing them, - * so "my.plugin" and "myplugin" would silently share the same key. + * Unlike sanitize_key(), which drops those characters, this keeps "my.plugin" and "myplugin" distinct. * * @param string $value Context or flag slug. */ diff --git a/inc/Utils/FeatureSelectorSettingsPage.php b/inc/Utils/FeatureSelectorSettingsPage.php index 6d2621f..9d32c24 100644 --- a/inc/Utils/FeatureSelectorSettingsPage.php +++ b/inc/Utils/FeatureSelectorSettingsPage.php @@ -15,25 +15,16 @@ /** * Admin settings page for a FeatureSelector registry. * - * Renders one checkbox per registered flag and wires the form to the WordPress - * Settings API. All flag states are stored in the single shared option managed - * by the injected {@see FeatureSelector}. + * Renders one checkbox per registered flag through the Settings API. The form + * posts to `options.php` with field names of the form + * `{shared_option_key}[{flag_key}]`, e.g. `my_plugin_features[dark-mode]`. * - * The form posts to `options.php` with array-style field names: - * {shared_option_key}[{flag_key}] e.g. elementary_features[dark-mode] + * A flag whose override constant is defined is rendered as a disabled + * checkbox, and saving the form keeps its stored value. * - * The sanitize callback writes only non-locked flags back to the stored array. - * Flags overridden by a PHP constant are rendered as locked (disabled checkbox) - * and are excluded from the sanitize pass so saving never overwrites the - * constant's intent in the options table. - * - * Boot order: register flags on the selector before `admin_init` fires. The - * flag list is read lazily when the Settings API hooks run, so flags registered - * after {@see FeatureSelectorSettingsPage::register_hooks()} still appear. - * - * Override the protected seams (menu slug, option group, titles, capability via - * the parent) or {@see FeatureSelectorSettingsPage::render_field()} to customise - * the page chrome. + * Register flags on the selector before `admin_init`. The flag list is read + * when the Settings API hooks run, so flags registered after + * {@see FeatureSelectorSettingsPage::register_hooks()} still appear. * * @since 1.0.0 */ @@ -41,8 +32,7 @@ abstract class FeatureSelectorSettingsPage extends AbstractSettingsPage { /** * Return the FeatureSelector whose flags this page manages. * - * Called lazily at hook time, so it's safe to resolve from a shared container - * here — the container is fully populated before any hook fires. + * Called from hook callbacks, not from the constructor. */ abstract protected function get_selector(): FeatureSelector; @@ -55,12 +45,6 @@ public static function get_slug(): string { /** * {@inheritDoc} - * - * `register_settings()` stays on both `admin_init` and `rest_api_init` - * (it only calls the REST-safe `register_setting()`), but sections and - * fields use `add_settings_section()`/`add_settings_field()` from - * `wp-admin/includes/template.php`, which is not loaded during REST - * requests — so field registration hooks `admin_init` only. */ public function register_hooks(): void { parent::register_hooks(); @@ -71,10 +55,7 @@ public function register_hooks(): void { /** * {@inheritDoc} * - * Slugifies the selector's context onto the base slug so the page slug - * stays a clean, valid menu slug regardless of context casing/spacing: - * `my-plugin` → `my-plugin-features`, `My Plugin v2.0` → - * `my-plugin-v2-0-features`, empty context → `features`. + * Slugifies the selector's context and prepends it to the base slug. * * @return non-empty-string */ @@ -87,9 +68,7 @@ protected function get_menu_slug(): string { /** * {@inheritDoc} * - * Underscored menu slug — intentionally kept in sync with the selector's - * shared_option_key() so that settings_fields() and the registered option - * name always match (both normalize context the same way). + * The menu slug with dashes replaced by underscores, e.g. `my_plugin_features`. * * @return non-empty-string */ @@ -132,11 +111,7 @@ protected function get_menu_title(): string { /** * {@inheritDoc} * - * Registers a single array option (the selector's shared option key) with - * a sanitize callback that validates each non-locked flag's value. - * - * Locked flags (constant-overridden) are excluded from the form but their - * previously stored value is preserved — see sanitize_settings(). + * Registers the selector's shared option as an array. */ protected function get_settings(): array { return [ @@ -149,14 +124,7 @@ protected function get_settings(): array { } /** - * Sanitize the submitted feature-flag array before it's written to the DB. - * - * For every registered, non-locked flag: true if the checkbox was submitted, - * false otherwise (unchecked checkboxes are absent from the POST body). - * - * For locked flags (constant-overridden): the previously stored value is - * carried forward so saving the form never silently resets a locked flag's - * database record to false. + * Sanitize the feature flag array before it is saved. * * @param mixed $input Raw value received from the Settings API. * @return array Sanitized flag-key => bool map. @@ -165,15 +133,11 @@ public function sanitize_settings( mixed $input ): array { $submitted = is_array( $input ) ? $input : []; /* - * This runs as a `sanitize_option_{key}` filter, which fires on EVERY write - * of the shared option — not only on this settings page's form. On a - * programmatic write (FeatureSelector::enable()/disable()) the incoming array - * is already the full intended state, so the checkbox rebuild below would - * wrongly reset every default-on flag that has never been stored to false. - * Only apply that rebuild for a genuine options.php submission of this option - * group; pass any other write through untouched. + * `sanitize_option_{key}` also fires for FeatureSelector::enable() and + * disable(). Their array is already complete, and rebuilding it from + * checkboxes would set every unstored, default-on flag to false. */ - // phpcs:ignore WordPress.Security.NonceVerification.Missing -- options.php verifies the nonce + capability before this filter runs; the marker only distinguishes a form save from a programmatic write. + // phpcs:ignore WordPress.Security.NonceVerification.Missing -- options.php verifies the nonce and capability before this filter runs. $option_page = isset( $_POST['option_page'] ) ? sanitize_text_field( wp_unslash( $_POST['option_page'] ) ) : ''; if ( $option_page !== $this->get_option_group() ) { @@ -193,7 +157,7 @@ public function sanitize_settings( mixed $input ): array { $key = $this->get_selector()->flag_key( $slug ); if ( defined( $this->get_selector()->constant_name( $slug ) ) ) { - // Preserve the stored value so the constant's intent in the DB is not overwritten. + // Keep the stored value of a flag locked by a constant. if ( array_key_exists( $key, $stored ) ) { $sanitized[ $key ] = (bool) $stored[ $key ]; } @@ -210,7 +174,7 @@ public function sanitize_settings( mixed $input ): array { /** * Register one settings field per flag, all attached to a single section. * - * Hooked to `admin_init` only — see {@see FeatureSelectorSettingsPage::register_hooks()}. + * @internal Hooked to `admin_init`. */ public function register_fields(): void { add_settings_section( @@ -257,10 +221,9 @@ public function render(): void { /** * Render one flag's checkbox. * - * Uses array-style field names ({shared_option_key}[{flag_key}]) so all - * flags post as a single option array. Reuses {@see FeatureSelector::is_enabled()} - * so a defined constant is reflected automatically; the checkbox is then - * disabled and a help message names the constant. + * The checked state comes from {@see FeatureSelector::is_enabled()}. When + * the flag's override constant is defined, the checkbox is disabled and a + * description names the constant. * * @param array{slug: string, name: string, description: string} $args Flag metadata. */ diff --git a/inc/Utils/Logger.php b/inc/Utils/Logger.php index 6e30f62..641536e 100644 --- a/inc/Utils/Logger.php +++ b/inc/Utils/Logger.php @@ -2,6 +2,17 @@ /** * Logger utility. * + * PSR-3-style logger that writes to error_log() when {@see Logger::is_enabled()} returns true. + * + * $log = new Logger( 'my-plugin' ); + * $log->info( 'Cache warmed', [ 'items' => 42 ] ); + * + * The method names match PSR-3, but only the debug, info, warning and error + * levels exist, and the class does not implement `Psr\Log\LoggerInterface`. + * + * Line format: `[LEVEL] [prefix] message {"context":"json"}`. + * The JSON is omitted when the context is empty. + * * @package rtCamp\WPPrimitives\Utils * @since 1.0.0 */ @@ -11,36 +22,7 @@ namespace rtCamp\WPPrimitives\Utils; /** - * PSR-3-style logger that writes to error_log() — but only when logging is enabled. - * - * Instance-based and context-scoped: construct one per consumer with that package's - * prefix, so a theme and a plugin sharing the PHP process each own an independent - * logger they configure (and can subclass) rather than routing every line through one - * shared global instance: - * - * $log = new Logger( 'my-plugin' ); - * $log->info( 'Cache warmed', [ 'items' => 42 ] ); - * - * Silent in production: {@see log()} writes nothing unless {@see is_enabled()} returns - * true, which by default tracks `WP_DEBUG`. So it is safe to leave calls in shipped - * code — they no-op on production where `WP_DEBUG` is off. - * - * PSR-3-*style*, not a full implementation: it ships the four levels rtCamp plugins - * actually use ({@see debug()}, {@see info()}, {@see warning()}, {@see error()}) plus - * the generic {@see log()}, and deliberately stops there — no `notice`/`critical`/etc., - * and no `psr/log` dependency (the framework carries zero runtime deps). The method - * names match PSR-3 so a later swap to Monolog or another PSR-3 logger needs no caller - * changes. - * - * Format: `[LEVEL] [prefix] message {"context":"json"}` (the JSON segment is omitted - * when there is no context). - * - * Not `final`: downstream packages may extend it — e.g. override {@see is_enabled()} to - * gate on an env var or feature flag instead of `WP_DEBUG`, or to force logging on for a - * specific subsystem. Internal calls go through `$this` so such overrides take effect. - * - * @package rtCamp\WPPrimitives\Utils - * @since 1.0.0 + * Class Logger */ class Logger { /** @@ -53,7 +35,7 @@ class Logger { /** * Construct a logger for a consumer. * - * @param string $prefix Label shown in every log line — typically the consumer's slug. + * @param string $prefix Label shown in every log line, usually the theme or plugin slug. */ public function __construct( string $prefix = 'rtcamp' ) { $this->prefix = $prefix; @@ -62,8 +44,7 @@ public function __construct( string $prefix = 'rtcamp' ) { /** * Log a message at an arbitrary PSR-3 level. * - * No-ops (writes nothing) when logging is disabled — see {@see is_enabled()} — so it - * is safe to leave calls in shipped code. + * Writes nothing when {@see Logger::is_enabled()} returns false. * * @param string $level PSR-3 level: debug, info, warning, error. * @param string $message Message body. @@ -80,7 +61,7 @@ public function log( string $level, string $message, array $context = [] ): void $context_part = is_string( $encoded_context ) ? ' ' . $encoded_context : ''; } - // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logger IS the centralised error_log() wrapper; callers route through it instead of calling error_log() directly. The sniff's intent (no debug output in production) is satisfied by the is_enabled()/WP_DEBUG gate above. + // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- It's a logger utility. error_log( sprintf( '[%s] [%s] %s%s', strtoupper( $level ), $this->prefix, $message, $context_part ) ); } @@ -125,12 +106,9 @@ public function error( string $message, array $context = [] ): void { } /** - * Whether {@see log()} should write. + * Whether {@see Logger::log()} should write. * - * Defaults to `WP_DEBUG`, which is what keeps logs silent in production. Protected - * override seam (mirrors {@see Encryptor::key()}): a consumer can subclass to gate on - * an env var, a feature flag, or to force logging on for a specific subsystem — - * without touching the formatting in {@see log()}. + * Returns the value of `WP_DEBUG`. Subclasses can override it, e.g. to check an env variable or a feature flag. * * @return bool True when logging is active. */ diff --git a/inc/Utils/Timer.php b/inc/Utils/Timer.php index 8a3879b..77dba3f 100644 --- a/inc/Utils/Timer.php +++ b/inc/Utils/Timer.php @@ -13,28 +13,18 @@ /** * Class - Timer * - * Named timing segments that persist across scopes within a single request: start a - * timer in one hook or file and stop it in another, with no globals or hand-passed - * `microtime( true )` values. - * - * Instance-based, not a singleton. The cross-scope sharing the start-here / stop-there - * pattern needs is met by holding one instance and sharing it — register it as - * `Shareable` in the consumer's container (the same pattern as {@see Cache}) so - * every hook resolves the same object. A theme and a plugin - * in the same process then each keep their own decoupled timer set, instead of writing - * into one global instance: + * Named timers for one request. A timer can be started in one hook and stopped + * in another when both use the same instance. * * $timer = new Timer(); * $timer->start( 'render' ); - * // … later, in another hook holding the same instance … - * $elapsed = $timer->stop( 'render' ); // float seconds + * // ... Later, in another hook with the same instance: + * $elapsed = $timer->stop( 'render' ); * - * Misuse (empty/duplicate/never-started/already-stopped labels) is reported via - * `_doing_it_wrong()` — the WordPress convention for developer error — rather than by - * throwing. The read methods ({@see get()}, {@see get_all()}) stay silent and simply - * return null / an empty entry, so inspecting timers never emits notices. + * start(), stop() and lap() report an empty, duplicate, unstarted or stopped + * label with `_doing_it_wrong()`. get() and get_all() emit no notices. * - * Times are returned as float seconds, consistent with `$wpdb->queries` timing. + * Times are in seconds, as floats. * * @since 1.0.0 */ @@ -49,8 +39,7 @@ class Timer { /** * Start a named timer. * - * No-op (plus `_doing_it_wrong()`) when the label is empty or already started — a - * second start would otherwise silently discard the original start time. + * No-op (plus `_doing_it_wrong()`) when the label is empty or already started. * * @param string $label Unique identifier for this timer. */ @@ -87,15 +76,13 @@ public function start( string $label ): void { /** * Stop a named timer and return its elapsed time. * - * Return paths: - * - empty label → 0.0 plus `_doing_it_wrong()`; - * - never-started label → 0.0 plus `_doing_it_wrong()`; - * - already-stopped → cached elapsed plus `_doing_it_wrong()` (no recompute); - * - running → fresh elapsed, and the timer is marked stopped. + * An empty or unstarted label returns 0.0 and triggers `_doing_it_wrong()`. + * A stopped timer returns its recorded elapsed time and triggers + * `_doing_it_wrong()`. * * @param string $label Timer to stop. * - * @return float Elapsed seconds (0.0 when never started or the label is empty). + * @return float Elapsed seconds. */ public function stop( string $label ): float { if ( '' === $label ) { @@ -141,9 +128,9 @@ public function stop( string $label ): float { /** * Record an intermediate split on a running timer. * - * Stores the elapsed seconds since start at the moment {@see lap()} is called. - * Reports via `_doing_it_wrong()` (and records nothing) when either argument is - * empty, the timer was never started, or it has already been stopped. + * Stores the seconds elapsed since the timer started. Records nothing and + * triggers `_doing_it_wrong()` when either argument is empty or the timer is + * not running. * * @param string $label Timer label. * @param string $name Lap name. @@ -199,9 +186,8 @@ public function lap( string $label, string $name ): void { /** * Get timing data for a single timer. * - * Silent read: returns null for an empty or unknown label, and never emits a - * notice. For a still-running timer, `elapsed` is the time since start at the - * moment {@see get()} is called, without stopping it. + * Returns null for an empty or unknown label. For a running timer, `elapsed` + * is the time since it started. * * @param string $label Timer label. * @@ -229,10 +215,8 @@ public function get( string $label ): ?array { /** * Get every recorded timer. * - * Each entry carries a computed `elapsed`; for running timers that is the - * time-since-start measured against a single snapshot taken when - * {@see get_all()} is called, so every running timer is read against the same - * "now" regardless of iteration order. + * The `elapsed` value of every running timer is measured against the same + * microtime() reading. * * @return array}> */ diff --git a/inc/Utils/Transients.php b/inc/Utils/Transients.php index 6d1c945..4562b42 100644 --- a/inc/Utils/Transients.php +++ b/inc/Utils/Transients.php @@ -13,23 +13,14 @@ /** * Class - Transients * - * Wraps WordPress's transient API with a per-instance key prefix, so two modules - * living in the same PHP process that happen to pick the same logical key never - * clobber each other — the classic `set_transient( 'user_count', … )` collision. - * - * This is the one utility here that is multi-instance out of necessity rather than - * convenience: there is no shared/singleton form, because isolated key namespaces - * are the entire point. Each consumer constructs its own wrapper with a unique - * prefix, and every key is namespaced before it reaches WordPress: + * Wraps the WordPress transient API and prefixes every key, so two instances + * with different prefixes can use the same key. * * $store = new Transients( 'my-module' ); * $store->set( 'user_count', 42, HOUR_IN_SECONDS ); - * $store->get( 'user_count' ); // 42 — isolated from any other module's 'user_count'. + * $store->get( 'user_count' ); // 42 * - * Regular (single-site) transients only; a multisite / site-transient variant can - * arrive later by overriding the {@see resolve_key()} seam, with no breaking change. - * Not `final`, and internal calls go through `$this` so such overrides take effect — - * the same extension pattern as {@see Cache::resolve_group()}. + * Uses regular (single-site) transients. * * @since 1.0.0 */ @@ -46,8 +37,7 @@ class Transients { /** * Construct a Transients wrapper bound to a key prefix. * - * @param string $prefix Per-instance namespace prepended to every key. A - * construction-time identity — readonly, not runtime-mutable. + * @param string $prefix Prefix added to every key. */ public function __construct( protected readonly string $prefix, @@ -56,10 +46,7 @@ public function __construct( /** * Get a transient value. * - * Returns `mixed` because transients can hold any serialisable value (mirrors - * WordPress's own `get_transient()` signature). - * - * @param string $key Logical key (namespaced before lookup). + * @param string $key Unprefixed key. * * @return mixed Stored value, or `false` if missing or expired. */ @@ -70,7 +57,7 @@ public function get( string $key ): mixed { /** * Set a transient with an optional expiration. * - * @param string $key Logical key (namespaced before write). + * @param string $key Unprefixed key. * @param mixed $value Value to store. Must be serialisable. * @param int $expiration TTL in seconds. Defaults to one day; `0` means no expiry. * @@ -83,7 +70,7 @@ public function set( string $key, mixed $value, int $expiration = DAY_IN_SECONDS /** * Delete a transient. * - * @param string $key Logical key (namespaced before delete). + * @param string $key Unprefixed key. * * @return bool True if the transient was deleted, false otherwise. */ @@ -92,27 +79,20 @@ public function delete( string $key ): bool { } /** - * Namespace a logical key with this instance's prefix. - * - * Format: `:_`. The leading length header is - * digits-only and terminated by the first `:`, so the prefix/key boundary stays - * unambiguous even when either part contains underscores. Without it, - * `( 'mod', 'a_b' )` and `( 'mod_a', 'b' )` would both collapse to `mod_a_b` and - * silently target the same WordPress transient. + * Prefix a key with this instance's prefix. * - * A namespaced key longer than {@see Transients::MAX_NAME_LENGTH} is replaced by - * `h:`. WordPress cannot store such a name: the - * option rows are truncated, so the value is never found again (or, just past - * the limit, its expiry is silently lost). Keys within the limit are unchanged, - * and a hashed key can never equal an unhashed one, which always starts with - * digits. + * Format: `:_`. + * The length makes the boundary between prefix and key unambiguous, so `( 'mod', 'a_b' )` + * and `( 'mod_a', 'b' )` give different names. * - * Protected override seam (mirrors {@see Cache::resolve_group()}): subclass to - * change the namespacing scheme, for instance a multisite / site-transient variant. + * A name longer than {@see Transients::MAX_NAME_LENGTH} is replaced by + * `h:`, because WordPress truncates the option rows and + * would not find the value again. A hashed name cannot equal an unhashed one, + * which always starts with a digit. * - * @param string $key Logical key supplied by the caller. + * @param string $key Unprefixed key. * - * @return string Fully namespaced key passed to WordPress's transient API. + * @return string Transient name passed to WordPress. */ protected function resolve_key( string $key ): string { $name = strlen( $this->prefix ) . ':' . $this->prefix . '_' . $key; diff --git a/phpcs.xml.dist b/phpcs.xml.dist index 208d586..10d257e 100644 --- a/phpcs.xml.dist +++ b/phpcs.xml.dist @@ -19,9 +19,9 @@ How to scan: include CLI args so you don't need to pass them manually Usage instructions: https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki/Usage --> - + - + @@ -63,7 +63,7 @@ - + tests/* diff --git a/tests/phpunit/Fixtures/BareSingleton.php b/tests/phpunit/Fixtures/BareSingleton.php index 2963cf2..daaac1c 100644 --- a/tests/phpunit/Fixtures/BareSingleton.php +++ b/tests/phpunit/Fixtures/BareSingleton.php @@ -1,9 +1,6 @@ 3 ) { - // A regression would recurse forever; fail loudly instead. + // Stops infinite recursion if get_instance() constructs again. throw new \RuntimeException( 'Singleton re-entered its own construction.' ); } diff --git a/tests/phpunit/Fixtures/ShareableRegistrable.php b/tests/phpunit/Fixtures/ShareableRegistrable.php index 43eccae..0e588fe 100644 --- a/tests/phpunit/Fixtures/ShareableRegistrable.php +++ b/tests/phpunit/Fixtures/ShareableRegistrable.php @@ -13,8 +13,7 @@ use rtCamp\WPPrimitives\Contracts\Interfaces\Shareable; /** - * Implements both Registrable and Shareable — hooks fire AND the instance - * is cached in the container. + * Registrable and Shareable fixture that records whether register_hooks() ran. */ final class ShareableRegistrable implements Registrable, Shareable { public static bool $registered = false; diff --git a/tests/phpunit/Fixtures/SingletonExample.php b/tests/phpunit/Fixtures/SingletonExample.php index 06d4162..45c936b 100644 --- a/tests/phpunit/Fixtures/SingletonExample.php +++ b/tests/phpunit/Fixtures/SingletonExample.php @@ -19,7 +19,7 @@ class SingletonExample { use Singleton; /** - * Tracks how many times the constructor ran — a true singleton runs it once. + * Number of times the constructor ran. */ public static int $construct_count = 0; diff --git a/tests/phpunit/Integration/AssetLoaderHandleTest.php b/tests/phpunit/Integration/AssetLoaderHandleTest.php index 4a76e33..6a1a4a4 100644 --- a/tests/phpunit/Integration/AssetLoaderHandleTest.php +++ b/tests/phpunit/Integration/AssetLoaderHandleTest.php @@ -35,7 +35,7 @@ public function test_empty_subclass_prefix_returns_the_name_unchanged(): void { } /** - * Subclass overriding HANDLE_PREFIX, to prove the override is honoured. + * Subclass with a custom HANDLE_PREFIX. */ final class AssetLoaderWithPluginPrefix extends AssetLoader { diff --git a/tests/phpunit/Integration/AssetLoaderTest.php b/tests/phpunit/Integration/AssetLoaderTest.php index c5c60a7..516b7f2 100644 --- a/tests/phpunit/Integration/AssetLoaderTest.php +++ b/tests/phpunit/Integration/AssetLoaderTest.php @@ -2,11 +2,6 @@ /** * Asset loader tests. * - * Runs against a real WordPress instance (wp-env): registrations are asserted - * by reading the actual wp_scripts()/wp_styles()/wp_script_modules() registries - * rather than stubbed globals, and incorrect-usage notices via - * WP_UnitTestCase::setExpectedIncorrectUsage(). - * * @package rtCamp\WPPrimitives\Tests\Integration */ @@ -29,9 +24,7 @@ final class AssetLoaderTest extends TestCase { public function set_up(): void { parent::set_up(); - // Start each test from clean dependency registries so handles registered - // in one test don't leak into the next (WP_UnitTestCase does not reset - // these between tests). + // WP_UnitTestCase does not reset these registries between tests. $GLOBALS['wp_scripts'] = null; $GLOBALS['wp_styles'] = null; $this->reset_script_modules(); @@ -73,7 +66,7 @@ public function test_register_script_builds_src_and_reads_manifest(): void { $this->assertSame( 'https://example.test/theme/assets/build/js/app.js', $script->src ); $this->assertSame( [ 'wp-dom' ], $script->deps ); $this->assertSame( 'v1', $script->ver ); - // in_footer defaults to true → footer group. + // in_footer defaults to true, which puts the script in footer group 1. $this->assertSame( 1, $script->extra['group'] ?? null ); } @@ -108,7 +101,7 @@ public function test_register_script_module_maps_dependencies_to_id_form(): void $this->assertNotNull( $module ); $this->assertSame( 'https://example.test/theme/assets/build/js/module.js', $module['src'] ); $this->assertSame( 'v3', $module['version'] ); - // WordPress normalises each dependency to id/import form (import: static default). + // WordPress normalises each dependency to an id/import pair, with import defaulting to static. $this->assertSame( [ [ @@ -202,10 +195,8 @@ public function test_invalid_manifest_is_ignored_and_falls_back_to_filemtime(): } public function test_register_block_manifest_registers_collection(): void { - // A real block.json plus a manifest describing it, both under the loader's - // base. Spans the supported range: WP 6.8+ registers via the manifest - // collection API; 6.5–6.7 falls back to per-block registration from disk - // (which reads the block.json), so both paths register the same block. + // WP 6.8+ registers the block through the manifest collection API. WP 6.5 to 6.7 + // registers it from block.json on disk. $this->write_asset( 'build/blocks/example/block.json', '{"$schema":"https://schemas.wp.org/trunk/block.json","apiVersion":3,"name":"wp-primitives/example","title":"Example","category":"widgets"}' @@ -225,8 +216,6 @@ public function test_register_block_manifest_registers_collection(): void { } public function test_legacy_fallback_ignores_a_manifest_that_is_not_an_array(): void { - // Only the 6.5 to 6.7 fallback reads the manifest itself; on 6.8+ core - // does, so the guard under test only exists on older cores. if ( function_exists( 'wp_register_block_types_from_metadata_collection' ) ) { $this->markTestSkipped( 'The per-block fallback only runs on WordPress < 6.8.' ); } @@ -235,7 +224,6 @@ public function test_legacy_fallback_ignores_a_manifest_that_is_not_an_array(): 'build/blocks/example/block.json', '{"$schema":"https://schemas.wp.org/trunk/block.json","apiVersion":3,"name":"wp-primitives/example","title":"Example","category":"widgets"}' ); - // A manifest that evaluates to something other than an array. $this->write_asset( 'build/blocks-manifest.php', 'loader->register_block_manifest( 'build/blocks', 'build/blocks-manifest.php' ); @@ -270,15 +258,12 @@ public function test_missing_script_module_file_warns_and_returns_false(): void } public function test_register_script_rejects_path_traversal_in_filename(): void { - // A `..` in the filename would let the require()'d .asset.php escape the - // assets directory; the loader refuses it (returns false, registers nothing). + // A `..` in the filename would let the required .asset.php file escape the assets directory. $this->assertFalse( $this->loader->register_script( 'evil', '../../wp-config' ) ); $this->assertNull( $this->registered_script( 'evil' ) ); } public function test_has_asset_rejects_path_traversal_in_the_filename(): void { - // has_asset() is public API in its own right, so its guard needs direct - // coverage rather than being exercised only through register_script(). $this->write_asset( 'assets/build/js/real.js', '' ); $this->assertTrue( $this->loader->has_asset( 'js/real', 'js' ) ); @@ -295,14 +280,6 @@ public function test_has_asset_rejects_traversal_built_from_the_extension(): voi } public function test_has_asset_probe_cannot_reach_a_file_outside_the_assets_dir(): void { - // Prove the guard is load-bearing rather than rejecting a path that would - // have missed anyway: build the exact string the unguarded sprintf() would - // produce, assert a real file sits at it, then assert has_asset() still - // refuses. If the path arithmetic ever stops escaping, the first assertion - // fails loudly instead of the test passing for the wrong reason. - // The assets directory has to exist for the traversal to resolve at all — - // POSIX walks every component, so `assets/build/../..` is ENOENT if - // `assets/build` was never created. $this->write_asset( 'assets/build/js/real.js', '' ); $this->write_asset( 'outside.txt', 'secret' ); diff --git a/tests/phpunit/Integration/Components/ComponentLoaderTest.php b/tests/phpunit/Integration/Components/ComponentLoaderTest.php index 7f158bf..3984fb5 100644 --- a/tests/phpunit/Integration/Components/ComponentLoaderTest.php +++ b/tests/phpunit/Integration/Components/ComponentLoaderTest.php @@ -2,12 +2,6 @@ /** * Component loader tests. * - * Runs against a real WordPress instance (wp-env): the theme hierarchy is - * pointed at fixture directories via TestCase::set_theme_dirs, assets are - * asserted by reading the real wp_scripts()/wp_styles() registries, render - * hooks are captured with a real add_action() recorder, and incorrect usage - * via WP_UnitTestCase::setExpectedIncorrectUsage(). - * * @package rtCamp\WPPrimitives\Tests\Integration\Components */ @@ -57,14 +51,13 @@ public function set_up(): void { // A distinct child theme is active by default. $this->set_theme_dirs( $this->parent_dir, $this->parent_uri, $this->child_dir, $this->child_uri ); - // Start each test from clean dependency registries (WP_UnitTestCase does - // not reset these between tests). + // WP_UnitTestCase does not reset these registries between tests. $GLOBALS['wp_scripts'] = null; $GLOBALS['wp_styles'] = null; TestComponentLoader::$test_context = 'wp-primitives'; - // Record the render actions so tests can assert they fired. + // Record each render action as it fires. $this->rendered_hooks = []; foreach ( [ 'before', 'after' ] as $phase ) { $hook = "wp-primitives/component_{$phase}_render"; @@ -76,7 +69,7 @@ function () use ( $hook ): void { ); } - // Default loader: its own (self) base is the parent (template) theme. + // The default loader's own base is the parent theme. $this->loader = new TestComponentLoader( $this->theme_asset_loader() ); $this->loader->clear_cache(); } @@ -127,9 +120,6 @@ public function test_renders_component_with_arguments(): void { } public function test_render_hooks_are_isolated_per_loader_context(): void { - // The point of namespacing the hooks is that one package's listeners do not - // fire for another's loader. Asserting only the default `wp-primitives` - // names would pass even if the context were ignored entirely. $this->write_parent_component( 'alert', 'write_parent_component( 'alert', 'theme_asset_loader() ); $other->clear_cache(); @@ -298,7 +287,6 @@ public function test_child_theme_overrides_a_parent_component_asset(): void { } public function test_resolves_asset_when_no_child_theme_is_active(): void { - // No child theme: stylesheet directory equals template directory. $this->use_single_theme(); $this->write_parent_component( 'alert', 'temp_dir . '/plugin'; $loader = new TestComponentLoader( $this->plugin_asset_loader( $plugin_dir ) ); - // PHP + its own style ship in the plugin; the style is overridden in the parent theme. + // The plugin ships the component and its style. The parent theme overrides the style. $this->write_plugin_component( $plugin_dir, 'alert', 'write_plugin_asset( $plugin_dir, 'css/components/alert.css', '.plugin{}' ); $this->write_parent_asset( 'css/components/alert.css', '.parent{}' ); @@ -331,13 +319,12 @@ public function test_allow_override_false_resolves_from_the_package_only(): void $plugin_dir = $this->temp_dir . '/plugin'; $loader = new TestComponentLoader( $this->plugin_asset_loader( $plugin_dir ) ); - // Component PHP + style in the plugin, and overridden in the parent theme. + // The plugin ships the component and its style. The parent theme overrides both. $this->write_plugin_component( $plugin_dir, 'alert', 'write_plugin_asset( $plugin_dir, 'css/components/alert.css', '.plugin{}' ); $this->write_parent_component( 'alert', 'write_parent_asset( 'css/components/alert.css', '.theme{}' ); - // allow_override = false → resolve PHP + assets from the plugin (self) only. $html = $loader->get( 'alert', [], @@ -358,7 +345,7 @@ public function test_each_asset_type_resolves_independently_across_the_hierarchy $plugin_dir = $this->temp_dir . '/plugin'; $loader = new TestComponentLoader( $this->plugin_asset_loader( $plugin_dir ) ); - // PHP + both assets in the plugin; CSS overridden in parent, JS in child. + // The plugin ships both assets. The parent theme overrides the CSS and the child theme overrides the JS. $this->write_plugin_component( $plugin_dir, 'alert', 'write_plugin_asset( $plugin_dir, 'css/components/alert.css', '.plugin{}' ); $this->write_plugin_asset( $plugin_dir, 'js/components/alert.js', 'plugin' ); @@ -461,7 +448,7 @@ public function test_render_without_an_asset_loader_throws(): void { $this->expectException( \RuntimeException::class ); - // No loader injected and get_asset_loader() not overridden. + // No asset loader is injected and get_asset_loader() is not overridden. ( new ComponentLoader() )->get( 'alert' ); } @@ -489,8 +476,6 @@ public function test_component_without_asset_files_registers_nothing(): void { } public function test_clear_cache_resets_the_memoised_asset_loader_hierarchy(): void { - // Resolving a component memoises the child -> parent -> package loader - // list; clear_cache() must drop it so a later theme change is picked up. $this->write_parent_component( 'alert', 'loader->get( 'alert', diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarLegacyCoreTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarLegacyCoreTest.php index caf55a3..0712cc0 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarLegacyCoreTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarLegacyCoreTest.php @@ -2,11 +2,6 @@ /** * AbstractAbilityRegistrar tests for cores without the Abilities API. * - * The registrar promises to be inert on WordPress older than 6.9: its hooks - * never fire there, and calling its callbacks directly must still be a silent - * no-op rather than a fatal "call to undefined function". These tests only run - * on such cores (the 6.5 to 6.8 cells of the CI matrix) and are skipped on 6.9+. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ @@ -30,13 +25,13 @@ protected function setUp(): void { } /** - * A registrar that records every seam the callbacks touch. + * Build a registrar that records each overridable method it calls. */ private function make_recording_registrar(): AbstractAbilityRegistrar { return new class() extends AbstractAbilityRegistrar { /** - * Seams that were called, in order. + * Names of the methods called, in order. * * @var array */ @@ -68,7 +63,7 @@ public function test_register_category_is_a_no_op_without_the_abilities_api(): v $registrar->register_category(); - $this->assertSame( [], $registrar->calls, 'no seam may run when the API is missing' ); + $this->assertSame( [], $registrar->calls, 'no method may run when the API is missing' ); } public function test_register_abilities_is_a_no_op_without_the_abilities_api(): void { @@ -86,6 +81,6 @@ public function test_hooks_are_still_added_so_a_later_core_upgrade_picks_them_up $this->assertSame( 10, has_action( 'wp_abilities_api_categories_init', [ $registrar, 'register_category' ] ) ); $this->assertSame( 10, has_action( 'wp_abilities_api_init', [ $registrar, 'register_abilities' ] ) ); - $this->assertSame( [], $registrar->calls, 'adding the hooks must not touch any seam' ); + $this->assertSame( [], $registrar->calls, 'adding the hooks must not call any method' ); } } diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarTest.php index 7e4213a..0add553 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityRegistrarTest.php @@ -2,15 +2,6 @@ /** * AbstractAbilityRegistrar tests. * - * These exercise the real Abilities API (WordPress 6.9+): the registrar's - * hooks fire through core's lazy registry initialization, then abilities are - * read back with wp_get_ability(). On older cores every test is skipped. - * Both core registries are singletons, so they are reset via reflection - * around every test (the suite runs in random order). The hooks each - * registrar adds need no such cleanup — WP_UnitTestCase::tear_down() restores - * $wp_filter wholesale after every test. Tests use anonymous classes - * throughout so each scenario is self-contained. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ @@ -46,8 +37,7 @@ protected function tearDown(): void { } /** - * Null both core registry singletons so each test starts from a cold, - * uninitialized Abilities API. + * Set both core registry singletons to null so the next access initializes the Abilities API again. */ private function reset_abilities_registries(): void { foreach ( [ \WP_Abilities_Registry::class, \WP_Ability_Categories_Registry::class ] as $registry ) { @@ -62,8 +52,9 @@ private function reset_abilities_registries(): void { } /** - * Initialize the Abilities API exactly like production: the first registry - * access fires wp_abilities_api_categories_init, then wp_abilities_api_init. + * Initialize the Abilities API. + * + * The first registry access fires wp_abilities_api_categories_init, then wp_abilities_api_init. */ private function init_abilities_api(): void { \WP_Abilities_Registry::get_instance(); @@ -116,14 +107,14 @@ public function execute( mixed $input ): array|\WP_Error { } /** - * Concrete AbstractAbilityRegistrar with injectable seams. + * Build a concrete AbstractAbilityRegistrar. * - * The Abilities API rejects empty category descriptions, so the abstract - * category_description() always returns a real string here. + * The Abilities API rejects an empty category description, so + * $description defaults to a non-empty string. * * @param string $slug Category slug. * @param array $abilities Abilities to register. - * @param string $label Optional category_label() override. + * @param string $label Value for category_label(). Empty uses the parent default. * @param string $description Category description. */ private function make_registrar( @@ -213,8 +204,7 @@ public function test_category_registration_is_idempotent_across_registrars(): vo $this->init_abilities_api(); - // The first registrar wins; the second skips its wp_register_ability_category() - // call instead of triggering a duplicate-registration notice. + // The second registrar skips wp_register_ability_category(), which would otherwise raise a duplicate-registration notice. $category = wp_get_ability_category( 'test-plugin' ); $this->assertInstanceOf( \WP_Ability_Category::class, $category ); diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityTest.php index 8c21f25..cce1197 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAbilityTest.php @@ -2,11 +2,6 @@ /** * AbstractAbility tests. * - * AbstractAbility is pure argument-mapping: it never calls the Abilities API - * itself, so these tests run on every supported WordPress version. The - * registration round-trip lives in AbstractAbilityRegistrarTest. Tests use - * anonymous classes throughout so each scenario is self-contained. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ @@ -24,14 +19,14 @@ */ final class AbstractAbilityTest extends TestCase { /** - * Concrete AbstractAbility with every seam injectable. + * Build a concrete AbstractAbility. * * @param string $name Ability name. * @param string $category Category slug. * @param array $input_schema Input schema. * @param array $output_schema Output schema. - * @param array $meta Meta override. - * @param \Closure|null $permission Optional permission() override. + * @param array $meta Value for meta(). + * @param \Closure|null $permission Replaces permission() when set. */ private function make_ability( string $name = 'test-plugin/do-thing', @@ -106,8 +101,7 @@ public function test_args_maps_label_description_category_and_callbacks(): void } public function test_callbacks_are_safe_to_invoke_without_arguments(): void { - // Core invokes both callbacks with zero arguments when the ability - // declares no input schema; the closure wrappers absorb that. + // Core calls both callbacks with no arguments when the ability has no input schema. $args = $this->make_ability()->args(); $this->assertSame( [ 'received' => null ], $args['execute_callback']() ); diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAdminPageTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAdminPageTest.php index 2b37d7f..7f2d68f 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractAdminPageTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractAdminPageTest.php @@ -2,11 +2,6 @@ /** * AbstractAdminPage tests. * - * Integration tests against real WordPress (wp-env): asserts top-level and - * submenu pages are registered with WordPress' admin-menu globals. add_menu_page() - * lives in wp-admin/includes/plugin.php and checks the current user's capability, - * so both are set up here. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractBlockTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractBlockTest.php index bb19f7e..10e58b1 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractBlockTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractBlockTest.php @@ -2,10 +2,6 @@ /** * AbstractBlock tests. * - * Integration tests against real WordPress (wp-env): asserts the block is - * registered with WP_Block_Type_Registry and wired to the instance's render - * callback. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ @@ -72,10 +68,7 @@ public function test_render_returns_markup(): void { } public function test_block_dir_without_block_json_falls_back_to_the_block_name(): void { - // Regression: an unbuilt block directory used to reach register_block_type() - // as a "block name", so WordPress rejected it with a namespace-prefix - // notice and nothing was registered. WP_UnitTestCase fails the test on any - // unexpected _doing_it_wrong(), so the absence of a notice is asserted too. + // WP_UnitTestCase fails the test on any unexpected _doing_it_wrong(), so this also checks that no notice fires. $dir = sys_get_temp_dir() . '/wpf-unbuilt-' . str_replace( '.', '', uniqid( '', true ) ); mkdir( $dir, 0777, true ); diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractFeatureTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractFeatureTest.php index 8064c49..1b77cac 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractFeatureTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractFeatureTest.php @@ -2,10 +2,6 @@ /** * AbstractFeature tests. * - * AbstractFeature is a framework contract: the concrete FeatureSelector and - * the abstract get_slug() / get_feature_registry() are the moving parts. - * Tests use anonymous classes throughout so each scenario is self-contained. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ @@ -25,15 +21,15 @@ */ final class AbstractFeatureTest extends TestCase { /** - * Concrete AbstractFeature backed by a local FeatureSelector. + * Build a concrete AbstractFeature that registers into $registry. * - * Constructor promotion assigns $registry before parent::__construct() runs, - * so get_feature_registry() is safe to call from the parent constructor. + * PHP assigns promoted properties before parent::__construct() runs, so the + * parent constructor can call get_feature_registry(). * - * @param FeatureSelector $registry Selector instance to register into. + * @param FeatureSelector $registry Selector to register into. * @param string $slug Flag slug. - * @param string $name Optional override for get_name(). - * @param string $description Optional override for get_description(). + * @param string $name Value for get_name(). Empty uses the parent default. + * @param string $description Value for get_description(). Empty uses the parent default. */ private function make_feature( FeatureSelector $registry, diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractModuleTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractModuleTest.php index de14445..6585733 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractModuleTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractModuleTest.php @@ -2,10 +2,6 @@ /** * AbstractModule tests. * - * The module is an orchestrator: it has no WordPress registration of its own, - * it delegates to the Registrable classes from get_classes() via the Loader - * trait. Verified with the shared Loader fixtures. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractPostTypeTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractPostTypeTest.php index b142d3b..24762a8 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractPostTypeTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractPostTypeTest.php @@ -2,10 +2,6 @@ /** * AbstractPostType tests. * - * Asserts the option-building contract (defaults, label assembly, the - * get_custom_options() override merge) and the real WordPress registration: - * register() actually registers the post type and associates its taxonomies. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractRESTControllerTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractRESTControllerTest.php index c8e3d30..82d4698 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractRESTControllerTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractRESTControllerTest.php @@ -2,10 +2,6 @@ /** * AbstractRESTController tests. * - * Integration tests against real WordPress (wp-env): asserts routes register - * on rest_api_init, the endpoint dispatches, and the base register_routes() - * throws to force subclass implementation. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractSettingsPageTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractSettingsPageTest.php index f81e0d0..3748272 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractSettingsPageTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractSettingsPageTest.php @@ -2,11 +2,6 @@ /** * AbstractSettingsPage tests. * - * Integration tests against real WordPress (wp-env): asserts the three hooks - * are wired, settings register with the Settings API, the page is added as a - * submenu under its parent, and the get_menu_slug() seam redirects the slug - * registered with the admin menu. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ @@ -85,9 +80,8 @@ public function test_register_settings_registers_the_setting(): void { } public function test_register_hooks_aligns_the_save_capability_with_get_capability(): void { - // options.php gates the save on option_page_capability_{group}, which - // defaults to manage_options. A page that lowers get_capability() would - // otherwise render for a user who then silently fails to save. + // options.php checks option_page_capability_{group}, which defaults to + // manage_options, before saving. $page = new class() extends AbstractSettingsPage { public static function get_slug(): string { return 'wpf-test-settings'; @@ -123,7 +117,6 @@ public function render(): void {} public function test_save_capability_filter_is_scoped_to_this_pages_option_group(): void { $this->settings_page()->register_hooks(); - // Another plugin's option group must be left untouched. $this->assertSame( 'manage_options', apply_filters( 'option_page_capability_some_other_group', 'manage_options' ) @@ -164,7 +157,6 @@ public function render(): void {} $page->register_page(); - // get_menu_slug() overrides the static get_slug() as the admin-menu slug. $slugs = wp_list_pluck( $GLOBALS['submenu']['options-general.php'] ?? [], 2 ); $this->assertContains( 'wpf-test-overridden-slug', $slugs ); $this->assertNotContains( self::SLUG, $slugs ); diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractShortcodeTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractShortcodeTest.php index d69db87..ed8aa34 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractShortcodeTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractShortcodeTest.php @@ -2,10 +2,6 @@ /** * AbstractShortcode tests. * - * Integration tests against real WordPress (wp-env): asserts the tag is - * registered and that do_shortcode() renders through the callback with the - * default attributes merged. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractTaxonomyTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractTaxonomyTest.php index 00ce470..dfd9221 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractTaxonomyTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractTaxonomyTest.php @@ -91,8 +91,6 @@ protected function get_custom_options(): array { } public function test_static_get_slug_and_object_types_are_accessible_without_instance(): void { - // One of the reasons we kept get_slug() static — code that wires the - // taxonomy into other systems shouldn't need to instantiate it first. $tax = $this->basic_taxonomy(); $this->assertSame( 'genre', $tax::get_slug() ); diff --git a/tests/phpunit/Integration/Contracts/Abstracts/AbstractUserRoleTest.php b/tests/phpunit/Integration/Contracts/Abstracts/AbstractUserRoleTest.php index b2fae75..2a31f36 100644 --- a/tests/phpunit/Integration/Contracts/Abstracts/AbstractUserRoleTest.php +++ b/tests/phpunit/Integration/Contracts/Abstracts/AbstractUserRoleTest.php @@ -2,10 +2,6 @@ /** * AbstractUserRole tests. * - * Integration tests against real WordPress (wp-env): asserts the versioned - * role registration — capabilities applied, version stored, gating on the - * stored version, and full removal. - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Abstracts */ diff --git a/tests/phpunit/Integration/Contracts/Interfaces/InterfaceContractsTest.php b/tests/phpunit/Integration/Contracts/Interfaces/InterfaceContractsTest.php index ceb83b8..73db342 100644 --- a/tests/phpunit/Integration/Contracts/Interfaces/InterfaceContractsTest.php +++ b/tests/phpunit/Integration/Contracts/Interfaces/InterfaceContractsTest.php @@ -2,10 +2,6 @@ /** * Interface contract smoke tests. * - * Reflection-based checks that the interface signatures haven't been - * accidentally changed by a refactor. These are cheap and catch the - * most common breakage (renames, missing methods, inheritance changes). - * * @package rtCamp\WPPrimitives\Tests\Integration\Contracts\Interfaces */ diff --git a/tests/phpunit/Integration/LoaderTest.php b/tests/phpunit/Integration/LoaderTest.php index 8930c22..bd1832e 100644 --- a/tests/phpunit/Integration/LoaderTest.php +++ b/tests/phpunit/Integration/LoaderTest.php @@ -2,13 +2,6 @@ /** * Loader trait tests. * - * Verifies the load() contract: - * - Plain Registrable → register_hooks() called - * - ConditionallyRegistrable + can_register()=true → register_hooks() called - * - ConditionallyRegistrable + can_register()=false → register_hooks() skipped - * - Shareable → instance cached, retrievable via get_shared() - * - A class that is both Shareable and Registrable gets both treatments - * * @package rtCamp\WPPrimitives\Tests\Integration */ @@ -53,9 +46,6 @@ public function test_conditional_registrable_is_skipped_when_can_register_is_fal } public function test_a_class_listed_twice_is_loaded_once(): void { - // Without de-duplication the class is constructed twice and registers its - // hooks on two separate instances, so the hook body runs twice while the - // container keeps only the last instance. $loader = new LoaderRunner(); $loader->run( [ CountingRegistrable::class, CountingRegistrable::class ] ); @@ -64,8 +54,6 @@ public function test_a_class_listed_twice_is_loaded_once(): void { } public function test_the_shared_instance_is_the_one_that_registered_hooks(): void { - // The de-duplication must keep a single instance, not quietly replace the - // registered one with a second construction. $loader = new LoaderRunner(); $loader->run( [ CountingRegistrable::class, CountingRegistrable::class ] ); diff --git a/tests/phpunit/Integration/SingletonTest.php b/tests/phpunit/Integration/SingletonTest.php index 84c2ae4..4c2b397 100644 --- a/tests/phpunit/Integration/SingletonTest.php +++ b/tests/phpunit/Integration/SingletonTest.php @@ -30,9 +30,6 @@ public function test_get_instance_returns_concrete_class(): void { } public function test_constructor_runs_only_once_regardless_of_call_count(): void { - // Multiple calls to get_instance() must never construct more than once. - // Order-independent: tests run in random order, but the count is - // bounded at 1 for the lifetime of the process. SingletonExample::get_instance(); SingletonExample::get_instance(); SingletonExample::get_instance(); @@ -58,20 +55,12 @@ public function test_default_constructor_is_used_when_not_overridden(): void { $this->assertInstanceOf( BareSingleton::class, BareSingleton::get_instance() ); } - public function test_the_documented_early_assignment_guard_supports_reentrant_construction(): void { - // Regression: the trait documents that a heavy constructor should assign - // `static::$instance = $this;` first, so work done during construction (a - // Main running a Loader) can call get_instance() re-entrantly and receive - // the same object. This pins that contract — the property must stay - // protected and assignable, and the guard must short-circuit a second - // construction. Changing the storage broke a real consumer once already. + public function test_early_assignment_guard_supports_reentrant_construction(): void { $instance = ReentrantSingleton::get_instance(); $this->assertSame( 1, ReentrantSingleton::$construct_count ); $this->assertSame( $instance, ReentrantSingleton::$seen_during_construction ); - // The re-entrant caller saw the constructor's progress on this object, - // not a fresh copy with default property values. $this->assertSame( 'yes', ReentrantSingleton::$seen_during_construction->ready ); } @@ -85,9 +74,6 @@ public function test_a_throwing_constructor_is_not_left_published(): void { $this->assertSame( 'construction failed', $e->getMessage() ); } - // Nothing is stored until the constructor returns, so the failed attempt - // cached nothing: once construction can succeed, get_instance() builds a - // fresh, working instance. FlakySingleton::$fail = false; $this->assertInstanceOf( FlakySingleton::class, FlakySingleton::get_instance() ); diff --git a/tests/phpunit/Integration/TemplateLoaderTest.php b/tests/phpunit/Integration/TemplateLoaderTest.php index 87eba86..0e8d2ed 100644 --- a/tests/phpunit/Integration/TemplateLoaderTest.php +++ b/tests/phpunit/Integration/TemplateLoaderTest.php @@ -2,11 +2,6 @@ /** * Tests for the TemplateLoader class. * - * Runs against a real WordPress instance (wp-env): the theme hierarchy is - * pointed at fixture directories via the template_directory/stylesheet_directory - * filters (TestCase::set_theme_dirs), and rendering is asserted through real - * load_template() output rather than a stub call log. - * * @package rtCamp\WPPrimitives\Tests\Integration */ @@ -136,8 +131,7 @@ public function test_child_theme_overrides_parent(): void { } public function test_theme_package_layer_is_deduplicated(): void { - // Theme consumer: its own templates ARE the parent-theme override path, - // so the package layer must collapse rather than be searched twice. + // A theme's package directory is also its parent theme override path. $this->use_single_theme(); $theme_loader = new TemplateLoader( 'thm', $this->tmp . '/parent/templates', 'templates' ); @@ -148,7 +142,6 @@ public function test_theme_package_layer_is_deduplicated(): void { } public function test_theme_child_overrides_the_theme_package(): void { - // Theme ships card.php; a child theme overrides it. Same loader, no plugin layer. $this->use_child_theme(); $theme_loader = new TemplateLoader( 'thm', $this->tmp . '/parent/templates', 'templates' ); @@ -167,8 +160,6 @@ public function test_theme_child_overrides_the_theme_package(): void { } public function test_child_theme_package_has_no_parent_fallback(): void { - // A loader owned by the child theme: nothing sits above it, so the parent - // theme is NOT searched as a fallback (mirrors ComponentLoader). $this->use_child_theme(); $child_loader = new TemplateLoader( 'ct', $this->tmp . '/child/templates', 'templates' ); @@ -189,8 +180,7 @@ public function test_name_variant_is_preferred_over_base_slug(): void { } public function test_name_variant_wins_across_layers_over_base_slug(): void { - // WP locate_template precedence: a more specific name dominates location. - // The parent's card-featured.php must beat the child's card.php. + // As in locate_template(), a name variant in any layer beats the base slug in a higher layer. $this->use_child_theme(); $this->write( $this->tmp . '/child/my-plugin/card.php' ); $this->write( $this->tmp . '/parent/my-plugin/card-featured.php' ); @@ -218,8 +208,6 @@ public function test_locate_returns_false_when_not_found(): void { } public function test_get_rethrows_and_balances_the_buffer_when_a_template_throws(): void { - // get() must clear its own output buffer and re-throw rather than leave a - // half-rendered buffer open for the caller to inherit. $this->use_single_theme(); $this->write( $this->tmp . '/plugin/templates/boom.php', 'use_single_theme(); $this->write( $this->tmp . '/parent/my-plugin/card.php' ); $this->write( $this->tmp . '/child/my-plugin/card.php' ); @@ -346,8 +331,6 @@ public function test_a_theme_switch_is_not_served_from_the_previous_themes_cache } public function test_switching_back_reuses_the_original_themes_entry(): void { - // The key is per-path-set rather than a blanket invalidation, so switching - // back must return the first theme's result again. $this->use_single_theme(); $this->write( $this->tmp . '/parent/my-plugin/card.php' ); $this->write( $this->tmp . '/child/my-plugin/card.php' ); @@ -367,7 +350,6 @@ public function test_switching_back_reuses_the_original_themes_entry(): void { public function test_locate_returns_false_when_no_candidate_names(): void { $this->use_single_theme(); - // A filter that empties the candidate list short-circuits to false. add_filter( 'my_plugin/template_file_names', static fn (): array => [] ); $this->assertFalse( $this->loader()->locate( 'card' ) ); diff --git a/tests/phpunit/Integration/Utils/CacheTest.php b/tests/phpunit/Integration/Utils/CacheTest.php index d25be5d..58c3cac 100644 --- a/tests/phpunit/Integration/Utils/CacheTest.php +++ b/tests/phpunit/Integration/Utils/CacheTest.php @@ -14,11 +14,6 @@ /** * Tests for Cache. - * - * Runs against real WordPress (wp-env). With no persistent object cache - * configured, wp_cache_* is backed by the in-process non-persistent cache; it is - * flushed in set_up so no entry leaks between tests under random execution order. - * Each test also uses a distinct context/group so namespaced keys never collide. */ final class CacheTest extends TestCase { /** @@ -105,7 +100,7 @@ static function (): string { $this->assertFalse( wp_cache_get( 'k_lock', 'ctx-swr-throw:g' ), - 'A throwing callback must still release the lock (finally), not strand it for LOCK_TTL.' + 'A throwing callback must still release the lock.' ); } @@ -131,7 +126,7 @@ public function test_remember_swr_returns_stale_without_regenerating_when_lock_i $returned = $cache->remember_swr( 'k', static fn (): string => 'new', 'g', 100 ); $this->assertSame( 'old', $returned, 'a losing caller is served stale immediately' ); - $this->assertFalse( wp_cache_get( 'k', 'ctx-swr-locked:g' ), 'the loser must not regenerate — that is the stampede prevention' ); + $this->assertFalse( wp_cache_get( 'k', 'ctx-swr-locked:g' ), 'the loser must not regenerate' ); } public function test_empty_context_passes_groups_through_verbatim(): void { @@ -151,7 +146,7 @@ public function test_flush_group_clears_only_the_namespaced_group(): void { $cache->set( 'b', 2, 'g' ); $cache->set( 'c', 3, 'other' ); - // Core's non-persistent cache supports group flushing (WordPress 6.1+). + // Core's non-persistent cache supports flush_group since WordPress 6.1. $this->assertTrue( wp_cache_supports( 'flush_group' ), 'precondition: core cache supports flush_group' ); $this->assertTrue( $cache->flush_group( 'g' ) ); @@ -184,7 +179,6 @@ static function () use ( &$calls ): string { public function test_remember_swr_cold_start_falls_back_to_the_callback_when_the_lock_never_frees(): void { $cache = new Cache( 'ctx-swr-wait' ); - // Another process holds the lock on a cold start (no fresh, no stale) and never finishes: after the bounded wait the caller regenerates itself. //phpcs:ignore WordPressVIPMinimum.Performance.LowExpiryCacheTime.LowCacheTime $this->assertTrue( wp_cache_add( 'k_lock', 1, 'ctx-swr-wait:g', 30 ), 'precondition: hold the lock' ); @@ -206,8 +200,7 @@ static function () use ( &$calls ): string { } public function test_remember_swr_cold_start_waits_for_the_lock_holder_to_publish(): void { - // Simulate the lock holder finishing during our wait: the second read of - // the fresh key (the first retry) finds the value it published. + // The lock holder publishes the value before the second read of the fresh key, which is the first retry. $cache = new class( 'ctx-swr-publish' ) extends Cache { /** diff --git a/tests/phpunit/Integration/Utils/EncryptorTest.php b/tests/phpunit/Integration/Utils/EncryptorTest.php index 8cd68d7..b1b79f8 100644 --- a/tests/phpunit/Integration/Utils/EncryptorTest.php +++ b/tests/phpunit/Integration/Utils/EncryptorTest.php @@ -2,7 +2,7 @@ /** * Encryptor tests. * - * @package rtCamp\WPPrimitives\Tests\Integration + * @package rtCamp\WPPrimitives\Tests\Integration\Utils */ declare( strict_types = 1 ); @@ -27,11 +27,9 @@ private function encryptor( string $key = self::KEY ): Encryptor { } /** - * The key OpenSSL actually receives, so tests can assert on the derivation - * directly rather than inferring it from roundtrip behaviour. + * Return the key passed to OpenSSL. * - * The cipher_key() method is deliberately private — it must not be part of the override - * seam — so reach it by reflection rather than widening the API for tests. + * Encryptor::cipher_key() is private, so this calls it by reflection. * * @param Encryptor $encryptor Instance to derive for. */ @@ -51,8 +49,7 @@ public function test_encrypt_decrypt_roundtrips_plaintext(): void { } public function test_each_encryption_produces_different_ciphertext(): void { - // GCM uses a random IV per call, so the same plaintext must never - // produce identical ciphertext — that's a hard correctness invariant. + // GCM uses a random IV per call. $encryptor = $this->encryptor(); $a = $encryptor->encrypt( 'hello world' ); @@ -91,10 +88,6 @@ public function test_decrypt_returns_false_for_tampered_ciphertext(): void { } public function test_decrypt_rejects_a_truncated_tag_for_every_tag_value(): void { - // Regression: a payload holding only the IV plus a 1-byte "tag" left the - // ciphertext empty, and OpenSSL authenticates a truncated GCM tag at its - // truncated length, so 1 of these 256 forgeries decrypted to ''. Every - // candidate must be rejected now, not just most of them. $encryptor = $this->encryptor(); $iv = str_repeat( "\x01", 12 ); @@ -127,8 +120,7 @@ public function data_short_payload_lengths(): array { } public function test_empty_plaintext_roundtrips(): void { - // The smallest legitimate payload is IV + full tag with no ciphertext; - // the length guard must still let it through. + // The smallest valid payload is the IV plus a full tag, with no ciphertext. $encryptor = $this->encryptor(); $encrypted = $encryptor->encrypt( '' ); @@ -165,9 +157,7 @@ public function test_decrypt_fails_closed_without_openssl(): void { $this->assertFalse( $encryptor->decrypt( $encrypted ) ); } - public function test_key_seam_can_be_overridden_by_a_subclass(): void { - // A subclass can source the key from anywhere via the key() seam, while - // reusing the crypto unchanged. + public function test_key_can_be_overridden_by_a_subclass(): void { $encryptor = new class() extends Encryptor { protected function key(): string { return str_repeat( 'z', 32 ); @@ -186,8 +176,6 @@ public function test_missing_key_throws(): void { } public function test_non_gcm_cipher_is_rejected(): void { - // The payload layout (IV + tag + ciphertext) is GCM-specific, so a - // non-AEAD cipher must be rejected at construction. $this->expectException( \InvalidArgumentException::class ); new Encryptor( self::KEY, 'aes-256-cbc' ); @@ -207,8 +195,7 @@ public function test_alternate_gcm_cipher_roundtrips(): void { * @param string $secret Secret of a length other than the cipher key length. */ public function test_any_length_secret_derives_a_full_cipher_length_key( string $secret ): void { - // OpenSSL would NUL-pad a short secret and truncate a long one; the - // derivation must instead map any length to the full key length. + // OpenSSL NUL-pads a short key and truncates a long one, so the secret is hashed to the cipher key length first. $this->assertSame( 32, strlen( $this->derived_key( new Encryptor( $secret ) ) ) ); $encryptor = $this->encryptor( $secret ); @@ -236,9 +223,7 @@ public function test_derived_key_length_follows_the_cipher(): void { } public function test_secrets_differing_only_past_the_key_length_are_not_equivalent(): void { - // Regression: OpenSSL truncates an over-long key, so rotating only the - // tail of a long secret used to be a silent no-op. Hashing must make the - // whole secret significant. + // OpenSSL truncates an over-long key, so without hashing only the first 32 bytes of the secret would count. $shared = str_repeat( 'k', 32 ); $first = $shared . 'tail-one'; $second = $shared . 'tail-two'; @@ -254,10 +239,6 @@ public function test_secrets_differing_only_past_the_key_length_are_not_equivale } public function test_subclass_key_override_still_goes_through_the_derivation(): void { - // Regression: the derivation used to live inside key(), the documented - // override seam, so a subclass sourcing its secret from a KMS or env var - // bypassed it and handed OpenSSL a raw wrong-length key. The seam now - // returns a raw secret and the derivation sits behind it. $override = new class() extends Encryptor { protected function key(): string { return 'short'; @@ -266,8 +247,7 @@ protected function key(): string { $this->assertSame( 32, strlen( $this->derived_key( $override ) ) ); - // Same secret via either route must derive the same key, so ciphertext - // from one decrypts with the other. + // The same secret derives the same key from key() or the constructor. $encrypted = $override->encrypt( 'via override' ); $this->assertIsString( $encrypted ); $this->assertSame( 'via override', $this->encryptor( 'short' )->decrypt( $encrypted ) ); @@ -285,15 +265,13 @@ protected function key(): string { $encrypted = $first->encrypt( 'override rotation' ); $this->assertIsString( $encrypted ); - // Rotating only the tail of an over-long secret must actually change the - // key even when the secret arrives through the override seam. + // Rotating only the tail of an over-long secret must actually change the key. $this->assertFalse( $this->encryptor( $shared . 'tail-two' )->decrypt( $encrypted ) ); $this->assertSame( 'override rotation', $this->encryptor( $shared . 'tail-one' )->decrypt( $encrypted ) ); } public function test_short_secret_is_not_equivalent_to_its_nul_padded_form(): void { - // Regression: OpenSSL NUL-pads a short key, which made 'secret' and - // 'secret' + NULs the same key and quietly weakened the cipher. + // OpenSSL NUL-pads a short key, so without hashing 'secret' and its NUL-padded form would be the same key. $secret = 'secret'; $padded = $secret . str_repeat( "\0", 32 - strlen( $secret ) ); diff --git a/tests/phpunit/Integration/Utils/FeatureSelectorSettingsPageTest.php b/tests/phpunit/Integration/Utils/FeatureSelectorSettingsPageTest.php index 903af20..e387224 100644 --- a/tests/phpunit/Integration/Utils/FeatureSelectorSettingsPageTest.php +++ b/tests/phpunit/Integration/Utils/FeatureSelectorSettingsPageTest.php @@ -2,7 +2,7 @@ /** * FeatureSelectorSettingsPage utility tests. * - * @package rtCamp\WPPrimitives\Tests\Integration + * @package rtCamp\WPPrimitives\Tests\Integration\Utils */ declare( strict_types = 1 ); @@ -15,10 +15,6 @@ /** * Tests for FeatureSelectorSettingsPage. - * - * Integration tests against real WordPress (wp-env): hooks, the registered - * setting, the admin submenu, and settings sections/fields are read back from - * WordPress' own registries rather than stubs. */ final class FeatureSelectorSettingsPageTest extends TestCase { @@ -51,9 +47,7 @@ public function set_up(): void { } public function tear_down(): void { - // Several tests simulate an options.php form save by setting this - // superglobal. Clear it here so a failing assertion mid-test cannot - // leak the form-save context into whichever test runs next. + // Several tests set this to simulate an options.php form save. unset( $_POST['option_page'] ); parent::tear_down(); @@ -62,8 +56,7 @@ public function tear_down(): void { /** * Instantiate a concrete FeatureSelectorSettingsPage backed by $selector. * - * FeatureSelectorSettingsPage is abstract (get_selector() must be provided by - * the consumer), so tests use an anonymous class to supply the implementation. + * The anonymous class implements the abstract get_selector(). * * @param FeatureSelector $selector Selector to back the page. */ @@ -115,8 +108,7 @@ public function test_register_hooks_keeps_field_registration_off_rest_api_init() $this->assertNotFalse( has_action( 'admin_init', [ $this->page, 'register_settings' ] ) ); $this->assertNotFalse( has_action( 'rest_api_init', [ $this->page, 'register_settings' ] ) ); - // add_settings_section/field are undefined during REST requests — - // register_fields must be wired to admin_init only. + // add_settings_section() and add_settings_field() are undefined during REST requests. $this->assertNotFalse( has_action( 'admin_init', [ $this->page, 'register_fields' ] ) ); $this->assertFalse( has_action( 'rest_api_init', [ $this->page, 'register_fields' ] ) ); } @@ -161,17 +153,15 @@ public function test_register_settings_registers_a_single_array_setting(): void $registered = get_registered_settings(); - // All flags share one option: the page registers exactly one setting and - // no per-flag settings. + // All flags share one option. $this->assertArrayHasKey( 'my_plugin_features', $registered ); $this->assertArrayNotHasKey( 'my_plugin_feature_dark_mode', $registered ); $this->assertSame( 'array', $registered['my_plugin_features']['type'] ); $this->assertSame( [], $registered['my_plugin_features']['default'] ); - // On a genuine options.php form save the sanitize callback rebuilds the - // stored array: a checked flag becomes true, an unchecked (absent) flag - // becomes false. Simulate that form-save context. + // On an options.php form save, sanitize_settings() stores a checked flag as + // true and an absent flag as false. $_POST['option_page'] = 'my_plugin_features'; $this->assertSame( @@ -195,16 +185,14 @@ public function test_saving_preserves_a_locked_flags_stored_value_and_still_rend $this->page->register_fields(); - // Saving the page (nothing submitted) rebuilds the stored array: the free - // flag follows the empty form and turns off, but the locked flag carries - // no field, so its stored value is preserved rather than reset to false. + // An empty form save turns the free flag off and keeps the stored value of the flag locked by a constant. $_POST['option_page'] = 'my_plugin_features'; $sanitized = $this->page->sanitize_settings( [] ); $this->assertTrue( $sanitized['reg-locked'] ); $this->assertFalse( $sanitized['free-flag'] ); - // It still renders as a (disabled) field so the lock stays visible. + // The locked flag still renders, as a disabled field. $this->assertArrayHasKey( 'reg-locked', $GLOBALS['wp_settings_fields']['my-plugin-features']['my_plugin_features_section'] @@ -212,11 +200,6 @@ public function test_saving_preserves_a_locked_flags_stored_value_and_still_rend } public function test_programmatic_enable_after_register_settings_does_not_reset_other_flags(): void { - // Regression: sanitize_settings() is a sanitize_option_{key} filter that - // fires on EVERY write of the shared option. register_settings() installs - // it (as it would on any admin/REST request), then a programmatic enable() - // writes the option. That write must NOT route through the form rebuild and - // reset the other default-on, never-stored flags to false. $this->selector->register( [ 'feature-a', 'feature-b', 'feature-c' ] ); $this->page->register_settings(); @@ -228,9 +211,6 @@ public function test_programmatic_enable_after_register_settings_does_not_reset_ } public function test_flags_registered_after_hooks_still_appear(): void { - // Consumers register flags at plugins_loaded/init — after register_hooks() - // but before admin_init fires register_fields(). The field list must be - // read lazily at that point, not captured when the hooks were wired. $this->page->register_hooks(); $this->selector->register( [ 'late-flag' ] ); @@ -288,7 +268,7 @@ public function test_render_field_omits_description_paragraph_when_empty(): void public function test_render_field_prints_description_when_present(): void { $this->selector->register( [ 'dark-mode' => [ 'description' => 'Switch the UI to dark.' ] ] ); - $this->selector->disable( 'dark-mode' ); // Default is on; force off so "unchecked" is meaningful. + $this->selector->disable( 'dark-mode' ); // Flags default to on. $output = $this->render_field_output( 'dark-mode' ); @@ -306,7 +286,7 @@ public function test_render_field_locks_checkbox_when_constant_defined(): void { $output = $this->render_field_output( 'locked-flag' ); $this->assertStringContainsString( 'disabled', $output ); - $this->assertStringContainsString( 'checked', $output ); // Constant value is reflected. + $this->assertStringContainsString( 'checked', $output ); // The checkbox shows the constant's value. $this->assertStringContainsString( 'MY_PLUGIN_FEATURE_LOCKED_FLAG', $output ); } diff --git a/tests/phpunit/Integration/Utils/FeatureSelectorTest.php b/tests/phpunit/Integration/Utils/FeatureSelectorTest.php index 579ed7c..9b2aca4 100644 --- a/tests/phpunit/Integration/Utils/FeatureSelectorTest.php +++ b/tests/phpunit/Integration/Utils/FeatureSelectorTest.php @@ -2,7 +2,7 @@ /** * FeatureSelector utility tests. * - * @package rtCamp\WPPrimitives\Tests\Integration + * @package rtCamp\WPPrimitives\Tests\Integration\Utils */ declare( strict_types = 1 ); @@ -14,16 +14,6 @@ /** * Tests for FeatureSelector. - * - * Integration tests against real WordPress (wp-env): toggles persist through the - * options API and each test's writes are rolled back by WP_UnitTestCase. The - * loud `_doing_it_wrong()` paths are asserted with setExpectedIncorrectUsage(); - * a path that should stay silent simply omits it (an unexpected notice fails the - * test). - * - * Constants are process-global and immutable, so every constant-precedence test - * uses a flag slug unique to that test and a guarded define() to stay idempotent - * across re-runs in the same process. */ final class FeatureSelectorTest extends TestCase { /** @@ -124,7 +114,6 @@ public function test_register_keeps_first_registration_and_warns_on_duplicate(): $this->selector->register( [ 'my-flag' => [ 'name' => 'Original' ] ] ); $this->selector->register( [ 'my-flag' => [ 'name' => 'Updated' ] ] ); - // First write wins; the duplicate is ignored and flagged loudly. $this->assertSame( 'Original', $this->selector->get_features()['my-flag']['name'] ); } @@ -134,14 +123,11 @@ public function test_register_warns_on_slugs_that_normalize_to_the_same_key(): v $this->selector->register( [ 'beta-search' ] ); $this->selector->register( [ 'beta search' ] ); // Normalizes to the same key. - // First registration wins; the colliding slug is rejected and flagged. $this->assertSame( [ 'beta-search' ], $this->selector->get_registered() ); } public function test_register_skips_malformed_entries(): void { - // Malformed: int key with array value, string key with string value. - // No setExpectedIncorrectUsage(): skipping is silent, so an unexpected - // _doing_it_wrong() here would fail the test. + // An int key with an array value and a string key with a string value are both skipped without a _doing_it_wrong() notice. $this->selector->register( [ 0 => [ 'name' => 'Nameless' ], @@ -173,8 +159,6 @@ public function test_enable_and_disable_persist_to_option(): void { } public function test_enable_refuses_and_warns_for_an_unregistered_flag(): void { - // A typo'd toggle is a programming error: nothing is persisted, and the - // caller is flagged loudly rather than silently believing it took effect. $this->setExpectedIncorrectUsage( 'rtCamp\WPPrimitives\Utils\FeatureSelector::enable' ); $this->assertFalse( $this->selector->enable( 'drak-mode' ) ); @@ -191,11 +175,10 @@ public function test_disable_refuses_and_warns_for_an_unregistered_flag(): void public function test_disable_turns_off_a_never_stored_default_on_flag(): void { $this->selector->register( [ 'fresh-flag' ] ); - // Enabled by default, with no option ever written. + // Enabled by default, with no option written. $this->assertTrue( $this->selector->is_enabled( 'fresh-flag' ) ); $this->assertFalse( get_option( 'my_plugin_features', false ) ); - // disable() must persist `false` even though no row existed yet. $this->selector->disable( 'fresh-flag' ); $this->assertFalse( $this->selector->is_enabled( 'fresh-flag' ) ); @@ -208,8 +191,6 @@ public function test_all_flags_for_a_context_share_one_option_row(): void { $this->selector->enable( 'feature-a' ); $this->selector->disable( 'feature-b' ); - // All toggles live in one option (a single autoloaded row), not one - // option per flag. $this->assertSame( [ 'feature-a' => true, @@ -224,8 +205,6 @@ public function test_all_flags_for_a_context_share_one_option_row(): void { public function test_unregistered_flag_fails_closed(): void { $this->selector->register( [ 'dark-mode' ] ); - // A mistyped or never-registered slug returns false rather than inheriting - // the default-on, and the read stays silent (no _doing_it_wrong()). $this->assertFalse( $this->selector->is_enabled( 'drak-mode' ) ); $this->assertFalse( $this->selector->is_enabled( 'totally-unknown' ) ); } @@ -235,9 +214,7 @@ public function test_unregistered_flag_fails_closed_even_with_a_defined_constant define( 'MY_PLUGIN_FEATURE_PHANTOM', true ); } - // The registry is authoritative: a flag that was never registered stays - // off even if a matching override constant happens to be defined — the - // registry check runs before the constant lookup. + // The registry check runs before the constant lookup. $this->assertFalse( $this->selector->is_enabled( 'phantom' ) ); } @@ -248,7 +225,6 @@ public function test_true_constant_overrides_disabled_option(): void { $this->selector->register( [ 'forced-on' ] ); - // Even with the option explicitly set to false, the constant wins. $this->selector->disable( 'forced-on' ); $this->assertTrue( $this->selector->is_enabled( 'forced-on' ) ); @@ -273,8 +249,7 @@ public function test_string_false_constant_disables_the_flag(): void { $this->selector->register( [ 'string-off' ] ); - // A constant typed as the string 'false' (a common wp-config mistake) - // must disable the flag — a bare `(bool) 'false'` would be true. + // wp-config.php users often write 'false' as a string, and `(bool) 'false'` is true. $this->assertFalse( $this->selector->is_enabled( 'string-off' ) ); } @@ -287,10 +262,6 @@ public function test_key_derivation_is_symmetrical(): void { } public function test_slugs_with_repeated_dashes_get_distinct_constants(): void { - // Regression: the constant used to be derived via normalize(), which - // collapses runs of dashes, so these two slugs shared one constant and a - // single define() would lock both. flag_key() keeps them apart, and the - // constant must follow the same partition as storage. $this->assertNotSame( $this->selector->flag_key( 'beta-search' ), $this->selector->flag_key( 'beta--search' ) @@ -306,9 +277,6 @@ public function test_slugs_with_repeated_dashes_get_distinct_constants(): void { } public function test_constant_name_follows_the_same_partition_as_storage(): void { - // Two slugs that flag_key() maps to the same storage key must also map to - // the same constant — otherwise a flag could be locked under one spelling - // and read under another. $this->assertSame( $this->selector->flag_key( 'Dark Mode' ), $this->selector->flag_key( 'dark-mode' ) @@ -329,13 +297,12 @@ public function test_empty_context_uses_bare_feature_prefix(): void { } public function test_context_is_normalized(): void { - // Context normalization uses underscores for the option name. $this->assertSame( 'my_plugin_features', ( new FeatureSelector( 'My-Plugin' ) )->shared_option_key() ); - // Runs of spaces/dots and other invalid characters collapse to one underscore. + // Runs of spaces, dots and other invalid characters collapse to one underscore. $this->assertSame( 'my_plugin_v2_0_features', ( new FeatureSelector( 'My Plugin v2.0' ) )->shared_option_key() @@ -348,8 +315,6 @@ public function test_same_flag_in_different_contexts_does_not_collide(): void { $this->selector->register( [ 'shared-flag' ] ); $other->register( [ 'shared-flag' ] ); - // Same slug, opposite states: each context reads its own option key, - // so toggling one cannot affect the other. $this->selector->enable( 'shared-flag' ); $other->disable( 'shared-flag' ); diff --git a/tests/phpunit/Integration/Utils/LoggerTest.php b/tests/phpunit/Integration/Utils/LoggerTest.php index dd717bf..26c5fff 100644 --- a/tests/phpunit/Integration/Utils/LoggerTest.php +++ b/tests/phpunit/Integration/Utils/LoggerTest.php @@ -14,15 +14,6 @@ /** * Tests for Logger. - * - * Runs against real WordPress (wp-env), where WP_DEBUG is true — so the default logger - * writes, and wp_json_encode() is the real function rather than a stub. Output is - * captured by pointing PHP's error_log at a per-test temp file. The "silent in - * production" path is exercised through a subclass that overrides the is_enabled() seam - * to return false, since the WP_DEBUG constant cannot be toggled mid-request. - * - * Assertions match on the unique message each test logs rather than on an empty file, - * so unrelated error_log noise from the environment can't make a test flaky. */ final class LoggerTest extends TestCase { @@ -115,8 +106,6 @@ public function test_no_context_omits_the_json_segment(): void { } public function test_default_logger_is_enabled_under_wp_debug(): void { - // The wp-env test environment defines WP_DEBUG = true, so the default - // is_enabled() gate is open and the line is written. $this->assertTrue( defined( 'WP_DEBUG' ) && WP_DEBUG, 'wp-env should run tests with WP_DEBUG enabled.' ); ( new Logger( 'enabled' ) )->info( 'written-because-debug' ); @@ -125,8 +114,7 @@ public function test_default_logger_is_enabled_under_wp_debug(): void { } public function test_unencodable_context_is_dropped_without_trailing_space(): void { - // INF can't be JSON-encoded, so wp_json_encode() returns false. The message - // must still log, with the context dropped and no stray trailing space. + // wp_json_encode() returns false for INF. ( new Logger( 'p' ) )->error( 'enc-fail', [ 'x' => INF ] ); $contents = $this->captured(); diff --git a/tests/phpunit/Integration/Utils/TimerTest.php b/tests/phpunit/Integration/Utils/TimerTest.php index 6ca9075..962ffca 100644 --- a/tests/phpunit/Integration/Utils/TimerTest.php +++ b/tests/phpunit/Integration/Utils/TimerTest.php @@ -14,25 +14,17 @@ /** * Tests for Timer. - * - * Runs against real WordPress (wp-env) so `_doing_it_wrong()` routes through WP's real - * handler and the polyfilled setExpectedIncorrectUsage() picks misuse up without - * stubbing. Timer is instance-based, so each test gets a fresh instance — no process - * state leaks between tests (unlike the old singleton form). - * - * usleep() may sleep slightly longer than asked depending on scheduler load, so timing - * assertions only check `> 0.0` with `< 1.0` as a runaway guard — never an exact value. */ final class TimerTest extends TestCase { /** - * Fresh timer per test. + * Timer under test. * * @var Timer */ private Timer $timer; /** - * Build a fresh, isolated Timer for each test. + * Create a new Timer for each test. */ protected function setUp(): void { parent::setUp(); @@ -62,7 +54,7 @@ public function test_start_twice_warns_and_keeps_the_first_start(): void { $first = $this->timer->get( 'double_start' ); usleep( 5000 ); - $this->timer->start( 'double_start' ); // Warns; first start wins. + $this->timer->start( 'double_start' ); $second = $this->timer->get( 'double_start' ); $this->assertSame( $first['start'], $second['start'] ); @@ -89,7 +81,7 @@ public function test_stop_already_stopped_returns_cached_elapsed(): void { usleep( 5000 ); $this->setExpectedIncorrectUsage( Timer::class . '::stop' ); - $second = $this->timer->stop( 'stop_twice' ); // Warns; returns cached elapsed. + $second = $this->timer->stop( 'stop_twice' ); $this->assertSame( $first, $second ); } diff --git a/tests/phpunit/Integration/Utils/TransientsTest.php b/tests/phpunit/Integration/Utils/TransientsTest.php index cc59d15..2cc734e 100644 --- a/tests/phpunit/Integration/Utils/TransientsTest.php +++ b/tests/phpunit/Integration/Utils/TransientsTest.php @@ -14,14 +14,6 @@ /** * Tests for Transients. - * - * Runs against real WordPress (wp-env): get/set/delete hit the real transient API, - * which — with no persistent object cache configured — is backed by the options - * table and rolled back per test by WP_UnitTestCase's DB transaction. - * - * Each test uses a distinct prefix so that, even if a non-persistent object cache - * holds entries across tests under `executionOrder="random"`, no two tests can - * resolve to the same namespaced key. */ final class TransientsTest extends TestCase { public function test_set_then_get_round_trips_a_value(): void { @@ -60,8 +52,7 @@ public function test_delete_removes_only_this_instances_entry(): void { } public function test_prefix_key_boundary_is_unambiguous(): void { - // Without the length-prefixed key format, ( 'mod', 'a_b' ) and ( 'mod_a', 'b' ) - // would both collapse to mod_a_b and clobber each other. + // The length prefix keeps these two names from both resolving to rtb_x_y. $one = new Transients( 'rtb' ); // 'rtb' + '_' + 'x_y' $two = new Transients( 'rtb_x' ); // 'rtb_x' + '_' + 'y' @@ -73,14 +64,12 @@ public function test_prefix_key_boundary_is_unambiguous(): void { } public function test_over_long_key_still_round_trips_through_the_database(): void { - // Regression: a namespaced name past 172 characters was truncated by the - // options table, so once the in-request option cache was gone (a new request) - // the value could never be read back. Flushing the object cache simulates that. $store = new Transients( 'rt_long' ); $key = str_repeat( 'k', 200 ); $this->assertTrue( $store->set( $key, 'long-value', HOUR_IN_SECONDS ) ); + // Force the read to go to the database. wp_cache_flush(); $this->assertSame( 'long-value', $store->get( $key ) ); @@ -124,7 +113,6 @@ public function test_key_at_the_limit_is_not_hashed(): void { public function test_value_is_stored_under_the_namespaced_key(): void { ( new Transients( 'rt_ns' ) )->set( 'thing', 'v' ); - // The bare, unprefixed key must not resolve; the namespaced one must. $this->assertFalse( get_transient( 'thing' ) ); $this->assertSame( 'v', get_transient( '5:rt_ns_thing' ) ); } diff --git a/tests/phpunit/TestCase.php b/tests/phpunit/TestCase.php index 9ea730b..e3771e1 100644 --- a/tests/phpunit/TestCase.php +++ b/tests/phpunit/TestCase.php @@ -1,11 +1,6 @@ string, 'import' => string ]`). + * Each dependency in the result has the shape `[ 'id' => string, 'import' => string ]`. * * @param string $id Module identifier. * diff --git a/tests/phpunit/bootstrap.php b/tests/phpunit/bootstrap.php index 3e16dfe..0222c85 100644 --- a/tests/phpunit/bootstrap.php +++ b/tests/phpunit/bootstrap.php @@ -14,7 +14,7 @@ require_once TESTS_REPO_ROOT_DIR . '/vendor/autoload.php'; } -// When run in the wp-env context, point at the test config it provides. +// wp-env provides its own test config. if ( ! defined( 'WP_TESTS_CONFIG_FILE_PATH' ) && false !== getenv( 'WP_PHPUNIT__TESTS_CONFIG' ) ) { define( 'WP_TESTS_CONFIG_FILE_PATH', getenv( 'WP_PHPUNIT__TESTS_CONFIG' ) ); }