xref: /PHP-7.1/ext/spl/examples/dbareader.inc (revision 03f3b847)
1<?php
2
3/** @file dbareader.inc
4 * @ingroup Examples
5 * @brief class DbaReader
6 * @author  Marcus Boerger
7 * @date    2003 - 2005
8 *
9 * SPL - Standard PHP Library
10 */
11
12/** @ingroup Examples
13 * @brief   This implements a DBA Iterator.
14 * @author  Marcus Boerger
15 * @version 1.0
16 */
17class DbaReader implements Iterator
18{
19
20	protected $db = NULL;
21	private $key = false;
22	private $val = false;
23
24	/**
25	 * Open database $file with $handler in read only mode.
26	 *
27	 * @param file    Database file to open.
28	 * @param handler Handler to use for database access.
29	 */
30	function __construct($file, $handler) {
31		if (!$this->db = dba_open($file, 'r', $handler)) {
32		    throw new exception('Could not open file ' . $file);
33		}
34	}
35
36	/**
37	 * Close database.
38	 */
39	function __destruct() {
40		dba_close($this->db);
41	}
42
43	/**
44	 * Rewind to first element.
45	 */
46	function rewind() {
47		$this->key = dba_firstkey($this->db);
48		$this->fetch_data();
49	}
50
51	/**
52	 * Move to next element.
53	 *
54	 * @return void
55	 */
56	function next() {
57		$this->key = dba_nextkey($this->db);
58		$this->fetch_data();
59	}
60
61    /**
62     * Fetches the current data if $key is valid
63     */
64	private function fetch_data() {
65		if ($this->key !== false) {
66			$this->val = dba_fetch($this->key, $this->db);
67		}
68	}
69
70	/**
71	 * @return Current data.
72	 */
73	function current() {
74		return $this->val;
75	}
76
77	/**
78	 * @return Whether more elements are available.
79	 */
80	function valid() {
81		if ($this->db && $this->key !== false) {
82			return true;
83		} else {
84			return false;
85		}
86	}
87
88	/**
89	 * @return Current key.
90	 */
91	function key() {
92		return $this->key;
93	}
94}
95
96?>
97