Problem/Motivation

In subentity_theme_suggestions_alter(), $view_mode is only assigned inside the first if block but is read inside a second, independent if block. If $variables['elements']['#view_mode'] is empty or absent, the variable is never initialized and PHP 8 emits an E_WARNING (Undefined variable $view_mode).

// $view_mode is only set here...
if (!empty($variables['elements']['#view_mode'])) {
  $view_mode = $variables['elements']['#view_mode'];
  $suggestions[] = $hook . '__' . $view_mode;
}

// ...but read here, in a completely independent if block.
if ($subentity->bundle() !== 'subentity') {
  $bundle = $subentity->bundle();
  $suggestions[] = $hook . '__' . $bundle;
  if (!empty($view_mode)) { // E_WARNING if the first if was not entered
    $suggestions[] = $hook . '__' . $bundle . '__' . $view_mode;
  }
}

Proposed resolution

Initialize $view_mode to NULL before both blocks so the second check is always against a defined value:

$view_mode = NULL;

if (!empty($variables['elements']['#view_mode'])) {
  $view_mode = $variables['elements']['#view_mode'];
  $suggestions[] = $hook . '__' . $view_mode;
}

if ($subentity->bundle() !== 'subentity') {
  $bundle = $subentity->bundle();
  $suggestions[] = $hook . '__' . $bundle;
  if (!empty($view_mode)) {
    $suggestions[] = $hook . '__' . $bundle . '__' . $view_mode;
  }
}

Remaining tasks

  • Apply the one-line fix in subentity.module.
  • Add a unit or kernel test asserting that subentity_theme_suggestions_alter() does not produce warnings when #view_mode is absent.

Issue fork subentity-3593864

Command icon Show commands

Start within a Git clone of the project using the version control instructions.

Or, if you do not have SSH keys set up on git.drupalcode.org:

Comments

macsim created an issue. See original summary.

  • macsim committed 57394c1d on 3.x
    fix: #3593864 Fix uninitialized  variable in...
macsim’s picture

Status: Active » Fixed

Now that this issue is closed, review the contribution record.

As a contributor, attribute any organization that helped you, or if you volunteered your own time.

Maintainers, credit people who helped resolve this issue.

macsim’s picture

Version: 3.x-dev » 3.0.x-dev
macsim’s picture

Status: Fixed » Closed (fixed)