From f234090794408f41673888c24292f0ca321c1d52 Mon Sep 17 00:00:00 2001 From: "Md. Arifur Rahman" Date: Fri, 2 Oct 2026 11:00:10 +0600 Subject: [PATCH 1/6] Document why NodeJS is needed to run the tests Explains that the build step downloads the pinned Gutenberg artifact from ghcr.io and copies the block editor files into src/, which the tests load. Also notes engine-strict and that the production build is not needed for PHPUnit. Fixes #243. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/README.md b/README.md index 4302671..1ad1a37 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,22 @@ nodejs --version npm --version ``` +#### Why NodeJS is needed + +The PHPUnit tests are PHP, but they do not run on a plain checkout of `wordpress-develop`. Some files that WordPress loads are not in version control. A build step creates them. + +`prepare.php` runs `npm install && npm run build` in the checkout. For the tests, the important part is the Gutenberg step (`build:gutenberg` in the [Gruntfile](https://github.com/WordPress/wordpress-develop/blob/trunk/Gruntfile.js)): + +1. It downloads the built Gutenberg artifact for the version pinned in `package.json` (`gutenberg.sha`). The download comes from `ghcr.io`, so the server must be able to connect to it. +2. It copies the block editor PHP files, routes, blocks, scripts, styles and `theme.json` into `src/`. + +The tests load WordPress from `src/` (`ABSPATH` in `wp-tests-config.php`). These files were removed from version control in [changeset 61438](https://core.trac.wordpress.org/changeset/61438). Without the build, the tests fail when they load WordPress, for example on a missing `src/wp-includes/build/routes.php` ([#292](https://github.com/WordPress/phpunit-test-runner/issues/292)). + +Also: + +- Use the Node.js and npm versions in the `engines` field of `wordpress-develop/package.json`. Its `.npmrc` sets `engine-strict = true`, so `npm install` stops on older versions. +- `npm run build` also makes the production build: it copies files to `build/` and minifies JavaScript and CSS. The PHPUnit tests do not use these files. WordPress Core runs its own PHPUnit workflow after `npm ci` and `npm run build:dev`. [#244](https://github.com/WordPress/phpunit-test-runner/issues/244) tracks ways to make this step smaller. + ### PHP Composer _This is a simple example for Debian / Ubuntu._ From 363246467afc7b716fc943527e82c329d5d8786c Mon Sep 17 00:00:00 2001 From: "Md. Arifur Rahman" Date: Fri, 2 Oct 2026 22:55:34 +0600 Subject: [PATCH 2/6] Rework the Node.js section after review Make it a standalone ### section, open with why a PHP suite needs Node.js, list the Gutenberg steps in order, and add a summary sentence (from the review). Keep the ghcr.io network requirement, the changeset and issue references, and the build:dev note. Mention that devEngines also enforces the npm version. --- README.md | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/README.md b/README.md index 1ad1a37..6f755f2 100644 --- a/README.md +++ b/README.md @@ -130,21 +130,27 @@ nodejs --version npm --version ``` -#### Why NodeJS is needed +### Why Node.js is needed -The PHPUnit tests are PHP, but they do not run on a plain checkout of `wordpress-develop`. Some files that WordPress loads are not in version control. A build step creates them. +The PHPUnit tests are written in PHP, but `prepare.php` needs Node.js and npm to prepare the WordPress checkout before the tests can run. -`prepare.php` runs `npm install && npm run build` in the checkout. For the tests, the important part is the Gutenberg step (`build:gutenberg` in the [Gruntfile](https://github.com/WordPress/wordpress-develop/blob/trunk/Gruntfile.js)): +The tests load WordPress from `src/` (`ABSPATH` in `wp-tests-config.php`). Some files that WordPress loads from there are not in version control: they were removed in [changeset 61438](https://core.trac.wordpress.org/changeset/61438), and the build creates them. -1. It downloads the built Gutenberg artifact for the version pinned in `package.json` (`gutenberg.sha`). The download comes from `ghcr.io`, so the server must be able to connect to it. -2. It copies the block editor PHP files, routes, blocks, scripts, styles and `theme.json` into `src/`. +`prepare.php` runs `npm install && npm run build`. For the tests, the important part is the Gutenberg step (`build:gutenberg` in the [Gruntfile](https://github.com/WordPress/wordpress-develop/blob/trunk/Gruntfile.js)): -The tests load WordPress from `src/` (`ABSPATH` in `wp-tests-config.php`). These files were removed from version control in [changeset 61438](https://core.trac.wordpress.org/changeset/61438). Without the build, the tests fail when they load WordPress, for example on a missing `src/wp-includes/build/routes.php` ([#292](https://github.com/WordPress/phpunit-test-runner/issues/292)). +1. It uses the Gutenberg version that WordPress pins in `package.json` (`gutenberg.sha`). +2. It downloads the pre-built Gutenberg artifact for that version from GitHub Container Registry (`ghcr.io`). The server must be able to connect to `ghcr.io`. +3. It copies the block editor PHP files, routes, blocks, scripts, styles and `theme.json` into `src/`. -Also: +If this step does not run, the tests fail while WordPress loads, for example on a missing `src/wp-includes/build/routes.php` ([#292](https://github.com/WordPress/phpunit-test-runner/issues/292)). This is why Node.js and npm are requirements, even though the tests are PHP. -- Use the Node.js and npm versions in the `engines` field of `wordpress-develop/package.json`. Its `.npmrc` sets `engine-strict = true`, so `npm install` stops on older versions. -- `npm run build` also makes the production build: it copies files to `build/` and minifies JavaScript and CSS. The PHPUnit tests do not use these files. WordPress Core runs its own PHPUnit workflow after `npm ci` and `npm run build:dev`. [#244](https://github.com/WordPress/phpunit-test-runner/issues/244) tracks ways to make this step smaller. +Versions: + +- Use the Node.js and npm versions in the `engines` field of `wordpress-develop/package.json`. Its `.npmrc` sets `engine-strict = true`, and `devEngines` also requires the npm version, so `npm install` stops on older versions. + +Extra work: + +- `npm run build` does more than PHPUnit needs. It also makes the production build in `build/` and minifies JavaScript and CSS. The tests do not use these files. WordPress Core runs its own PHPUnit workflow after `npm ci` and `npm run build:dev`. [#244](https://github.com/WordPress/phpunit-test-runner/issues/244) tracks ways to make this step smaller. ### PHP Composer From 148566c3a0f601f1ce4a715da2e339b4462404d0 Mon Sep 17 00:00:00 2001 From: "Md. Arifur Rahman" Date: Tue, 6 Oct 2026 19:46:34 +0600 Subject: [PATCH 3/6] Use the reviewed wording for the Node.js section Base the section on the wording suggested in review, and use real headings for Versions and Extra work (review suggestions). Keep the facts hosts need: the build commands, changeset 61438, gutenberg.sha, the ghcr.io connection, the routes.php example, devEngines with the EBADDEVENGINES error, and Core's build:dev workflow. --- README.md | 25 ++++++++++++++----------- 1 file changed, 14 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index 6f755f2..f7a5d9f 100644 --- a/README.md +++ b/README.md @@ -132,25 +132,28 @@ npm --version ### Why Node.js is needed -The PHPUnit tests are written in PHP, but `prepare.php` needs Node.js and npm to prepare the WordPress checkout before the tests can run. +The PHPUnit test suite itself is written in PHP, but Node.js is required to prepare the WordPress source code before the tests can run. -The tests load WordPress from `src/` (`ABSPATH` in `wp-tests-config.php`). Some files that WordPress loads from there are not in version control: they were removed in [changeset 61438](https://core.trac.wordpress.org/changeset/61438), and the build creates them. +The test runner uses `prepare.php` to set up a WordPress checkout and prepare it for PHPUnit. As part of this process, it runs the WordPress build tasks (`npm install && npm run build`), including the Gutenberg build step (`build:gutenberg` in the [Gruntfile](https://github.com/WordPress/wordpress-develop/blob/trunk/Gruntfile.js)). This is necessary because some files used by WordPress Core are generated or assembled as part of the build process rather than being available directly in the `wordpress-develop` checkout. These files were removed from version control in [changeset 61438](https://core.trac.wordpress.org/changeset/61438). -`prepare.php` runs `npm install && npm run build`. For the tests, the important part is the Gutenberg step (`build:gutenberg` in the [Gruntfile](https://github.com/WordPress/wordpress-develop/blob/trunk/Gruntfile.js)): +The Gutenberg build step: -1. It uses the Gutenberg version that WordPress pins in `package.json` (`gutenberg.sha`). -2. It downloads the pre-built Gutenberg artifact for that version from GitHub Container Registry (`ghcr.io`). The server must be able to connect to `ghcr.io`. -3. It copies the block editor PHP files, routes, blocks, scripts, styles and `theme.json` into `src/`. +1. Uses the Gutenberg version pinned by WordPress Core (`gutenberg.sha` in `package.json`). +2. Downloads the corresponding pre-built Gutenberg artifact from GitHub Container Registry (`ghcr.io`), so the server must be able to connect to `ghcr.io`. +3. Copies the required Gutenberg files into the WordPress `src/` directory. +4. Makes those files available to the WordPress installation that PHPUnit loads during the test run. -If this step does not run, the tests fail while WordPress loads, for example on a missing `src/wp-includes/build/routes.php` ([#292](https://github.com/WordPress/phpunit-test-runner/issues/292)). This is why Node.js and npm are requirements, even though the tests are PHP. +The PHPUnit test suite loads WordPress from the `src/` directory. Therefore, these build steps must complete successfully before the tests can run. If the Gutenberg files have not been prepared, the test suite can fail while loading WordPress because required files are missing, for example `src/wp-includes/build/routes.php` ([#292](https://github.com/WordPress/phpunit-test-runner/issues/292)). -Versions: +This is why Node.js and npm are requirements for the test runner even though the tests themselves are written in PHP. -- Use the Node.js and npm versions in the `engines` field of `wordpress-develop/package.json`. Its `.npmrc` sets `engine-strict = true`, and `devEngines` also requires the npm version, so `npm install` stops on older versions. +#### Versions -Extra work: +The Node.js and npm versions must be compatible with the versions specified in the `engines` and `devEngines` fields of `wordpress-develop/package.json`. Because of these fields and the repository's `engine-strict` npm setting, using an unsupported Node.js or npm version causes `npm install` to fail, for example with `npm error code EBADDEVENGINES`. -- `npm run build` does more than PHPUnit needs. It also makes the production build in `build/` and minifies JavaScript and CSS. The tests do not use these files. WordPress Core runs its own PHPUnit workflow after `npm ci` and `npm run build:dev`. [#244](https://github.com/WordPress/phpunit-test-runner/issues/244) tracks ways to make this step smaller. +#### Extra work + +`npm run build` performs more work than is required by PHPUnit. The complete WordPress build also creates the production `build/` directory and performs tasks such as JavaScript and CSS minification. The PHPUnit tests primarily need the files prepared in `src/`. The additional build work is currently part of the preparation process. WordPress Core's own PHPUnit workflow runs `npm ci` and `npm run build:dev` instead, and [#244](https://github.com/WordPress/phpunit-test-runner/issues/244) tracks ways to make this step smaller. ### PHP Composer From 4814a42d233258bac2ac9a0b30c46c3e2b2be6d7 Mon Sep 17 00:00:00 2001 From: "Md. Arifur Rahman" Date: Wed, 7 Oct 2026 16:26:06 +0600 Subject: [PATCH 4/6] Name the ghcr.io download redirect domain GHCR answers the blob request with a 307 to pkg-containers.githubusercontent.com, so a host with an outbound allowlist needs both domains. --- .env.default | 85 -- .github/ISSUE_TEMPLATE/bug_report.md | 27 - .github/ISSUE_TEMPLATE/feature_request.md | 20 - .../ISSUE_TEMPLATE/test_reporter_request.md | 25 - .github/SECURITY.md | 23 - .github/dependabot.yml | 21 - .github/workflows/coding-standards.yml | 97 --- .github/workflows/phpunit-tests.yml | 101 --- .github/workflows/props-bot.yml | 92 --- .github/workflows/tests.yml | 94 --- .gitignore | 16 - .travis.yml | 16 - LICENSE | 339 -------- README.md | 2 +- cleanup-db.php | 266 ------- cleanup.php | 72 -- composer.json | 22 - composer.lock | 437 ----------- functions.php | 734 ------------------ phpcs.xml.dist | 64 -- prepare.php | 527 ------------- report.php | 148 ---- test.php | 79 -- 23 files changed, 1 insertion(+), 3306 deletions(-) delete mode 100644 .env.default delete mode 100644 .github/ISSUE_TEMPLATE/bug_report.md delete mode 100644 .github/ISSUE_TEMPLATE/feature_request.md delete mode 100644 .github/ISSUE_TEMPLATE/test_reporter_request.md delete mode 100644 .github/SECURITY.md delete mode 100644 .github/dependabot.yml delete mode 100644 .github/workflows/coding-standards.yml delete mode 100644 .github/workflows/phpunit-tests.yml delete mode 100644 .github/workflows/props-bot.yml delete mode 100644 .github/workflows/tests.yml delete mode 100644 .gitignore delete mode 100644 .travis.yml delete mode 100644 LICENSE delete mode 100644 cleanup-db.php delete mode 100644 cleanup.php delete mode 100644 composer.json delete mode 100644 composer.lock delete mode 100644 functions.php delete mode 100644 phpcs.xml.dist delete mode 100644 prepare.php delete mode 100644 report.php delete mode 100644 test.php diff --git a/.env.default b/.env.default deleted file mode 100644 index df58ae0..0000000 --- a/.env.default +++ /dev/null @@ -1,85 +0,0 @@ -### -# Configuration environment variables used by the test runner -# -# # Create a copy for your local environment -# $ cp .env.default .env -# -# # Make any necessary changes to the default values -# $ vim .env -# -# # Load your variables into your environment -# $ source .env -### - -# Path to the directory where files can be prepared before being delivered to the environment. -export WPT_PREPARE_DIR="/tmp/wp-test-runner" - -# Path to the directory where the WordPress develop checkout can be placed and tests can be run. -# When running tests in the same environment, set WPT_TEST_DIR to WPT_PREPARE_DIR -export WPT_TEST_DIR="wp-test-runner" - -# API key to authenticate with the reporting service in 'username:password' format. -export WPT_REPORT_API_KEY="" - -# (Optionally) define an alternate reporting URL -export WPT_REPORT_URL="" - -# Credentials for a database that can be written to and reset. -# WARNING!!! This database will be destroyed between tests. Only use safe database credentials. -# Please note that you must escape _or_ refrain from using # as special character in your credentials. -export WPT_DB_NAME="" -export WPT_DB_USER="" -export WPT_DB_PASSWORD="" -export WPT_DB_HOST="" - -# (Optionally) set a custom table prefix to permit concurrency against the same database. -export WPT_TABLE_PREFIX="${WPT_TABLE_PREFIX-wptests_}" - -# (Optionally) define the PHP executable to be called -export WPT_PHP_EXECUTABLE="${WPT_PHP_EXECUTABLE-php}" - -# (Optionally) define the PHPUnit command execution call. -# Use if `php phpunit.phar` can't be called directly for some reason. -export WPT_PHPUNIT_CMD="" - -# (Optionally) define the command execution to remove the test directory -# Use if `rm -r` can't be called directly for some reason. -export WPT_RM_TEST_DIR_CMD="" - -# SSH connection string (can also be an alias). -# Leave empty if tests are meant to run in the same environment. -export WPT_SSH_CONNECT="" - -# Any options to be passed to the SSH connection -# Defaults to '-o StrictHostKeyChecking=no' -export WPT_SSH_OPTIONS="" - -# SSH private key, base64 encoded. -export WPT_SSH_PRIVATE_KEY_BASE64="" - -# Whether to enable debug Mode. -# -# Enabling debug mode will output verbose logging and details about each part -# of the test runner. -# -# 0 = Debug mode off -# 1 = Debug mode on -# -# Any other truthy value will also enable debug mode. -export WPT_DEBUG= - -# Certificate validation -# Use 1 to validate, and 0 to not validate -export WPT_CERTIFICATE_VALIDATION=1 - -# WordPress flavor -# 0 = WordPress (simple version) -# 1 = WordPress Multisite -export WPT_FLAVOR=0 - -# Extra tests (groups) -# 0 = none -# 1 = ajax -# 2 = ms-files -# 3 = external-http -export WPT_EXTRATESTS=0 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md deleted file mode 100644 index 160740e..0000000 --- a/.github/ISSUE_TEMPLATE/bug_report.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -name: Bug report -about: Create a report to help us improve -title: '' -labels: bug -assignees: '' - ---- - -**Describe the bug** -A clear and concise description of what the bug is. - -**To Reproduce** -Steps to reproduce the behavior: -1. Go to '...' -2. Click on '....' -3. Scroll down to '....' -4. See error - -**Expected behavior** -A clear and concise description of what you expected to happen. - -**Screenshots** -If applicable, add screenshots to help explain your problem. - -**Additional context** -Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md deleted file mode 100644 index 6532412..0000000 --- a/.github/ISSUE_TEMPLATE/feature_request.md +++ /dev/null @@ -1,20 +0,0 @@ ---- -name: Feature request -about: Suggest an idea for this project -title: '' -labels: enhancement -assignees: '' - ---- - -**Is your feature request related to a problem? Please describe.** -A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] - -**Describe the solution you'd like** -A clear and concise description of what you want to happen. - -**Describe alternatives you've considered** -A clear and concise description of any alternative solutions or features you've considered. - -**Additional context** -Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/test_reporter_request.md b/.github/ISSUE_TEMPLATE/test_reporter_request.md deleted file mode 100644 index 8d821df..0000000 --- a/.github/ISSUE_TEMPLATE/test_reporter_request.md +++ /dev/null @@ -1,25 +0,0 @@ ---- -name: Test Reporter request -about: Requesting your bot user to be added to this WordPress.org site as a “Test - Reporter”. -title: "[Test Reporter] " -labels: test-reporter-request -assignees: '' - ---- - -Requesting your bot user to be added to this WordPress.org site [as a “Test Reporter”](https://make.wordpress.org/hosting/test-results/). - -For more information, please visit the [Getting Started](https://make.wordpress.org/hosting/test-results-getting-started/) Guide or the [Hosting Handbook](https://make.wordpress.org/hosting/handbook/tests/). - -**Preconditions Checklist:** - -* [ ] I've added a Gravatar/logo to the profile. -* [ ] I've added a URL to the profile, to make it clear to users what hosting company is being represented in the results. -* [ ] I've set the email address to something monitored by a human. -* [ ] I've set the email address to one that uses the domain name of the hosting company. - -**Bot Profile Details:** - -* Bot email address: -* Bot WordPress profile: diff --git a/.github/SECURITY.md b/.github/SECURITY.md deleted file mode 100644 index 1d8dd95..0000000 --- a/.github/SECURITY.md +++ /dev/null @@ -1,23 +0,0 @@ -# Security Policy - -## Supported scope - -The WordPress PHPUnit Test Runner is the tooling hosting providers use to run the WordPress core test suite and report results. This repository contains those scripts and their GitHub configuration. - -This policy covers security-sensitive issues in the code and configuration of this repository. It does not define support for WordPress core, plugins, themes, hosting stacks, server packages, or hosting platforms. - -## Reporting vulnerabilities - -For WordPress core, plugins, themes, WordPress.org, or the wider WordPress ecosystem, follow the official [WordPress security reporting guidance](https://wordpress.org/about/security/). WordPress core vulnerabilities should be reported through the [WordPress HackerOne program](https://hackerone.com/wordpress). - -Do not report exploitable security vulnerabilities in public GitHub issues or pull requests. For a vulnerability in the test runner scripts themselves, use the reporting channels from the official guidance above rather than a public issue, so hosts running the tooling are not exposed before a fix is available. - -If the vulnerability is in a hosting platform, server package, or other third-party project, report it to that project or vendor through their security reporting process. - -## Other issues - -If you find a bug or an insecure default in the test runner that is not an exploitable vulnerability, open a public issue in this repository: - -https://github.com/WordPress/phpunit-test-runner/issues - -Include the affected script, the behaviour you observed, and any safer replacement you are suggesting. Do not include exploit details or private vulnerability information in public issues. diff --git a/.github/dependabot.yml b/.github/dependabot.yml deleted file mode 100644 index f88fa2f..0000000 --- a/.github/dependabot.yml +++ /dev/null @@ -1,21 +0,0 @@ -# Configure Dependabot scanning. -version: 2 - -updates: - # Check for updates to GitHub Actions. - - package-ecosystem: "github-actions" - directory: "/" - schedule: - interval: "daily" - open-pull-requests-limit: 10 - groups: - github-actions: - patterns: - - "*" - - # Check for updates to Composer packages. - - package-ecosystem: "composer" - directory: "/" - schedule: - interval: "weekly" - open-pull-requests-limit: 5 diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml deleted file mode 100644 index d8e21d9..0000000 --- a/.github/workflows/coding-standards.yml +++ /dev/null @@ -1,97 +0,0 @@ -name: Coding Standards - -on: - push: - branches: - - master - pull_request: - branches: - - master - paths: - - '**.php' - - 'composer.*' - - 'phpcs.xml.dist' - - '.github/workflows/coding-standards.yml' - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} - cancel-in-progress: true - -permissions: {} - -jobs: - lint: - name: PHP Syntax Check - runs-on: ubuntu-24.04 - timeout-minutes: 5 - permissions: - contents: read - - steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} - persist-credentials: false - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: '8.2' - coverage: none - - - name: Check PHP syntax - run: find . -name "*.php" -not -path "./.git/*" -not -path "./vendor/*" | xargs -n1 php -l - - phpcs: - name: Coding Standards - runs-on: ubuntu-24.04 - timeout-minutes: 10 - permissions: - contents: read - - steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} - persist-credentials: false - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: '8.2' - coverage: none - tools: cs2pr - - - name: "Get last Monday's date" - id: get-date - run: echo "date=$(/bin/date -u --date='last Mon' "+%F")" >> "$GITHUB_OUTPUT" - - - name: Cache PHPCS scan cache - uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 - with: - path: .cache/phpcs.json - key: ${{ runner.os }}-date-${{ steps.get-date.outputs.date }}-phpcs-cache-${{ hashFiles('**/composer.json', 'phpcs.xml.dist') }} - - - name: Install Composer dependencies - uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 - with: - custom-cache-suffix: ${{ steps.get-date.outputs.date }} - - - name: Make Composer packages available globally - run: echo "${PWD}/vendor/bin" >> "$GITHUB_PATH" - - - name: Run PHPCS - id: phpcs - run: | - mkdir -p .cache - phpcs -n --report-full --cache=./.cache/phpcs.json --report-checkstyle=./.cache/phpcs-report.xml - - - name: Show PHPCS results in PR - if: ${{ always() && steps.phpcs.outcome == 'failure' }} - run: cs2pr ./.cache/phpcs-report.xml - - - name: Ensure version-controlled files are not modified or deleted - run: git diff --exit-code diff --git a/.github/workflows/phpunit-tests.yml b/.github/workflows/phpunit-tests.yml deleted file mode 100644 index a0d8353..0000000 --- a/.github/workflows/phpunit-tests.yml +++ /dev/null @@ -1,101 +0,0 @@ -name: PHPUnit Tests - -on: - push: - branches: - - master - pull_request: - branches: - - master - paths: - - '**.php' - - '.github/workflows/phpunit-tests.yml' - workflow_dispatch: - -concurrency: - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} - cancel-in-progress: true - -permissions: {} - -jobs: - test: - name: PHP ${{ matrix.php }} / MySQL ${{ matrix.db-version }} - runs-on: ubuntu-24.04 - timeout-minutes: 30 - permissions: - contents: read - - strategy: - fail-fast: false - matrix: - php: [ '7.4', '8.0', '8.2' ] - db-version: [ '8.0' ] - - services: - mysql: - image: mysql:${{ matrix.db-version }} - env: - MYSQL_ROOT_PASSWORD: root - MYSQL_DATABASE: wordpress_test - MYSQL_USER: wp_test - MYSQL_PASSWORD: wp_test - ports: - - 3306:3306 - options: >- - --health-cmd="mysqladmin ping" - --health-interval=10s - --health-timeout=5s - --health-retries=3 - - env: - WPT_PREPARE_DIR: /tmp/wp-test-runner - WPT_TEST_DIR: /tmp/wp-test-runner - WPT_DB_NAME: wordpress_test - WPT_DB_USER: wp_test - WPT_DB_PASSWORD: wp_test - WPT_DB_HOST: 127.0.0.1 - WPT_REPORT_API_KEY: '' - - steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - with: - show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} - persist-credentials: false - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: ${{ matrix.php }} - coverage: none - - - name: Set up Node.js - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: 24 - - - name: Prepare environment - run: php prepare.php - - - name: Run unit tests - run: php test.php - continue-on-error: true - - - name: Report results - run: php report.php - continue-on-error: true - - - name: Cleanup - run: php cleanup.php - - - name: Verify database cleanup - env: - MYSQL_PWD: wp_test - run: | - TABLES=$(mysql -h 127.0.0.1 -u wp_test wordpress_test -N -e "SHOW TABLES LIKE 'wptests\_%'") - if [ -n "$TABLES" ]; then - echo "Test tables remain after cleanup:" - echo "$TABLES" - exit 1 - fi diff --git a/.github/workflows/props-bot.yml b/.github/workflows/props-bot.yml deleted file mode 100644 index 61eca3e..0000000 --- a/.github/workflows/props-bot.yml +++ /dev/null @@ -1,92 +0,0 @@ -name: Props Bot - -on: - # This event runs anytime a PR is (re)opened, updated, marked ready for review, or labeled. - # GitHub does not allow filtering the `labeled` event by a specific label. - # However, the logic below will short-circuit the workflow when the `props-bot` label is not the one being added. - # Note: The pull_request_target event is used instead of pull_request because this workflow needs permission to comment - # on the pull request. Because this event grants extra permissions to `GITHUB_TOKEN`, any code changes within the PR - # should be considered untrusted. See https://securitylab.github.com/research/github-actions-preventing-pwn-requests/. - pull_request_target: - types: - - opened - - synchronize - - reopened - - labeled - - ready_for_review - # This event runs anytime a comment is added or deleted. - # You cannot filter this event for PR comments only. - # However, the logic below does short-circuit the workflow for issues. - issue_comment: - types: - - created - # This event will run everytime a new PR review is initially submitted. - pull_request_review: - types: - - submitted - # This event runs anytime a PR review comment is created or deleted. - pull_request_review_comment: - types: - - created - -# Cancels all previous workflow runs for pull requests that have not completed. -concurrency: - # The concurrency group contains the workflow name and the branch name for pull requests - # or the commit hash for any other events. - group: ${{ github.workflow }}-${{ contains( fromJSON( '["pull_request_target", "pull_request_review", "pull_request_review_comment"]' ), github.event_name ) && github.head_ref || github.sha }} - cancel-in-progress: true - -# Disable permissions for all available scopes by default. -# Any needed permissions should be configured at the job level. -permissions: {} - -jobs: - # Compiles a list of props for a pull request. - # - # Performs the following steps: - # - Collects a list of contributor props and leaves a comment. - # - Removes the props-bot label, if necessary. - props-bot: - name: Generate a list of props - runs-on: ubuntu-24.04 - permissions: - # The action needs permission `write` permission for PRs in order to add a comment. - pull-requests: write - contents: read - timeout-minutes: 20 - # The job will run when pull requests are open, ready for review and: - # - # - A comment is added to the pull request. - # - A review is created or commented on (unless PR originates from a fork). - # - The pull request is opened, synchronized, marked ready for review, or reopened. - # - The `props-bot` label is added to the pull request. - if: | - ( - github.event_name == 'issue_comment' && github.event.issue.pull_request || - ( contains( fromJSON( '["pull_request_review", "pull_request_review_comment"]' ), github.event_name ) && ! github.event.pull_request.head.repo.fork ) || - github.event_name == 'pull_request_target' && github.event.action != 'labeled' || - 'props-bot' == github.event.label.name - ) && - ( ! github.event.pull_request.draft && github.event.pull_request.state == 'open' || ! github.event.issue.draft && github.event.issue.state == 'open' ) - - steps: - - name: Gather a list of contributors - uses: WordPress/props-bot-action@trunk - with: - format: 'git' - - - name: Remove the props-bot label - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 - if: ${{ github.event.action == 'labeled' && 'props-bot' == github.event.label.name }} - with: - retries: 2 - retry-exempt-status-codes: 418 - script: | - github.rest.issues.removeLabel({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: process.env.ISSUE_NUMBER, - name: 'props-bot' - }); - env: - ISSUE_NUMBER: ${{ github.event.number }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml deleted file mode 100644 index 4f9cee9..0000000 --- a/.github/workflows/tests.yml +++ /dev/null @@ -1,94 +0,0 @@ -name: WordPress PHPUnit tests - -on: - # The workflow should be run on a schedule using the 'schedule' event trigger. - # - # For more details on how to configure the schedule event, see https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#onschedule. - # - # Below are some options for different schedules. Running the tests every hour is recommended, - # but every 3-6 hours is also helpful. Times are in UTC. - schedule: - # By default, the workflow will run every hour. - - cron: '0 * * * *' - # Every 3 hours. - # - cron: '0 0/3 * * *' - # Every 6 hours. - # - cron: '0 0/6 * * *' - # Every 12 hours. - # - cron: '0 0/12 * * *' - # Once per day at 00:00. - # - cron: '0 0 * * *' - # Every 30 minutes. - # - cron: '0/30 * * * *' - workflow_dispatch: - -# Cancels all previous workflow runs for pull requests that have not completed. -concurrency: - # The concurrency group contains the workflow name and the branch name for pull requests - # or the commit hash for any other events. - group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} - cancel-in-progress: true - -jobs: - # Tests the PHPUnit test runner. - # - # Performs the following steps: - # - Checks out the repository. - # - Installs PHP. - # - Installs NodeJS 14 with caching configured. - # - Prepares the environment for tests. - # - Runs the tests. - # - Reports the results. - # - Cleans up. - test: - name: Run Core PHPUnit tests - runs-on: ubuntu-latest - - # Remove this line if Github Actions is your preferred means of running the tests. - if: ${{ false }} - - env: - # This is only a subset/example of env vars available. See the `.env.default` file for a full list. - WPT_PREPARE_DIR: ${{ secrets.WPT_PREPARE_DIR }} - WPT_TEST_DIR: ${{ secrets.WPT_TEST_DIR }} - WPT_REPORT_API_KEY: ${{ secrets.WPT_REPORT_API_KEY }} - WPT_PHP_EXECUTABLE: ${{ secrets.WPT_PHP_EXECUTABLE }} - # Database settings - WPT_DB_NAME: ${{ secrets.WPT_DB_NAME }} - WPT_DB_USER: ${{ secrets.WPT_DB_USER }} - WPT_DB_PASSWORD: ${{ secrets.WPT_DB_PASSWORD }} - WPT_DB_HOST: ${{ secrets.WPT_DB_HOST }} - # SSH settings for connecting to the test environment. - WPT_SSH_CONNECT: ${{ secrets.WPT_SSH_CONNECT }} - WPT_SSH_PRIVATE_KEY_BASE64: ${{ secrets.WPT_SSH_PRIVATE_KEY_BASE64 }} - - steps: - - name: Checkout repository - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 - - - name: Set up PHP - uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 - with: - php-version: '7.4' - coverage: none - - - name: Install NodeJS - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 - with: - node-version: 24 - - - name: Prepare environment - run: php prepare.php - - - name: Run unit tests - run: php test.php - # Prevent the workflow from stopping if there are test failures. - continue-on-error: true - - - name: Report the results - run: php report.php - # Prevent the workflow from stopping if the reporting fails. - continue-on-error: true - - - name: Cleanup - run: php cleanup.php diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 023e69a..0000000 --- a/.gitignore +++ /dev/null @@ -1,16 +0,0 @@ -.DS_Store -.env* -vendor/ -.cache/ -package-lock.json -commit.json -ignore.json - -# Exclude the default test directory. -wp-test-runner/ - -# Files related to applying patches -*.rej -*.orig -*.patch -*.diff diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 4369ea3..0000000 --- a/.travis.yml +++ /dev/null @@ -1,16 +0,0 @@ -language: php -node_js: - - 20 - -before_install: - - npm install -g npm@latest - -install: - - php prepare.php - -script: - - php test.php - -after_script: - - php report.php - - php cleanup.php diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 23cb790..0000000 --- a/LICENSE +++ /dev/null @@ -1,339 +0,0 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 - - Copyright (C) 1989, 1991 Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA - Everyone is permitted to copy and distribute verbatim copies - of this license document, but changing it is not allowed. - - Preamble - - The licenses for most software are designed to take away your -freedom to share and change it. By contrast, the GNU General Public -License is intended to guarantee your freedom to share and change free -software--to make sure the software is free for all its users. This -General Public License applies to most of the Free Software -Foundation's software and to any other program whose authors commit to -using it. (Some other Free Software Foundation software is covered by -the GNU Lesser General Public License instead.) You can apply it to -your programs, too. - - When we speak of free software, we are referring to freedom, not -price. Our General Public Licenses are designed to make sure that you -have the freedom to distribute copies of free software (and charge for -this service if you wish), that you receive source code or can get it -if you want it, that you can change the software or use pieces of it -in new free programs; and that you know you can do these things. - - To protect your rights, we need to make restrictions that forbid -anyone to deny you these rights or to ask you to surrender the rights. -These restrictions translate to certain responsibilities for you if you -distribute copies of the software, or if you modify it. - - For example, if you distribute copies of such a program, whether -gratis or for a fee, you must give the recipients all the rights that -you have. You must make sure that they, too, receive or can get the -source code. And you must show them these terms so they know their -rights. - - We protect your rights with two steps: (1) copyright the software, and -(2) offer you this license which gives you legal permission to copy, -distribute and/or modify the software. - - Also, for each author's protection and ours, we want to make certain -that everyone understands that there is no warranty for this free -software. If the software is modified by someone else and passed on, we -want its recipients to know that what they have is not the original, so -that any problems introduced by others will not reflect on the original -authors' reputations. - - Finally, any free program is threatened constantly by software -patents. We wish to avoid the danger that redistributors of a free -program will individually obtain patent licenses, in effect making the -program proprietary. To prevent this, we have made it clear that any -patent must be licensed for everyone's free use or not licensed at all. - - The precise terms and conditions for copying, distribution and -modification follow. - - GNU GENERAL PUBLIC LICENSE - TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION - - 0. This License applies to any program or other work which contains -a notice placed by the copyright holder saying it may be distributed -under the terms of this General Public License. The "Program", below, -refers to any such program or work, and a "work based on the Program" -means either the Program or any derivative work under copyright law: -that is to say, a work containing the Program or a portion of it, -either verbatim or with modifications and/or translated into another -language. (Hereinafter, translation is included without limitation in -the term "modification".) Each licensee is addressed as "you". - -Activities other than copying, distribution and modification are not -covered by this License; they are outside its scope. The act of -running the Program is not restricted, and the output from the Program -is covered only if its contents constitute a work based on the -Program (independent of having been made by running the Program). -Whether that is true depends on what the Program does. - - 1. You may copy and distribute verbatim copies of the Program's -source code as you receive it, in any medium, provided that you -conspicuously and appropriately publish on each copy an appropriate -copyright notice and disclaimer of warranty; keep intact all the -notices that refer to this License and to the absence of any warranty; -and give any other recipients of the Program a copy of this License -along with the Program. - -You may charge a fee for the physical act of transferring a copy, and -you may at your option offer warranty protection in exchange for a fee. - - 2. You may modify your copy or copies of the Program or any portion -of it, thus forming a work based on the Program, and copy and -distribute such modifications or work under the terms of Section 1 -above, provided that you also meet all of these conditions: - - a) You must cause the modified files to carry prominent notices - stating that you changed the files and the date of any change. - - b) You must cause any work that you distribute or publish, that in - whole or in part contains or is derived from the Program or any - part thereof, to be licensed as a whole at no charge to all third - parties under the terms of this License. - - c) If the modified program normally reads commands interactively - when run, you must cause it, when started running for such - interactive use in the most ordinary way, to print or display an - announcement including an appropriate copyright notice and a - notice that there is no warranty (or else, saying that you provide - a warranty) and that users may redistribute the program under - these conditions, and telling the user how to view a copy of this - License. (Exception: if the Program itself is interactive but - does not normally print such an announcement, your work based on - the Program is not required to print an announcement.) - -These requirements apply to the modified work as a whole. If -identifiable sections of that work are not derived from the Program, -and can be reasonably considered independent and separate works in -themselves, then this License, and its terms, do not apply to those -sections when you distribute them as separate works. But when you -distribute the same sections as part of a whole which is a work based -on the Program, the distribution of the whole must be on the terms of -this License, whose permissions for other licensees extend to the -entire whole, and thus to each and every part regardless of who wrote it. - -Thus, it is not the intent of this section to claim rights or contest -your rights to work written entirely by you; rather, the intent is to -exercise the right to control the distribution of derivative or -collective works based on the Program. - -In addition, mere aggregation of another work not based on the Program -with the Program (or with a work based on the Program) on a volume of -a storage or distribution medium does not bring the other work under -the scope of this License. - - 3. You may copy and distribute the Program (or a work based on it, -under Section 2) in object code or executable form under the terms of -Sections 1 and 2 above provided that you also do one of the following: - - a) Accompany it with the complete corresponding machine-readable - source code, which must be distributed under the terms of Sections - 1 and 2 above on a medium customarily used for software interchange; or, - - b) Accompany it with a written offer, valid for at least three - years, to give any third party, for a charge no more than your - cost of physically performing source distribution, a complete - machine-readable copy of the corresponding source code, to be - distributed under the terms of Sections 1 and 2 above on a medium - customarily used for software interchange; or, - - c) Accompany it with the information you received as to the offer - to distribute corresponding source code. (This alternative is - allowed only for noncommercial distribution and only if you - received the program in object code or executable form with such - an offer, in accord with Subsection b above.) - -The source code for a work means the preferred form of the work for -making modifications to it. For an executable work, complete source -code means all the source code for all modules it contains, plus any -associated interface definition files, plus the scripts used to -control compilation and installation of the executable. However, as a -special exception, the source code distributed need not include -anything that is normally distributed (in either source or binary -form) with the major components (compiler, kernel, and so on) of the -operating system on which the executable runs, unless that component -itself accompanies the executable. - -If distribution of executable or object code is made by offering -access to copy from a designated place, then offering equivalent -access to copy the source code from the same place counts as -distribution of the source code, even though third parties are not -compelled to copy the source along with the object code. - - 4. You may not copy, modify, sublicense, or distribute the Program -except as expressly provided under this License. Any attempt -otherwise to copy, modify, sublicense or distribute the Program is -void, and will automatically terminate your rights under this License. -However, parties who have received copies, or rights, from you under -this License will not have their licenses terminated so long as such -parties remain in full compliance. - - 5. You are not required to accept this License, since you have not -signed it. However, nothing else grants you permission to modify or -distribute the Program or its derivative works. These actions are -prohibited by law if you do not accept this License. Therefore, by -modifying or distributing the Program (or any work based on the -Program), you indicate your acceptance of this License to do so, and -all its terms and conditions for copying, distributing or modifying -the Program or works based on it. - - 6. Each time you redistribute the Program (or any work based on the -Program), the recipient automatically receives a license from the -original licensor to copy, distribute or modify the Program subject to -these terms and conditions. You may not impose any further -restrictions on the recipients' exercise of the rights granted herein. -You are not responsible for enforcing compliance by third parties to -this License. - - 7. If, as a consequence of a court judgment or allegation of patent -infringement or for any other reason (not limited to patent issues), -conditions are imposed on you (whether by court order, agreement or -otherwise) that contradict the conditions of this License, they do not -excuse you from the conditions of this License. If you cannot -distribute so as to satisfy simultaneously your obligations under this -License and any other pertinent obligations, then as a consequence you -may not distribute the Program at all. For example, if a patent -license would not permit royalty-free redistribution of the Program by -all those who receive copies directly or indirectly through you, then -the only way you could satisfy both it and this License would be to -refrain entirely from distribution of the Program. - -If any portion of this section is held invalid or unenforceable under -any particular circumstance, the balance of the section is intended to -apply and the section as a whole is intended to apply in other -circumstances. - -It is not the purpose of this section to induce you to infringe any -patents or other property right claims or to contest validity of any -such claims; this section has the sole purpose of protecting the -integrity of the free software distribution system, which is -implemented by public license practices. Many people have made -generous contributions to the wide range of software distributed -through that system in reliance on consistent application of that -system; it is up to the author/donor to decide if he or she is willing -to distribute software through any other system and a licensee cannot -impose that choice. - -This section is intended to make thoroughly clear what is believed to -be a consequence of the rest of this License. - - 8. If the distribution and/or use of the Program is restricted in -certain countries either by patents or by copyrighted interfaces, the -original copyright holder who places the Program under this License -may add an explicit geographical distribution limitation excluding -those countries, so that distribution is permitted only in or among -countries not thus excluded. In such case, this License incorporates -the limitation as if written in the body of this License. - - 9. The Free Software Foundation may publish revised and/or new versions -of the General Public License from time to time. Such new versions will -be similar in spirit to the present version, but may differ in detail to -address new problems or concerns. - -Each version is given a distinguishing version number. If the Program -specifies a version number of this License which applies to it and "any -later version", you have the option of following the terms and conditions -either of that version or of any later version published by the Free -Software Foundation. If the Program does not specify a version number of -this License, you may choose any version ever published by the Free Software -Foundation. - - 10. If you wish to incorporate parts of the Program into other free -programs whose distribution conditions are different, write to the author -to ask for permission. For software which is copyrighted by the Free -Software Foundation, write to the Free Software Foundation; we sometimes -make exceptions for this. Our decision will be guided by the two goals -of preserving the free status of all derivatives of our free software and -of promoting the sharing and reuse of software generally. - - NO WARRANTY - - 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY -FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN -OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES -PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED -OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS -TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE -PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, -REPAIR OR CORRECTION. - - 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING -WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR -REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, -INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING -OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED -TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY -YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER -PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE -POSSIBILITY OF SUCH DAMAGES. - - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs - - If you develop a new program, and you want it to be of the greatest -possible use to the public, the best way to achieve this is to make it -free software which everyone can redistribute and change under these terms. - - To do so, attach the following notices to the program. It is safest -to attach them to the start of each source file to most effectively -convey the exclusion of warranty; and each file should have at least -the "copyright" line and a pointer to where the full notice is found. - - {description} - Copyright (C) {year} {fullname} - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2 of the License, or - (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License along - with this program; if not, write to the Free Software Foundation, Inc., - 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. - -Also add information on how to contact you by electronic and paper mail. - -If the program is interactive, make it output a short notice like this -when it starts in an interactive mode: - - Gnomovision version 69, Copyright (C) year name of author - Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. - This is free software, and you are welcome to redistribute it - under certain conditions; type `show c' for details. - -The hypothetical commands `show w' and `show c' should show the appropriate -parts of the General Public License. Of course, the commands you use may -be called something other than `show w' and `show c'; they could even be -mouse-clicks or menu items--whatever suits your program. - -You should also get your employer (if you work as a programmer) or your -school, if any, to sign a "copyright disclaimer" for the program, if -necessary. Here is a sample; alter the names: - - Yoyodyne, Inc., hereby disclaims all copyright interest in the program - `Gnomovision' (which makes passes at compilers) written by James Hacker. - - {signature of Ty Coon}, 1 April 1989 - Ty Coon, President of Vice - -This General Public License does not permit incorporating your program into -proprietary programs. If your program is a subroutine library, you may -consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Lesser General -Public License instead of this License. diff --git a/README.md b/README.md index f7a5d9f..80cc8b9 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ The test runner uses `prepare.php` to set up a WordPress checkout and prepare it The Gutenberg build step: 1. Uses the Gutenberg version pinned by WordPress Core (`gutenberg.sha` in `package.json`). -2. Downloads the corresponding pre-built Gutenberg artifact from GitHub Container Registry (`ghcr.io`), so the server must be able to connect to `ghcr.io`. +2. Downloads the corresponding pre-built Gutenberg artifact from GitHub Container Registry (`ghcr.io`). The download redirects to `pkg-containers.githubusercontent.com`, so the server must be able to connect to both domains. 3. Copies the required Gutenberg files into the WordPress `src/` directory. 4. Makes those files available to the WordPress installation that PHPUnit loads during the test run. diff --git a/cleanup-db.php b/cleanup-db.php deleted file mode 100644 index 0f41e8c..0000000 --- a/cleanup-db.php +++ /dev/null @@ -1,266 +0,0 @@ - 'php -- /path/to/test/dir' < cleanup-db.php - * - * or executed directly when the tests ran locally: - * - * php cleanup-db.php /path/to/test/dir - * - * Database credentials are read from the wp-tests-config.php file inside the - * given directory, exactly as the test suite read them, so no password ever - * appears on a command line or in a process list. The file is parsed rather - * than included, because prepare.php prepends a logger with side effects to - * the generated configuration. - * - * Exit code 0 means every matching table was dropped. Exit code 1 means the - * cleanup could not run or did not complete; the caller treats that as a - * warning, not as a fatal error. - * - * @link https://github.com/wordpress/phpunit-test-runner/ Original source repository - * - * @package WordPress - */ - -// phpcs:disable WordPress.DB.RestrictedFunctions, WordPress.DB.RestrictedClasses -- WordPress is not loaded in this standalone script, so $wpdb is unavailable by design and mysqli is used directly. See the file docblock. - -// Report mysqli failures through return values on every PHP version rather -// than exceptions, which became the default in PHP 8.1. -mysqli_report( MYSQLI_REPORT_OFF ); - -/** - * Writes a message to STDERR and exits with a failure code. - * - * @param string $message The message to display. - */ -function wpt_db_cleanup_fail( $message ) { - fwrite( STDERR, 'Database cleanup: ' . $message . PHP_EOL ); - exit( 1 ); -} - -/** - * Extracts a single-quoted or double-quoted PHP string literal assignment - * from configuration file contents. - * - * Handles the formats produced by wp-tests-config-sample.php and prepare.php, - * such as `define( 'DB_NAME', 'value' );` and `$table_prefix = 'wptests_';`. - * Escaped quotes and backslashes inside the literal are unescaped. - * - * @param string $contents The configuration file contents. - * @param string $pattern Regular expression with the literal in group 2 and - * its quote character in group 1. - * @return string|null The parsed value, or null when not found. - */ -function wpt_db_cleanup_parse( $contents, $pattern ) { - if ( 1 !== preg_match( $pattern, $contents, $matches ) ) { - return null; - } - $quote = $matches[1]; - - // Unescape in a single pass, so an escaped backslash is never rescanned. - return strtr( - $matches[2], - array( - '\\\\' => '\\', - '\\' . $quote => $quote, - ) - ); -} - -/** - * Reads one constant defined in the configuration file contents. - * - * @param string $contents The configuration file contents. - * @param string $name The constant name, for example 'DB_NAME'. - * @return string|null The constant value, or null when not found. - */ -function wpt_db_cleanup_constant( $contents, $name ) { - $name = preg_quote( $name, '/' ); - - return wpt_db_cleanup_parse( - $contents, - '/^[ \t]*define\s*\(\s*[\'"]' . $name . '[\'"]\s*,\s*([\'"])((?:\\\\.|(?!\1).)*)\1\s*\)/m' - ); -} - -/** - * Splits a DB_HOST value into host, port and socket. - * - * This mirrors wpdb::parse_db_host(), so every DB_HOST notation the test - * suite accepted is interpreted the same way here: `host`, `host:port`, - * `host:/path/to/socket`, IPv6 addresses with or without brackets, and a - * bracketed IPv6 address with a port. - * - * @param string $db_host The DB_HOST value from the configuration. - * @return array|false Host, port (int|null) and socket (string|null), in - * that order, or false when the value cannot be parsed. - */ -function wpt_db_cleanup_parse_host( $db_host ) { - $socket = null; - - // First peel off the socket parameter from the right, if it exists. - $socket_pos = strpos( $db_host, ':/' ); - if ( false !== $socket_pos ) { - $socket = substr( $db_host, $socket_pos + 1 ); - $db_host = substr( $db_host, 0, $socket_pos ); - } - - /* - * An IPv6 address will always contain at least two colons. Anything - * else is treated as IPv4 or a hostname, where at most one port - * suffix can follow. - */ - if ( substr_count( $db_host, ':' ) > 1 ) { - $pattern = '#^(?:\[)?(?P[0-9a-fA-F:]+)(?:\]:(?P[\d]+))?#'; - } else { - $pattern = '#^(?P[^:/]*)(?::(?P[\d]+))?#'; - } - - if ( 1 !== preg_match( $pattern, $db_host, $matches ) ) { - return false; - } - - $host = ! empty( $matches['host'] ) ? $matches['host'] : ''; - $port = ! empty( $matches['port'] ) ? (int) $matches['port'] : null; - - return array( $host, $port, $socket ); -} - -if ( empty( $argv[1] ) ) { - wpt_db_cleanup_fail( 'usage: php cleanup-db.php ' ); -} - -$config_path = rtrim( $argv[1], '/' ) . '/wp-tests-config.php'; - -if ( ! is_readable( $config_path ) ) { - wpt_db_cleanup_fail( 'configuration file not found: ' . $config_path ); -} - -if ( ! extension_loaded( 'mysqli' ) ) { - wpt_db_cleanup_fail( 'the mysqli extension is not available.' ); -} - -$config_contents = file_get_contents( $config_path ); - -$db_name = wpt_db_cleanup_constant( $config_contents, 'DB_NAME' ); -$db_user = wpt_db_cleanup_constant( $config_contents, 'DB_USER' ); -$db_pass = wpt_db_cleanup_constant( $config_contents, 'DB_PASSWORD' ); -$db_host = wpt_db_cleanup_constant( $config_contents, 'DB_HOST' ); -$prefix = wpt_db_cleanup_parse( - $config_contents, - '/^[ \t]*\$table_prefix\s*=\s*([\'"])((?:\\\\.|(?!\1).)*)\1\s*;/m' -); - -if ( null === $db_name || '' === $db_name || null === $db_user || '' === $db_user || null === $db_pass || null === $db_host || '' === $db_host ) { - wpt_db_cleanup_fail( 'could not parse the database settings from ' . $config_path ); -} - -// Refuse to run with an empty prefix: the LIKE pattern would match every -// table in the database, not only the ones the test suite created. -if ( null === $prefix || '' === $prefix ) { - wpt_db_cleanup_fail( 'could not determine a non-empty $table_prefix from ' . $config_path ); -} - -$parsed_host = wpt_db_cleanup_parse_host( $db_host ); - -if ( false === $parsed_host ) { - wpt_db_cleanup_fail( 'could not parse the DB_HOST value: ' . $db_host ); -} - -list( $host, $port, $socket ) = $parsed_host; - -if ( null !== $socket ) { - $mysqli = new mysqli( $host, $db_user, $db_pass, $db_name, null === $port ? (int) ini_get( 'mysqli.default_port' ) : $port, $socket ); -} elseif ( null !== $port ) { - $mysqli = new mysqli( $host, $db_user, $db_pass, $db_name, $port ); -} else { - $mysqli = new mysqli( $host, $db_user, $db_pass, $db_name ); -} - -if ( $mysqli->connect_errno ) { - wpt_db_cleanup_fail( 'could not connect to the database: ' . $mysqli->connect_error ); -} - -/* - * Collect every base table whose name starts with the test table prefix. - * This covers the tables of multisite sub-sites, such as wptests_2_posts, - * and tables left behind by older WordPress branches or interrupted runs, - * which a fixed list of current core tables would miss. - * - * LIKE wildcard characters in the prefix are escaped, so the underscore in - * the default wptests_ prefix matches only a literal underscore. - */ -$statement = $mysqli->prepare( - 'SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = \'BASE TABLE\' AND TABLE_NAME LIKE ?' -); - -if ( false === $statement ) { - wpt_db_cleanup_fail( 'could not prepare the table lookup: ' . $mysqli->error ); -} - -$like = addcslashes( $prefix, '\\_%' ) . '%'; -$statement->bind_param( 's', $like ); - -if ( ! $statement->execute() ) { - wpt_db_cleanup_fail( 'could not list the test tables: ' . $statement->error ); -} - -$tables = array(); -$table = ''; -$statement->bind_result( $table ); - -/* - * fetch() returns true for a row, null when the rows are exhausted and - * false on error. Treating an error as the end of the list would drop - * only part of the tables while still reporting success. - */ -while ( true ) { - $fetch_result = $statement->fetch(); - if ( true !== $fetch_result ) { - break; - } - $tables[] = $table; -} - -if ( false === $fetch_result ) { - wpt_db_cleanup_fail( 'could not read the table list: ' . $statement->error ); -} - -$statement->close(); - -if ( array() === $tables ) { - echo 'Database cleanup: no tables with prefix ' . $prefix . ' found.' . PHP_EOL; - $mysqli->close(); - exit( 0 ); -} - -$mysqli->query( 'SET foreign_key_checks = 0' ); - -$failed = array(); -foreach ( $tables as $table_name ) { - $escaped = '`' . str_replace( '`', '``', $table_name ) . '`'; - if ( ! $mysqli->query( 'DROP TABLE ' . $escaped ) ) { - $failed[] = $table_name . ' (' . $mysqli->error . ')'; - } -} - -$mysqli->query( 'SET foreign_key_checks = 1' ); -$mysqli->close(); - -if ( array() !== $failed ) { - wpt_db_cleanup_fail( 'could not drop: ' . implode( ', ', $failed ) ); -} - -echo 'Database cleanup: dropped ' . count( $tables ) . ' tables with prefix ' . $prefix . '.' . PHP_EOL; -exit( 0 ); diff --git a/cleanup.php b/cleanup.php deleted file mode 100644 index e8f12aa..0000000 --- a/cleanup.php +++ /dev/null @@ -1,72 +0,0 @@ -=7.4" - }, - "require-dev": { - "squizlabs/php_codesniffer": "^3.10", - "wp-coding-standards/wpcs": "^3.1" - }, - "scripts": { - "format": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcbf --report=summary,source", - "lint": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcs --report=summary,source", - "lint:errors": "@lint -n" - }, - "config": { - "allow-plugins": { - "dealerdirect/phpcodesniffer-composer-installer": true - } - } -} diff --git a/composer.lock b/composer.lock deleted file mode 100644 index 790eaca..0000000 --- a/composer.lock +++ /dev/null @@ -1,437 +0,0 @@ -{ - "_readme": [ - "This file locks the dependencies of your project to a known state", - "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", - "This file is @generated automatically" - ], - "content-hash": "79d9a0c20b4f79f48f5eac80ed70f5bb", - "packages": [], - "packages-dev": [ - { - "name": "dealerdirect/phpcodesniffer-composer-installer", - "version": "v1.2.1", - "source": { - "type": "git", - "url": "https://github.com/PHPCSStandards/composer-installer.git", - "reference": "963f0c67bffde0eac41b56be71ac0e8ba132f0bd" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/PHPCSStandards/composer-installer/zipball/963f0c67bffde0eac41b56be71ac0e8ba132f0bd", - "reference": "963f0c67bffde0eac41b56be71ac0e8ba132f0bd", - "shasum": "" - }, - "require": { - "composer-plugin-api": "^2.2", - "php": ">=5.4", - "squizlabs/php_codesniffer": "^3.1.0 || ^4.0" - }, - "require-dev": { - "composer/composer": "^2.2", - "ext-json": "*", - "ext-zip": "*", - "php-parallel-lint/php-parallel-lint": "^1.4.0", - "phpcompatibility/php-compatibility": "^9.0 || ^10.0.0@dev", - "yoast/phpunit-polyfills": "^1.0" - }, - "type": "composer-plugin", - "extra": { - "class": "PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" - }, - "autoload": { - "psr-4": { - "PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Franck Nijhof", - "email": "opensource@frenck.dev", - "homepage": "https://frenck.dev", - "role": "Open source developer" - }, - { - "name": "Contributors", - "homepage": "https://github.com/PHPCSStandards/composer-installer/graphs/contributors" - } - ], - "description": "PHP_CodeSniffer Standards Composer Installer Plugin", - "keywords": [ - "PHPCodeSniffer", - "PHP_CodeSniffer", - "code quality", - "codesniffer", - "composer", - "installer", - "phpcbf", - "phpcs", - "plugin", - "qa", - "quality", - "standard", - "standards", - "style guide", - "stylecheck", - "tests" - ], - "support": { - "issues": "https://github.com/PHPCSStandards/composer-installer/issues", - "security": "https://github.com/PHPCSStandards/composer-installer/security/policy", - "source": "https://github.com/PHPCSStandards/composer-installer" - }, - "funding": [ - { - "url": "https://github.com/PHPCSStandards", - "type": "github" - }, - { - "url": "https://github.com/jrfnl", - "type": "github" - }, - { - "url": "https://opencollective.com/php_codesniffer", - "type": "open_collective" - }, - { - "url": "https://thanks.dev/u/gh/phpcsstandards", - "type": "thanks_dev" - } - ], - "time": "2026-05-06T08:26:05+00:00" - }, - { - "name": "phpcsstandards/phpcsextra", - "version": "1.5.1", - "source": { - "type": "git", - "url": "https://github.com/PHPCSStandards/PHPCSExtra.git", - "reference": "39467533fdb742446d68c1d10ac33d625ee0311c" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/PHPCSStandards/PHPCSExtra/zipball/39467533fdb742446d68c1d10ac33d625ee0311c", - "reference": "39467533fdb742446d68c1d10ac33d625ee0311c", - "shasum": "" - }, - "require": { - "php": ">=5.4", - "phpcsstandards/phpcsutils": "^1.2.3", - "squizlabs/php_codesniffer": "^3.13.5 || ^4.0.1" - }, - "require-dev": { - "php-parallel-lint/php-console-highlighter": "^1.0", - "php-parallel-lint/php-parallel-lint": "^1.4.0", - "phpcsstandards/phpcsdevcs": "^1.2.0", - "phpcsstandards/phpcsdevtools": "^1.2.1", - "phpunit/phpunit": "^4.5 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4" - }, - "type": "phpcodesniffer-standard", - "extra": { - "branch-alias": { - "dev-stable": "1.x-dev", - "dev-develop": "1.x-dev" - } - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "LGPL-3.0-or-later" - ], - "authors": [ - { - "name": "Juliette Reinders Folmer", - "homepage": "https://github.com/jrfnl", - "role": "lead" - }, - { - "name": "Contributors", - "homepage": "https://github.com/PHPCSStandards/PHPCSExtra/graphs/contributors" - } - ], - "description": "A collection of sniffs and standards for use with PHP_CodeSniffer.", - "keywords": [ - "PHP_CodeSniffer", - "phpcbf", - "phpcodesniffer-standard", - "phpcs", - "standards", - "static analysis" - ], - "support": { - "issues": "https://github.com/PHPCSStandards/PHPCSExtra/issues", - "security": "https://github.com/PHPCSStandards/PHPCSExtra/security/policy", - "source": "https://github.com/PHPCSStandards/PHPCSExtra" - }, - "funding": [ - { - "url": "https://github.com/PHPCSStandards", - "type": "github" - }, - { - "url": "https://github.com/jrfnl", - "type": "github" - }, - { - "url": "https://opencollective.com/php_codesniffer", - "type": "open_collective" - }, - { - "url": "https://thanks.dev/u/gh/phpcsstandards", - "type": "thanks_dev" - } - ], - "time": "2026-07-27T11:13:17+00:00" - }, - { - "name": "phpcsstandards/phpcsutils", - "version": "1.2.3", - "source": { - "type": "git", - "url": "https://github.com/PHPCSStandards/PHPCSUtils.git", - "reference": "5f35d9408c54d7b529501f3c688b6eae562aea1f" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/PHPCSStandards/PHPCSUtils/zipball/5f35d9408c54d7b529501f3c688b6eae562aea1f", - "reference": "5f35d9408c54d7b529501f3c688b6eae562aea1f", - "shasum": "" - }, - "require": { - "dealerdirect/phpcodesniffer-composer-installer": "^0.4.1 || ^0.5 || ^0.6.2 || ^0.7 || ^1.0", - "php": ">=5.4", - "squizlabs/php_codesniffer": "^3.13.5 || ^4.0.1" - }, - "require-dev": { - "ext-filter": "*", - "php-parallel-lint/php-console-highlighter": "^1.0", - "php-parallel-lint/php-parallel-lint": "^1.4.0", - "phpcsstandards/phpcsdevcs": "^1.2.0", - "yoast/phpunit-polyfills": "^1.1.0 || ^2.0.0 || ^3.0.0" - }, - "type": "phpcodesniffer-standard", - "extra": { - "branch-alias": { - "dev-stable": "1.x-dev", - "dev-develop": "1.x-dev" - } - }, - "autoload": { - "classmap": [ - "PHPCSUtils/" - ] - }, - "notification-url": "https://packagist.org/downloads/", - "license": [ - "LGPL-3.0-or-later" - ], - "authors": [ - { - "name": "Juliette Reinders Folmer", - "homepage": "https://github.com/jrfnl", - "role": "lead" - }, - { - "name": "Contributors", - "homepage": "https://github.com/PHPCSStandards/PHPCSUtils/graphs/contributors" - } - ], - "description": "A suite of utility functions for use with PHP_CodeSniffer", - "homepage": "https://phpcsutils.com/", - "keywords": [ - "PHP_CodeSniffer", - "phpcbf", - "phpcodesniffer-standard", - "phpcs", - "phpcs3", - "phpcs4", - "standards", - "static analysis", - "tokens", - "utility" - ], - "support": { - "docs": "https://phpcsutils.com/", - "issues": "https://github.com/PHPCSStandards/PHPCSUtils/issues", - "security": "https://github.com/PHPCSStandards/PHPCSUtils/security/policy", - "source": "https://github.com/PHPCSStandards/PHPCSUtils" - }, - "funding": [ - { - "url": "https://github.com/PHPCSStandards", - "type": "github" - }, - { - "url": "https://github.com/jrfnl", - "type": "github" - }, - { - "url": "https://opencollective.com/php_codesniffer", - "type": "open_collective" - }, - { - "url": "https://thanks.dev/u/gh/phpcsstandards", - "type": "thanks_dev" - } - ], - "time": "2026-07-27T10:28:41+00:00" - }, - { - "name": "squizlabs/php_codesniffer", - "version": "3.13.6", - "source": { - "type": "git", - "url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git", - "reference": "4c378e1a528ea066890fc2397cbdd2f94eb2fc91" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/4c378e1a528ea066890fc2397cbdd2f94eb2fc91", - "reference": "4c378e1a528ea066890fc2397cbdd2f94eb2fc91", - "shasum": "" - }, - "require": { - "ext-simplexml": "*", - "ext-tokenizer": "*", - "ext-xmlwriter": "*", - "php": ">=5.4.0" - }, - "require-dev": { - "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4" - }, - "bin": [ - "bin/phpcbf", - "bin/phpcs" - ], - "type": "library", - "notification-url": "https://packagist.org/downloads/", - "license": [ - "BSD-3-Clause" - ], - "authors": [ - { - "name": "Greg Sherwood", - "role": "Former lead" - }, - { - "name": "Juliette Reinders Folmer", - "role": "Current lead" - }, - { - "name": "Contributors", - "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer/graphs/contributors" - } - ], - "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", - "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer", - "keywords": [ - "phpcs", - "standards", - "static analysis" - ], - "support": { - "issues": "https://github.com/PHPCSStandards/PHP_CodeSniffer/issues", - "security": "https://github.com/PHPCSStandards/PHP_CodeSniffer/security/policy", - "source": "https://github.com/PHPCSStandards/PHP_CodeSniffer", - "wiki": "https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki" - }, - "funding": [ - { - "url": "https://github.com/PHPCSStandards", - "type": "github" - }, - { - "url": "https://github.com/jrfnl", - "type": "github" - }, - { - "url": "https://opencollective.com/php_codesniffer", - "type": "open_collective" - }, - { - "url": "https://thanks.dev/u/gh/phpcsstandards", - "type": "thanks_dev" - } - ], - "time": "2026-08-06T00:17:32+00:00" - }, - { - "name": "wp-coding-standards/wpcs", - "version": "3.4.1", - "source": { - "type": "git", - "url": "https://github.com/WordPress/WordPress-Coding-Standards.git", - "reference": "ec2ff942335f33683a5957a85d138753876a05cf" - }, - "dist": { - "type": "zip", - "url": "https://api.github.com/repos/WordPress/WordPress-Coding-Standards/zipball/ec2ff942335f33683a5957a85d138753876a05cf", - "reference": "ec2ff942335f33683a5957a85d138753876a05cf", - "shasum": "" - }, - "require": { - "ext-filter": "*", - "ext-libxml": "*", - "ext-tokenizer": "*", - "ext-xmlreader": "*", - "php": ">=7.2", - "phpcsstandards/phpcsextra": "^1.5.1", - "phpcsstandards/phpcsutils": "^1.2.3", - "squizlabs/php_codesniffer": "^3.13.5" - }, - "require-dev": { - "php-parallel-lint/php-console-highlighter": "^1.0.0", - "php-parallel-lint/php-parallel-lint": "^1.4.0", - "phpcompatibility/php-compatibility": "^10.0.0@dev", - "phpcsstandards/phpcsdevtools": "^1.2.0", - "phpunit/phpunit": "^8.0 || ^9.0" - }, - "suggest": { - "ext-iconv": "For improved results", - "ext-mbstring": "For improved results" - }, - "type": "phpcodesniffer-standard", - "notification-url": "https://packagist.org/downloads/", - "license": [ - "MIT" - ], - "authors": [ - { - "name": "Contributors", - "homepage": "https://github.com/WordPress/WordPress-Coding-Standards/graphs/contributors" - } - ], - "description": "PHP_CodeSniffer rules (sniffs) to enforce WordPress coding conventions", - "keywords": [ - "phpcs", - "standards", - "static analysis", - "wordpress" - ], - "support": { - "issues": "https://github.com/WordPress/WordPress-Coding-Standards/issues", - "source": "https://github.com/WordPress/WordPress-Coding-Standards", - "wiki": "https://github.com/WordPress/WordPress-Coding-Standards/wiki" - }, - "funding": [ - { - "url": "https://opencollective.com/php_codesniffer", - "type": "custom" - } - ], - "time": "2026-07-27T11:53:23+00:00" - } - ], - "aliases": [], - "minimum-stability": "stable", - "stability-flags": {}, - "prefer-stable": false, - "prefer-lowest": false, - "platform": { - "php": ">=7.4" - }, - "platform-dev": {}, - "plugin-api-version": "2.9.0" -} diff --git a/functions.php b/functions.php deleted file mode 100644 index 66ec652..0000000 --- a/functions.php +++ /dev/null @@ -1,734 +0,0 @@ - '' !== $test_dir ? $test_dir : '/tmp/wp-test-runner', - ); - - return array_merge( - $runner_configuration, - array( - 'WPT_PREPARE_DIR' => '' !== $prepare_dir ? $prepare_dir : '/tmp/wp-test-runner', - 'WPT_SSH_CONNECT' => trim( getenv( 'WPT_SSH_CONNECT' ) ), - 'WPT_SSH_OPTIONS' => '' !== $ssh_options ? $ssh_options : '-o StrictHostKeyChecking=no', - 'WPT_PHP_EXECUTABLE' => '' !== $php_exec ? $php_exec : 'php', - 'WPT_RM_TEST_DIR_CMD' => '' !== $rm_test_dir ? $rm_test_dir : 'rm -rf ' . escapeshellarg( $runner_configuration['WPT_TEST_DIR'] ), - 'WPT_REPORT_API_KEY' => trim( getenv( 'WPT_REPORT_API_KEY' ) ), - 'WPT_DEBUG' => (bool) getenv( 'WPT_DEBUG' ), - ) - ); -} - -/** - * Executes a set of shell commands. - * - * Each command is logged before being executed. - * - * When a non-zero return code is encountered, the error message is displayed - * and the runner will fail. - * - * @param array $operations A list of shell commands (strings) to execute. - * Each command should be a valid shell command and properly escaped for safety. - * The commands are executed in the order they appear in the array. - * - * @return void This function does not return a value. However, it will output - * the result of each shell command to the standard output and log the - * execution. It will also halt on the first command that fails, displaying an - * error message. - * - * @uses log_message() to log each operation before execution. This can be used - * for debugging or auditing purposes. - * - * @uses passthru() to execute the shell command, which provides direct output - * to the browser. Be aware that using this function with untrusted input can - * lead to security vulnerabilities, such as command injection attacks. - * - * @uses error_message() to display an error message if a shell command fails. - * The execution stops at the first failure. - */ -function perform_operations( $operations ) { - foreach ( $operations as $operation ) { - log_message( $operation ); - passthru( $operation, $return_code ); - - // Check for command execution failure. - if ( 0 !== $return_code ) { - error_message( 'Failed to perform operation: ' . $operation . '.' ); - return; - } - } -} - -/** - * Writes a message to the standard output (STDOUT). - * - * The message is appended with PHP_EOL to ensure proper line breaks on - * different operating systems. - * - * @param string $message The message to be logged. - * - * @return void This function does not return a value. It directly writes the - * message to STDOUT, which is typically visible in the console or terminal - * where the PHP script is executed. - * - * @uses fwrite() to write the message to STDOUT. This is a low-level file - * operation function that works with various file streams, including standard - * output, standard error, and regular files. - */ -function log_message( $message ) { - fwrite( STDOUT, $message . PHP_EOL ); -} - -/** - * Displays an error message and terminates the test runner execution. - * - * The error message is prefixed with "Error: " and appended with PHP_EOL - * before being written to the standard output (STDOUT). - * - * After outputting the error message, the script will be terminated with a - * status code of 1. - * - * @param string $message The error message to be logged. This string will be - * output as provided, but prefixed with "Error: " to indicate its nature, - * followed by a system-specific newline character. - * - * @return void This function does not return a value. It directly writes the - * error message to STDERR and then terminates the script execution using - * `exit(1)`, indicating an error condition to the environment. - * - * @uses fwrite() to write the error message to STDERR. This function is used - * for low-level writing to file streams or output streams, in this case, - * STDERR, which is specifically for error reporting. - */ -function error_message( $message ) { - fwrite( STDERR, 'Error: ' . $message . PHP_EOL ); - exit( 1 ); -} - -/** - * Ensures a single trailing slash is present at the end of a given string. - * - * File system operations often expect a single trailing slash when referring - * to directories or paths. This ensures that only one trailing slash is - * present at the end of a given string. - * - * @param string $string The input string to which a trailing slash will be - * added. This could be a file path, URL, or any other string that requires a - * trailing slash for proper formatting or usage. - * - * @return string The modified string with a single trailing slash appended at - * the end. If the input string already has one or more trailing slashes, they - * will be trimmed to a single slash. - * - * @uses rtrim() to remove any existing trailing slashes from the input string - * before appending a new trailing slash. This ensures that the result - * consistently has exactly one trailing slash, regardless of the input string's - * initial state. - */ -function trailingslashit( $str ) { - return rtrim( $str, '/' ) . '/'; -} - -/** - * Extracts test results from a JUnit XML string. - * - * This extracts the relevant information from the test results into a format - * accepted and understood by the WordPress Test Reporter plugin. - * - * The data specifically extracted is: - * - Total number of tests. - * - Number of failures. - * - Number of errors. - * - Overall execution time. - * - * When the XML data is missing, empty, unparseable, or carries no usable - * result counts, execution stops with an error instead of returning an - * empty or hollow result, because such a result is either rejected much - * later with a confusing error or displayed in a misleading way. See - * issue #311. - * - * @param string $xml_string The JUnit XML data as a string. This should be - * well-formed XML representing the results of test executions, typically - * generated by testing frameworks compatible with JUnit reporting. - * - * @return string A JSON encoded string that represents a summary of the test - * results, including overall metrics and detailed information about each failed - * or errored test case. The JSON structure will include keys for 'tests', - * 'failures', 'errors', 'time', and 'testsuites', where 'testsuites' is an - * array of test suites that contains the failures or errors. - * - * @uses simplexml_load_string() to parse the JUnit XML data into an object for - * easy access and manipulation of the XML elements. - * - * @uses xpath() to query specific elements within the XML structure, - * particularly to find test suites with failures or errors. - * - * @uses json_encode() to convert the array structure containing the test - * results into a JSON formatted string. - */ -function process_junit_xml( $xml_string ) { - if ( empty( $xml_string ) ) { - error_message( 'junit.xml is missing or empty, so there are no test results to report. Aborting instead of reporting an empty result as a success. See https://github.com/WordPress/phpunit-test-runner/issues/311.' ); - } - - $previous_libxml_setting = libxml_use_internal_errors( true ); - libxml_clear_errors(); - - $xml = simplexml_load_string( $xml_string ); - - $errors = libxml_get_errors(); - libxml_clear_errors(); - libxml_use_internal_errors( $previous_libxml_setting ); - - if ( false === $xml ) { - $detail = ''; - if ( ! empty( $errors ) ) { - $first = $errors[0]; - $detail = ' First parser error: ' . trim( $first->message ) . ' at line ' . (int) $first->line . '.'; - } - error_message( 'junit.xml could not be parsed as XML, so the test results are unreadable. Aborting instead of reporting an unreadable result as a success.' . $detail . ' See https://github.com/WordPress/phpunit-test-runner/issues/311.' ); - } - - $xml_string = null; - - // PHPUnit wraps everything in , but a root - // element is also a legitimate JUnit shape from other producers. - $project = 'testsuite' === $xml->getName() ? $xml : $xml->testsuite; - $results = array(); - - if ( - ! isset( $project['tests'] ) || '' === (string) $project['tests'] || - ! isset( $project['failures'] ) || '' === (string) $project['failures'] || - ! isset( $project['errors'] ) || '' === (string) $project['errors'] - ) { - error_message( 'junit.xml parsed but contains no usable test result counts, so the test results are unusable. A result without failure and error counts would be displayed as a success. Aborting instead. See https://github.com/WordPress/phpunit-test-runner/issues/311.' ); - } - - $results = array( - 'tests' => (string) $project['tests'], - 'failures' => (string) $project['failures'], - 'errors' => (string) $project['errors'], - 'time' => (string) $project['time'], - ); - - $results['testsuites'] = array(); - - $testsuites = $xml->xpath( '//testsuite[ ( count( testcase ) > 0 ) and ( @errors > 0 or @failures > 0 ) ]' ); - foreach ( $testsuites as $testsuite ) { - $result = array( - 'name' => (string) $testsuite['name'], - 'tests' => (string) $testsuite['tests'], - 'failures' => (string) $testsuite['failures'], - 'errors' => (string) $testsuite['errors'], - ); - - if ( empty( $result['failures'] ) && empty( $result['errors'] ) ) { - continue; - } - $failures = array(); - foreach ( $testsuite->testcase as $testcase ) { - // Capture both failure and error children. - foreach ( array( 'failure', 'error' ) as $key ) { - if ( isset( $testcase->{$key} ) ) { - $failures[ (string) $testcase['name'] ] = array( - 'name' => (string) $testcase['name'], - $key => (string) $testcase->{$key}, - ); - } - } - } - if ( $failures ) { - $results['testsuites'][ (string) $testsuite['name'] ] = $result; - $results['testsuites'][ (string) $testsuite['name'] ]['testcases'] = $failures; - } - } - - return json_encode( $results ); -} - -/** - * Submits test results to a reporting API endpoint. - * - * This submits test results and related metadata to a site running the - * WordPress Test Reporter plugin using cURL. - * - * Reports are always submitted to WordPress.org Unless the WPT_REPORT_URL - * environment variable is set. - * - * @param string $results The test results in a processed format (e.g., JSON) - * ready for submission to the reporting API. - * - * @param string $rev The SVN revision associated with the test results. This - * often corresponds to a specific code commit or build identifier. - * - * @param string $message The SVN commit message associated with the revision, - * providing context or notes about the changes. - * - * @param string $env The environment data in JSON format, detailing the - * conditions under which the tests were run, such as operating system, PHP - * version, etc. - * - * @param string $api_key The API key for authenticating with the reporting API, - * ensuring secure and authorized access. - * - * @return array An array containing two elements: the HTTP status code of the - * response (int) and the body of the response (string) from the reporting API. - * This can be used to verify successful submission or to handle errors. - * - * @uses curl_init(), curl_setopt(), and curl_exec() to perform the HTTP POST - * request to the reporting API. - * - * @uses json_encode() to encode the data payload as a JSON string for - * submission. - * - * @uses base64_encode() to encode the API key for HTTP Basic Authentication in - * the Authorization header. - */ -function upload_results( $results, $rev, $message, $env, $api_key ) { - $wpt_report_url = getenv( 'WPT_REPORT_URL' ); - if ( ! $wpt_report_url ) { - $wpt_report_url = 'https://make.wordpress.org/hosting/wp-json/wp-unit-test-api/v1/results'; - } - $process = curl_init( $wpt_report_url ); - $access_token = base64_encode( $api_key ); - $data = array( - 'results' => $results, - 'commit' => $rev, - 'message' => $message, - 'env' => $env, - ); - $data_string = json_encode( $data ); - - // Set CURL options. - curl_setopt( $process, CURLOPT_TIMEOUT, 30 ); - curl_setopt( $process, CURLOPT_POST, 1 ); - curl_setopt( $process, CURLOPT_CUSTOMREQUEST, 'POST' ); - curl_setopt( $process, CURLOPT_USERAGENT, 'WordPress PHPUnit Test Runner' ); - curl_setopt( $process, CURLOPT_POSTFIELDS, $data_string ); - curl_setopt( $process, CURLOPT_RETURNTRANSFER, true ); - curl_setopt( - $process, - CURLOPT_HTTPHEADER, - array( - "Authorization: Basic $access_token", - 'Content-Type: application/json', - 'Content-Length: ' . strlen( $data_string ), - ) - ); - - $return = curl_exec( $process ); - $status_code = curl_getinfo( $process, CURLINFO_HTTP_CODE ); - curl_close( $process ); - - return array( $status_code, $return ); -} - -/** - * Parse a WordPress-style database host into mysqli connection pieces. - * - * @param string $host Database host string. - * - * @return array|false Parsed connection pieces, or false on invalid input. - */ -function wpt_runner_parse_db_host( $host ) { - $host = (string) $host; - $socket = null; - $port = null; - $is_ipv6 = false; - - if ( '' === $host ) { - return false; - } - - $socket_pos = strpos( $host, ':/' ); - if ( false !== $socket_pos ) { - $socket = substr( $host, $socket_pos + 1 ); - $host = substr( $host, 0, $socket_pos ); - } - - if ( substr_count( $host, ':' ) > 1 ) { - if ( 1 !== preg_match( '/^(?:\[(?P[0-9a-fA-F:.]+)\](?::(?P[0-9]+))?|(?P[0-9a-fA-F:.]+))$/', $host, $matches ) ) { - return false; - } - $parsed_host = ! empty( $matches['host'] ) ? $matches['host'] : ( isset( $matches['host_unbracketed'] ) ? $matches['host_unbracketed'] : '' ); - $is_ipv6 = true; - } else { - if ( 1 !== preg_match( '/^(?P[^:]*)(?::(?P[0-9]+))?$/', $host, $matches ) ) { - return false; - } - $parsed_host = $matches['host']; - } - - if ( '' === $parsed_host ) { - return false; - } - - if ( isset( $matches['port'] ) && '' !== $matches['port'] ) { - $port = (int) $matches['port']; - } - - return array( - 'host' => $parsed_host, - 'port' => $port, - 'socket' => $socket, - 'is_ipv6' => $is_ipv6, - ); -} - -// The report.php fallback runs without WordPress bootstrap, so $wpdb is unavailable. -// phpcs:disable WordPress.DB.RestrictedFunctions -- Direct mysqli is limited to database version reporting. -/** - * Gets the database server version, if it can be detected safely. - * - * @param string $db_host Database host. - * @param string $db_user Database user. - * @param string $db_password Database password. - * @param string $db_name Database name. - * - * @return string Raw server version string, or an empty string. - */ -function wpt_runner_get_db_server_version( $db_host, $db_user, $db_password, $db_name ) { - $db_host = trim( (string) $db_host ); - $db_user = trim( (string) $db_user ); - $db_password = (string) $db_password; - $db_name = trim( (string) $db_name ); - - if ( '' === $db_host ) { - $db_host = 'localhost'; - } - - if ( '' === $db_user || '' === $db_name ) { - return ''; - } - - if ( ! class_exists( 'mysqli' ) ) { - return ''; - } - - $required_functions = array( - 'mysqli_close', - 'mysqli_fetch_row', - 'mysqli_free_result', - 'mysqli_init', - 'mysqli_options', - 'mysqli_query', - 'mysqli_real_connect', - ); - - foreach ( $required_functions as $function_name ) { - if ( ! function_exists( $function_name ) ) { - return ''; - } - } - - $parsed_host = wpt_runner_parse_db_host( $db_host ); - if ( false === $parsed_host ) { - return ''; - } - $connect_host = $parsed_host['host']; - // mysqlnd expects IPv6 hosts in brackets, matching WordPress core's connection handling. - if ( $parsed_host['is_ipv6'] && extension_loaded( 'mysqlnd' ) ) { - $connect_host = '[' . $connect_host . ']'; - } - - $mysqli = null; - $mysqli_report_mode = null; - - try { - if ( class_exists( 'mysqli_driver' ) ) { - $mysqli_driver = new mysqli_driver(); - $mysqli_report_mode = $mysqli_driver->report_mode; - } - - if ( function_exists( 'mysqli_report' ) ) { - mysqli_report( MYSQLI_REPORT_OFF ); - } - - $mysqli = mysqli_init(); - if ( false === $mysqli ) { - return ''; - } - - if ( defined( 'MYSQLI_OPT_CONNECT_TIMEOUT' ) ) { - mysqli_options( $mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, 5 ); - } - - if ( ! @mysqli_real_connect( - $mysqli, - $connect_host, - $db_user, - $db_password, - $db_name, - $parsed_host['port'], - $parsed_host['socket'] - ) ) { - return ''; - } - - $result = @mysqli_query( $mysqli, 'SELECT VERSION()' ); - if ( ! is_object( $result ) ) { - return ''; - } - - $row = mysqli_fetch_row( $result ); - mysqli_free_result( $result ); - - if ( ! is_array( $row ) || ! isset( $row[0] ) || '' === (string) $row[0] ) { - return ''; - } - - return (string) $row[0]; - } catch ( Throwable $e ) { - return ''; - } finally { - if ( $mysqli instanceof mysqli ) { - @mysqli_close( $mysqli ); - } - if ( null !== $mysqli_report_mode && function_exists( 'mysqli_report' ) ) { - mysqli_report( $mysqli_report_mode ); - } - } -} - -// phpcs:enable WordPress.DB.RestrictedFunctions - -/** - * Collects details about the testing environment. - * - * The versions of PHP, PHP modules, database software, and system utilities - * can impact the results of the test suite. This gathers the relevant details - * to include in test report submissions. - * - * @return array An associative array containing detailed environment - * information. The array includes: - * - 'php_version': The current PHP version. - * - 'php_modules': An associative array of selected PHP modules and their versions. - * - 'system_utils': Versions of certain system utilities such as 'curl', 'imagemagick', - * 'graphicsmagick', and 'openssl'. - * - 'mysql_version': The version of the database server. - * - 'os_name': The name of the operating system. - * - 'os_version': The version of the operating system. - * - * @uses phpversion() to get the PHP version and module versions. - * - * @uses shell_exec() to execute system commands for retrieving OS details - * and versions of utilities like curl and OpenSSL. - * - * @uses class_exists() to check for the availability of the Imagick and Gmagick - * classes for version detection. - */ -function get_env_details() { - - $gd_info = array(); - if ( extension_loaded( 'gd' ) ) { - $gd_info = gd_info(); - } - $imagick_info = array(); - if ( extension_loaded( 'imagick' ) ) { - $imagick_info = Imagick::queryFormats(); - } - - $wpt_db_host = trim( getenv( 'WPT_DB_HOST' ) ); - if ( ! $wpt_db_host ) { - $wpt_db_host = 'localhost'; - } - $wpt_db_user = trim( getenv( 'WPT_DB_USER' ) ); - $wpt_db_password = getenv( 'WPT_DB_PASSWORD' ); - if ( false === $wpt_db_password ) { - $wpt_db_password = ''; - } - $wpt_db_name = trim( getenv( 'WPT_DB_NAME' ) ); - - $env = array( - 'php_version' => phpversion(), - 'php_modules' => array(), - 'gd_info' => $gd_info, - 'imagick_info' => $imagick_info, - 'mysql_version' => wpt_runner_get_db_server_version( $wpt_db_host, $wpt_db_user, $wpt_db_password, $wpt_db_name ), - 'system_utils' => array(), - 'os_name' => trim( shell_exec( 'uname -s' ) ), - 'os_version' => trim( shell_exec( 'uname -r' ) ), - ); - unset( $gd_info, $imagick_info ); - - $php_modules = array( - 'bcmath', - 'ctype', - 'curl', - 'date', - 'dom', - 'exif', - 'fileinfo', - 'filter', - 'ftp', - 'gd', - 'gettext', - 'gmagick', - 'hash', - 'iconv', - 'imagick', - 'imap', - 'intl', - 'json', - 'libsodium', - 'libxml', - 'mbstring', - 'mcrypt', - 'mod_xml', - 'mysqli', - 'mysqlnd', - 'openssl', - 'pcre', - 'pdo_mysql', - 'soap', - 'sockets', - 'sodium', - 'xml', - 'xmlreader', - 'zip', - 'zlib', - ); - foreach ( $php_modules as $php_module ) { - $env['php_modules'][ $php_module ] = phpversion( $php_module ); - } - - function curl_selected_bits( $k ) { - return in_array( $k, array( 'version', 'ssl_version', 'libz_version' ), true ); - } - $curl_bits = curl_version(); - $env['system_utils']['curl'] = implode( ' ', array_values( array_filter( $curl_bits, 'curl_selected_bits', ARRAY_FILTER_USE_KEY ) ) ); - - if ( class_exists( 'Imagick' ) ) { - $imagick = new Imagick(); - $version = $imagick->getVersion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); - $env['system_utils']['imagemagick'] = $version[1]; - } elseif ( class_exists( 'Gmagick' ) ) { - $gmagick = new Gmagick(); - $version = $gmagick->getversion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); - $env['system_utils']['graphicsmagick'] = $version[1]; - } - - $env['system_utils']['openssl'] = str_replace( 'OpenSSL ', '', trim( shell_exec( 'openssl version' ) ) ); - - return $env; -} - -/** - * Drops the WordPress test tables so the next run starts clean. - * - * Stale rows survive the test suite's own install step, because WordPress - * boots before the tables are dropped and writes data it loaded into memory, - * such as user roles, back into the fresh tables. See issue #110. - * - * The tables live in the test environment, so when an SSH connection is - * configured the cleanup-db.php script is piped to the remote PHP binary on - * stdin. The script reads the database credentials from wp-tests-config.php - * in the test directory, so no password appears on any command line. - * - * A failure is reported as a warning rather than stopping execution, so the - * directory cleanup in cleanup.php always runs. Set the WPT_SKIP_DB_CLEANUP - * environment variable to skip this step entirely. - * - * @param array $runner_vars Test runner configuration options. - * - * @uses log_message() to log the executed command and any warning. - */ -function cleanup_database( $runner_vars ) { - if ( (bool) getenv( 'WPT_SKIP_DB_CLEANUP' ) ) { - log_message( 'WPT_SKIP_DB_CLEANUP is set, skipping database cleanup.' ); - return; - } - - $script = __DIR__ . '/cleanup-db.php'; - - if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { - $remote_command = $runner_vars['WPT_PHP_EXECUTABLE'] . ' -- ' . escapeshellarg( $runner_vars['WPT_TEST_DIR'] ); - $command = 'ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] ) . ' ' . escapeshellarg( $remote_command ) . ' < ' . escapeshellarg( $script ); - } else { - $command = $runner_vars['WPT_PHP_EXECUTABLE'] . ' ' . escapeshellarg( $script ) . ' ' . escapeshellarg( $runner_vars['WPT_TEST_DIR'] ); - } - - log_message( $command ); - passthru( $command, $return_code ); - - if ( 0 !== $return_code ) { - log_message( 'Warning: database cleanup did not complete, continuing with directory cleanup.' ); - } -} diff --git a/phpcs.xml.dist b/phpcs.xml.dist deleted file mode 100644 index a32f244..0000000 --- a/phpcs.xml.dist +++ /dev/null @@ -1,64 +0,0 @@ - - - Apply WordPress Coding Standards to all test runner files. - - - - - - - - - - - - - - - - - - - - - - - - . - - - /vendor/* - - - - - - - - - - warning - - - diff --git a/prepare.php b/prepare.php deleted file mode 100644 index 16d6d75..0000000 --- a/prepare.php +++ /dev/null @@ -1,527 +0,0 @@ - 1 ) { - if ( 1 !== preg_match( '/^(?:\[(?P[0-9a-fA-F:.]+)\](?::(?P[0-9]+))?|(?P[0-9a-fA-F:.]+))$/', $host, $matches ) ) { - return false; - } - $parsed_host = ! empty( $matches['host'] ) ? $matches['host'] : ( isset( $matches['host_unbracketed'] ) ? $matches['host_unbracketed'] : '' ); - $is_ipv6 = true; - } else { - if ( 1 !== preg_match( '/^(?P[^:]*)(?::(?P[0-9]+))?$/', $host, $matches ) ) { - return false; - } - $parsed_host = $matches['host']; - } - - if ( '' === $parsed_host ) { - return false; - } - - if ( isset( $matches['port'] ) && '' !== $matches['port'] ) { - $port = (int) $matches['port']; - } - - return array( - 'host' => $parsed_host, - 'port' => $port, - 'socket' => $socket, - 'is_ipv6' => $is_ipv6, - ); - } -} -if ( ! function_exists( 'wpt_runner_get_db_server_version' ) ) { - - // wp-tests-config.php is read before WordPress creates the global $wpdb. - // Using $wpdb here can leave the database server version empty during bootstrap. - // phpcs:disable WordPress.DB.RestrictedFunctions -- Direct mysqli is limited to database version reporting. - function wpt_runner_get_db_server_version( $db_host, $db_user, $db_password, $db_name ) { - $db_host = trim( (string) $db_host ); - $db_user = trim( (string) $db_user ); - $db_password = (string) $db_password; - $db_name = trim( (string) $db_name ); - - if ( '' === $db_host ) { - $db_host = 'localhost'; - } - - if ( '' === $db_user || '' === $db_name ) { - return ''; - } - - if ( ! class_exists( 'mysqli' ) ) { - return ''; - } - - $required_functions = array( - 'mysqli_close', - 'mysqli_fetch_row', - 'mysqli_free_result', - 'mysqli_init', - 'mysqli_options', - 'mysqli_query', - 'mysqli_real_connect', - ); - - foreach ( $required_functions as $function_name ) { - if ( ! function_exists( $function_name ) ) { - return ''; - } - } - - $parsed_host = wpt_runner_parse_db_host( $db_host ); - if ( false === $parsed_host ) { - return ''; - } - $connect_host = $parsed_host['host']; - // mysqlnd expects IPv6 hosts in brackets, matching WordPress core's connection handling. - if ( $parsed_host['is_ipv6'] && extension_loaded( 'mysqlnd' ) ) { - $connect_host = '[' . $connect_host . ']'; - } - - $mysqli = null; - $mysqli_report_mode = null; - - try { - if ( class_exists( 'mysqli_driver' ) ) { - $mysqli_driver = new mysqli_driver(); - $mysqli_report_mode = $mysqli_driver->report_mode; - } - - if ( function_exists( 'mysqli_report' ) ) { - mysqli_report( MYSQLI_REPORT_OFF ); - } - - $mysqli = mysqli_init(); - if ( false === $mysqli ) { - return ''; - } - - if ( defined( 'MYSQLI_OPT_CONNECT_TIMEOUT' ) ) { - mysqli_options( $mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, 5 ); - } - - if ( ! @mysqli_real_connect( - $mysqli, - $connect_host, - $db_user, - $db_password, - $db_name, - $parsed_host['port'], - $parsed_host['socket'] - ) ) { - return ''; - } - - $result = @mysqli_query( $mysqli, 'SELECT VERSION()' ); - if ( ! is_object( $result ) ) { - return ''; - } - - $row = mysqli_fetch_row( $result ); - mysqli_free_result( $result ); - - if ( ! is_array( $row ) || ! isset( $row[0] ) || '' === (string) $row[0] ) { - return ''; - } - - return (string) $row[0]; - } catch ( Throwable $e ) { - return ''; - } finally { - if ( $mysqli instanceof mysqli ) { - @mysqli_close( $mysqli ); - } - if ( null !== $mysqli_report_mode && function_exists( 'mysqli_report' ) ) { - mysqli_report( $mysqli_report_mode ); - } - } - } - // phpcs:enable WordPress.DB.RestrictedFunctions -} -$env = array( - 'php_version' => phpversion(), - 'php_modules' => array(), - 'gd_info' => $gd_info, - 'imagick_info' => $imagick_info, - 'mysql_version' => wpt_runner_get_db_server_version( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME ), - 'system_utils' => array(), - 'os_name' => trim( shell_exec( 'uname -s' ) ), - 'os_version' => trim( shell_exec( 'uname -r' ) ), -); -$php_modules = array( - 'bcmath', - 'ctype', - 'curl', - 'date', - 'dom', - 'exif', - 'fileinfo', - 'filter', - 'ftp', - 'gd', - 'gettext', - 'gmagick', - 'hash', - 'iconv', - 'imagick', - 'imap', - 'intl', - 'json', - 'libsodium', - 'libxml', - 'mbstring', - 'mcrypt', - 'mod_xml', - 'mysqli', - 'mysqlnd', - 'openssl', - 'pcre', - 'pdo_mysql', - 'soap', - 'sockets', - 'sodium', - 'xml', - 'xmlreader', - 'zip', - 'zlib', -); -foreach ( $php_modules as $php_module ) { - $env['php_modules'][ $php_module ] = phpversion( $php_module ); -} -function curl_selected_bits( $k ) { - return in_array( $k, array( 'version', 'ssl_version', 'libz_version' ), true ); -} -$curl_bits = curl_version(); -$env['system_utils']['curl'] = implode( ' ', array_values( array_filter( $curl_bits, 'curl_selected_bits', ARRAY_FILTER_USE_KEY ) ) ); -if ( class_exists( 'Imagick' ) ) { - $imagick = new Imagick(); - $version = $imagick->getVersion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); - $env['system_utils']['imagemagick'] = $version[1]; -} elseif ( class_exists( 'Gmagick' ) ) { - $gmagick = new Gmagick(); - $version = $gmagick->getversion(); - preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); - $env['system_utils']['graphicsmagick'] = $version[1]; -} -$env['system_utils']['openssl'] = str_replace( 'OpenSSL ', '', trim( shell_exec( 'openssl version' ) ) ); -file_put_contents( __DIR__ . '/tests/phpunit/build/logs/env.json', json_encode( $env, JSON_PRETTY_PRINT ) ); -if ( 'cli' === php_sapi_name() && defined( 'WP_INSTALLING' ) && WP_INSTALLING ) { - echo PHP_EOL; - echo 'PHP version: ' . phpversion() . ' (' . realpath( $_SERVER['_'] ) . ')' . PHP_EOL; - echo PHP_EOL; -} -EOT; - -// Initialize a string that will be used to identify the post-database-settings section in the configuration file. -$logger_replace_string = 'define( \'DB_COLLATE\', \'\' );' . PHP_EOL; - -if ( false === strpos( $contents, $logger_replace_string ) ) { - error_message( 'Unable to insert the system logger after the database constants in wp-tests-config.php.' ); -} - -// Append the logger script to the database settings constants to ensure DB_* constants are available. -$system_logger = $logger_replace_string . $system_logger; - -// Define a string that will set the 'WP_PHP_BINARY' constant to the path of the PHP executable. -$php_binary_string = 'define( \'WP_PHP_BINARY\', \'' . $runner_vars['WPT_PHP_EXECUTABLE'] . '\' );'; - -/* - * Map configuration file placeholders to environment-specific values. - * - * This is used in the subsequent str_replace operation to replace placeholder - * values in the wp-tests-config-sample.php file with the ones provided. - */ -$wpt_table_prefix = trim( getenv( 'WPT_TABLE_PREFIX' ) ); -$search_replace = array( - 'wptests_' => '' !== $wpt_table_prefix ? $wpt_table_prefix : 'wptests_', - 'youremptytestdbnamehere' => trim( getenv( 'WPT_DB_NAME' ) ), - 'yourusernamehere' => trim( getenv( 'WPT_DB_USER' ) ), - 'yourpasswordhere' => trim( getenv( 'WPT_DB_PASSWORD' ) ), - 'localhost' => trim( getenv( 'WPT_DB_HOST' ) ), - 'define( \'WP_PHP_BINARY\', \'php\' );' => $php_binary_string, - $logger_replace_string => $system_logger, -); - -// Replace the placeholders in the wp-tests-config-sample.php file content with actual values. -$contents = str_replace( array_keys( $search_replace ), array_values( $search_replace ), $contents ); - -// Write the modified content to the wp-tests-config.php file, which will be used by the test suite. -file_put_contents( $runner_vars['WPT_PREPARE_DIR'] . '/wp-tests-config.php', $contents ); - -/* - * Construct a command that generates a PHP version string compatible with - * PHPUnit version requirements. - */ -$php_version_cmd = $runner_vars['WPT_PHP_EXECUTABLE'] . " -r \"print PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;\""; - -/** - * If an SSH connection string is provided, the command to determine the PHP version is modified - * to execute remotely over SSH. This is required if the test environment is not the local machine. - */ -if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { - // The PHP version check command is prefixed with the SSH command, including SSH options, - // and the connection string, ensuring the command is executed on the remote machine. - $php_version_cmd = 'ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] ) . ' ' . escapeshellarg( $php_version_cmd ); -} - -// Initialize return value variable for the exec function call. -$retval = 0; - -/* - * Execute the constructed command to obtain the PHP version of the test - * environment. - * - * The output is stored in $env_php_version and the return value of the - * command execution is stored in $retval. - */ -$env_php_version = exec( $php_version_cmd, $output, $retval ); - -// Check if the command execution was successful by inspecting the return value. -if ( 0 !== $retval ) { - error_message( 'Could not retrieve the environment PHP Version.' ); -} - -// Log the obtained PHP version for confirmation and debugging purposes. -log_message( 'Environment PHP Version: ' . $env_php_version ); - -/* - * Confirm that the environment meets the minimum PHP version requirement. - * - * When the requirements are not met, execution will end with an error message. - */ -if ( version_compare( $env_php_version, '7.2', '<' ) ) { - // Logs an error message indicating the test runner's incompatibility with PHP versions below 7.2. - error_message( 'The test runner is not compatible with PHP < 7.2.' ); -} - - -// Check if Composer is installed and available in the PATH. -$composer_cmd = 'cd ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] ) . ' && '; -$retval = 0; -$composer_path = escapeshellarg( system( 'which composer', $retval ) ); - -if ( 0 === $retval ) { - - // If Composer is available, prepare the command to use the Composer binary. - $composer_cmd .= $composer_path . ' '; - -} else { - - // If Composer is not available, download the Composer phar file. - log_message( 'Local Composer not found. Downloading latest stable ...' ); - - perform_operations( - array( - 'wget -O ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] . '/composer.phar' ) . ' https://getcomposer.org/composer-stable.phar', - ) - ); - - // Update the command to use the downloaded Composer phar file. - $composer_cmd .= $runner_vars['WPT_PHP_EXECUTABLE'] . ' composer.phar '; -} - -// Set the PHP version for Composer to ensure compatibility and update dependencies. -perform_operations( - array( - $composer_cmd . 'config platform.php ' . escapeshellarg( $env_php_version ), - $composer_cmd . 'update', - ) -); - -/* - * Transfer the built WordPress codebase to the remote test environment. - * - * When an SSH connection is configured, rsync is used to copy the files - * required to run the WordPress PHPUnit test suite. - * - * The -r option for rsync enables recursive copying to handle nested directory - * structures. - */ -if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { - // Initialize rsync options with recursive copying. - $rsync_options = '-r'; - - // If debug mode is set to verbose, append 'v' to rsync options for verbose output. - if ( $runner_vars['WPT_DEBUG'] ) { - $rsync_options = $rsync_options . 'v'; - } - - // Perform the rsync operation with the configured options and exclude patterns. - // This operation synchronizes the test environment with the prepared files, excluding - // version control directories and other non-essential files for test execution. - perform_operations( - array( - 'rsync ' . $rsync_options - . ' --exclude=".git/"' - . ' --exclude="node_modules/"' - . ' --exclude="composer.phar"' - . ' --exclude=".cache/"' - . ' --exclude=".devcontainer/"' - . ' --exclude=".github/"' - . ' --exclude="tools/"' - // Exclude all subdirectories in tests/ except phpunit/. - . ' --exclude="tests/*" --include="tests/phpunit/**"' - . ' -e "ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . '" ' - . escapeshellarg( trailingslashit( $runner_vars['WPT_PREPARE_DIR'] ) ) - . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] . ':' . $runner_vars['WPT_TEST_DIR'] ), - ) - ); -} - -// Log a success message indicating that the environment has been prepared. -log_message( 'Success: Prepared environment.' ); diff --git a/report.php b/report.php deleted file mode 100644 index b45ee39..0000000 --- a/report.php +++ /dev/null @@ -1,148 +0,0 @@ - Date: Wed, 7 Oct 2026 16:27:06 +0600 Subject: [PATCH 5/6] Restore files deleted by mistake in 4814a42 4814a42 recorded the deletion of 22 files that were missing from my local working copy. Restore them unchanged. The only change left from that commit is the ghcr.io redirect sentence in README.md. --- .env.default | 85 ++ .github/ISSUE_TEMPLATE/bug_report.md | 27 + .github/ISSUE_TEMPLATE/feature_request.md | 20 + .../ISSUE_TEMPLATE/test_reporter_request.md | 25 + .github/SECURITY.md | 23 + .github/dependabot.yml | 21 + .github/workflows/coding-standards.yml | 97 +++ .github/workflows/phpunit-tests.yml | 101 +++ .github/workflows/props-bot.yml | 92 +++ .github/workflows/tests.yml | 94 +++ .gitignore | 16 + .travis.yml | 16 + LICENSE | 339 ++++++++ cleanup-db.php | 266 +++++++ cleanup.php | 72 ++ composer.json | 22 + composer.lock | 437 +++++++++++ functions.php | 734 ++++++++++++++++++ phpcs.xml.dist | 64 ++ prepare.php | 527 +++++++++++++ report.php | 148 ++++ test.php | 79 ++ 22 files changed, 3305 insertions(+) create mode 100644 .env.default create mode 100644 .github/ISSUE_TEMPLATE/bug_report.md create mode 100644 .github/ISSUE_TEMPLATE/feature_request.md create mode 100644 .github/ISSUE_TEMPLATE/test_reporter_request.md create mode 100644 .github/SECURITY.md create mode 100644 .github/dependabot.yml create mode 100644 .github/workflows/coding-standards.yml create mode 100644 .github/workflows/phpunit-tests.yml create mode 100644 .github/workflows/props-bot.yml create mode 100644 .github/workflows/tests.yml create mode 100644 .gitignore create mode 100644 .travis.yml create mode 100644 LICENSE create mode 100644 cleanup-db.php create mode 100644 cleanup.php create mode 100644 composer.json create mode 100644 composer.lock create mode 100644 functions.php create mode 100644 phpcs.xml.dist create mode 100644 prepare.php create mode 100644 report.php create mode 100644 test.php diff --git a/.env.default b/.env.default new file mode 100644 index 0000000..df58ae0 --- /dev/null +++ b/.env.default @@ -0,0 +1,85 @@ +### +# Configuration environment variables used by the test runner +# +# # Create a copy for your local environment +# $ cp .env.default .env +# +# # Make any necessary changes to the default values +# $ vim .env +# +# # Load your variables into your environment +# $ source .env +### + +# Path to the directory where files can be prepared before being delivered to the environment. +export WPT_PREPARE_DIR="/tmp/wp-test-runner" + +# Path to the directory where the WordPress develop checkout can be placed and tests can be run. +# When running tests in the same environment, set WPT_TEST_DIR to WPT_PREPARE_DIR +export WPT_TEST_DIR="wp-test-runner" + +# API key to authenticate with the reporting service in 'username:password' format. +export WPT_REPORT_API_KEY="" + +# (Optionally) define an alternate reporting URL +export WPT_REPORT_URL="" + +# Credentials for a database that can be written to and reset. +# WARNING!!! This database will be destroyed between tests. Only use safe database credentials. +# Please note that you must escape _or_ refrain from using # as special character in your credentials. +export WPT_DB_NAME="" +export WPT_DB_USER="" +export WPT_DB_PASSWORD="" +export WPT_DB_HOST="" + +# (Optionally) set a custom table prefix to permit concurrency against the same database. +export WPT_TABLE_PREFIX="${WPT_TABLE_PREFIX-wptests_}" + +# (Optionally) define the PHP executable to be called +export WPT_PHP_EXECUTABLE="${WPT_PHP_EXECUTABLE-php}" + +# (Optionally) define the PHPUnit command execution call. +# Use if `php phpunit.phar` can't be called directly for some reason. +export WPT_PHPUNIT_CMD="" + +# (Optionally) define the command execution to remove the test directory +# Use if `rm -r` can't be called directly for some reason. +export WPT_RM_TEST_DIR_CMD="" + +# SSH connection string (can also be an alias). +# Leave empty if tests are meant to run in the same environment. +export WPT_SSH_CONNECT="" + +# Any options to be passed to the SSH connection +# Defaults to '-o StrictHostKeyChecking=no' +export WPT_SSH_OPTIONS="" + +# SSH private key, base64 encoded. +export WPT_SSH_PRIVATE_KEY_BASE64="" + +# Whether to enable debug Mode. +# +# Enabling debug mode will output verbose logging and details about each part +# of the test runner. +# +# 0 = Debug mode off +# 1 = Debug mode on +# +# Any other truthy value will also enable debug mode. +export WPT_DEBUG= + +# Certificate validation +# Use 1 to validate, and 0 to not validate +export WPT_CERTIFICATE_VALIDATION=1 + +# WordPress flavor +# 0 = WordPress (simple version) +# 1 = WordPress Multisite +export WPT_FLAVOR=0 + +# Extra tests (groups) +# 0 = none +# 1 = ajax +# 2 = ms-files +# 3 = external-http +export WPT_EXTRATESTS=0 diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..160740e --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,27 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +**Describe the bug** +A clear and concise description of what the bug is. + +**To Reproduce** +Steps to reproduce the behavior: +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +**Expected behavior** +A clear and concise description of what you expected to happen. + +**Screenshots** +If applicable, add screenshots to help explain your problem. + +**Additional context** +Add any other context about the problem here. diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..6532412 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. \ No newline at end of file diff --git a/.github/ISSUE_TEMPLATE/test_reporter_request.md b/.github/ISSUE_TEMPLATE/test_reporter_request.md new file mode 100644 index 0000000..8d821df --- /dev/null +++ b/.github/ISSUE_TEMPLATE/test_reporter_request.md @@ -0,0 +1,25 @@ +--- +name: Test Reporter request +about: Requesting your bot user to be added to this WordPress.org site as a “Test + Reporter”. +title: "[Test Reporter] " +labels: test-reporter-request +assignees: '' + +--- + +Requesting your bot user to be added to this WordPress.org site [as a “Test Reporter”](https://make.wordpress.org/hosting/test-results/). + +For more information, please visit the [Getting Started](https://make.wordpress.org/hosting/test-results-getting-started/) Guide or the [Hosting Handbook](https://make.wordpress.org/hosting/handbook/tests/). + +**Preconditions Checklist:** + +* [ ] I've added a Gravatar/logo to the profile. +* [ ] I've added a URL to the profile, to make it clear to users what hosting company is being represented in the results. +* [ ] I've set the email address to something monitored by a human. +* [ ] I've set the email address to one that uses the domain name of the hosting company. + +**Bot Profile Details:** + +* Bot email address: +* Bot WordPress profile: diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000..1d8dd95 --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1,23 @@ +# Security Policy + +## Supported scope + +The WordPress PHPUnit Test Runner is the tooling hosting providers use to run the WordPress core test suite and report results. This repository contains those scripts and their GitHub configuration. + +This policy covers security-sensitive issues in the code and configuration of this repository. It does not define support for WordPress core, plugins, themes, hosting stacks, server packages, or hosting platforms. + +## Reporting vulnerabilities + +For WordPress core, plugins, themes, WordPress.org, or the wider WordPress ecosystem, follow the official [WordPress security reporting guidance](https://wordpress.org/about/security/). WordPress core vulnerabilities should be reported through the [WordPress HackerOne program](https://hackerone.com/wordpress). + +Do not report exploitable security vulnerabilities in public GitHub issues or pull requests. For a vulnerability in the test runner scripts themselves, use the reporting channels from the official guidance above rather than a public issue, so hosts running the tooling are not exposed before a fix is available. + +If the vulnerability is in a hosting platform, server package, or other third-party project, report it to that project or vendor through their security reporting process. + +## Other issues + +If you find a bug or an insecure default in the test runner that is not an exploitable vulnerability, open a public issue in this repository: + +https://github.com/WordPress/phpunit-test-runner/issues + +Include the affected script, the behaviour you observed, and any safer replacement you are suggesting. Do not include exploit details or private vulnerability information in public issues. diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..f88fa2f --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,21 @@ +# Configure Dependabot scanning. +version: 2 + +updates: + # Check for updates to GitHub Actions. + - package-ecosystem: "github-actions" + directory: "/" + schedule: + interval: "daily" + open-pull-requests-limit: 10 + groups: + github-actions: + patterns: + - "*" + + # Check for updates to Composer packages. + - package-ecosystem: "composer" + directory: "/" + schedule: + interval: "weekly" + open-pull-requests-limit: 5 diff --git a/.github/workflows/coding-standards.yml b/.github/workflows/coding-standards.yml new file mode 100644 index 0000000..d8e21d9 --- /dev/null +++ b/.github/workflows/coding-standards.yml @@ -0,0 +1,97 @@ +name: Coding Standards + +on: + push: + branches: + - master + pull_request: + branches: + - master + paths: + - '**.php' + - 'composer.*' + - 'phpcs.xml.dist' + - '.github/workflows/coding-standards.yml' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + cancel-in-progress: true + +permissions: {} + +jobs: + lint: + name: PHP Syntax Check + runs-on: ubuntu-24.04 + timeout-minutes: 5 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} + persist-credentials: false + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.2' + coverage: none + + - name: Check PHP syntax + run: find . -name "*.php" -not -path "./.git/*" -not -path "./vendor/*" | xargs -n1 php -l + + phpcs: + name: Coding Standards + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} + persist-credentials: false + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '8.2' + coverage: none + tools: cs2pr + + - name: "Get last Monday's date" + id: get-date + run: echo "date=$(/bin/date -u --date='last Mon' "+%F")" >> "$GITHUB_OUTPUT" + + - name: Cache PHPCS scan cache + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: .cache/phpcs.json + key: ${{ runner.os }}-date-${{ steps.get-date.outputs.date }}-phpcs-cache-${{ hashFiles('**/composer.json', 'phpcs.xml.dist') }} + + - name: Install Composer dependencies + uses: ramsey/composer-install@65e4f84970763564f46a70b8a54b90d033b3bdda # 4.0.0 + with: + custom-cache-suffix: ${{ steps.get-date.outputs.date }} + + - name: Make Composer packages available globally + run: echo "${PWD}/vendor/bin" >> "$GITHUB_PATH" + + - name: Run PHPCS + id: phpcs + run: | + mkdir -p .cache + phpcs -n --report-full --cache=./.cache/phpcs.json --report-checkstyle=./.cache/phpcs-report.xml + + - name: Show PHPCS results in PR + if: ${{ always() && steps.phpcs.outcome == 'failure' }} + run: cs2pr ./.cache/phpcs-report.xml + + - name: Ensure version-controlled files are not modified or deleted + run: git diff --exit-code diff --git a/.github/workflows/phpunit-tests.yml b/.github/workflows/phpunit-tests.yml new file mode 100644 index 0000000..a0d8353 --- /dev/null +++ b/.github/workflows/phpunit-tests.yml @@ -0,0 +1,101 @@ +name: PHPUnit Tests + +on: + push: + branches: + - master + pull_request: + branches: + - master + paths: + - '**.php' + - '.github/workflows/phpunit-tests.yml' + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + cancel-in-progress: true + +permissions: {} + +jobs: + test: + name: PHP ${{ matrix.php }} / MySQL ${{ matrix.db-version }} + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read + + strategy: + fail-fast: false + matrix: + php: [ '7.4', '8.0', '8.2' ] + db-version: [ '8.0' ] + + services: + mysql: + image: mysql:${{ matrix.db-version }} + env: + MYSQL_ROOT_PASSWORD: root + MYSQL_DATABASE: wordpress_test + MYSQL_USER: wp_test + MYSQL_PASSWORD: wp_test + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + + env: + WPT_PREPARE_DIR: /tmp/wp-test-runner + WPT_TEST_DIR: /tmp/wp-test-runner + WPT_DB_NAME: wordpress_test + WPT_DB_USER: wp_test + WPT_DB_PASSWORD: wp_test + WPT_DB_HOST: 127.0.0.1 + WPT_REPORT_API_KEY: '' + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + show-progress: ${{ runner.debug == '1' && 'true' || 'false' }} + persist-credentials: false + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: ${{ matrix.php }} + coverage: none + + - name: Set up Node.js + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Prepare environment + run: php prepare.php + + - name: Run unit tests + run: php test.php + continue-on-error: true + + - name: Report results + run: php report.php + continue-on-error: true + + - name: Cleanup + run: php cleanup.php + + - name: Verify database cleanup + env: + MYSQL_PWD: wp_test + run: | + TABLES=$(mysql -h 127.0.0.1 -u wp_test wordpress_test -N -e "SHOW TABLES LIKE 'wptests\_%'") + if [ -n "$TABLES" ]; then + echo "Test tables remain after cleanup:" + echo "$TABLES" + exit 1 + fi diff --git a/.github/workflows/props-bot.yml b/.github/workflows/props-bot.yml new file mode 100644 index 0000000..61eca3e --- /dev/null +++ b/.github/workflows/props-bot.yml @@ -0,0 +1,92 @@ +name: Props Bot + +on: + # This event runs anytime a PR is (re)opened, updated, marked ready for review, or labeled. + # GitHub does not allow filtering the `labeled` event by a specific label. + # However, the logic below will short-circuit the workflow when the `props-bot` label is not the one being added. + # Note: The pull_request_target event is used instead of pull_request because this workflow needs permission to comment + # on the pull request. Because this event grants extra permissions to `GITHUB_TOKEN`, any code changes within the PR + # should be considered untrusted. See https://securitylab.github.com/research/github-actions-preventing-pwn-requests/. + pull_request_target: + types: + - opened + - synchronize + - reopened + - labeled + - ready_for_review + # This event runs anytime a comment is added or deleted. + # You cannot filter this event for PR comments only. + # However, the logic below does short-circuit the workflow for issues. + issue_comment: + types: + - created + # This event will run everytime a new PR review is initially submitted. + pull_request_review: + types: + - submitted + # This event runs anytime a PR review comment is created or deleted. + pull_request_review_comment: + types: + - created + +# Cancels all previous workflow runs for pull requests that have not completed. +concurrency: + # The concurrency group contains the workflow name and the branch name for pull requests + # or the commit hash for any other events. + group: ${{ github.workflow }}-${{ contains( fromJSON( '["pull_request_target", "pull_request_review", "pull_request_review_comment"]' ), github.event_name ) && github.head_ref || github.sha }} + cancel-in-progress: true + +# Disable permissions for all available scopes by default. +# Any needed permissions should be configured at the job level. +permissions: {} + +jobs: + # Compiles a list of props for a pull request. + # + # Performs the following steps: + # - Collects a list of contributor props and leaves a comment. + # - Removes the props-bot label, if necessary. + props-bot: + name: Generate a list of props + runs-on: ubuntu-24.04 + permissions: + # The action needs permission `write` permission for PRs in order to add a comment. + pull-requests: write + contents: read + timeout-minutes: 20 + # The job will run when pull requests are open, ready for review and: + # + # - A comment is added to the pull request. + # - A review is created or commented on (unless PR originates from a fork). + # - The pull request is opened, synchronized, marked ready for review, or reopened. + # - The `props-bot` label is added to the pull request. + if: | + ( + github.event_name == 'issue_comment' && github.event.issue.pull_request || + ( contains( fromJSON( '["pull_request_review", "pull_request_review_comment"]' ), github.event_name ) && ! github.event.pull_request.head.repo.fork ) || + github.event_name == 'pull_request_target' && github.event.action != 'labeled' || + 'props-bot' == github.event.label.name + ) && + ( ! github.event.pull_request.draft && github.event.pull_request.state == 'open' || ! github.event.issue.draft && github.event.issue.state == 'open' ) + + steps: + - name: Gather a list of contributors + uses: WordPress/props-bot-action@trunk + with: + format: 'git' + + - name: Remove the props-bot label + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + if: ${{ github.event.action == 'labeled' && 'props-bot' == github.event.label.name }} + with: + retries: 2 + retry-exempt-status-codes: 418 + script: | + github.rest.issues.removeLabel({ + owner: context.repo.owner, + repo: context.repo.repo, + issue_number: process.env.ISSUE_NUMBER, + name: 'props-bot' + }); + env: + ISSUE_NUMBER: ${{ github.event.number }} diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml new file mode 100644 index 0000000..4f9cee9 --- /dev/null +++ b/.github/workflows/tests.yml @@ -0,0 +1,94 @@ +name: WordPress PHPUnit tests + +on: + # The workflow should be run on a schedule using the 'schedule' event trigger. + # + # For more details on how to configure the schedule event, see https://docs.github.com/en/actions/reference/workflow-syntax-for-github-actions#onschedule. + # + # Below are some options for different schedules. Running the tests every hour is recommended, + # but every 3-6 hours is also helpful. Times are in UTC. + schedule: + # By default, the workflow will run every hour. + - cron: '0 * * * *' + # Every 3 hours. + # - cron: '0 0/3 * * *' + # Every 6 hours. + # - cron: '0 0/6 * * *' + # Every 12 hours. + # - cron: '0 0/12 * * *' + # Once per day at 00:00. + # - cron: '0 0 * * *' + # Every 30 minutes. + # - cron: '0/30 * * * *' + workflow_dispatch: + +# Cancels all previous workflow runs for pull requests that have not completed. +concurrency: + # The concurrency group contains the workflow name and the branch name for pull requests + # or the commit hash for any other events. + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + cancel-in-progress: true + +jobs: + # Tests the PHPUnit test runner. + # + # Performs the following steps: + # - Checks out the repository. + # - Installs PHP. + # - Installs NodeJS 14 with caching configured. + # - Prepares the environment for tests. + # - Runs the tests. + # - Reports the results. + # - Cleans up. + test: + name: Run Core PHPUnit tests + runs-on: ubuntu-latest + + # Remove this line if Github Actions is your preferred means of running the tests. + if: ${{ false }} + + env: + # This is only a subset/example of env vars available. See the `.env.default` file for a full list. + WPT_PREPARE_DIR: ${{ secrets.WPT_PREPARE_DIR }} + WPT_TEST_DIR: ${{ secrets.WPT_TEST_DIR }} + WPT_REPORT_API_KEY: ${{ secrets.WPT_REPORT_API_KEY }} + WPT_PHP_EXECUTABLE: ${{ secrets.WPT_PHP_EXECUTABLE }} + # Database settings + WPT_DB_NAME: ${{ secrets.WPT_DB_NAME }} + WPT_DB_USER: ${{ secrets.WPT_DB_USER }} + WPT_DB_PASSWORD: ${{ secrets.WPT_DB_PASSWORD }} + WPT_DB_HOST: ${{ secrets.WPT_DB_HOST }} + # SSH settings for connecting to the test environment. + WPT_SSH_CONNECT: ${{ secrets.WPT_SSH_CONNECT }} + WPT_SSH_PRIVATE_KEY_BASE64: ${{ secrets.WPT_SSH_PRIVATE_KEY_BASE64 }} + + steps: + - name: Checkout repository + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + + - name: Set up PHP + uses: shivammathur/setup-php@f3e473d116dcccaddc5834248c87452386958240 # v2.37.2 + with: + php-version: '7.4' + coverage: none + + - name: Install NodeJS + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0 + with: + node-version: 24 + + - name: Prepare environment + run: php prepare.php + + - name: Run unit tests + run: php test.php + # Prevent the workflow from stopping if there are test failures. + continue-on-error: true + + - name: Report the results + run: php report.php + # Prevent the workflow from stopping if the reporting fails. + continue-on-error: true + + - name: Cleanup + run: php cleanup.php diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..023e69a --- /dev/null +++ b/.gitignore @@ -0,0 +1,16 @@ +.DS_Store +.env* +vendor/ +.cache/ +package-lock.json +commit.json +ignore.json + +# Exclude the default test directory. +wp-test-runner/ + +# Files related to applying patches +*.rej +*.orig +*.patch +*.diff diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..4369ea3 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,16 @@ +language: php +node_js: + - 20 + +before_install: + - npm install -g npm@latest + +install: + - php prepare.php + +script: + - php test.php + +after_script: + - php report.php + - php cleanup.php diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..23cb790 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + {description} + Copyright (C) {year} {fullname} + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + {signature of Ty Coon}, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/cleanup-db.php b/cleanup-db.php new file mode 100644 index 0000000..0f41e8c --- /dev/null +++ b/cleanup-db.php @@ -0,0 +1,266 @@ + 'php -- /path/to/test/dir' < cleanup-db.php + * + * or executed directly when the tests ran locally: + * + * php cleanup-db.php /path/to/test/dir + * + * Database credentials are read from the wp-tests-config.php file inside the + * given directory, exactly as the test suite read them, so no password ever + * appears on a command line or in a process list. The file is parsed rather + * than included, because prepare.php prepends a logger with side effects to + * the generated configuration. + * + * Exit code 0 means every matching table was dropped. Exit code 1 means the + * cleanup could not run or did not complete; the caller treats that as a + * warning, not as a fatal error. + * + * @link https://github.com/wordpress/phpunit-test-runner/ Original source repository + * + * @package WordPress + */ + +// phpcs:disable WordPress.DB.RestrictedFunctions, WordPress.DB.RestrictedClasses -- WordPress is not loaded in this standalone script, so $wpdb is unavailable by design and mysqli is used directly. See the file docblock. + +// Report mysqli failures through return values on every PHP version rather +// than exceptions, which became the default in PHP 8.1. +mysqli_report( MYSQLI_REPORT_OFF ); + +/** + * Writes a message to STDERR and exits with a failure code. + * + * @param string $message The message to display. + */ +function wpt_db_cleanup_fail( $message ) { + fwrite( STDERR, 'Database cleanup: ' . $message . PHP_EOL ); + exit( 1 ); +} + +/** + * Extracts a single-quoted or double-quoted PHP string literal assignment + * from configuration file contents. + * + * Handles the formats produced by wp-tests-config-sample.php and prepare.php, + * such as `define( 'DB_NAME', 'value' );` and `$table_prefix = 'wptests_';`. + * Escaped quotes and backslashes inside the literal are unescaped. + * + * @param string $contents The configuration file contents. + * @param string $pattern Regular expression with the literal in group 2 and + * its quote character in group 1. + * @return string|null The parsed value, or null when not found. + */ +function wpt_db_cleanup_parse( $contents, $pattern ) { + if ( 1 !== preg_match( $pattern, $contents, $matches ) ) { + return null; + } + $quote = $matches[1]; + + // Unescape in a single pass, so an escaped backslash is never rescanned. + return strtr( + $matches[2], + array( + '\\\\' => '\\', + '\\' . $quote => $quote, + ) + ); +} + +/** + * Reads one constant defined in the configuration file contents. + * + * @param string $contents The configuration file contents. + * @param string $name The constant name, for example 'DB_NAME'. + * @return string|null The constant value, or null when not found. + */ +function wpt_db_cleanup_constant( $contents, $name ) { + $name = preg_quote( $name, '/' ); + + return wpt_db_cleanup_parse( + $contents, + '/^[ \t]*define\s*\(\s*[\'"]' . $name . '[\'"]\s*,\s*([\'"])((?:\\\\.|(?!\1).)*)\1\s*\)/m' + ); +} + +/** + * Splits a DB_HOST value into host, port and socket. + * + * This mirrors wpdb::parse_db_host(), so every DB_HOST notation the test + * suite accepted is interpreted the same way here: `host`, `host:port`, + * `host:/path/to/socket`, IPv6 addresses with or without brackets, and a + * bracketed IPv6 address with a port. + * + * @param string $db_host The DB_HOST value from the configuration. + * @return array|false Host, port (int|null) and socket (string|null), in + * that order, or false when the value cannot be parsed. + */ +function wpt_db_cleanup_parse_host( $db_host ) { + $socket = null; + + // First peel off the socket parameter from the right, if it exists. + $socket_pos = strpos( $db_host, ':/' ); + if ( false !== $socket_pos ) { + $socket = substr( $db_host, $socket_pos + 1 ); + $db_host = substr( $db_host, 0, $socket_pos ); + } + + /* + * An IPv6 address will always contain at least two colons. Anything + * else is treated as IPv4 or a hostname, where at most one port + * suffix can follow. + */ + if ( substr_count( $db_host, ':' ) > 1 ) { + $pattern = '#^(?:\[)?(?P[0-9a-fA-F:]+)(?:\]:(?P[\d]+))?#'; + } else { + $pattern = '#^(?P[^:/]*)(?::(?P[\d]+))?#'; + } + + if ( 1 !== preg_match( $pattern, $db_host, $matches ) ) { + return false; + } + + $host = ! empty( $matches['host'] ) ? $matches['host'] : ''; + $port = ! empty( $matches['port'] ) ? (int) $matches['port'] : null; + + return array( $host, $port, $socket ); +} + +if ( empty( $argv[1] ) ) { + wpt_db_cleanup_fail( 'usage: php cleanup-db.php ' ); +} + +$config_path = rtrim( $argv[1], '/' ) . '/wp-tests-config.php'; + +if ( ! is_readable( $config_path ) ) { + wpt_db_cleanup_fail( 'configuration file not found: ' . $config_path ); +} + +if ( ! extension_loaded( 'mysqli' ) ) { + wpt_db_cleanup_fail( 'the mysqli extension is not available.' ); +} + +$config_contents = file_get_contents( $config_path ); + +$db_name = wpt_db_cleanup_constant( $config_contents, 'DB_NAME' ); +$db_user = wpt_db_cleanup_constant( $config_contents, 'DB_USER' ); +$db_pass = wpt_db_cleanup_constant( $config_contents, 'DB_PASSWORD' ); +$db_host = wpt_db_cleanup_constant( $config_contents, 'DB_HOST' ); +$prefix = wpt_db_cleanup_parse( + $config_contents, + '/^[ \t]*\$table_prefix\s*=\s*([\'"])((?:\\\\.|(?!\1).)*)\1\s*;/m' +); + +if ( null === $db_name || '' === $db_name || null === $db_user || '' === $db_user || null === $db_pass || null === $db_host || '' === $db_host ) { + wpt_db_cleanup_fail( 'could not parse the database settings from ' . $config_path ); +} + +// Refuse to run with an empty prefix: the LIKE pattern would match every +// table in the database, not only the ones the test suite created. +if ( null === $prefix || '' === $prefix ) { + wpt_db_cleanup_fail( 'could not determine a non-empty $table_prefix from ' . $config_path ); +} + +$parsed_host = wpt_db_cleanup_parse_host( $db_host ); + +if ( false === $parsed_host ) { + wpt_db_cleanup_fail( 'could not parse the DB_HOST value: ' . $db_host ); +} + +list( $host, $port, $socket ) = $parsed_host; + +if ( null !== $socket ) { + $mysqli = new mysqli( $host, $db_user, $db_pass, $db_name, null === $port ? (int) ini_get( 'mysqli.default_port' ) : $port, $socket ); +} elseif ( null !== $port ) { + $mysqli = new mysqli( $host, $db_user, $db_pass, $db_name, $port ); +} else { + $mysqli = new mysqli( $host, $db_user, $db_pass, $db_name ); +} + +if ( $mysqli->connect_errno ) { + wpt_db_cleanup_fail( 'could not connect to the database: ' . $mysqli->connect_error ); +} + +/* + * Collect every base table whose name starts with the test table prefix. + * This covers the tables of multisite sub-sites, such as wptests_2_posts, + * and tables left behind by older WordPress branches or interrupted runs, + * which a fixed list of current core tables would miss. + * + * LIKE wildcard characters in the prefix are escaped, so the underscore in + * the default wptests_ prefix matches only a literal underscore. + */ +$statement = $mysqli->prepare( + 'SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA = DATABASE() AND TABLE_TYPE = \'BASE TABLE\' AND TABLE_NAME LIKE ?' +); + +if ( false === $statement ) { + wpt_db_cleanup_fail( 'could not prepare the table lookup: ' . $mysqli->error ); +} + +$like = addcslashes( $prefix, '\\_%' ) . '%'; +$statement->bind_param( 's', $like ); + +if ( ! $statement->execute() ) { + wpt_db_cleanup_fail( 'could not list the test tables: ' . $statement->error ); +} + +$tables = array(); +$table = ''; +$statement->bind_result( $table ); + +/* + * fetch() returns true for a row, null when the rows are exhausted and + * false on error. Treating an error as the end of the list would drop + * only part of the tables while still reporting success. + */ +while ( true ) { + $fetch_result = $statement->fetch(); + if ( true !== $fetch_result ) { + break; + } + $tables[] = $table; +} + +if ( false === $fetch_result ) { + wpt_db_cleanup_fail( 'could not read the table list: ' . $statement->error ); +} + +$statement->close(); + +if ( array() === $tables ) { + echo 'Database cleanup: no tables with prefix ' . $prefix . ' found.' . PHP_EOL; + $mysqli->close(); + exit( 0 ); +} + +$mysqli->query( 'SET foreign_key_checks = 0' ); + +$failed = array(); +foreach ( $tables as $table_name ) { + $escaped = '`' . str_replace( '`', '``', $table_name ) . '`'; + if ( ! $mysqli->query( 'DROP TABLE ' . $escaped ) ) { + $failed[] = $table_name . ' (' . $mysqli->error . ')'; + } +} + +$mysqli->query( 'SET foreign_key_checks = 1' ); +$mysqli->close(); + +if ( array() !== $failed ) { + wpt_db_cleanup_fail( 'could not drop: ' . implode( ', ', $failed ) ); +} + +echo 'Database cleanup: dropped ' . count( $tables ) . ' tables with prefix ' . $prefix . '.' . PHP_EOL; +exit( 0 ); diff --git a/cleanup.php b/cleanup.php new file mode 100644 index 0000000..e8f12aa --- /dev/null +++ b/cleanup.php @@ -0,0 +1,72 @@ +=7.4" + }, + "require-dev": { + "squizlabs/php_codesniffer": "^3.10", + "wp-coding-standards/wpcs": "^3.1" + }, + "scripts": { + "format": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcbf --report=summary,source", + "lint": "@php ./vendor/squizlabs/php_codesniffer/bin/phpcs --report=summary,source", + "lint:errors": "@lint -n" + }, + "config": { + "allow-plugins": { + "dealerdirect/phpcodesniffer-composer-installer": true + } + } +} diff --git a/composer.lock b/composer.lock new file mode 100644 index 0000000..790eaca --- /dev/null +++ b/composer.lock @@ -0,0 +1,437 @@ +{ + "_readme": [ + "This file locks the dependencies of your project to a known state", + "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", + "This file is @generated automatically" + ], + "content-hash": "79d9a0c20b4f79f48f5eac80ed70f5bb", + "packages": [], + "packages-dev": [ + { + "name": "dealerdirect/phpcodesniffer-composer-installer", + "version": "v1.2.1", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/composer-installer.git", + "reference": "963f0c67bffde0eac41b56be71ac0e8ba132f0bd" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/composer-installer/zipball/963f0c67bffde0eac41b56be71ac0e8ba132f0bd", + "reference": "963f0c67bffde0eac41b56be71ac0e8ba132f0bd", + "shasum": "" + }, + "require": { + "composer-plugin-api": "^2.2", + "php": ">=5.4", + "squizlabs/php_codesniffer": "^3.1.0 || ^4.0" + }, + "require-dev": { + "composer/composer": "^2.2", + "ext-json": "*", + "ext-zip": "*", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpcompatibility/php-compatibility": "^9.0 || ^10.0.0@dev", + "yoast/phpunit-polyfills": "^1.0" + }, + "type": "composer-plugin", + "extra": { + "class": "PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\Plugin" + }, + "autoload": { + "psr-4": { + "PHPCSStandards\\Composer\\Plugin\\Installers\\PHPCodeSniffer\\": "src/" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Franck Nijhof", + "email": "opensource@frenck.dev", + "homepage": "https://frenck.dev", + "role": "Open source developer" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/composer-installer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer Standards Composer Installer Plugin", + "keywords": [ + "PHPCodeSniffer", + "PHP_CodeSniffer", + "code quality", + "codesniffer", + "composer", + "installer", + "phpcbf", + "phpcs", + "plugin", + "qa", + "quality", + "standard", + "standards", + "style guide", + "stylecheck", + "tests" + ], + "support": { + "issues": "https://github.com/PHPCSStandards/composer-installer/issues", + "security": "https://github.com/PHPCSStandards/composer-installer/security/policy", + "source": "https://github.com/PHPCSStandards/composer-installer" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcsstandards", + "type": "thanks_dev" + } + ], + "time": "2026-05-06T08:26:05+00:00" + }, + { + "name": "phpcsstandards/phpcsextra", + "version": "1.5.1", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/PHPCSExtra.git", + "reference": "39467533fdb742446d68c1d10ac33d625ee0311c" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/PHPCSExtra/zipball/39467533fdb742446d68c1d10ac33d625ee0311c", + "reference": "39467533fdb742446d68c1d10ac33d625ee0311c", + "shasum": "" + }, + "require": { + "php": ">=5.4", + "phpcsstandards/phpcsutils": "^1.2.3", + "squizlabs/php_codesniffer": "^3.13.5 || ^4.0.1" + }, + "require-dev": { + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpcsstandards/phpcsdevcs": "^1.2.0", + "phpcsstandards/phpcsdevtools": "^1.2.1", + "phpunit/phpunit": "^4.5 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4" + }, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-stable": "1.x-dev", + "dev-develop": "1.x-dev" + } + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-or-later" + ], + "authors": [ + { + "name": "Juliette Reinders Folmer", + "homepage": "https://github.com/jrfnl", + "role": "lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHPCSExtra/graphs/contributors" + } + ], + "description": "A collection of sniffs and standards for use with PHP_CodeSniffer.", + "keywords": [ + "PHP_CodeSniffer", + "phpcbf", + "phpcodesniffer-standard", + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHPCSStandards/PHPCSExtra/issues", + "security": "https://github.com/PHPCSStandards/PHPCSExtra/security/policy", + "source": "https://github.com/PHPCSStandards/PHPCSExtra" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcsstandards", + "type": "thanks_dev" + } + ], + "time": "2026-07-27T11:13:17+00:00" + }, + { + "name": "phpcsstandards/phpcsutils", + "version": "1.2.3", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/PHPCSUtils.git", + "reference": "5f35d9408c54d7b529501f3c688b6eae562aea1f" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/PHPCSUtils/zipball/5f35d9408c54d7b529501f3c688b6eae562aea1f", + "reference": "5f35d9408c54d7b529501f3c688b6eae562aea1f", + "shasum": "" + }, + "require": { + "dealerdirect/phpcodesniffer-composer-installer": "^0.4.1 || ^0.5 || ^0.6.2 || ^0.7 || ^1.0", + "php": ">=5.4", + "squizlabs/php_codesniffer": "^3.13.5 || ^4.0.1" + }, + "require-dev": { + "ext-filter": "*", + "php-parallel-lint/php-console-highlighter": "^1.0", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpcsstandards/phpcsdevcs": "^1.2.0", + "yoast/phpunit-polyfills": "^1.1.0 || ^2.0.0 || ^3.0.0" + }, + "type": "phpcodesniffer-standard", + "extra": { + "branch-alias": { + "dev-stable": "1.x-dev", + "dev-develop": "1.x-dev" + } + }, + "autoload": { + "classmap": [ + "PHPCSUtils/" + ] + }, + "notification-url": "https://packagist.org/downloads/", + "license": [ + "LGPL-3.0-or-later" + ], + "authors": [ + { + "name": "Juliette Reinders Folmer", + "homepage": "https://github.com/jrfnl", + "role": "lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHPCSUtils/graphs/contributors" + } + ], + "description": "A suite of utility functions for use with PHP_CodeSniffer", + "homepage": "https://phpcsutils.com/", + "keywords": [ + "PHP_CodeSniffer", + "phpcbf", + "phpcodesniffer-standard", + "phpcs", + "phpcs3", + "phpcs4", + "standards", + "static analysis", + "tokens", + "utility" + ], + "support": { + "docs": "https://phpcsutils.com/", + "issues": "https://github.com/PHPCSStandards/PHPCSUtils/issues", + "security": "https://github.com/PHPCSStandards/PHPCSUtils/security/policy", + "source": "https://github.com/PHPCSStandards/PHPCSUtils" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcsstandards", + "type": "thanks_dev" + } + ], + "time": "2026-07-27T10:28:41+00:00" + }, + { + "name": "squizlabs/php_codesniffer", + "version": "3.13.6", + "source": { + "type": "git", + "url": "https://github.com/PHPCSStandards/PHP_CodeSniffer.git", + "reference": "4c378e1a528ea066890fc2397cbdd2f94eb2fc91" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/PHPCSStandards/PHP_CodeSniffer/zipball/4c378e1a528ea066890fc2397cbdd2f94eb2fc91", + "reference": "4c378e1a528ea066890fc2397cbdd2f94eb2fc91", + "shasum": "" + }, + "require": { + "ext-simplexml": "*", + "ext-tokenizer": "*", + "ext-xmlwriter": "*", + "php": ">=5.4.0" + }, + "require-dev": { + "phpunit/phpunit": "^4.0 || ^5.0 || ^6.0 || ^7.0 || ^8.0 || ^9.3.4" + }, + "bin": [ + "bin/phpcbf", + "bin/phpcs" + ], + "type": "library", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "BSD-3-Clause" + ], + "authors": [ + { + "name": "Greg Sherwood", + "role": "Former lead" + }, + { + "name": "Juliette Reinders Folmer", + "role": "Current lead" + }, + { + "name": "Contributors", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer tokenizes PHP, JavaScript and CSS files and detects violations of a defined set of coding standards.", + "homepage": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "keywords": [ + "phpcs", + "standards", + "static analysis" + ], + "support": { + "issues": "https://github.com/PHPCSStandards/PHP_CodeSniffer/issues", + "security": "https://github.com/PHPCSStandards/PHP_CodeSniffer/security/policy", + "source": "https://github.com/PHPCSStandards/PHP_CodeSniffer", + "wiki": "https://github.com/PHPCSStandards/PHP_CodeSniffer/wiki" + }, + "funding": [ + { + "url": "https://github.com/PHPCSStandards", + "type": "github" + }, + { + "url": "https://github.com/jrfnl", + "type": "github" + }, + { + "url": "https://opencollective.com/php_codesniffer", + "type": "open_collective" + }, + { + "url": "https://thanks.dev/u/gh/phpcsstandards", + "type": "thanks_dev" + } + ], + "time": "2026-08-06T00:17:32+00:00" + }, + { + "name": "wp-coding-standards/wpcs", + "version": "3.4.1", + "source": { + "type": "git", + "url": "https://github.com/WordPress/WordPress-Coding-Standards.git", + "reference": "ec2ff942335f33683a5957a85d138753876a05cf" + }, + "dist": { + "type": "zip", + "url": "https://api.github.com/repos/WordPress/WordPress-Coding-Standards/zipball/ec2ff942335f33683a5957a85d138753876a05cf", + "reference": "ec2ff942335f33683a5957a85d138753876a05cf", + "shasum": "" + }, + "require": { + "ext-filter": "*", + "ext-libxml": "*", + "ext-tokenizer": "*", + "ext-xmlreader": "*", + "php": ">=7.2", + "phpcsstandards/phpcsextra": "^1.5.1", + "phpcsstandards/phpcsutils": "^1.2.3", + "squizlabs/php_codesniffer": "^3.13.5" + }, + "require-dev": { + "php-parallel-lint/php-console-highlighter": "^1.0.0", + "php-parallel-lint/php-parallel-lint": "^1.4.0", + "phpcompatibility/php-compatibility": "^10.0.0@dev", + "phpcsstandards/phpcsdevtools": "^1.2.0", + "phpunit/phpunit": "^8.0 || ^9.0" + }, + "suggest": { + "ext-iconv": "For improved results", + "ext-mbstring": "For improved results" + }, + "type": "phpcodesniffer-standard", + "notification-url": "https://packagist.org/downloads/", + "license": [ + "MIT" + ], + "authors": [ + { + "name": "Contributors", + "homepage": "https://github.com/WordPress/WordPress-Coding-Standards/graphs/contributors" + } + ], + "description": "PHP_CodeSniffer rules (sniffs) to enforce WordPress coding conventions", + "keywords": [ + "phpcs", + "standards", + "static analysis", + "wordpress" + ], + "support": { + "issues": "https://github.com/WordPress/WordPress-Coding-Standards/issues", + "source": "https://github.com/WordPress/WordPress-Coding-Standards", + "wiki": "https://github.com/WordPress/WordPress-Coding-Standards/wiki" + }, + "funding": [ + { + "url": "https://opencollective.com/php_codesniffer", + "type": "custom" + } + ], + "time": "2026-07-27T11:53:23+00:00" + } + ], + "aliases": [], + "minimum-stability": "stable", + "stability-flags": {}, + "prefer-stable": false, + "prefer-lowest": false, + "platform": { + "php": ">=7.4" + }, + "platform-dev": {}, + "plugin-api-version": "2.9.0" +} diff --git a/functions.php b/functions.php new file mode 100644 index 0000000..66ec652 --- /dev/null +++ b/functions.php @@ -0,0 +1,734 @@ + '' !== $test_dir ? $test_dir : '/tmp/wp-test-runner', + ); + + return array_merge( + $runner_configuration, + array( + 'WPT_PREPARE_DIR' => '' !== $prepare_dir ? $prepare_dir : '/tmp/wp-test-runner', + 'WPT_SSH_CONNECT' => trim( getenv( 'WPT_SSH_CONNECT' ) ), + 'WPT_SSH_OPTIONS' => '' !== $ssh_options ? $ssh_options : '-o StrictHostKeyChecking=no', + 'WPT_PHP_EXECUTABLE' => '' !== $php_exec ? $php_exec : 'php', + 'WPT_RM_TEST_DIR_CMD' => '' !== $rm_test_dir ? $rm_test_dir : 'rm -rf ' . escapeshellarg( $runner_configuration['WPT_TEST_DIR'] ), + 'WPT_REPORT_API_KEY' => trim( getenv( 'WPT_REPORT_API_KEY' ) ), + 'WPT_DEBUG' => (bool) getenv( 'WPT_DEBUG' ), + ) + ); +} + +/** + * Executes a set of shell commands. + * + * Each command is logged before being executed. + * + * When a non-zero return code is encountered, the error message is displayed + * and the runner will fail. + * + * @param array $operations A list of shell commands (strings) to execute. + * Each command should be a valid shell command and properly escaped for safety. + * The commands are executed in the order they appear in the array. + * + * @return void This function does not return a value. However, it will output + * the result of each shell command to the standard output and log the + * execution. It will also halt on the first command that fails, displaying an + * error message. + * + * @uses log_message() to log each operation before execution. This can be used + * for debugging or auditing purposes. + * + * @uses passthru() to execute the shell command, which provides direct output + * to the browser. Be aware that using this function with untrusted input can + * lead to security vulnerabilities, such as command injection attacks. + * + * @uses error_message() to display an error message if a shell command fails. + * The execution stops at the first failure. + */ +function perform_operations( $operations ) { + foreach ( $operations as $operation ) { + log_message( $operation ); + passthru( $operation, $return_code ); + + // Check for command execution failure. + if ( 0 !== $return_code ) { + error_message( 'Failed to perform operation: ' . $operation . '.' ); + return; + } + } +} + +/** + * Writes a message to the standard output (STDOUT). + * + * The message is appended with PHP_EOL to ensure proper line breaks on + * different operating systems. + * + * @param string $message The message to be logged. + * + * @return void This function does not return a value. It directly writes the + * message to STDOUT, which is typically visible in the console or terminal + * where the PHP script is executed. + * + * @uses fwrite() to write the message to STDOUT. This is a low-level file + * operation function that works with various file streams, including standard + * output, standard error, and regular files. + */ +function log_message( $message ) { + fwrite( STDOUT, $message . PHP_EOL ); +} + +/** + * Displays an error message and terminates the test runner execution. + * + * The error message is prefixed with "Error: " and appended with PHP_EOL + * before being written to the standard output (STDOUT). + * + * After outputting the error message, the script will be terminated with a + * status code of 1. + * + * @param string $message The error message to be logged. This string will be + * output as provided, but prefixed with "Error: " to indicate its nature, + * followed by a system-specific newline character. + * + * @return void This function does not return a value. It directly writes the + * error message to STDERR and then terminates the script execution using + * `exit(1)`, indicating an error condition to the environment. + * + * @uses fwrite() to write the error message to STDERR. This function is used + * for low-level writing to file streams or output streams, in this case, + * STDERR, which is specifically for error reporting. + */ +function error_message( $message ) { + fwrite( STDERR, 'Error: ' . $message . PHP_EOL ); + exit( 1 ); +} + +/** + * Ensures a single trailing slash is present at the end of a given string. + * + * File system operations often expect a single trailing slash when referring + * to directories or paths. This ensures that only one trailing slash is + * present at the end of a given string. + * + * @param string $string The input string to which a trailing slash will be + * added. This could be a file path, URL, or any other string that requires a + * trailing slash for proper formatting or usage. + * + * @return string The modified string with a single trailing slash appended at + * the end. If the input string already has one or more trailing slashes, they + * will be trimmed to a single slash. + * + * @uses rtrim() to remove any existing trailing slashes from the input string + * before appending a new trailing slash. This ensures that the result + * consistently has exactly one trailing slash, regardless of the input string's + * initial state. + */ +function trailingslashit( $str ) { + return rtrim( $str, '/' ) . '/'; +} + +/** + * Extracts test results from a JUnit XML string. + * + * This extracts the relevant information from the test results into a format + * accepted and understood by the WordPress Test Reporter plugin. + * + * The data specifically extracted is: + * - Total number of tests. + * - Number of failures. + * - Number of errors. + * - Overall execution time. + * + * When the XML data is missing, empty, unparseable, or carries no usable + * result counts, execution stops with an error instead of returning an + * empty or hollow result, because such a result is either rejected much + * later with a confusing error or displayed in a misleading way. See + * issue #311. + * + * @param string $xml_string The JUnit XML data as a string. This should be + * well-formed XML representing the results of test executions, typically + * generated by testing frameworks compatible with JUnit reporting. + * + * @return string A JSON encoded string that represents a summary of the test + * results, including overall metrics and detailed information about each failed + * or errored test case. The JSON structure will include keys for 'tests', + * 'failures', 'errors', 'time', and 'testsuites', where 'testsuites' is an + * array of test suites that contains the failures or errors. + * + * @uses simplexml_load_string() to parse the JUnit XML data into an object for + * easy access and manipulation of the XML elements. + * + * @uses xpath() to query specific elements within the XML structure, + * particularly to find test suites with failures or errors. + * + * @uses json_encode() to convert the array structure containing the test + * results into a JSON formatted string. + */ +function process_junit_xml( $xml_string ) { + if ( empty( $xml_string ) ) { + error_message( 'junit.xml is missing or empty, so there are no test results to report. Aborting instead of reporting an empty result as a success. See https://github.com/WordPress/phpunit-test-runner/issues/311.' ); + } + + $previous_libxml_setting = libxml_use_internal_errors( true ); + libxml_clear_errors(); + + $xml = simplexml_load_string( $xml_string ); + + $errors = libxml_get_errors(); + libxml_clear_errors(); + libxml_use_internal_errors( $previous_libxml_setting ); + + if ( false === $xml ) { + $detail = ''; + if ( ! empty( $errors ) ) { + $first = $errors[0]; + $detail = ' First parser error: ' . trim( $first->message ) . ' at line ' . (int) $first->line . '.'; + } + error_message( 'junit.xml could not be parsed as XML, so the test results are unreadable. Aborting instead of reporting an unreadable result as a success.' . $detail . ' See https://github.com/WordPress/phpunit-test-runner/issues/311.' ); + } + + $xml_string = null; + + // PHPUnit wraps everything in , but a root + // element is also a legitimate JUnit shape from other producers. + $project = 'testsuite' === $xml->getName() ? $xml : $xml->testsuite; + $results = array(); + + if ( + ! isset( $project['tests'] ) || '' === (string) $project['tests'] || + ! isset( $project['failures'] ) || '' === (string) $project['failures'] || + ! isset( $project['errors'] ) || '' === (string) $project['errors'] + ) { + error_message( 'junit.xml parsed but contains no usable test result counts, so the test results are unusable. A result without failure and error counts would be displayed as a success. Aborting instead. See https://github.com/WordPress/phpunit-test-runner/issues/311.' ); + } + + $results = array( + 'tests' => (string) $project['tests'], + 'failures' => (string) $project['failures'], + 'errors' => (string) $project['errors'], + 'time' => (string) $project['time'], + ); + + $results['testsuites'] = array(); + + $testsuites = $xml->xpath( '//testsuite[ ( count( testcase ) > 0 ) and ( @errors > 0 or @failures > 0 ) ]' ); + foreach ( $testsuites as $testsuite ) { + $result = array( + 'name' => (string) $testsuite['name'], + 'tests' => (string) $testsuite['tests'], + 'failures' => (string) $testsuite['failures'], + 'errors' => (string) $testsuite['errors'], + ); + + if ( empty( $result['failures'] ) && empty( $result['errors'] ) ) { + continue; + } + $failures = array(); + foreach ( $testsuite->testcase as $testcase ) { + // Capture both failure and error children. + foreach ( array( 'failure', 'error' ) as $key ) { + if ( isset( $testcase->{$key} ) ) { + $failures[ (string) $testcase['name'] ] = array( + 'name' => (string) $testcase['name'], + $key => (string) $testcase->{$key}, + ); + } + } + } + if ( $failures ) { + $results['testsuites'][ (string) $testsuite['name'] ] = $result; + $results['testsuites'][ (string) $testsuite['name'] ]['testcases'] = $failures; + } + } + + return json_encode( $results ); +} + +/** + * Submits test results to a reporting API endpoint. + * + * This submits test results and related metadata to a site running the + * WordPress Test Reporter plugin using cURL. + * + * Reports are always submitted to WordPress.org Unless the WPT_REPORT_URL + * environment variable is set. + * + * @param string $results The test results in a processed format (e.g., JSON) + * ready for submission to the reporting API. + * + * @param string $rev The SVN revision associated with the test results. This + * often corresponds to a specific code commit or build identifier. + * + * @param string $message The SVN commit message associated with the revision, + * providing context or notes about the changes. + * + * @param string $env The environment data in JSON format, detailing the + * conditions under which the tests were run, such as operating system, PHP + * version, etc. + * + * @param string $api_key The API key for authenticating with the reporting API, + * ensuring secure and authorized access. + * + * @return array An array containing two elements: the HTTP status code of the + * response (int) and the body of the response (string) from the reporting API. + * This can be used to verify successful submission or to handle errors. + * + * @uses curl_init(), curl_setopt(), and curl_exec() to perform the HTTP POST + * request to the reporting API. + * + * @uses json_encode() to encode the data payload as a JSON string for + * submission. + * + * @uses base64_encode() to encode the API key for HTTP Basic Authentication in + * the Authorization header. + */ +function upload_results( $results, $rev, $message, $env, $api_key ) { + $wpt_report_url = getenv( 'WPT_REPORT_URL' ); + if ( ! $wpt_report_url ) { + $wpt_report_url = 'https://make.wordpress.org/hosting/wp-json/wp-unit-test-api/v1/results'; + } + $process = curl_init( $wpt_report_url ); + $access_token = base64_encode( $api_key ); + $data = array( + 'results' => $results, + 'commit' => $rev, + 'message' => $message, + 'env' => $env, + ); + $data_string = json_encode( $data ); + + // Set CURL options. + curl_setopt( $process, CURLOPT_TIMEOUT, 30 ); + curl_setopt( $process, CURLOPT_POST, 1 ); + curl_setopt( $process, CURLOPT_CUSTOMREQUEST, 'POST' ); + curl_setopt( $process, CURLOPT_USERAGENT, 'WordPress PHPUnit Test Runner' ); + curl_setopt( $process, CURLOPT_POSTFIELDS, $data_string ); + curl_setopt( $process, CURLOPT_RETURNTRANSFER, true ); + curl_setopt( + $process, + CURLOPT_HTTPHEADER, + array( + "Authorization: Basic $access_token", + 'Content-Type: application/json', + 'Content-Length: ' . strlen( $data_string ), + ) + ); + + $return = curl_exec( $process ); + $status_code = curl_getinfo( $process, CURLINFO_HTTP_CODE ); + curl_close( $process ); + + return array( $status_code, $return ); +} + +/** + * Parse a WordPress-style database host into mysqli connection pieces. + * + * @param string $host Database host string. + * + * @return array|false Parsed connection pieces, or false on invalid input. + */ +function wpt_runner_parse_db_host( $host ) { + $host = (string) $host; + $socket = null; + $port = null; + $is_ipv6 = false; + + if ( '' === $host ) { + return false; + } + + $socket_pos = strpos( $host, ':/' ); + if ( false !== $socket_pos ) { + $socket = substr( $host, $socket_pos + 1 ); + $host = substr( $host, 0, $socket_pos ); + } + + if ( substr_count( $host, ':' ) > 1 ) { + if ( 1 !== preg_match( '/^(?:\[(?P[0-9a-fA-F:.]+)\](?::(?P[0-9]+))?|(?P[0-9a-fA-F:.]+))$/', $host, $matches ) ) { + return false; + } + $parsed_host = ! empty( $matches['host'] ) ? $matches['host'] : ( isset( $matches['host_unbracketed'] ) ? $matches['host_unbracketed'] : '' ); + $is_ipv6 = true; + } else { + if ( 1 !== preg_match( '/^(?P[^:]*)(?::(?P[0-9]+))?$/', $host, $matches ) ) { + return false; + } + $parsed_host = $matches['host']; + } + + if ( '' === $parsed_host ) { + return false; + } + + if ( isset( $matches['port'] ) && '' !== $matches['port'] ) { + $port = (int) $matches['port']; + } + + return array( + 'host' => $parsed_host, + 'port' => $port, + 'socket' => $socket, + 'is_ipv6' => $is_ipv6, + ); +} + +// The report.php fallback runs without WordPress bootstrap, so $wpdb is unavailable. +// phpcs:disable WordPress.DB.RestrictedFunctions -- Direct mysqli is limited to database version reporting. +/** + * Gets the database server version, if it can be detected safely. + * + * @param string $db_host Database host. + * @param string $db_user Database user. + * @param string $db_password Database password. + * @param string $db_name Database name. + * + * @return string Raw server version string, or an empty string. + */ +function wpt_runner_get_db_server_version( $db_host, $db_user, $db_password, $db_name ) { + $db_host = trim( (string) $db_host ); + $db_user = trim( (string) $db_user ); + $db_password = (string) $db_password; + $db_name = trim( (string) $db_name ); + + if ( '' === $db_host ) { + $db_host = 'localhost'; + } + + if ( '' === $db_user || '' === $db_name ) { + return ''; + } + + if ( ! class_exists( 'mysqli' ) ) { + return ''; + } + + $required_functions = array( + 'mysqli_close', + 'mysqli_fetch_row', + 'mysqli_free_result', + 'mysqli_init', + 'mysqli_options', + 'mysqli_query', + 'mysqli_real_connect', + ); + + foreach ( $required_functions as $function_name ) { + if ( ! function_exists( $function_name ) ) { + return ''; + } + } + + $parsed_host = wpt_runner_parse_db_host( $db_host ); + if ( false === $parsed_host ) { + return ''; + } + $connect_host = $parsed_host['host']; + // mysqlnd expects IPv6 hosts in brackets, matching WordPress core's connection handling. + if ( $parsed_host['is_ipv6'] && extension_loaded( 'mysqlnd' ) ) { + $connect_host = '[' . $connect_host . ']'; + } + + $mysqli = null; + $mysqli_report_mode = null; + + try { + if ( class_exists( 'mysqli_driver' ) ) { + $mysqli_driver = new mysqli_driver(); + $mysqli_report_mode = $mysqli_driver->report_mode; + } + + if ( function_exists( 'mysqli_report' ) ) { + mysqli_report( MYSQLI_REPORT_OFF ); + } + + $mysqli = mysqli_init(); + if ( false === $mysqli ) { + return ''; + } + + if ( defined( 'MYSQLI_OPT_CONNECT_TIMEOUT' ) ) { + mysqli_options( $mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, 5 ); + } + + if ( ! @mysqli_real_connect( + $mysqli, + $connect_host, + $db_user, + $db_password, + $db_name, + $parsed_host['port'], + $parsed_host['socket'] + ) ) { + return ''; + } + + $result = @mysqli_query( $mysqli, 'SELECT VERSION()' ); + if ( ! is_object( $result ) ) { + return ''; + } + + $row = mysqli_fetch_row( $result ); + mysqli_free_result( $result ); + + if ( ! is_array( $row ) || ! isset( $row[0] ) || '' === (string) $row[0] ) { + return ''; + } + + return (string) $row[0]; + } catch ( Throwable $e ) { + return ''; + } finally { + if ( $mysqli instanceof mysqli ) { + @mysqli_close( $mysqli ); + } + if ( null !== $mysqli_report_mode && function_exists( 'mysqli_report' ) ) { + mysqli_report( $mysqli_report_mode ); + } + } +} + +// phpcs:enable WordPress.DB.RestrictedFunctions + +/** + * Collects details about the testing environment. + * + * The versions of PHP, PHP modules, database software, and system utilities + * can impact the results of the test suite. This gathers the relevant details + * to include in test report submissions. + * + * @return array An associative array containing detailed environment + * information. The array includes: + * - 'php_version': The current PHP version. + * - 'php_modules': An associative array of selected PHP modules and their versions. + * - 'system_utils': Versions of certain system utilities such as 'curl', 'imagemagick', + * 'graphicsmagick', and 'openssl'. + * - 'mysql_version': The version of the database server. + * - 'os_name': The name of the operating system. + * - 'os_version': The version of the operating system. + * + * @uses phpversion() to get the PHP version and module versions. + * + * @uses shell_exec() to execute system commands for retrieving OS details + * and versions of utilities like curl and OpenSSL. + * + * @uses class_exists() to check for the availability of the Imagick and Gmagick + * classes for version detection. + */ +function get_env_details() { + + $gd_info = array(); + if ( extension_loaded( 'gd' ) ) { + $gd_info = gd_info(); + } + $imagick_info = array(); + if ( extension_loaded( 'imagick' ) ) { + $imagick_info = Imagick::queryFormats(); + } + + $wpt_db_host = trim( getenv( 'WPT_DB_HOST' ) ); + if ( ! $wpt_db_host ) { + $wpt_db_host = 'localhost'; + } + $wpt_db_user = trim( getenv( 'WPT_DB_USER' ) ); + $wpt_db_password = getenv( 'WPT_DB_PASSWORD' ); + if ( false === $wpt_db_password ) { + $wpt_db_password = ''; + } + $wpt_db_name = trim( getenv( 'WPT_DB_NAME' ) ); + + $env = array( + 'php_version' => phpversion(), + 'php_modules' => array(), + 'gd_info' => $gd_info, + 'imagick_info' => $imagick_info, + 'mysql_version' => wpt_runner_get_db_server_version( $wpt_db_host, $wpt_db_user, $wpt_db_password, $wpt_db_name ), + 'system_utils' => array(), + 'os_name' => trim( shell_exec( 'uname -s' ) ), + 'os_version' => trim( shell_exec( 'uname -r' ) ), + ); + unset( $gd_info, $imagick_info ); + + $php_modules = array( + 'bcmath', + 'ctype', + 'curl', + 'date', + 'dom', + 'exif', + 'fileinfo', + 'filter', + 'ftp', + 'gd', + 'gettext', + 'gmagick', + 'hash', + 'iconv', + 'imagick', + 'imap', + 'intl', + 'json', + 'libsodium', + 'libxml', + 'mbstring', + 'mcrypt', + 'mod_xml', + 'mysqli', + 'mysqlnd', + 'openssl', + 'pcre', + 'pdo_mysql', + 'soap', + 'sockets', + 'sodium', + 'xml', + 'xmlreader', + 'zip', + 'zlib', + ); + foreach ( $php_modules as $php_module ) { + $env['php_modules'][ $php_module ] = phpversion( $php_module ); + } + + function curl_selected_bits( $k ) { + return in_array( $k, array( 'version', 'ssl_version', 'libz_version' ), true ); + } + $curl_bits = curl_version(); + $env['system_utils']['curl'] = implode( ' ', array_values( array_filter( $curl_bits, 'curl_selected_bits', ARRAY_FILTER_USE_KEY ) ) ); + + if ( class_exists( 'Imagick' ) ) { + $imagick = new Imagick(); + $version = $imagick->getVersion(); + preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); + $env['system_utils']['imagemagick'] = $version[1]; + } elseif ( class_exists( 'Gmagick' ) ) { + $gmagick = new Gmagick(); + $version = $gmagick->getversion(); + preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); + $env['system_utils']['graphicsmagick'] = $version[1]; + } + + $env['system_utils']['openssl'] = str_replace( 'OpenSSL ', '', trim( shell_exec( 'openssl version' ) ) ); + + return $env; +} + +/** + * Drops the WordPress test tables so the next run starts clean. + * + * Stale rows survive the test suite's own install step, because WordPress + * boots before the tables are dropped and writes data it loaded into memory, + * such as user roles, back into the fresh tables. See issue #110. + * + * The tables live in the test environment, so when an SSH connection is + * configured the cleanup-db.php script is piped to the remote PHP binary on + * stdin. The script reads the database credentials from wp-tests-config.php + * in the test directory, so no password appears on any command line. + * + * A failure is reported as a warning rather than stopping execution, so the + * directory cleanup in cleanup.php always runs. Set the WPT_SKIP_DB_CLEANUP + * environment variable to skip this step entirely. + * + * @param array $runner_vars Test runner configuration options. + * + * @uses log_message() to log the executed command and any warning. + */ +function cleanup_database( $runner_vars ) { + if ( (bool) getenv( 'WPT_SKIP_DB_CLEANUP' ) ) { + log_message( 'WPT_SKIP_DB_CLEANUP is set, skipping database cleanup.' ); + return; + } + + $script = __DIR__ . '/cleanup-db.php'; + + if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { + $remote_command = $runner_vars['WPT_PHP_EXECUTABLE'] . ' -- ' . escapeshellarg( $runner_vars['WPT_TEST_DIR'] ); + $command = 'ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] ) . ' ' . escapeshellarg( $remote_command ) . ' < ' . escapeshellarg( $script ); + } else { + $command = $runner_vars['WPT_PHP_EXECUTABLE'] . ' ' . escapeshellarg( $script ) . ' ' . escapeshellarg( $runner_vars['WPT_TEST_DIR'] ); + } + + log_message( $command ); + passthru( $command, $return_code ); + + if ( 0 !== $return_code ) { + log_message( 'Warning: database cleanup did not complete, continuing with directory cleanup.' ); + } +} diff --git a/phpcs.xml.dist b/phpcs.xml.dist new file mode 100644 index 0000000..a32f244 --- /dev/null +++ b/phpcs.xml.dist @@ -0,0 +1,64 @@ + + + Apply WordPress Coding Standards to all test runner files. + + + + + + + + + + + + + + + + + + + + + + + + . + + + /vendor/* + + + + + + + + + + warning + + + diff --git a/prepare.php b/prepare.php new file mode 100644 index 0000000..16d6d75 --- /dev/null +++ b/prepare.php @@ -0,0 +1,527 @@ + 1 ) { + if ( 1 !== preg_match( '/^(?:\[(?P[0-9a-fA-F:.]+)\](?::(?P[0-9]+))?|(?P[0-9a-fA-F:.]+))$/', $host, $matches ) ) { + return false; + } + $parsed_host = ! empty( $matches['host'] ) ? $matches['host'] : ( isset( $matches['host_unbracketed'] ) ? $matches['host_unbracketed'] : '' ); + $is_ipv6 = true; + } else { + if ( 1 !== preg_match( '/^(?P[^:]*)(?::(?P[0-9]+))?$/', $host, $matches ) ) { + return false; + } + $parsed_host = $matches['host']; + } + + if ( '' === $parsed_host ) { + return false; + } + + if ( isset( $matches['port'] ) && '' !== $matches['port'] ) { + $port = (int) $matches['port']; + } + + return array( + 'host' => $parsed_host, + 'port' => $port, + 'socket' => $socket, + 'is_ipv6' => $is_ipv6, + ); + } +} +if ( ! function_exists( 'wpt_runner_get_db_server_version' ) ) { + + // wp-tests-config.php is read before WordPress creates the global $wpdb. + // Using $wpdb here can leave the database server version empty during bootstrap. + // phpcs:disable WordPress.DB.RestrictedFunctions -- Direct mysqli is limited to database version reporting. + function wpt_runner_get_db_server_version( $db_host, $db_user, $db_password, $db_name ) { + $db_host = trim( (string) $db_host ); + $db_user = trim( (string) $db_user ); + $db_password = (string) $db_password; + $db_name = trim( (string) $db_name ); + + if ( '' === $db_host ) { + $db_host = 'localhost'; + } + + if ( '' === $db_user || '' === $db_name ) { + return ''; + } + + if ( ! class_exists( 'mysqli' ) ) { + return ''; + } + + $required_functions = array( + 'mysqli_close', + 'mysqli_fetch_row', + 'mysqli_free_result', + 'mysqli_init', + 'mysqli_options', + 'mysqli_query', + 'mysqli_real_connect', + ); + + foreach ( $required_functions as $function_name ) { + if ( ! function_exists( $function_name ) ) { + return ''; + } + } + + $parsed_host = wpt_runner_parse_db_host( $db_host ); + if ( false === $parsed_host ) { + return ''; + } + $connect_host = $parsed_host['host']; + // mysqlnd expects IPv6 hosts in brackets, matching WordPress core's connection handling. + if ( $parsed_host['is_ipv6'] && extension_loaded( 'mysqlnd' ) ) { + $connect_host = '[' . $connect_host . ']'; + } + + $mysqli = null; + $mysqli_report_mode = null; + + try { + if ( class_exists( 'mysqli_driver' ) ) { + $mysqli_driver = new mysqli_driver(); + $mysqli_report_mode = $mysqli_driver->report_mode; + } + + if ( function_exists( 'mysqli_report' ) ) { + mysqli_report( MYSQLI_REPORT_OFF ); + } + + $mysqli = mysqli_init(); + if ( false === $mysqli ) { + return ''; + } + + if ( defined( 'MYSQLI_OPT_CONNECT_TIMEOUT' ) ) { + mysqli_options( $mysqli, MYSQLI_OPT_CONNECT_TIMEOUT, 5 ); + } + + if ( ! @mysqli_real_connect( + $mysqli, + $connect_host, + $db_user, + $db_password, + $db_name, + $parsed_host['port'], + $parsed_host['socket'] + ) ) { + return ''; + } + + $result = @mysqli_query( $mysqli, 'SELECT VERSION()' ); + if ( ! is_object( $result ) ) { + return ''; + } + + $row = mysqli_fetch_row( $result ); + mysqli_free_result( $result ); + + if ( ! is_array( $row ) || ! isset( $row[0] ) || '' === (string) $row[0] ) { + return ''; + } + + return (string) $row[0]; + } catch ( Throwable $e ) { + return ''; + } finally { + if ( $mysqli instanceof mysqli ) { + @mysqli_close( $mysqli ); + } + if ( null !== $mysqli_report_mode && function_exists( 'mysqli_report' ) ) { + mysqli_report( $mysqli_report_mode ); + } + } + } + // phpcs:enable WordPress.DB.RestrictedFunctions +} +$env = array( + 'php_version' => phpversion(), + 'php_modules' => array(), + 'gd_info' => $gd_info, + 'imagick_info' => $imagick_info, + 'mysql_version' => wpt_runner_get_db_server_version( DB_HOST, DB_USER, DB_PASSWORD, DB_NAME ), + 'system_utils' => array(), + 'os_name' => trim( shell_exec( 'uname -s' ) ), + 'os_version' => trim( shell_exec( 'uname -r' ) ), +); +$php_modules = array( + 'bcmath', + 'ctype', + 'curl', + 'date', + 'dom', + 'exif', + 'fileinfo', + 'filter', + 'ftp', + 'gd', + 'gettext', + 'gmagick', + 'hash', + 'iconv', + 'imagick', + 'imap', + 'intl', + 'json', + 'libsodium', + 'libxml', + 'mbstring', + 'mcrypt', + 'mod_xml', + 'mysqli', + 'mysqlnd', + 'openssl', + 'pcre', + 'pdo_mysql', + 'soap', + 'sockets', + 'sodium', + 'xml', + 'xmlreader', + 'zip', + 'zlib', +); +foreach ( $php_modules as $php_module ) { + $env['php_modules'][ $php_module ] = phpversion( $php_module ); +} +function curl_selected_bits( $k ) { + return in_array( $k, array( 'version', 'ssl_version', 'libz_version' ), true ); +} +$curl_bits = curl_version(); +$env['system_utils']['curl'] = implode( ' ', array_values( array_filter( $curl_bits, 'curl_selected_bits', ARRAY_FILTER_USE_KEY ) ) ); +if ( class_exists( 'Imagick' ) ) { + $imagick = new Imagick(); + $version = $imagick->getVersion(); + preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); + $env['system_utils']['imagemagick'] = $version[1]; +} elseif ( class_exists( 'Gmagick' ) ) { + $gmagick = new Gmagick(); + $version = $gmagick->getversion(); + preg_match( '/Magick (\d+\.\d+\.\d+-\d+|\d+\.\d+\.\d+|\d+\.\d+\-\d+|\d+\.\d+)/', $version['versionString'], $version ); + $env['system_utils']['graphicsmagick'] = $version[1]; +} +$env['system_utils']['openssl'] = str_replace( 'OpenSSL ', '', trim( shell_exec( 'openssl version' ) ) ); +file_put_contents( __DIR__ . '/tests/phpunit/build/logs/env.json', json_encode( $env, JSON_PRETTY_PRINT ) ); +if ( 'cli' === php_sapi_name() && defined( 'WP_INSTALLING' ) && WP_INSTALLING ) { + echo PHP_EOL; + echo 'PHP version: ' . phpversion() . ' (' . realpath( $_SERVER['_'] ) . ')' . PHP_EOL; + echo PHP_EOL; +} +EOT; + +// Initialize a string that will be used to identify the post-database-settings section in the configuration file. +$logger_replace_string = 'define( \'DB_COLLATE\', \'\' );' . PHP_EOL; + +if ( false === strpos( $contents, $logger_replace_string ) ) { + error_message( 'Unable to insert the system logger after the database constants in wp-tests-config.php.' ); +} + +// Append the logger script to the database settings constants to ensure DB_* constants are available. +$system_logger = $logger_replace_string . $system_logger; + +// Define a string that will set the 'WP_PHP_BINARY' constant to the path of the PHP executable. +$php_binary_string = 'define( \'WP_PHP_BINARY\', \'' . $runner_vars['WPT_PHP_EXECUTABLE'] . '\' );'; + +/* + * Map configuration file placeholders to environment-specific values. + * + * This is used in the subsequent str_replace operation to replace placeholder + * values in the wp-tests-config-sample.php file with the ones provided. + */ +$wpt_table_prefix = trim( getenv( 'WPT_TABLE_PREFIX' ) ); +$search_replace = array( + 'wptests_' => '' !== $wpt_table_prefix ? $wpt_table_prefix : 'wptests_', + 'youremptytestdbnamehere' => trim( getenv( 'WPT_DB_NAME' ) ), + 'yourusernamehere' => trim( getenv( 'WPT_DB_USER' ) ), + 'yourpasswordhere' => trim( getenv( 'WPT_DB_PASSWORD' ) ), + 'localhost' => trim( getenv( 'WPT_DB_HOST' ) ), + 'define( \'WP_PHP_BINARY\', \'php\' );' => $php_binary_string, + $logger_replace_string => $system_logger, +); + +// Replace the placeholders in the wp-tests-config-sample.php file content with actual values. +$contents = str_replace( array_keys( $search_replace ), array_values( $search_replace ), $contents ); + +// Write the modified content to the wp-tests-config.php file, which will be used by the test suite. +file_put_contents( $runner_vars['WPT_PREPARE_DIR'] . '/wp-tests-config.php', $contents ); + +/* + * Construct a command that generates a PHP version string compatible with + * PHPUnit version requirements. + */ +$php_version_cmd = $runner_vars['WPT_PHP_EXECUTABLE'] . " -r \"print PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION . '.' . PHP_RELEASE_VERSION;\""; + +/** + * If an SSH connection string is provided, the command to determine the PHP version is modified + * to execute remotely over SSH. This is required if the test environment is not the local machine. + */ +if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { + // The PHP version check command is prefixed with the SSH command, including SSH options, + // and the connection string, ensuring the command is executed on the remote machine. + $php_version_cmd = 'ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] ) . ' ' . escapeshellarg( $php_version_cmd ); +} + +// Initialize return value variable for the exec function call. +$retval = 0; + +/* + * Execute the constructed command to obtain the PHP version of the test + * environment. + * + * The output is stored in $env_php_version and the return value of the + * command execution is stored in $retval. + */ +$env_php_version = exec( $php_version_cmd, $output, $retval ); + +// Check if the command execution was successful by inspecting the return value. +if ( 0 !== $retval ) { + error_message( 'Could not retrieve the environment PHP Version.' ); +} + +// Log the obtained PHP version for confirmation and debugging purposes. +log_message( 'Environment PHP Version: ' . $env_php_version ); + +/* + * Confirm that the environment meets the minimum PHP version requirement. + * + * When the requirements are not met, execution will end with an error message. + */ +if ( version_compare( $env_php_version, '7.2', '<' ) ) { + // Logs an error message indicating the test runner's incompatibility with PHP versions below 7.2. + error_message( 'The test runner is not compatible with PHP < 7.2.' ); +} + + +// Check if Composer is installed and available in the PATH. +$composer_cmd = 'cd ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] ) . ' && '; +$retval = 0; +$composer_path = escapeshellarg( system( 'which composer', $retval ) ); + +if ( 0 === $retval ) { + + // If Composer is available, prepare the command to use the Composer binary. + $composer_cmd .= $composer_path . ' '; + +} else { + + // If Composer is not available, download the Composer phar file. + log_message( 'Local Composer not found. Downloading latest stable ...' ); + + perform_operations( + array( + 'wget -O ' . escapeshellarg( $runner_vars['WPT_PREPARE_DIR'] . '/composer.phar' ) . ' https://getcomposer.org/composer-stable.phar', + ) + ); + + // Update the command to use the downloaded Composer phar file. + $composer_cmd .= $runner_vars['WPT_PHP_EXECUTABLE'] . ' composer.phar '; +} + +// Set the PHP version for Composer to ensure compatibility and update dependencies. +perform_operations( + array( + $composer_cmd . 'config platform.php ' . escapeshellarg( $env_php_version ), + $composer_cmd . 'update', + ) +); + +/* + * Transfer the built WordPress codebase to the remote test environment. + * + * When an SSH connection is configured, rsync is used to copy the files + * required to run the WordPress PHPUnit test suite. + * + * The -r option for rsync enables recursive copying to handle nested directory + * structures. + */ +if ( ! empty( $runner_vars['WPT_SSH_CONNECT'] ) ) { + // Initialize rsync options with recursive copying. + $rsync_options = '-r'; + + // If debug mode is set to verbose, append 'v' to rsync options for verbose output. + if ( $runner_vars['WPT_DEBUG'] ) { + $rsync_options = $rsync_options . 'v'; + } + + // Perform the rsync operation with the configured options and exclude patterns. + // This operation synchronizes the test environment with the prepared files, excluding + // version control directories and other non-essential files for test execution. + perform_operations( + array( + 'rsync ' . $rsync_options + . ' --exclude=".git/"' + . ' --exclude="node_modules/"' + . ' --exclude="composer.phar"' + . ' --exclude=".cache/"' + . ' --exclude=".devcontainer/"' + . ' --exclude=".github/"' + . ' --exclude="tools/"' + // Exclude all subdirectories in tests/ except phpunit/. + . ' --exclude="tests/*" --include="tests/phpunit/**"' + . ' -e "ssh ' . $runner_vars['WPT_SSH_OPTIONS'] . '" ' + . escapeshellarg( trailingslashit( $runner_vars['WPT_PREPARE_DIR'] ) ) + . ' ' . escapeshellarg( $runner_vars['WPT_SSH_CONNECT'] . ':' . $runner_vars['WPT_TEST_DIR'] ), + ) + ); +} + +// Log a success message indicating that the environment has been prepared. +log_message( 'Success: Prepared environment.' ); diff --git a/report.php b/report.php new file mode 100644 index 0000000..b45ee39 --- /dev/null +++ b/report.php @@ -0,0 +1,148 @@ + Date: Wed, 7 Oct 2026 17:41:47 +0600 Subject: [PATCH 6/6] Describe routes.php as a past case routes.php is in version control again since r62118, so cite #292 as something that happened instead of a current example. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 80cc8b9..bddcdca 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ The Gutenberg build step: 3. Copies the required Gutenberg files into the WordPress `src/` directory. 4. Makes those files available to the WordPress installation that PHPUnit loads during the test run. -The PHPUnit test suite loads WordPress from the `src/` directory. Therefore, these build steps must complete successfully before the tests can run. If the Gutenberg files have not been prepared, the test suite can fail while loading WordPress because required files are missing, for example `src/wp-includes/build/routes.php` ([#292](https://github.com/WordPress/phpunit-test-runner/issues/292)). +The PHPUnit test suite loads WordPress from the `src/` directory. Therefore, these build steps must complete successfully before the tests can run. If the Gutenberg files have not been prepared, the test suite can fail while loading WordPress because required files are missing, as happened with `src/wp-includes/build/routes.php` in [#292](https://github.com/WordPress/phpunit-test-runner/issues/292). This is why Node.js and npm are requirements for the test runner even though the tests themselves are written in PHP.