Skip to content

Only insert at the first occurrence of the placement anchor - #66

Merged
swissspidy merged 2 commits into
mainfrom
231-config-command-fix-1dk8vy
Aug 29, 2026
Merged

swissspidy merged 2 commits into
mainfrom
231-config-command-fix-1dk8vy

Conversation

@swissspidy

@swissspidy swissspidy commented Aug 29, 2026 •

Copy link
Copy Markdown
Member

Fixes wp-cli/config-command#231.

Problem

WPConfigTransformer::add() replaced the placement anchor using str_replace():

$contents = str_replace( $anchor, $new_src, $this->wp_config_src );

str_replace() replaces every occurrence. So if the anchor string appears more than once in wp-config.php — e.g. a /* That's all, stop editing! */ line duplicated by a provisioning script, a copy/paste edit, or a merged config fragment — wp config add / wp config set inserted the define() once per occurrence, and WordPress then emitted Constant XXX already defined notices.

Running wp config add FOO bar against such a file produced:

define( 'DB_NAME', 'test_db' );

define( 'FOO', 'bar' );
/* That's all, stop editing! Happy publishing. */

define( 'WP_DEBUG', false );

define( 'FOO', 'bar' );
/* That's all, stop editing! Happy publishing. */

Fix

Reuse the offset from the anchor lookup that add() already performs, and replace only that one occurrence with substr_replace():

$anchor_pos = strpos( $this->wp_config_src, $anchor );

if ( false === $anchor_pos ) {
	throw new Exception( 'Unable to locate placement anchor.' );
}

// Only replace the first occurrence, in case the anchor appears more than once.
$contents = substr_replace( $this->wp_config_src, $new_src, $anchor_pos, strlen( $anchor ) );

The config is now inserted exactly once, at the first occurrence, for both before and after placement. Behavior is unchanged for the common single-anchor case, for the EOF anchor, and for a missing anchor (which still throws Unable to locate placement anchor.).

Tests

New tests/DuplicateAnchorTest.php builds a wp-config.php whose anchor comment appears twice and covers:

  • adding a constant inserts it exactly once and leaves both anchor comments intact
  • adding a variable inserts it exactly once and leaves both anchor comments intact
  • before placement lands at the first anchor, not the last
  • after placement lands at the first anchor and inserts once
  • an anchor that is not present still throws

The three duplication assertions fail against main and pass with this change, so they guard the regression rather than passing either way.

Note: this only affects add(). update() matches on the existing config source rather than the anchor, so it was not affected.

Follow-up

wp-cli/config-command pins wp-cli/wp-config-transformer: ^1.4.0, so config-command picks this up once a new release is tagged; no change is needed there.


🤖 Generated with Claude Code

https://claude.ai/code/session_01NU3fkN1bbTGQXuTFWBsBcr

`WPConfigTransformer::add()` used `str_replace()` to swap the anchor for
the anchor plus the new config. `str_replace()` replaces every occurrence,
so a `wp-config.php` in which the anchor string appears more than once —
for instance a duplicated `/* That's all, stop editing! */` line left
behind by a provisioning script or a merged config fragment — got the
config defined once per occurrence, triggering `Constant XXX already
defined` notices.

Use `substr_replace()` at the offset already computed for the anchor
lookup so only the first occurrence is replaced.

See wp-cli/config-command#231

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

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.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@coderabbitai

coderabbitai Bot commented Aug 29, 2026 •

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f29abf0f-3229-4cac-9ff5-325c631e208c

📥 Commits

Reviewing files that changed from the base of the PR and between 3a662d9 and ccef0a7.

📒 Files selected for processing (3)
  • README.md
  • src/WPConfigTransformer.php
  • tests/DuplicateAnchorTest.php

Included review availability: Your plan provides up to 1 included review per hour; 0 remain after this review.


📝 Walkthrough

Walkthrough

WPConfigTransformer::add() now uses only the first matching anchor. Documentation and tests cover duplicate anchors, placement behavior, and missing-anchor errors.

Changes

Anchor replacement behavior

Layer / File(s) Summary
First-anchor replacement behavior
src/WPConfigTransformer.php, README.md
add() replaces only the first anchor occurrence. The documentation states this behavior.
Duplicate-anchor validation
tests/DuplicateAnchorTest.php
Tests verify constant and variable insertion, before and after placement, duplicate-anchor preservation, and the existing missing-anchor exception.

Estimated code review effort: 2 (Simple) | ~10 minutes

Merge Risk: ⚪ Minimal · up to ccef0

The change prevents duplicate configuration entries when the placement anchor appears more than once while preserving existing behavior for normal configurations and missing anchors. No actionable merge-blocking risk remains beyond normal checks and review.

Suggested reviewers: brianhenryie, ernilambar, janw-me, mrsdizzie, schlessera

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 2 files. (1 skipped: 1… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: inserting content only at the first occurrence of the placement anchor.
Full details: Docstring Coverage

Explanation

Docstring coverage is 22.22% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 9 functions across 2 files. (1 skipped: 1 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 2
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🛠️ Fix failing CI checks 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch 231-config-command-fix-1dk8vy

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.

The added inline comment splits the assignment block, so the two
`$new_src` assignments form their own alignment group.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NU3fkN1bbTGQXuTFWBsBcr
@codecov

codecov Bot commented Aug 29, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@swissspidy swissspidy added this to the 1.4.7 milestone Aug 29, 2026
@swissspidy
swissspidy merged commit dfc9fb7 into main Aug 29, 2026
19 checks passed
@swissspidy
swissspidy deleted the 231-config-command-fix-1dk8vy branch August 29, 2026 14:36
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Duplicated constants in wp-config if anchor is duplicated

2 participants