function StatementTest::testStatementForeachTwice

Same name in other branches
  1. 11.x core/tests/Drupal/KernelTests/Core/Database/StatementTest.php \Drupal\KernelTests\Core\Database\StatementTest::testStatementForeachTwice()

Tests a follow-on iteration on a statement using foreach.

File

core/tests/Drupal/KernelTests/Core/Database/StatementTest.php, line 231

Class

StatementTest
Tests the Statement classes.

Namespace

Drupal\KernelTests\Core\Database

Code

public function testStatementForeachTwice() : void {
    $statement = $this->connection
        ->query('SELECT * FROM {test}');
    $count = 0;
    foreach ($statement as $row) {
        $count++;
        $this->assertNotNull($row);
        if ($count > 2) {
            break;
        }
    }
    $this->assertSame(3, $count);
    // Restart iterating through the same statement. The foreach loop will try
    // rewinding the statement which should fail, and the counter should not be
    // increased.
    $this->expectError();
    $this->expectErrorMessage('Attempted rewinding a StatementInterface object when fetching has already started. Refactor your code to avoid rewinding statement objects.');
    foreach ($statement as $row) {
        // No-op.
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.