1: <?php
2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13:
14:
15: 16: 17: 18: 19: 20: 21: 22: 23:
24: class Horde_Db_Migration_Base
25: {
26: 27: 28: 29:
30: public $version = null;
31:
32: 33: 34: 35:
36: protected $_logger;
37:
38: 39: 40: 41:
42: protected $_connection;
43:
44:
45: 46: 47:
48:
49: 50:
51: public function __construct(Horde_Db_Adapter $connection, $version = null)
52: {
53: $this->_connection = $connection;
54: $this->version = $version;
55: }
56:
57:
58: 59: 60:
61:
62: 63: 64: 65: 66:
67: public function __call($method, $args)
68: {
69: $a = array();
70: foreach ($args as $arg) {
71: if (is_array($arg)) {
72: $vals = array();
73: foreach ($arg as $key => $value) {
74: $vals[] = var_export($key, true) . ' => ' . var_export($value, true);
75: }
76: $a[] = 'array(' . implode(', ', $vals) . ')';
77: } else {
78: $a[] = var_export($arg, true);
79: }
80: }
81: $this->say("$method(" . implode(", ", $a) . ")");
82:
83:
84: $t = new Horde_Support_Timer();
85: $t->push();
86: $result = call_user_func_array(array($this->_connection, $method), $args);
87: $time = $t->pop();
88:
89:
90: $this->say(sprintf("%.4fs", $time), 'subitem');
91: if (is_int($result)) {
92: $this->say("$result rows", 'subitem');
93: }
94:
95: return $result;
96: }
97:
98: public function upWithBechmarks()
99: {
100: $this->migrate('up');
101: }
102:
103: public function downWithBenchmarks()
104: {
105: $this->migrate('down');
106: }
107:
108: 109: 110:
111: public function migrate($direction)
112: {
113: if (!method_exists($this, $direction)) { return; }
114:
115: if ($direction == 'up') { $this->announce("migrating"); }
116: if ($direction == 'down') { $this->announce("reverting"); }
117:
118: $result = null;
119: $t = new Horde_Support_Timer();
120: $t->push();
121: $result = $this->$direction();
122: $time = $t->pop();
123:
124: if ($direction == 'up') {
125: $this->announce("migrated (" . sprintf("%.4fs", $time) . ")");
126: $this->log();
127: }
128: if ($direction == 'down') {
129: $this->announce("reverted (" . sprintf("%.4fs", $time) . ")");
130: $this->log();
131: }
132: return $result;
133: }
134:
135: 136: 137:
138: public function log($text = '')
139: {
140: if ($this->_logger) {
141: $this->_logger->info($text);
142: }
143: }
144:
145: 146: 147:
148: public function setLogger($logger)
149: {
150: $this->_logger = $logger;
151: }
152:
153: 154: 155: 156:
157: public function announce($message)
158: {
159: $text = "$this->version " . get_class($this) . ": $message";
160: $length = 75 - strlen($text) > 0 ? 75 - strlen($text) : 0;
161:
162: $this->log(sprintf("== %s %s", $text, str_repeat('=', $length)));
163: }
164:
165: 166: 167: 168:
169: public function say($message, $subitem = false)
170: {
171: $this->log(($subitem ? " ->" : "--") . " $message");
172: }
173: }
174: