\Drupal calls should be avoided in classes, use dependency injection instead

Created on 16 May 2025, 4 days ago

Problem/Motivation

There are a few places in this module where \Drupal:: calls are used in classes. Best practice is to use dependency injection instead.

References:

This is a follow-up to πŸ“Œ Fix PHPStan errors Active , which added a phpstan-baseline.neon file to document and ignore these errors and allow PHPStan tests to pass.

Steps to reproduce

Remove the phpstan-baseline.neon file from the root directory of the codebase and run PHPStan. Observe the following errors:

 ------ ------------------------------------------------------------------------------ 
  Line   web/modules/jsonapi_schema/src/Normalizer/DataDefinitionNormalizer.php        
 ------ ------------------------------------------------------------------------------ 
  91     \Drupal calls should be avoided in classes, use dependency injection instead  
 ------ ------------------------------------------------------------------------------ 

 ------ ------------------------------------------------------------------------------------- 
  Line   web/modules/jsonapi_schema/src/Normalizer/RelationshipFieldDefinitionNormalizer.php  
 ------ ------------------------------------------------------------------------------------- 
  104    \Drupal calls should be avoided in classes, use dependency injection instead         
 ------ ------------------------------------------------------------------------------------- 

Proposed resolution

We should use dependency injection instead of \Drupal calls.

However, doing so would mean changing the __construct() arguments for our DataDefinitionNormalizer class, which all of our normalizer classes extend from, and which may be extended by contrib/custom normalizers downstream. As such, this should be considered a breaking change, and should not be done until we are ready to take a major version release, in line with semantic versioning.

Here is the parent issue for version 2.0: 🌱 [Meta, Plan] Version 2.0 Active .

Remaining tasks

  1. Open a merge request that removes phpstan-baseline.neon and replaces \Drupal calls with dependency injection.
  2. Keep the merge request updated if new \Drupal calls are introduced after πŸ“Œ Fix PHPStan errors Active is merged.
  3. Merge into the 2.x branch.
  4. Document this as a breaking change in the 2.0.0 release notes.

User interface changes

None.

API changes

This will change the __construct() parameters of the JSON:API Schema normalizer classes. Downstream classes in contrib or custom modules may need to update their code accordingly, if they are overriding the __construct() method themselves.

Data model changes

None.

πŸ“Œ Task
Status

Active

Version

1.0

Component

Code

Created by

πŸ‡ΊπŸ‡ΈUnited States m.stenta

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Merge Requests

Comments & Activities

Production build 0.71.5 2024