Add hasValues() method to Drupal\Core\TypedData\ListInterface as the opposite of isEmpty()

Created on 23 February 2025, 13 days ago

Problem/Motivation

The Drupal\Core\TypedData\ListInterface provides an isEmpty() method to check if a list has no values. However, there is no corresponding method to check if a list has values, leading to redundant negations like:

if (!$list->isEmpty()) {
    // The list has values.
}

A dedicated method would improve readability, making the code more intuitive and aligning with other API conventions.

Steps to reproduce

  1. Retrieve a list using a method that returns a ListInterface instance.
  2. Check if it contains values using !isEmpty() instead of a dedicated method.
  3. Notice the lack of a direct hasValues() method, requiring a negation.

Proposed resolution

  • Add a new hasValues() method to Drupal\Core\TypedData\ListInterface.
  • Implement hasValues() in Drupal\Core\TypedData\Plugin\DataType\ItemList and other necessary classes.
  • The method should return TRUE if the list contains at least one value, and FALSE otherwise.

Example Usage:

if ($this->get('field_example')->hasValues()) {
    // The list has values.
}

Remaining tasks

  • Implement hasValues() in ItemList.
  • Add the method to ListInterface.
  • Write test coverage for the new method.
  • Update documentation for ListInterface.
  • Figure out how to preserve backward compatibility
Feature request
Status

Active

Version

11.1 🔥

Component

base system

Created by

🇷🇺Russia Chi

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

Comments & Activities

Production build 0.71.5 2024