xref: /PHP-8.1/ext/pdo/tests/pdo_014.phpt (revision 74859783)
1--TEST--
2PDO Common: PDOStatement SPL iterator
3--EXTENSIONS--
4pdo
5--SKIPIF--
6<?php
7$dir = getenv('REDIR_TEST_DIR');
8if (false == $dir) die('skip no driver');
9require_once $dir . 'pdo_test.inc';
10PDOTest::skip();
11?>
12--FILE--
13<?php
14if (getenv('REDIR_TEST_DIR') === false) putenv('REDIR_TEST_DIR='.__DIR__ . '/../../pdo/tests/');
15require_once getenv('REDIR_TEST_DIR') . 'pdo_test.inc';
16$db = PDOTest::factory();
17
18$db->exec('CREATE TABLE test(id int NOT NULL PRIMARY KEY, val VARCHAR(10), grp VARCHAR(10))');
19$db->exec('INSERT INTO test VALUES(1, \'A\', \'Group1\')');
20$db->exec('INSERT INTO test VALUES(2, \'B\', \'Group2\')');
21$SELECT = 'SELECT val, grp FROM test';
22
23class Test
24{
25    function __construct($name = 'N/A')
26    {
27        echo __METHOD__ . "($name)\n";
28    }
29}
30
31$stmt = $db->query($SELECT, PDO::FETCH_CLASS, 'Test', array('WOW'));
32
33$it = new IteratorIterator($stmt); /* check if we can convert that thing */
34
35/*** HINT: If YOU plan to do so remember not to call rewind() -> see below ***/
36
37foreach($it as $data)
38{
39    var_dump($data);
40}
41
42$it->next();              /* must be allowed */
43var_dump($it->current()); /* must return NULL */
44var_dump($it->valid());   /* must return false */
45
46class PDOStatementAggregate extends PDOStatement implements IteratorAggregate
47{
48    private function __construct()
49    {
50        echo __METHOD__ . "\n";
51        $this->setFetchMode(PDO::FETCH_NUM);
52        /* default fetch mode is BOTH, so we see if the ctor can overwrite that */
53    }
54
55    function getIterator(): Iterator
56    {
57        echo __METHOD__ . "\n";
58        $this->execute();
59        return new IteratorIterator($this, 'PDOStatement');
60    }
61}
62
63$stmt = $db->prepare($SELECT, array(PDO::ATTR_STATEMENT_CLASS=>array('PDOStatementAggregate')));
64
65foreach($stmt as $data)
66{
67    var_dump($data);
68}
69
70?>
71--EXPECTF--
72Test::__construct(WOW)
73object(Test)#%d (2) {
74  ["val"]=>
75  string(1) "A"
76  ["grp"]=>
77  string(6) "Group1"
78}
79Test::__construct(WOW)
80object(Test)#%d (2) {
81  ["val"]=>
82  string(1) "B"
83  ["grp"]=>
84  string(6) "Group2"
85}
86NULL
87bool(false)
88PDOStatementAggregate::__construct
89PDOStatementAggregate::getIterator
90array(2) {
91  [0]=>
92  string(1) "A"
93  [1]=>
94  string(6) "Group1"
95}
96array(2) {
97  [0]=>
98  string(1) "B"
99  [1]=>
100  string(6) "Group2"
101}
102