Skip to content

Extract HTTP mocking template into a real PHP file - #353

Merged
swissspidy merged 2 commits into
mainfrom
claude/php-syntax-highlighting-71e73h
Aug 9, 2026
Merged

Extract HTTP mocking template into a real PHP file#353
swissspidy merged 2 commits into
mainfrom
claude/php-syntax-highlighting-71e73h

Conversation

@swissspidy

@swissspidy swissspidy commented Aug 9, 2026

Copy link
Copy Markdown
Member

The mock transport used by Given that HTTP requests to ... will respond with: lived in an interpolating heredoc, so none of the project's quality
gates could see it. WP_CLI_CS deliberately excludes Generic.PHP.Syntax
because "the parallel linter command takes care of linting" -- but the
linter only sees the string, not the PHP inside it, so a typo in the mock
transport passed composer lint and only surfaced as a confusing runtime
failure inside the child WP-CLI process.

The heredoc also silently interpreted its own escapes. "\n\n" in the
pre_http_request branch was rendered as two literal newlines inside the
generated source, and "\r\n\r\n" as literal CR/LF bytes, leaving control
characters embedded in string literals in the generated file. Any tooling
that normalized line endings on that file would have broken the header and
body split.

Move the template to src/Context/templates/mock-requests.php and copy it
verbatim, with the mocked responses written alongside it as a generated
mock-requests-data.php that the template requires. The template is now an
ordinary PHP file: it is highlighted by editors, picked up by the recursive
parallel-lint scan, and free of the 76 \$ escapes. Emitting the response
data once instead of interpolating it into two places shrinks the step
definition from 166 lines to 33.

PHPStan excludes the template directory. It is executed by the child
process, where the Requests v1 classes it branches on may still exist, so
analyzing it against this package's dependency set only reports classes that
are absent here by design.

Behat now lints both generated files so the copied template and the
var_exported data are checked at runtime too.

Co-Authored-By: Claude Opus 5 noreply@anthropic.com
Claude-Session: https://claude.ai/code/session_01RiuykJaAqpdnCLsn4Ewmm8

Summary by CodeRabbit

  • Bug Fixes

    • Improved HTTP request mocking reliability across supported Requests versions.
    • Mocked responses now handle file output and WordPress HTTP response formatting more consistently.
  • Tests

    • Added validation that generated mock files exist and pass PHP syntax checks.
    • Expanded coverage for HTTP response matching and request handling.

The mock transport used by `Given that HTTP requests to ... will respond
with:` lived in an interpolating heredoc, so none of the project's quality
gates could see it. `WP_CLI_CS` deliberately excludes `Generic.PHP.Syntax`
because "the parallel linter command takes care of linting" -- but the
linter only sees the string, not the PHP inside it, so a typo in the mock
transport passed `composer lint` and only surfaced as a confusing runtime
failure inside the child WP-CLI process.

The heredoc also silently interpreted its own escapes. `"\n\n"` in the
`pre_http_request` branch was rendered as two literal newlines inside the
generated source, and `"\r\n\r\n"` as literal CR/LF bytes, leaving control
characters embedded in string literals in the generated file. Any tooling
that normalized line endings on that file would have broken the header and
body split.

Move the template to `src/Context/templates/mock-requests.php` and copy it
verbatim, with the mocked responses written alongside it as a generated
`mock-requests-data.php` that the template requires. The template is now an
ordinary PHP file: it is highlighted by editors, picked up by the recursive
`parallel-lint` scan, and free of the 76 `\$` escapes. Emitting the response
data once instead of interpolating it into two places shrinks the step
definition from 166 lines to 33.

PHPStan excludes the template directory. It is executed by the child
process, where the Requests v1 classes it branches on may still exist, so
analyzing it against this package's dependency set only reports classes that
are absent here by design.

Behat now lints both generated files so the copied template and the
`var_export`ed data are checked at runtime too.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RiuykJaAqpdnCLsn4Ewmm8
@swissspidy
swissspidy requested a review from a team as a code owner August 9, 2026 11:28
Copilot AI lite review requested due to automatic review settings August 9, 2026 11:28
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@swissspidy, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 52 minutes

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 36826fb3-cca1-4779-9898-f532fe771064

📥 Commits

Reviewing files that changed from the base of the PR and between 1e517c5 and e2772c4.

📒 Files selected for processing (1)
  • phpcs.xml.dist
📝 Walkthrough

Walkthrough

The HTTP mock setup now stores response data separately and copies a shared Requests-compatible transport template. The template supports Requests v1 and v2. Behat checks both generated files with PHP syntax validation, and PHPStan excludes the runtime templates.

Changes

HTTP Mocking

Layer / File(s) Summary
Compatible mock transport template
src/Context/templates/mock-requests.php, phpstan.neon.dist
Adds Requests v1/v2 transport wiring, URL matching, response parsing, CRLF normalization, file output, cURL fallback, and WordPress HTTP hooks.
Mock setup and syntax validation
src/Context/GivenStepDefinitions.php, features/behat-steps.feature
Writes serialized responses to mock-requests-data.php, copies the shared template, and validates both generated PHP files with php -l.

Estimated code review effort: 4 (Complex) | ~45 minutes

Sequence Diagram(s)

sequenceDiagram
  participant WordPress
  participant MockTransport
  participant Requests
  WordPress->>MockTransport: pre_http_request(url, options)
  MockTransport->>MockTransport: Match mocked URL
  MockTransport->>Requests: Parse matched response
  MockTransport-->>WordPress: Return WordPress-compatible response
Loading

Suggested labels: scope:testing

Suggested reviewers: brianhenryie, ernilambar, janw-me

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: moving HTTP mocking code into a standalone PHP template file.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches 💡 1
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/php-syntax-highlighting-71e73h

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@codecov

codecov Bot commented Aug 9, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 0% with 86 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
src/Context/templates/mock-requests.php 0.00% 82 Missing ⚠️
src/Context/GivenStepDefinitions.php 0.00% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/Context/templates/mock-requests.php`:
- Around line 49-57: Resolve the WP_CLI_CS violations in the conditional
declarations of WP_CLI_Tests_Mock_Requests_Transport by adding a narrowly scoped
PHPCS suppression covering only this compatibility branch, while preserving both
interface_exists() implementations and the shared trait usage.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 1dd1e0f3-9fe9-4eb3-b8b9-66c132d20571

📥 Commits

Reviewing files that changed from the base of the PR and between 4b2caf3 and 1e517c5.

📒 Files selected for processing (4)
  • features/behat-steps.feature
  • phpstan.neon.dist
  • src/Context/GivenStepDefinitions.php
  • src/Context/templates/mock-requests.php

Comment thread src/Context/templates/mock-requests.php

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR refactors the Behat HTTP-mocking step so the mock transport code lives in a real PHP template file (instead of an interpolated heredoc), allowing normal tooling (editor highlighting, parallel-lint, etc.) to validate it and avoiding heredoc escape/line-ending pitfalls when generating the runtime mock.

Changes:

  • Extract the HTTP mocking transport implementation into src/Context/templates/mock-requests.php and copy it verbatim into the run directory during tests.
  • Generate mocked response data separately as mock-requests-data.php and have the template require it at runtime.
  • Exclude the templates directory from PHPStan analysis and add Behat steps to php -l lint both generated files.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated no comments.

File Description
src/Context/templates/mock-requests.php New standalone PHP template implementing the Requests v1/v2-compatible mock transport and WP HTTP hook logic.
src/Context/GivenStepDefinitions.php Updates the HTTP-mocking step to write mock-requests-data.php and copy the template instead of building a heredoc.
phpstan.neon.dist Excludes the template directory from PHPStan, since it’s executed in a different dependency context.
features/behat-steps.feature Adds assertions and php -l lint checks for both generated mock files.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

The extracted template trips six PHPCS findings that cannot be resolved
without changing what the file does at runtime.

`Generic.Files.OneObjectStructurePerFile` and
`Generic.Classes.DuplicateClassName` fire because the transport class is
declared once per supported Requests major version. Collapsing that to a
single declaration would mean aliasing `Requests_Transport` onto
`WpOrg\Requests\Transport`, and WP-CLI itself branches on
`interface_exists()` for that name, so the alias could change how the
process under test resolves its own transport.

`Generic.CodeAnalysis.UnusedFunctionParameter` fires on `request_multiple()`
and `test()`, whose signatures are fixed by the transport interface. The
sniff already exempts this exact case elsewhere in the package -- it stays
quiet for `FeatureContext::forget_scenario()` because the class implements an
interface -- but the methods here live in a trait shared by both conditional
declarations, and a trait cannot declare `implements`.

Scope the three sniffs away from the templates directory, following the
convention this ruleset already uses for the stand-alone files under
`utils/`. Suppressing them inline instead would copy PHPCS pragmas into the
generated `mock-requests.php` in every test run directory, where they mean
nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RiuykJaAqpdnCLsn4Ewmm8
@swissspidy swissspidy added this to the 5.2.3 milestone Aug 9, 2026
@swissspidy
swissspidy merged commit 21780c6 into main Aug 9, 2026
64 of 65 checks passed
@swissspidy
swissspidy deleted the claude/php-syntax-highlighting-71e73h branch August 9, 2026 15:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants