summaryrefslogtreecommitdiff
path: root/ext/spl/examples/dbareader.inc
blob: 095c5c29d5169e204c66b1bbf3bd5331fde8a067 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
<?php

/** @file dbareader.inc
 * @ingroup Examples
 * @brief class DbaReader
 * @author  Marcus Boerger
 * @date    2003 - 2005
 *
 * SPL - Standard PHP Library
 */

/** @ingroup Examples
 * @brief   This implements a DBA Iterator.
 * @author  Marcus Boerger
 * @version 1.0
 */
class DbaReader implements Iterator
{

	protected $db = NULL;
	private $key = false;
	private $val = false;

	/**
	 * Open database $file with $handler in read only mode.
	 *
	 * @param file    Database file to open.
	 * @param handler Handler to use for database access.
	 */
	function __construct($file, $handler) {
		if (!$this->db = dba_open($file, 'r', $handler)) {
		    throw new exception('Could not open file ' . $file);
		}
	}

	/**
	 * Close database.
	 */
	function __destruct() {
		dba_close($this->db);
	}

	/**
	 * Rewind to first element.
	 */
	function rewind() {
		$this->key = dba_firstkey($this->db);
		$this->fetch_data();
	}

	/**
	 * Move to next element.
	 *
	 * @return void
	 */
	function next() {
		$this->key = dba_nextkey($this->db);
		$this->fetch_data();
	}

    /**
     * Fetches the current data if $key is valid
     */
	private function fetch_data() {
		if ($this->key !== false) {
			$this->val = dba_fetch($this->key, $this->db);
		}
	}

	/**
	 * @return Current data.
	 */
	function current() {
		return $this->val;
	}

	/**
	 * @return Whether more elements are available.
	 */
	function valid() {
		if ($this->db && $this->key !== false) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * @return Current key.
	 */
	function key() {
		return $this->key;
	}
}

?>