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