Skip to content

Fix #14402: Match the gettext MO context exactly - #21113

Merged
terabytesoftw merged 3 commits into
yiisoft:masterfrom
theluckystrike:fix/yii2-14402
Oct 30, 2026
Merged

terabytesoftw merged 3 commits into
yiisoft:masterfrom
theluckystrike:fix/yii2-14402

Conversation

@theluckystrike

@theluckystrike theluckystrike commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor
Q A
Is bugfix yes
New feature no
Breaks BC no
Fixed issues #14402

GettextMoFile::load() matched a message context with strncmp($id, $context, $separatorPosition). That compares only as many bytes as the context stored in the MO entry, so loading category backend/foo or backendbar also returned every message of context backend. The same happens to the common app and app/models category pair. GettextPoFile::load() doesn't have this bug because it compares the context with ===. The MO loader now does the same with substr($id, 0, $separatorPosition) === $context.

GettextMoFileTest::testLoadDoesNotMatchContextByPrefix loads context1/sub, context10 and context from the existing tests/data/i18n/test.mo. On master context1/sub returns the 3 context1 messages and the test fails with Tests: 3, Assertions: 29, Failures: 1. With this change all three return [], context1 still returns its 3 messages, and the file passes with OK (3 tests, 32 assertions).

End to end I ran a console Application with GettextMessageSource and an MO file holding contexts backend (Save) and backendbar (Cancel).

                                 master                   this branch
Yii::t('backendbar', 'Save')     Speichern (backend)      Save
Yii::t('backend/foo', 'Save')    Speichern (backend)      Save
Yii::t('backend', 'Save')        Speichern (backend)      Speichern (backend)
Yii::t('backendbar', 'Cancel')   Abbrechen (backendbar)   Abbrechen (backendbar)

Other runs on PHP 8.5.9.

vendor/bin/phpunit --group i18n --exclude-group db,wincache                 Tests: 721, Skipped: 1, Incomplete: 1, no failures
vendor/bin/phpunit --exclude-group db,wincache,mysql,pgsql,mssql,oci,cubrid  Tests: 5411, Skipped: 64, Incomplete: 3, no failures
vendor/bin/php-cs-fixer check --config=.php-cs-fixer.dist.php                Found 0 of 813 files that can be fixed
vendor/bin/phpstan analyse -c phpstan.dist.neon (changed files)              [OK] No errors

I didn't run DbMessageSourceTest (it needs MySQL) or the PHP 7.4 to 8.4 matrix.

Summary by Sourcery

Prevent gettext MO files from returning translations belonging to similarly prefixed contexts.

Bug Fixes:

  • Fix gettext MO loading so contexts are matched exactly instead of incorrectly matching contexts that merely share the requested context as a prefix.

Tests:

  • Add regression coverage for similarly prefixed gettext contexts while preserving exact-context loading.

@coderabbitai

coderabbitai Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Review in Change Stack →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Summary

Summary by CodeRabbit

  • Bug Fixes
    • Fixed gettext translation lookups that could return messages from a similarly named context. Messages are now returned only when the requested context matches exactly.
    • Requests for a context that is merely a prefix of another context no longer return the other context’s translations. Exact context matches continue to return their corresponding messages. This prevents unrelated translations from appearing in the wrong place.

GettextMoFile::load() now matches message contexts by exact equality. A regression test covers exact and non-matching contexts. The changelog records Bug #14402.

Changes: Gettext context matching

Layer / File(s) Summary
Implement and verify exact context matching
framework/i18n/GettextMoFile.php, tests/framework/i18n/GettextMoFileTest.php, framework/CHANGELOG.md
The loader now compares the extracted context with $context for exact equality. The test checks exact and non-matching contexts. The changelog records Bug #14402.

Suggested labels: type:bug, status:code review, type:test

Priority: Low

Change: Bug fix · Severity of issue fixed: Low

Merge Risk: Minimal · previous review d8532

The change prevents prefix-only context matches while preserving exact matches. No actionable merge-blocking issue is evident from the supplied changes.

Pre-merge checks: Passed 5
Check name Status Explanation
Title check Passed The title names the fix (exact context matching in the gettext MO loader) and the issue number. It matches the main change in GettextMoFile::load(), which now compares the full context instead of usin…
Description check Passed The description states the bug, the cause (strncmp comparing only the stored context length), the fix (substr comparison matching GettextPoFile), the new regression test, and the test runs. It relates…
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentat…
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.
Full details: Title check

Explanation

The title names the fix (exact context matching in the gettext MO loader) and the issue number. It matches the main change in GettextMoFile::load(), which now compares the full context instead of using a prefix comparison.

Full details: Description check

Explanation

The description states the bug, the cause (strncmp comparing only the stored context length), the fix (substr comparison matching GettextPoFile), the new regression test, and the test runs. It relates directly to the changeset.

Full details: Docstring Coverage

Explanation

Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff with cyclomatic complexity of at least 2. Documentation-only edits and deletions within surviving functions are included; unchanged diff context and fully deleted functions are excluded. Analyzed 1 functions across 2 files. (1 skipped: 1 unsupported.)

Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks each context string,
No longer fooled by prefixes creeping.
Exact matches pass along their way,
The tests keep watch both night and day.
A changelog notes the bug’s goodbye,
Then hops beneath the gettext sky.

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

@codecov

codecov Bot commented Oct 7, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 81.87%. Comparing base (697590d) to head (d2af409).
⚠️ Report is 1 commits behind head on master.
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff            @@
##             master   #21113   +/-   ##
=========================================
  Coverage     81.87%   81.87%           
  Complexity    11562    11562           
=========================================
  Files           374      374           
  Lines         30314    30314           
=========================================
  Hits          24820    24820           
  Misses         5494     5494           

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@theluckystrike theluckystrike changed the title Fix #14402 by matching the gettext MO context exactly Fix #14402: Match the gettext MO context exactly Oct 7, 2026
@theluckystrike

Copy link
Copy Markdown
Contributor Author

The phpstan / PHP 8.5-ubuntu-latest failure here is the master issue that #21115 fixes. PHPStan 2.3.0 flags QueryBuilder::getTableUniqueColumnNames(), which this PR doesn't touch. The PHP 8.6 job fails with the same 6 errors on #21111, from unserialize() in Cache::multiGet() and the missing SessionHandler::create_sid(), which #21098 covers.

`GettextMoFile::load()` compared the requested context with
`strncmp($id, $context, $separatorPosition)`, so only as many bytes as
the context stored in the MO entry were compared. A request for category
`backend/foo` or `backendbar` also loaded every message of context
`backend`. `GettextPoFile::load()` doesn't have this bug because it
compares the context with `===`. The MO loader now does the same with
`substr($id, 0, $separatorPosition) === $context`.

Commands I ran on PHP 8.5.9.

```
vendor/bin/phpunit tests/framework/i18n/GettextMoFileTest.php
  master code   1) testLoadDoesNotMatchContextByPrefix
                Failed asserting that two arrays are identical. (context1/sub returns the 3 context1 messages)
                Tests: 3, Assertions: 29, Failures: 1.
  this branch   OK (3 tests, 32 assertions)

vendor/bin/phpunit --group i18n --exclude-group db,wincache
  Tests: 721, Assertions: 4220, Skipped: 1, Incomplete: 1.
vendor/bin/phpunit --exclude-group db,wincache,mysql,pgsql,mssql,oci,cubrid
  Tests: 5411, Assertions: 17953, Skipped: 64, Incomplete: 3.
vendor/bin/php-cs-fixer check --config=.php-cs-fixer.dist.php
  Found 0 of 813 files that can be fixed
vendor/bin/phpstan analyse -c phpstan.dist.neon framework/i18n/GettextMoFile.php tests/framework/i18n/GettextMoFileTest.php
  [OK] No errors
```

A console Application with `GettextMessageSource` and an MO file that
holds contexts `backend` and `backendbar` gives this output.

```
                                 master                   this branch
Yii::t('backendbar', 'Save')     Speichern (backend)      Save
Yii::t('backend/foo', 'Save')    Speichern (backend)      Save
Yii::t('backend', 'Save')        Speichern (backend)      Speichern (backend)
Yii::t('backendbar', 'Cancel')   Abbrechen (backendbar)   Abbrechen (backendbar)
```

I didn't run `DbMessageSourceTest` (it needs a MySQL server) or the PHP
7.4 to 8.4 matrix.
@coderabbitai coderabbitai Bot added status:code review The pull request needs review. type:bug Bug labels Oct 26, 2026

@sourcery-ai sourcery-ai 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.

Sourcery assessment

Approved.

@terabytesoftw
terabytesoftw merged commit 2c9a5fd into yiisoft:master Oct 30, 2026
85 checks passed
@terabytesoftw

Copy link
Copy Markdown
Member

Thks 👍

@theluckystrike

theluckystrike commented Oct 31, 2026 via email •

Copy link
Copy Markdown
Contributor Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status:code review The pull request needs review. type:bug Bug type:test

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants