1: <?php
2:
3: 4: 5: 6: 7: 8: 9: 10: 11:
12:
13:
14:
15: 16: 17: 18: 19: 20:
21: class DatabaseReflection extends Object
22: {
23: const FIELD_TEXT = 'string',
24: FIELD_BINARY = 'bin',
25: FIELD_BOOL = 'bool',
26: FIELD_INTEGER = 'int',
27: FIELD_FLOAT = 'float',
28: FIELD_DATETIME = 'datetime';
29:
30:
31: private $primary;
32:
33:
34: private $foreign;
35:
36:
37: private $table;
38:
39:
40:
41: 42: 43: 44: 45: 46:
47: public function __construct($primary = 'id', $foreign = '%s_id', $table = '%s')
48: {
49: $this->primary = $primary;
50: $this->foreign = $foreign;
51: $this->table = $table;
52: }
53:
54:
55:
56: public function getPrimary($table)
57: {
58: return sprintf($this->primary, $table);
59: }
60:
61:
62:
63: public function getReferencingColumn($name, $table)
64: {
65: return $this->getReferencedColumn($table, $name);
66: }
67:
68:
69:
70: public function getReferencedColumn($name, $table)
71: {
72: if ($this->table !== '%s' && preg_match('(^' . str_replace('%s', '(.*)', preg_quote($this->table)) . '$)', $name, $match)) {
73: $name = $match[1];
74: }
75: return sprintf($this->foreign, $name, $table);
76: }
77:
78:
79:
80: public function getReferencedTable($name, $table)
81: {
82: return sprintf($this->table, $name, $table);
83: }
84:
85:
86:
87: 88: 89: 90: 91: 92:
93: public static function detectType($type)
94: {
95: static $types, $patterns = array(
96: 'BYTEA|BLOB|BIN' => self::FIELD_BINARY,
97: 'TEXT|CHAR' => self::FIELD_TEXT,
98: 'YEAR|BYTE|COUNTER|SERIAL|INT|LONG' => self::FIELD_INTEGER,
99: 'CURRENCY|REAL|MONEY|FLOAT|DOUBLE|DECIMAL|NUMERIC|NUMBER' => self::FIELD_FLOAT,
100: 'TIME|DATE' => self::FIELD_DATETIME,
101: 'BOOL|BIT' => self::FIELD_BOOL,
102: );
103:
104: if (!isset($types[$type])) {
105: $types[$type] = 'string';
106: foreach ($patterns as $s => $val) {
107: if (preg_match("#$s#i", $type)) {
108: return $types[$type] = $val;
109: }
110: }
111: }
112: return $types[$type];
113: }
114:
115: }
116: