FileListingTest.php / testFileListingPages - Make sure that the referenced value variable is unset after the loop

Created on 26 July 2023, 11 months ago
Updated 3 August 2023, 11 months ago

Problem/Motivation

When a reference is used in a foreach loop instead of using a simple variable, the reference remains assigned and keeps its "value" which is a reference, even after the foreach execution. Most of the time, this is not what the developer is expecting and the reference may be used wrongly in the rest of the code. For this reason, it is recommended to always unset a reference that is used in a foreach to avoid any unexpected side effects. Make sure that the referenced value variable is unset after the loop.

File: core/modules/file/tests/src/Functional/FileListingTest.php

line: 108
foreach ($nodes as &$node) {
      $this->drupalGet('node/' . $node->id() . '/edit');
      $file = $this->getTestFile('image');
      $edit = [
        'files[file_0]' => \Drupal::service('file_system')->realpath($file->getFileUri()),
      ];
      $this->submitForm($edit, 'Save');
      $node = Node::load($node->id());
 }

Steps to reproduce

Testprogramm:

<?php
$help = ['A' => 'b', 'C' => 'd'];
print_r($help);
foreach ($help as $id => &$help_info) {
        $help_info = [ 'id' => $id ];
}
print_r($help);
$i=0;
foreach ($help as $id => $help_info) {
        $i++;
}
print_r($help);
?>

The output is as follows:
Array
(
    [A] => b
    [C] => d
)
Array
(
    [A] => Array
        (
            [id] => A
        )
    [C] => Array
        (
            [id] => C
        )
)
Array
(
    [A] => Array
        (
            [id] => A
        )
    [C] => Array
        (
            [id] => A   <===
        )
)

Proposed resolution

line: 108
foreach ($nodes as &$node) {
      $this->drupalGet('node/' . $node->id() . '/edit');
      $file = $this->getTestFile('image');
      $edit = [
        'files[file_0]' => \Drupal::service('file_system')->realpath($file->getFileUri()),
      ];
      $this->submitForm($edit, 'Save');
      $node = Node::load($node->id());
 }
 unset($node);

Remaining tasks

no

User interface changes

no

API changes

no

Data model changes

no

Release notes snippet

🐛 Bug report
Status

Active

Version

11.0 🔥

Component
File module 

Last updated 3 days ago

Created by

🇩🇪Germany fnalb2

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

Comments & Activities

Production build 0.69.0 2024