FilterBuilder: change how we determine if a condition group is empty

Created on 4 April 2024, 10 months ago
Updated 19 April 2024, 9 months ago

Problem/Motivation

The code in \Drupal\search_api_opensearch\SearchAPI\Query\FilterBuilder::buildFilters() skips building filters if the current condition group is empty.

It determines whether the condition group is empty by converting the condition group to a string, and seeing if that is empty...

public function buildFilters(ConditionGroupInterface $condition_group, array $index_fields) {
  ...
  if (!empty($condition_group->__toString())) {
    ...

PHPStan running at rule level 2 identifies this as an issue, because ConditionGroupInterface doesn't define a __toString() method (note that \Drupal\search_api\Query\ConditionGroup does, however)...

But, converting the condition group to a string is not the fastest way to do this: to convert to a string, it has to load and parse its own internal protected array $conditions (this array is returned by public function &getConditions()) — then it build a new array of strings, and then joins all those strings together).

Proposed resolution

Make it (incrementally) faster, and remove the PHPStan lint, by checking empty($condition_group->getConditions()) instead. (this is also @drunken monkey’s preferred approach — see #3428603-10: Declare that ConditionGroupInterface or ConditionGroup implements \Stringable .

We can also make things slightly easier to read by returning early as well...

 $filters = [];
 
-if (!empty($condition_group->__toString())) {
-  ... modify $filters array ...
-}
 
+if (empty($condition_group->getConditions())) {
+  return $filters;
+}
+
+... modify $filters array ...
 
 return $filters;

Remaining tasks

  1. Review and feedback
  2. RTBC and feedback
  3. Commit

User interface changes

None.

API changes

None.

Data model changes

None.

Feature request
Status

Fixed

Version

2.0

Component

Code

Created by

🇨🇦Canada mparker17 UTC-4

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