xref: /PHP-8.3/ext/pdo/tests/pdo_014.phpt (revision 902d6439)
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    public $val;
26    public $grp;
27
28    function __construct($name = 'N/A')
29    {
30        echo __METHOD__ . "($name)\n";
31    }
32}
33
34$stmt = $db->query($SELECT, PDO::FETCH_CLASS, 'Test', array('WOW'));
35
36$it = new IteratorIterator($stmt); /* check if we can convert that thing */
37
38/*** HINT: If YOU plan to do so remember not to call rewind() -> see below ***/
39
40foreach($it as $data)
41{
42    var_dump($data);
43}
44
45$it->next();              /* must be allowed */
46var_dump($it->current()); /* must return NULL */
47var_dump($it->valid());   /* must return false */
48
49class PDOStatementAggregate extends PDOStatement implements IteratorAggregate
50{
51    private function __construct()
52    {
53        echo __METHOD__ . "\n";
54        $this->setFetchMode(PDO::FETCH_NUM);
55        /* default fetch mode is BOTH, so we see if the ctor can overwrite that */
56    }
57
58    function getIterator(): Iterator
59    {
60        echo __METHOD__ . "\n";
61        $this->execute();
62        return new IteratorIterator($this, 'PDOStatement');
63    }
64}
65
66$stmt = $db->prepare($SELECT, array(PDO::ATTR_STATEMENT_CLASS=>array('PDOStatementAggregate')));
67
68foreach($stmt as $data)
69{
70    var_dump($data);
71}
72
73?>
74--EXPECTF--
75Test::__construct(WOW)
76object(Test)#%d (2) {
77  ["val"]=>
78  string(1) "A"
79  ["grp"]=>
80  string(6) "Group1"
81}
82Test::__construct(WOW)
83object(Test)#%d (2) {
84  ["val"]=>
85  string(1) "B"
86  ["grp"]=>
87  string(6) "Group2"
88}
89NULL
90bool(false)
91PDOStatementAggregate::__construct
92PDOStatementAggregate::getIterator
93array(2) {
94  [0]=>
95  string(1) "A"
96  [1]=>
97  string(6) "Group1"
98}
99array(2) {
100  [0]=>
101  string(1) "B"
102  [1]=>
103  string(6) "Group2"
104}
105