Skip to content

Fix: FK reading grade of 0 < x < 1 collapses to 0 (normalize to 1)#1725

Merged
pattonwebz merged 3 commits into
developfrom
steve/pro-626-bug-fk-reading-grade-of-0-x-1-collapses-to-0-should
Jul 8, 2026
Merged

Fix: FK reading grade of 0 < x < 1 collapses to 0 (normalize to 1)#1725
pattonwebz merged 3 commits into
developfrom
steve/pro-626-bug-fk-reading-grade-of-0-x-1-collapses-to-0-should

Conversation

@SteveJonesDev

@SteveJonesDev SteveJonesDev commented May 29, 2026

Copy link
Copy Markdown
Member

Fixes #1497

Description

floor() applied directly to a Flesch-Kincaid grade in the range (0, 1) silently collapses it to 0. That 0 is then interpreted as "not enough content to determine a reading level," so content with a legitimately simple FK grade (e.g. 0.5 or 0.8) is misrepresented as uncalculable and incorrectly flagged as failing.

What changed

Introduces edac_normalize_fk_grade( float $fk_grade ): int in includes/helper-functions.php:

  • Returns 0 when the library returns ≤ 0 (truly not enough content)
  • Returns max(1, floor($fk_grade)) otherwise — so any positive sub-1 value becomes grade 1

Replaces the raw floor() pattern at all four affected call sites:

File Location
admin/class-ajax.php Classic metabox readability (line ~83)
admin/class-ajax.php Sidebar AJAX readability (line ~674)
includes/classes/class-summary-generator.php calculate_content_grade()
includes/classes/class-rest-api.php get_readability_data()

Tests

Adds tests/phpunit/helper-functions/NormalizeFkGradeTest.php with 11 data-driven cases covering: exact zero, negatives, the 0.01–0.99 boundary, 1.0, mid-grade values, and grades above 9.

Checklist

  • PR is linked to the main issue in the repo
  • Tests are added that cover changes

Summary by CodeRabbit

  • Bug Fixes
    • Improved simplified summary and readability reading-level calculations by normalizing Flesch–Kincaid grade values more consistently before applying “too high”/failure logic, yielding more accurate results for fractional and very low grade values.
  • Tests
    • Added automated PHPUnit coverage for the grade-normalization behavior, including zero/negative inputs and boundary/rounding cases.

Raw floor() on a Flesch-Kincaid grade between 0.01 and 0.99 collapsed
to 0, causing valid simple-grade content to be treated as
"not enough content" and flagged as failing. Introduces
edac_normalize_fk_grade() which returns 0 only for a true zero grade
and otherwise returns max(1, floor($fk_grade)). Applied to all four
call sites across class-ajax.php (×2), class-summary-generator.php,
and class-rest-api.php. Adds unit tests covering the boundary cases.

Fixes #1497

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8b524304-155d-45f5-ab88-146eba4080d1

📥 Commits

Reviewing files that changed from the base of the PR and between dfa89d2 and e616ede.

📒 Files selected for processing (2)
  • includes/helper-functions.php
  • tests/phpunit/helper-functions/NormalizeFkGradeTest.php
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/phpunit/helper-functions/NormalizeFkGradeTest.php
  • includes/helper-functions.php

📝 Walkthrough

Walkthrough

A new helper normalizes Flesch-Kincaid grades so values between 0 and 1 become 1 instead of 0. That normalization is then used in AJAX, REST API, and summary grade calculations, with tests covering boundary cases.

Changes

Flesch-Kincaid Grade Normalization

Layer / File(s) Summary
Normalization helper and tests
includes/helper-functions.php, tests/phpunit/helper-functions/NormalizeFkGradeTest.php
edac_normalize_fk_grade() returns 0 for non-positive inputs and max(1, floor($fk_grade)) for positive inputs; tests cover zero, negative, fractional, boundary, whole-number, false, and null cases.
AJAX simplified summary grading
admin/class-ajax.php
Ajax::summary() and Ajax::readability() now use edac_normalize_fk_grade() when computing $simplified_summary_grade.
REST API and Summary Generator integration
includes/classes/class-rest-api.php, includes/classes/class-summary-generator.php
Rest_API::get_readability_data() and Summary_Generator::calculate_content_grade() now normalize Flesch-Kincaid grades with edac_normalize_fk_grade() instead of direct flooring/casting.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related issues

Possibly related PRs

Suggested labels

codex

Suggested reviewers

  • pattonwebz

Poem

🐰 A tiny helper hopped in place,
Turning fraction-grades to their rightful face.
Zero stays zero, one stays one,
The reading score fix is neatly done.

🚥 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 accurately summarizes the main fix: normalizing sub-1 FK grades to 1 instead of 0.
Linked Issues check ✅ Passed The PR adds the normalization helper, updates all stated grade call sites, and includes boundary tests for the linked bug.
Out of Scope Changes check ✅ Passed The changes stay focused on FK grade normalization and test coverage, with no clear unrelated additions.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch steve/pro-626-bug-fk-reading-grade-of-0-x-1-collapses-to-0-should

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

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces a new helper function edac_normalize_fk_grade to safely normalize Flesch-Kincaid grade levels, preventing fractional grades between 0 and 1 from being incorrectly collapsed to 0. It also integrates this helper across various summary and readability calculation points and adds corresponding unit tests. The review feedback highlights a potential TypeError in PHP 8.0+ because the underlying library can return false (or null) on empty content, which would violate the strict float type hint on the helper function. It is recommended to remove the strict type hints from both the helper function and the test cases, cast the input to a float internally, and add test cases for false and null inputs.

Comment thread includes/helper-functions.php Outdated
Comment thread tests/phpunit/helper-functions/NormalizeFkGradeTest.php Outdated
Comment thread tests/phpunit/helper-functions/NormalizeFkGradeTest.php

@coderabbitai coderabbitai Bot 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.

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 `@includes/classes/class-rest-api.php`:
- Around line 1080-1083: The REST path incorrectly marks exactly 9th grade as
failing by setting $simplified_summary_grade_failed with the condition
"$simplified_summary_grade >= 9"; change the threshold to strictly greater-than
so it matches the “above 9th grade” semantics used elsewhere (i.e. use
"$simplified_summary_grade > 9"). Update the assignment that computes
$simplified_summary_grade_failed (after edac_normalize_fk_grade(
$text_statistics->fleschKincaidGradeLevel( $simplified_summary ) )) to use the >
operator so REST/sidebar agrees with the AJAX path.
🪄 Autofix (Beta)

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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 85e27011-3414-4f9a-be15-a271efea6a2b

📥 Commits

Reviewing files that changed from the base of the PR and between 6986dfa and a3d0cff.

📒 Files selected for processing (5)
  • admin/class-ajax.php
  • includes/classes/class-rest-api.php
  • includes/classes/class-summary-generator.php
  • includes/helper-functions.php
  • tests/phpunit/helper-functions/NormalizeFkGradeTest.php

Comment on lines +1080 to 1083
$simplified_summary_grade = edac_normalize_fk_grade( $text_statistics->fleschKincaidGradeLevel( $simplified_summary ) );
}

$simplified_summary_grade_failed = $simplified_summary_grade >= 9;

@coderabbitai coderabbitai Bot May 29, 2026

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Align REST failure threshold with “above 9th grade” semantics.

Line 1083 uses >= 9, which treats exactly 9th grade as failed. That conflicts with the “above 9th grade” behavior used in other updated paths, so REST/sidebar can disagree with AJAX for grade 9.

Proposed fix
-		$simplified_summary_grade_failed      = $simplified_summary_grade >= 9;
+		$simplified_summary_grade_failed      = $simplified_summary_grade > 9;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
$simplified_summary_grade = edac_normalize_fk_grade( $text_statistics->fleschKincaidGradeLevel( $simplified_summary ) );
}
$simplified_summary_grade_failed = $simplified_summary_grade >= 9;
$simplified_summary_grade = edac_normalize_fk_grade( $text_statistics->fleschKincaidGradeLevel( $simplified_summary ) );
}
$simplified_summary_grade_failed = $simplified_summary_grade > 9;
🤖 Prompt for 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.

In `@includes/classes/class-rest-api.php` around lines 1080 - 1083, The REST path
incorrectly marks exactly 9th grade as failing by setting
$simplified_summary_grade_failed with the condition "$simplified_summary_grade
>= 9"; change the threshold to strictly greater-than so it matches the “above
9th grade” semantics used elsewhere (i.e. use "$simplified_summary_grade > 9").
Update the assignment that computes $simplified_summary_grade_failed (after
edac_normalize_fk_grade( $text_statistics->fleschKincaidGradeLevel(
$simplified_summary ) )) to use the > operator so REST/sidebar agrees with the
AJAX path.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Intentionally not addressing this in PR #1725 — we've opened a dedicated issue #1797 to fix all the inconsistent grade-9 thresholds across the codebase (including this one and the class-ajax.php:669 case) with proper references to WCAG 3.1.5.

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.

@pattonwebz Understood — thanks for clarifying. Deferring this from #1725 and handling the grade-9 threshold consistency work in #1797 makes sense, especially if you want to align all affected paths together with the WCAG 3.1.5 rationale. I’m good to leave this out of the current PR.

pattonwebz and others added 2 commits June 27, 2026 14:36
The fleschKincaidGradeLevel() library method returns false when content
has no words or sentences. Remove the strict float type hint and cast
to float internally so empty-content posts don't throw a TypeError.
Add false and null test cases to cover this path.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Release tooling will replace x.x.x with the actual version on release.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

@pattonwebz pattonwebz left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I tested this and it is working for the most part. I did run into the issue that gemini called out about possible false value instead of a float. I tackled the AI review comments about it and added the test cases to cover false and null scenarios.

I also changed the since tags to be x.x.x and am opening a PR that will add a tool to fill their version numbers in as part of the release prep phase.

@pattonwebz
pattonwebz merged commit 137f04c into develop Jul 8, 2026
18 checks passed
@pattonwebz
pattonwebz deleted the steve/pro-626-bug-fk-reading-grade-of-0-x-1-collapses-to-0-should branch July 8, 2026 18:27
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.

Bug: FK Reading Grade of 0 < x < 1 Collapses to 0 (Should Normalize to 1 for Compliance)

2 participants