Multiselect::getOptions() in 2.x is confusing

Created on 9 December 2023, over 1 year ago
Updated 18 January 2024, over 1 year ago

Problem/Motivation

While I was updating the 2.x branch to use Drupal.org's GitLab CI β†’ for automated linting and testing, I noticed that tests were failing in the 2.x branch. Manual testing suggested that tests were failing due to TypeError: array_search(): Argument #2 ($haystack) must be of type array, string given in array_search() (line 93 of web/modules/contrib/multiselect/src/Element/Multiselect.php). I ended up fixing the broken tests in commit 9e76427.

However, while trying to figure out how to fix the tests, I noticed that the logic in \Drupal\multiselect\Element\Multiselect::getOptions() was really difficult to follow, especially on the following lines:

/* L81 */ if (!($value_valid && ((!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value']))) || $empty_choice))) {
/* L91 */ if ($value_valid && ((!$value_is_array && (string) $element['#value'] === $key || ($value_is_array && in_array($key, $element['#value']))) || $empty_choice)) {

From personal experience, logic that is hard to follow makes debugging and maintenance harder. As a co-maintainer of this project, I want this module to be as easy to maintain as possible, so that I don't have to spend a lot of (unpaid) time maintaining it.

Proposed resolution

(Optional) Add unit/kernel tests for \Drupal\multiselect\Element\Multiselect::getOptions() so that it's easier to see if refactoring breaks functionality.

Refactor the code in \Drupal\multiselect\Element\Multiselect::getOptions(). I daresay temporary variables and/or helper functions with descriptive names would make it easier to see the intent of the authors.

Remaining tasks

  1. Write a patch or merge request
  2. Review and feedback
  3. RTBC and feedback
  4. Commit

User interface changes

None.

API changes

None.

Data model changes

None.

✨ Feature request
Status

Needs review

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