xref: /php-src/ext/pdo/tests/pdo_014.phpt (revision c1fec9bb)
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 test014(id int NOT NULL PRIMARY KEY, val VARCHAR(10), grp VARCHAR(10))');
19$db->exec("INSERT INTO test014 VALUES(1, 'A', 'Group1')");
20$db->exec("INSERT INTO test014 VALUES(2, 'B', 'Group2')");
21$SELECT = 'SELECT val, grp FROM test014';
22
23class TestClass
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, TestClass::class, 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--CLEAN--
75<?php
76require_once getenv('REDIR_TEST_DIR') . 'pdo_test.inc';
77$db = PDOTest::factory();
78PDOTest::dropTableIfExists($db, "test014");
79?>
80--EXPECTF--
81TestClass::__construct(WOW)
82object(TestClass)#%d (2) {
83  ["val"]=>
84  string(1) "A"
85  ["grp"]=>
86  string(6) "Group1"
87}
88TestClass::__construct(WOW)
89object(TestClass)#%d (2) {
90  ["val"]=>
91  string(1) "B"
92  ["grp"]=>
93  string(6) "Group2"
94}
95NULL
96bool(false)
97PDOStatementAggregate::__construct
98PDOStatementAggregate::getIterator
99array(2) {
100  [0]=>
101  string(1) "A"
102  [1]=>
103  string(6) "Group1"
104}
105array(2) {
106  [0]=>
107  string(1) "B"
108  [1]=>
109  string(6) "Group2"
110}
111