diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..db235d5 --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,120 @@ +name: CI + +# Runs on every pull request, and on main after merge. Deliberately not tied to +# tags: release.yml only fires on a v*.*.* tag, which is far too late to learn +# that the coding standards or tests were broken. +on: + push: + branches: + - main + pull_request: + +# A new push to a branch makes the in-flight run for that branch pointless. +concurrency: + group: ci-${{ github.ref }} + cancel-in-progress: true + +permissions: + contents: read + +jobs: + php-lint: + name: PHP syntax (8.0) and coding standards + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + # The oldest PHP the plugin supports (Requires PHP in plugin.php, + # and the live server). + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.0' + coverage: none + + - name: Cache Composer packages + uses: actions/cache@v4 + with: + path: ~/.cache/composer/files + key: composer-${{ hashFiles('composer.lock') }} + restore-keys: composer- + + # PHPUnit 12 requires PHP 8.3, so the platform check is relaxed + # here; PHPUnit is installed but only ever run in the tests job. + # phpcs and WPCS support PHP 8.0. + - name: Install PHP dependencies + run: composer install --no-interaction --prefer-dist --ignore-platform-req=php + + - name: Validate composer.json + run: composer validate --no-check-publish + + # Catches syntax PHP 8.0 cannot parse, which PHPCS does not. + - name: Check PHP 8.0 syntax + run: | + for file in plugin.php uninstall.php lib/functions/*.php; do + php -l "$file" || exit 1 + done + + - name: Check coding standards + run: composer lint + + tests: + name: PHPUnit and node:test + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + # PHPUnit 12's minimum. + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.3' + coverage: none + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: 'npm' + + - name: Cache Composer packages + uses: actions/cache@v4 + with: + path: ~/.cache/composer/files + key: composer-${{ hashFiles('composer.lock') }} + restore-keys: composer- + + - name: Install PHP dependencies + run: composer install --no-interaction --prefer-dist + + - name: Install Node dependencies + run: npm ci + + - name: Run tests + run: npm test + + js: + name: package.json and formatting + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: 20 + cache: 'npm' + + - name: Install Node dependencies + run: npm ci + + - name: Lint package.json + run: npm run lint:pkg-json + + # wp-scripts format rewrites files in place and offers no --check + # mode, so run it and fail if the tree moved. It is the same + # command lint-staged runs on commit, so the hook and CI cannot + # disagree about what "formatted" means. + - name: Check formatting + run: | + npm run format + git diff --exit-code diff --git a/.husky/pre-commit b/.husky/pre-commit new file mode 100644 index 0000000..2312dc5 --- /dev/null +++ b/.husky/pre-commit @@ -0,0 +1 @@ +npx lint-staged diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..6aca7ac --- /dev/null +++ b/.prettierignore @@ -0,0 +1,11 @@ +# Written by ACF whenever a field group or post type is saved in the admin. +# Reformatting them would be undone on the next save and fail the CI check. +acf-json/ + +# Generated by commit-and-tag-version. +CHANGELOG.md + +# Dependencies and build output. +node_modules/ +vendor/ +*.zip diff --git a/CLAUDE.md b/CLAUDE.md index db0a322..2591024 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,28 +12,31 @@ A site-specific WordPress plugin for jasonchafin.com. It holds functionality tha Neither `vendor/` nor `node_modules/` is committed. Run `composer install` and `npm install` first. -- PHP lint: `composer lint`, and auto-fix with `composer lint-fix`. There is no `phpcs.xml`, so pass the standard and paths yourself: `vendor/bin/phpcs --standard=WordPress plugin.php uninstall.php lib/`. -- Tests: - - JS/config checks: `npm run test:unit` (Node's built-in `node:test`, files in `tests/*.test.js`). Run one file with `node --test tests/.test.js`. - - PHP: `composer test` or `npm run test:php` (PHPUnit, files in `tests/php/`). Run one test with `vendor/bin/phpunit --filter `. - - The PHP tests run without WordPress. `tests/php/bootstrap.php` stubs only the WP functions the loaded feature files call, and records the calls. A new feature file under test needs its WP calls stubbed there and a `require_once` added. - - `npm test` still runs `lint-staged`, which has no config. -- Release zip: `npm run zip`. It packages only the `files` list in `package.json` into a `jc-core-functionality/` root folder. Run `composer install --no-dev` first, or dev dependencies end up in `vendor/` in the zip. -- Release: `npm run release` (commit-and-tag-version). It bumps `package.json`, `package-lock.json` and the `Version:` header in `plugin.php` (via `wp-plugin-version-updater.js`), updates `CHANGELOG.md` from Conventional Commits, and tags `vX.Y.Z`. Pushing the tag triggers `.github/workflows/release.yml`, which runs `composer install --no-dev` and `plugin-zip`, then attaches `jc-core-functionality.zip` to a GitHub release. -- Release candidates: `npm run release -- --prerelease rc` tags `vX.Y.Z-rc.N`. The workflow publishes `-rc` tags as GitHub prereleases. PUC reads `/releases/latest`, which skips prereleases, so installed sites never see RCs. To test an RC on staging, install its zip by hand. If an RC is ever published without the prerelease flag, every site with the updater is offered it. +- PHP lint: `composer lint` (ruleset in `phpcs.xml.dist`: WordPress standard, `jc` prefix, `jc-core-functionality` text domain, `tests/` excluded). Auto-fix with `composer lint-fix`. Lint one file with `vendor/bin/phpcs `. +- Format: `npm run format` (wp-scripts/Prettier). `acf-json/` and `CHANGELOG.md` are excluded in `.prettierignore` because tools write them. +- Tests: + - JS/config checks: `npm run test:unit` (Node's built-in `node:test`, files in `tests/*.test.js`). Run one file with `node --test tests/.test.js`. + - PHP: `composer test` or `npm run test:php` (PHPUnit, files in `tests/php/`). Run one test with `vendor/bin/phpunit --filter `. + - The PHP tests run without WordPress. `tests/php/bootstrap.php` stubs only the WP functions the loaded feature files call, and records the calls. A new feature file under test needs its WP calls stubbed there and a `require_once` added. + - `npm test` runs both suites. + - PHPUnit 12 needs PHP 8.3, but the plugin supports 8.0 (`Requires PHP`). Keep plugin code 8.0-compatible; CI checks it with `php -l` on 8.0. +- Hooks and CI: `npm install` sets up a husky pre-commit hook that runs lint-staged (PHPCS on staged PHP, `wp-scripts format` on staged JS/JSON/YAML/Markdown). `.github/workflows/ci.yml` runs on every PR: PHP 8.0 syntax and PHPCS, tests on PHP 8.3, `lint:pkg-json` and a formatting check. +- Release zip: `npm run zip`. It packages only the `files` list in `package.json` into a `jc-core-functionality/` root folder. Run `composer install --no-dev` first, or dev dependencies end up in `vendor/` in the zip. +- Release: `npm run release` (commit-and-tag-version). It bumps `package.json`, `package-lock.json` and the `Version:` header in `plugin.php` (via `wp-plugin-version-updater.js`), updates `CHANGELOG.md` from Conventional Commits, and tags `vX.Y.Z`. Pushing the tag triggers `.github/workflows/release.yml`, which runs `composer install --no-dev` and `plugin-zip`, then attaches `jc-core-functionality.zip` to a GitHub release. +- Release candidates: `npm run release -- --prerelease rc` tags `vX.Y.Z-rc.N`. The workflow publishes `-rc` tags as GitHub prereleases. PUC reads `/releases/latest`, which skips prereleases, so installed sites never see RCs. To test an RC on staging, install its zip by hand. If an RC is ever published without the prerelease flag, every site with the updater is offered it. ## Architecture -- `plugin.php` is the only bootstrap. It defines `JC_DIR`, registers the update checker (below), adds a Settings link on the Plugins screen, and `include_once`s each file in `lib/functions/`. A new feature file needs its own include line added there. Nothing is namespaced or class-based: everything is global functions with a `jc_` prefix, hooked at file load. -- **Post types and custom fields live in `acf-json/`, not in PHP.** `general.php` redirects ACF's JSON load/save point to `JC_DIR . '/acf-json'` (and removes the theme's default load path). The `person` (People) and `quote` (Quotes) CPTs and their field groups are created by ACF from these JSON files. Edit them in the ACF admin UI so the JSON is rewritten, rather than by hand. -- Code depends on these ACF-defined objects by name. The `[quotes]` shortcode (`shortcodes.php`) queries post type `quote`. `general.php` registers the `subtitle` post meta for REST, and that name matches the ACF "Posts" field group. -- Block Bindings sources are registered in `general.php`: `jc/copyright` and `jc/user-data` (args `key` = `name|description|avatar` and `userId`). The settings page in `settings.php` is a static info page that documents features. Update it when you add user-facing features. -- **Updates come from GitHub releases** through plugin-update-checker (PUC), a Composer runtime dependency loaded from `vendor/`. It runs only in admin, cron and WP-CLI, and installs only the `jc-core-functionality.zip` release asset. The slug `jc-core-functionality` must match in `plugin.php`, `uninstall.php` (PUC's option, transient and cron names), `package.json` `name` and the release workflow. `tests/update-checker-config.test.js` enforces this. -- `uninstall.php` removes only PUC's data. By policy, `person` and `quote` content is never deleted. -- `gtm.php` hard-codes GTM container `GTM-WNP9BDSD`. `security-headers.php` builds a nonce-based CSP (`jc_csp_directives()`, filterable through `jc_csp_directives`) and sends it as Report-Only until `jc_csp_report_only` returns false. Admin and the Customizer preview are excluded. `csp-report.php` adds the `/wp-json/jc/v1/csp-report` endpoint, which logs violations as `[jc-csp]` lines in the PHP error log. Scripts must be printed through the script API to get the nonce; `tests/code-standards.test.js` rejects raw `' ), + ); + } + + #[\PHPUnit\Framework\Attributes\DataProvider( 'disabled_ids' )] + public function test_empty_or_invalid_ids_print_nothing( string $id ): void { + add_filter( + 'jc_gtm_container_id', + static function () use ( $id ) { + return $id; + } + ); + + $this->assertSame( '', jc_gtm_container_id() ); + $this->assertSame( '', $this->head() ); + $this->assertSame( '', $this->body() ); + } + + #[RunInSeparateProcess] + public function test_constant_overrides_the_default(): void { + define( 'JC_GTM_ID', 'GTM-STAGING1' ); + + $this->assertSame( 'GTM-STAGING1', jc_gtm_container_id() ); + $this->assertStringContainsString( '"GTM-STAGING1"', $this->head() ); + } + + #[RunInSeparateProcess] + public function test_empty_constant_disables_gtm(): void { + define( 'JC_GTM_ID', '' ); + + $this->assertSame( '', $this->head() ); + $this->assertSame( '', $this->body() ); + } +} diff --git a/tests/php/SettingsPageTest.php b/tests/php/SettingsPageTest.php index 25aab53..1d1e20e 100644 --- a/tests/php/SettingsPageTest.php +++ b/tests/php/SettingsPageTest.php @@ -78,4 +78,20 @@ public function test_block_binding_example_is_shown_as_text(): void { ); $this->assertSame( 0, $pre->getElementsByTagName( 'p' )->length ); } + + public function test_documents_the_user_data_binding(): void { + // #16: only jc/copyright was documented. + $doc = $this->parse( $this->render() ); + $pres = $doc->getElementsByTagName( 'pre' ); + + $this->assertSame( 2, $pres->length ); + $this->assertStringContainsString( '"source":"jc/user-data","args":{"key":"name","userId":1}', $pres->item( 1 )->textContent ); + } + + public function test_shows_the_active_gtm_container(): void { + $this->assertStringContainsString( 'GTM-WNP9BDSD', $this->render() ); + + add_filter( 'jc_gtm_container_id', '__return_empty_string' ); + $this->assertStringContainsString( 'none (disabled)', $this->render() ); + } } diff --git a/tests/php/bootstrap.php b/tests/php/bootstrap.php index 279922e..81e437f 100644 --- a/tests/php/bootstrap.php +++ b/tests/php/bootstrap.php @@ -57,6 +57,9 @@ final class WP_Stubs { /** @var array register_rest_route() calls. */ public static array $rest_routes = array(); + /** @var string[] Capabilities the current user has. */ + public static array $caps = array(); + public static function reset(): void { self::$plugin_data = array(); self::$plugin_data_calls = array(); @@ -67,6 +70,7 @@ public static function reset(): void { self::$transients = array(); self::$is_admin = false; self::$is_customize_preview = false; + self::$caps = array(); WP_Query::$posts = array(); WP_Query::$last_args = array(); $GLOBALS['post'] = null; @@ -133,6 +137,10 @@ function __return_false(): bool { return false; } +function __return_empty_string(): string { + return ''; +} + function is_admin(): bool { return WP_Stubs::$is_admin; } @@ -165,6 +173,27 @@ function wp_json_encode( $data ) { return json_encode( $data ); } +function current_user_can( string $capability ): bool { + return in_array( $capability, WP_Stubs::$caps, true ); +} + +function add_query_arg( string $key, string $value, string $url ): string { + return $url . ( str_contains( $url, '?' ) ? '&' : '?' ) . rawurlencode( $key ) . '=' . rawurlencode( $value ); +} + +/** + * Like core: attributes pass through wp_inline_script_attributes (where the + * CSP nonce is added), then the tag is printed. + */ +function wp_print_inline_script_tag( string $data, array $attributes = array() ): void { + $attributes = apply_filters( 'wp_inline_script_attributes', $attributes, $data ); + $attr = ''; + foreach ( $attributes as $name => $value ) { + $attr .= ' ' . $name . '="' . htmlspecialchars( (string) $value, ENT_QUOTES ) . '"'; + } + echo "{$data}\n"; +} + /** * Stand-in REST request carrying a raw body. */ @@ -255,6 +284,7 @@ function register_block_bindings_source( ...$args ) {} require_once JC_DIR . '/lib/functions/settings.php'; require_once JC_DIR . '/lib/functions/security-headers.php'; require_once JC_DIR . '/lib/functions/csp-report.php'; +require_once JC_DIR . '/lib/functions/gtm.php'; // Fire rest_api_init once so the route registration is recorded. foreach ( WP_Stubs::$filters['rest_api_init'] ?? array() as $callback ) { diff --git a/tests/plugin-metadata.test.js b/tests/plugin-metadata.test.js index 5b05d47..a39bf5e 100644 --- a/tests/plugin-metadata.test.js +++ b/tests/plugin-metadata.test.js @@ -18,7 +18,9 @@ const composer = JSON.parse( read( 'composer.json' ) ); const lock = JSON.parse( read( 'package-lock.json' ) ); const header = ( name ) => { - const match = plugin.match( new RegExp( `^ \\* ${ name }:\\s*(.+)$`, 'm' ) ); + const match = plugin.match( + new RegExp( `^ \\* ${ name }:\\s*(.+)$`, 'm' ) + ); return match && match[ 1 ].trim(); }; @@ -40,7 +42,10 @@ test( 'License URI points at the GPL-2.0 text', () => { test( 'LICENSE exists, is GPL-2.0, and ships in the zip', () => { assert.ok( pkg.files.includes( 'LICENSE' ) ); const license = read( 'LICENSE' ); - assert.match( license, /GNU GENERAL PUBLIC LICENSE\s+Version 2, June 1991/ ); + assert.match( + license, + /GNU GENERAL PUBLIC LICENSE\s+Version 2, June 1991/ + ); } ); test( 'every feature file is loaded exactly once, behind file_exists()', () => { diff --git a/tests/update-checker-config.test.js b/tests/update-checker-config.test.js index a9fef63..00dfc77 100644 --- a/tests/update-checker-config.test.js +++ b/tests/update-checker-config.test.js @@ -94,7 +94,10 @@ test( 'RC tags are published as prereleases, never as Latest', () => { ); assert.ok( triggers.length > 0, 'no tag triggers found' ); for ( const pattern of triggers.filter( ( p ) => /rc/i.test( p ) ) ) { - assert.ok( isPrerelease( pattern ), `${ pattern } would publish as Latest` ); + assert.ok( + isPrerelease( pattern ), + `${ pattern } would publish as Latest` + ); } } );