1: <?php
2: /**
3: * Copyright 2006-2012 Horde LLC (http://www.horde.org/)
4: *
5: * @author Chuck Hagenbuch <chuck@horde.org>
6: * @author James Pepin <james@jamespepin.com>
7: * @license http://www.horde.org/licenses/bsd
8: * @category Horde
9: * @package Db
10: */
11:
12: /**
13: * Class for parsing a stream into individual SQL statements.
14: *
15: * @author Chuck Hagenbuch <chuck@horde.org>
16: * @author James Pepin <james@jamespepin.com>
17: * @license http://www.horde.org/licenses/bsd
18: * @category Horde
19: * @package Db
20: */
21: class Horde_Db_StatementParser implements Iterator
22: {
23: protected $_count = 0;
24: protected $_currentStatement;
25:
26: public function __construct($file)
27: {
28: if (is_string($file)) {
29: $file = new SplFileObject($file, 'r');
30: }
31: $this->_file = $file;
32: }
33:
34: public function current()
35: {
36: if (is_null($this->_currentStatement)) {
37: $this->rewind();
38: }
39: return $this->_currentStatement;
40: }
41:
42: public function key()
43: {
44: if (is_null($this->_currentStatement)) {
45: $this->rewind();
46: }
47: return $this->_count;
48: }
49:
50: public function next()
51: {
52: if ($statement = $this->_getNextStatement()) {
53: $this->_count++;
54: return $statement;
55: }
56: return null;
57: }
58:
59: public function rewind()
60: {
61: $this->_count = 0;
62: $this->_currentStatement = null;
63: $this->_file->rewind();
64: $this->next();
65: }
66:
67: public function valid()
68: {
69: return !$this->_file->eof() && $this->_file->isReadable();
70: }
71:
72: /**
73: * Read the next sql statement from our file. Statements are terminated by
74: * semicolons.
75: *
76: * @return string The next SQL statement in the file.
77: */
78: protected function _getNextStatement()
79: {
80: $this->_currentStatement = '';
81: while (!$this->_file->eof()) {
82: $line = $this->_file->fgets();
83: if (!trim($line)) { continue; }
84: if (!$this->_currentStatement && substr($line, 0, 2) == '--') { continue; }
85:
86: $trimmedline = rtrim($line);
87: if (substr($trimmedline, -1) == ';') {
88: // Leave off the ending ;
89: $this->_currentStatement .= substr($trimmedline, 0, -1);
90: return $this->_currentStatement;
91: }
92:
93: $this->_currentStatement .= $line;
94: }
95:
96: return $this->_currentStatement;
97: }
98:
99: }
100: