Skip to content

Added project-level rector configuration and applied fixes.#328

Merged
AlexSkrypnyk merged 3 commits intomasterfrom
feature/rector-config
Apr 17, 2026
Merged

Added project-level rector configuration and applied fixes.#328
AlexSkrypnyk merged 3 commits intomasterfrom
feature/rector-config

Conversation

@AlexSkrypnyk
Copy link
Copy Markdown
Collaborator

@AlexSkrypnyk AlexSkrypnyk commented Apr 17, 2026

Summary

  • Added a project-level rector.php configuration targeting PHP 7.4, replacing the previous approach of copying palantirnet/drupal-rector's config into the drupal/ directory before running Rector against a limited set of files.
  • The new config enables dead code, code quality, coding style, early return, and instanceof rule sets, with targeted skips for rules that conflict with Drupal coding standards or the existing mixed-type codebase.
  • Simplified composer lint and composer lint-fix scripts to invoke rector process directly using the project-level config, removing the fragile cp + cd workaround.
  • Applied Rector fixes across 18 source and test files, covering: removal of useless variables, strict array_search() comparisons, ternary-to-null-coalescing simplifications, explicit return statements, encapsulated string literals converted to sprintf(), and dead code removal.

Test plan

  • Run composer lint and confirm Rector reports no remaining fixable issues.
  • Run composer test and confirm all existing tests pass.
  • Verify rector.php is picked up automatically without any cp or directory-change steps.

Summary by CodeRabbit

  • Bug Fixes

    • Enhanced permission and entity validation with stricter type checking
    • Improved error message clarity and consistency
  • Refactor

    • Streamlined internal logic and simplified code across multiple modules
    • Optimized field handling and validation workflows
  • Chores

    • Updated code quality configuration and development tooling

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Apr 17, 2026

Warning

Rate limit exceeded

@AlexSkrypnyk has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 47 minutes and 28 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 47 minutes and 28 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3c3339dc-b2c6-4f96-971c-79db51cca6bf

📥 Commits

Reviewing files that changed from the base of the PR and between 9a1545e and ea8f8a7.

📒 Files selected for processing (3)
  • src/Drupal/Driver/Cores/Drupal6.php
  • src/Drupal/Driver/Cores/Drupal8.php
  • src/Drupal/Driver/Fields/Drupal7/ListTextHandler.php
📝 Walkthrough

Walkthrough

This pull request refactors the codebase to improve code quality across multiple files. Key changes include: updating composer.json rector commands to use a centralized rector.php configuration, adding a new rector.php file with strict typing and multiple rule sets, adopting stricter type comparisons throughout the codebase, converting string concatenation to sprintf formatting in multiple locations, removing unnecessary intermediate variables and property initializations, and adjusting conditional logic in several field handlers.

Changes

Cohort / File(s) Summary
Configuration and Build
composer.json, rector.php
Updated composer script commands to use centralized Rector configuration; added new rector.php with strict typing, PHP 7.4 rulesets, and skip list configuration.
Core Drupal Drivers
src/Drupal/Driver/Cores/Drupal6.php, src/Drupal/Driver/Cores/Drupal7.php, src/Drupal/Driver/Cores/Drupal8.php
Applied stricter comparisons (strict ===/!==), replaced string concatenation with sprintf(), simplified return flows by removing intermediate variables, and adjusted conditional logic for null/empty checks.
Driver Base Classes
src/Drupal/Driver/DrupalDriver.php, src/Drupal/Driver/DrushDriver.php
Updated version caching check to strict null comparison, changed constant detection syntax, refactored argument parsing and output handling with stricter comparisons and sprintf() formatting.
Field Handlers (Drupal 7)
src/Drupal/Driver/Fields/Drupal7/AbstractHandler.php, src/Drupal/Driver/Fields/Drupal7/ListTextHandler.php, src/Drupal/Driver/Fields/Drupal7/TaxonomyTermReferenceHandler.php
Removed explicit null initialization from property declarations, applied strict array comparison in array_search() calls, and added explicit null return in vocabulary resolution.
Field Handlers (Drupal 8)
src/Drupal/Driver/Fields/Drupal8/AbstractHandler.php, src/Drupal/Driver/Fields/Drupal8/AddressHandler.php, src/Drupal/Driver/Fields/Drupal8/EntityReferenceHandler.php, src/Drupal/Driver/Fields/Drupal8/ImageHandler.php, src/Drupal/Driver/Fields/Drupal8/ListHandlerBase.php, src/Drupal/Driver/Fields/Drupal8/SupportedImageHandler.php, src/Drupal/Driver/Fields/Drupal8/TimeHandler.php
Removed explicit null property initialization, inverted conditional logic for bundle selection, replaced anonymous closures with arrow functions, simplified return flows, applied strict comparisons, removed type casts, and replaced string interpolation with sprintf().
Test Files
tests/Drupal/Tests/Driver/Drupal8FieldMethodsTest.php, tests/Drupal/Tests/Driver/Drupal8Test.php, tests/Drupal/Tests/Driver/FieldHandlerAbstractTestBase.php
Updated class constant references, replaced string concatenation with sprintf() in assertion messages, changed method visibility from public to protected, and added formatting whitespace.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~35 minutes

Possibly related PRs

Poem

🐰 Hopping through the code with care,
Stricter types beyond compare!
Sprintf hops where strings once played,
Properties cleaned, intermediate variables swayed,
Quality sprouts in every file,
This refactor brings us style! 🌱

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Added project-level rector configuration and applied fixes' accurately and specifically describes the main change in the PR: adding a rector.php configuration file and applying the resulting code fixes across the codebase.
Docstring Coverage ✅ Passed Docstring coverage is 97.73% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/rector-config

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 and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/Drupal/Driver/Cores/Drupal8.php (1)

210-218: ⚠️ Potential issue | 🟠 Major

Static cache is never populated — Rector broke the drupal_static reference pattern.

The original pattern was to assign the computed value back into the referenced $permissions so subsequent calls hit the static cache. Returning the service call directly from inside the !isset($permissions) branch means the reference is never written; the static cache stays NULL, every invocation re-executes the service lookup + getPermissions(), and the trailing return $permissions; at line 217 is unreachable on the first call and returns the empty uncached NULL path afterward... actually it never runs at all because the first-call branch always returns.

🔧 Suggested fix
   protected function getAllPermissions() {
     $permissions = &drupal_static(__FUNCTION__);

     if (!isset($permissions)) {
-      return \Drupal::service('user.permissions')->getPermissions();
+      $permissions = \Drupal::service('user.permissions')->getPermissions();
     }

     return $permissions;
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Drupal/Driver/Cores/Drupal8.php` around lines 210 - 218, The
drupal_static cache in getAllPermissions() is never populated because the code
returns the service result directly instead of assigning it into the referenced
$permissions; update getAllPermissions() so that when !isset($permissions) you
assign the result of \Drupal::service('user.permissions')->getPermissions() into
$permissions (via the existing drupal_static reference) and then return
$permissions, ensuring subsequent calls read the cached value rather than
re-calling the service.
🧹 Nitpick comments (3)
tests/Drupal/Tests/Driver/FieldHandlerAbstractTestBase.php (1)

15-17: Consider calling parent::tearDown().

The visibility change to protected is correct for PHPUnit 8+. While here, consider invoking parent::tearDown() after \Mockery::close() so future TestCase teardown hooks are not silently skipped. Non-blocking.

Proposed tweak
   protected function tearDown(): void {
     \Mockery::close();
+    parent::tearDown();
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/Drupal/Tests/Driver/FieldHandlerAbstractTestBase.php` around lines 15 -
17, The tearDown method currently calls \Mockery::close() but omits invoking the
base class teardown; update the FieldHandlerAbstractTestBase::tearDown() method
to call parent::tearDown() (after \Mockery::close()) so any TestCase teardown
hooks run as expected, keeping the method protected and returning void.
src/Drupal/Driver/Fields/Drupal8/EntityReferenceHandler.php (1)

21-25: Lines 23-25 are now dead code.

After the ternary on line 21, $label_key is unconditionally 'name' whenever $entity_type_id === 'user', so the if (!$label_key && $entity_type_id == 'user') block can never execute. Safe to remove for clarity (this block was likely already unreachable pre-refactor, but the ternary makes it obvious).

Proposed cleanup
     // Determine label field key.
     $label_key = $entity_type_id !== 'user' ? $entity_definition->getKey('label') : 'name';
-
-    if (!$label_key && $entity_type_id == 'user') {
-      $label_key = 'name';
-    }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Drupal/Driver/Fields/Drupal8/EntityReferenceHandler.php` around lines 21
- 25, The ternary assignment to $label_key in EntityReferenceHandler makes the
subsequent if check "if (!$label_key && $entity_type_id == 'user')" dead code;
remove that unreachable if block and any related comments so $label_key is only
set via "$label_key = $entity_type_id !== 'user' ?
$entity_definition->getKey('label') : 'name';" and ensure no other code relies
on the removed branch.
src/Drupal/Driver/Fields/Drupal8/AbstractHandler.php (1)

55-58: Dead code: $fieldsstring is built but never used.

The loop concatenates field names into $fieldsstring but the variable is never referenced afterward (it was presumably intended for the exception message on line 60, which now uses sprintf with only $field_name/$entity_type/$bundle). Rector's dead-code set should have flagged this — worth removing, or alternatively including $fieldsstring in the exception message to aid debugging.

♻️ Proposed cleanup
     $fields = $entity_field_manager->getFieldDefinitions($entity_type, $bundle);
-    $fieldsstring = '';
-    foreach ($fields as $key => $value) {
-      $fieldsstring = $fieldsstring . ", " . $key;
-    }
     if (empty($fields[$field_name])) {
       throw new \Exception(sprintf('The field "%s" does not exist on entity type "%s" bundle "%s".', $field_name, $entity_type, $bundle));
     }

Or, if the intent was to list available fields on error:

-    $fieldsstring = '';
-    foreach ($fields as $key => $value) {
-      $fieldsstring = $fieldsstring . ", " . $key;
-    }
     if (empty($fields[$field_name])) {
-      throw new \Exception(sprintf('The field "%s" does not exist on entity type "%s" bundle "%s".', $field_name, $entity_type, $bundle));
+      throw new \Exception(sprintf('The field "%s" does not exist on entity type "%s" bundle "%s". Available fields: %s.', $field_name, $entity_type, $bundle, implode(', ', array_keys($fields))));
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/Drupal/Driver/Fields/Drupal8/AbstractHandler.php` around lines 55 - 58,
Remove or use the dead variable $fieldsstring inside the loop over $fields:
either delete the $fieldsstring initialization and the foreach that concatenates
values since it is never read, or include $fieldsstring in the exception/sprintf
that currently references $field_name/$entity_type/$bundle so the built list of
available fields is reported on error; update the code around the foreach and
the exception (references: $fieldsstring, $fields, $field_name, $entity_type,
$bundle, sprintf in AbstractHandler) accordingly.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/Drupal/Driver/Cores/Drupal6.php`:
- Around line 360-362: The exception message contains a leftover "%s"
placeholder; replace the literal string with a formatted message using sprintf
so the vocabulary identifier is interpolated—change the throw in the Drupal6
class (where $term->vid is checked) to throw new \Exception(sprintf('No "%s"
vocabulary found.', $term->vid)); so the actual vocabulary value is shown.

In `@src/Drupal/Driver/Cores/Drupal8.php`:
- Around line 522-524: The sprintf call uses $entity (an object) causing a
TypeError and the format '%s->%s' is incorrect; update the exception in Drupal8
(in the entity creation code where $entity and $bundle_key are used) to pass a
string value for the bundle, e.g. use $entity->{$bundle_key} (or cast it to
string) instead of $entity and keep $bundle_key as the second arg so the call
becomes sprintf("Cannot create entity because provided bundle '%s->%s' does not
exist.", $entity->{$bundle_key}, $bundle_key); ensure the placeholder order
matches the passed values similar to Drupal7::entityCreate().

In `@src/Drupal/Driver/Fields/Drupal7/ListTextHandler.php`:
- Around line 28-31: The branch uses loose in_array but strict array_search
which can yield FALSE keys; in the ListTextHandler (same pattern as
Drupal8/ListHandlerBase::expand()) change the logic to perform a strict
array_search($value, $options, TRUE), check the result with !== FALSE, and only
then set $allowed_values[$value] = $key; also use strict in_array only if you
intend loose behavior—prefer using the strict array_search check and remove the
loose in_array to avoid assigning FALSE into $allowed_values (refer to $value,
$options, $allowed_values, array_search).

---

Outside diff comments:
In `@src/Drupal/Driver/Cores/Drupal8.php`:
- Around line 210-218: The drupal_static cache in getAllPermissions() is never
populated because the code returns the service result directly instead of
assigning it into the referenced $permissions; update getAllPermissions() so
that when !isset($permissions) you assign the result of
\Drupal::service('user.permissions')->getPermissions() into $permissions (via
the existing drupal_static reference) and then return $permissions, ensuring
subsequent calls read the cached value rather than re-calling the service.

---

Nitpick comments:
In `@src/Drupal/Driver/Fields/Drupal8/AbstractHandler.php`:
- Around line 55-58: Remove or use the dead variable $fieldsstring inside the
loop over $fields: either delete the $fieldsstring initialization and the
foreach that concatenates values since it is never read, or include
$fieldsstring in the exception/sprintf that currently references
$field_name/$entity_type/$bundle so the built list of available fields is
reported on error; update the code around the foreach and the exception
(references: $fieldsstring, $fields, $field_name, $entity_type, $bundle, sprintf
in AbstractHandler) accordingly.

In `@src/Drupal/Driver/Fields/Drupal8/EntityReferenceHandler.php`:
- Around line 21-25: The ternary assignment to $label_key in
EntityReferenceHandler makes the subsequent if check "if (!$label_key &&
$entity_type_id == 'user')" dead code; remove that unreachable if block and any
related comments so $label_key is only set via "$label_key = $entity_type_id !==
'user' ? $entity_definition->getKey('label') : 'name';" and ensure no other code
relies on the removed branch.

In `@tests/Drupal/Tests/Driver/FieldHandlerAbstractTestBase.php`:
- Around line 15-17: The tearDown method currently calls \Mockery::close() but
omits invoking the base class teardown; update the
FieldHandlerAbstractTestBase::tearDown() method to call parent::tearDown()
(after \Mockery::close()) so any TestCase teardown hooks run as expected,
keeping the method protected and returning void.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 05979bc8-634c-464f-9a3d-256d83cb6959

📥 Commits

Reviewing files that changed from the base of the PR and between c5134fa and 9a1545e.

📒 Files selected for processing (20)
  • composer.json
  • rector.php
  • src/Drupal/Driver/Cores/Drupal6.php
  • src/Drupal/Driver/Cores/Drupal7.php
  • src/Drupal/Driver/Cores/Drupal8.php
  • src/Drupal/Driver/DrupalDriver.php
  • src/Drupal/Driver/DrushDriver.php
  • src/Drupal/Driver/Fields/Drupal7/AbstractHandler.php
  • src/Drupal/Driver/Fields/Drupal7/ListTextHandler.php
  • src/Drupal/Driver/Fields/Drupal7/TaxonomyTermReferenceHandler.php
  • src/Drupal/Driver/Fields/Drupal8/AbstractHandler.php
  • src/Drupal/Driver/Fields/Drupal8/AddressHandler.php
  • src/Drupal/Driver/Fields/Drupal8/EntityReferenceHandler.php
  • src/Drupal/Driver/Fields/Drupal8/ImageHandler.php
  • src/Drupal/Driver/Fields/Drupal8/ListHandlerBase.php
  • src/Drupal/Driver/Fields/Drupal8/SupportedImageHandler.php
  • src/Drupal/Driver/Fields/Drupal8/TimeHandler.php
  • tests/Drupal/Tests/Driver/Drupal8FieldMethodsTest.php
  • tests/Drupal/Tests/Driver/Drupal8Test.php
  • tests/Drupal/Tests/Driver/FieldHandlerAbstractTestBase.php

Comment thread src/Drupal/Driver/Cores/Drupal6.php
Comment thread src/Drupal/Driver/Cores/Drupal8.php
Comment thread src/Drupal/Driver/Fields/Drupal7/ListTextHandler.php Outdated
@AlexSkrypnyk
Copy link
Copy Markdown
Collaborator Author

All three CodeRabbit findings fixed in ea8f8a7: restored sprintf in Drupal6 exception, corrected sprintf args in Drupal8 entityCreate, and replaced loose in_array + strict array_search with strict-only pattern in D7 ListTextHandler.

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.

1 participant