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