|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace SimpleCrud\Scheme; |
|
4
|
|
|
|
|
5
|
|
|
use SimpleCrud\SimpleCrud; |
|
6
|
|
|
|
|
7
|
|
|
/** |
|
8
|
|
|
* Base class used by all queries. |
|
9
|
|
|
*/ |
|
10
|
|
|
abstract class Scheme |
|
11
|
|
|
{ |
|
12
|
|
|
const HAS_ONE = 1; |
|
13
|
|
|
const HAS_MANY = 2; |
|
14
|
|
|
const HAS_MANY_TO_MANY = 4; |
|
15
|
|
|
|
|
16
|
|
|
protected $db; |
|
17
|
|
|
|
|
18
|
|
|
/** |
|
19
|
|
|
* Constructor. |
|
20
|
|
|
* |
|
21
|
|
|
* @param SimpleCrud $db |
|
22
|
|
|
*/ |
|
23
|
|
|
public function __construct(SimpleCrud $db) |
|
24
|
|
|
{ |
|
25
|
|
|
$this->db = $db; |
|
26
|
|
|
} |
|
27
|
|
|
|
|
28
|
|
|
/** |
|
29
|
|
|
* Return the database scheme. |
|
30
|
|
|
* |
|
31
|
|
|
* @return array |
|
32
|
|
|
*/ |
|
33
|
|
|
public function __invoke() |
|
34
|
|
|
{ |
|
35
|
|
|
$scheme = []; |
|
36
|
|
|
|
|
37
|
|
|
foreach ($this->getTables() as $table) { |
|
38
|
|
|
$scheme[$table] = [ |
|
39
|
|
|
'fields' => $this->getTableFields($table), |
|
40
|
|
|
'relations' => [], |
|
41
|
|
|
]; |
|
42
|
|
|
} |
|
43
|
|
|
|
|
44
|
|
|
foreach ($scheme as $table => &$info) { |
|
45
|
|
|
$foreingKey = "{$table}_id"; |
|
46
|
|
|
|
|
47
|
|
|
foreach ($scheme as $relTable => &$relInfo) { |
|
48
|
|
|
if (isset($relInfo['fields'][$foreingKey])) { |
|
49
|
|
|
$info['relations'][$relTable] = [self::HAS_MANY, $foreingKey]; |
|
50
|
|
|
$relInfo['relations'][$table] = [self::HAS_ONE, $foreingKey]; |
|
51
|
|
|
continue; |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
|
|
if ($table < $relTable) { |
|
55
|
|
|
$bridge = "{$table}_{$relTable}"; |
|
56
|
|
|
} else { |
|
57
|
|
|
$bridge = "{$relTable}_{$table}"; |
|
58
|
|
|
} |
|
59
|
|
|
|
|
60
|
|
|
if (isset($scheme[$bridge])) { |
|
61
|
|
|
$relForeingKey = "{$relTable}_id"; |
|
62
|
|
|
|
|
63
|
|
|
if (isset($scheme[$bridge]['fields'][$foreingKey]) && isset($scheme[$bridge]['fields'][$relForeingKey])) { |
|
64
|
|
|
$info['relations'][$relTable] = [self::HAS_MANY_TO_MANY, $bridge, $foreingKey, $relForeingKey]; |
|
65
|
|
|
$relInfo['relations'][$table] = [self::HAS_MANY_TO_MANY, $bridge, $relForeingKey, $foreingKey]; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
} |
|
70
|
|
|
|
|
71
|
|
|
return $scheme; |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
/** |
|
75
|
|
|
* Return all tables. |
|
76
|
|
|
* |
|
77
|
|
|
* @return array |
|
78
|
|
|
*/ |
|
79
|
|
|
abstract protected function getTables(); |
|
80
|
|
|
|
|
81
|
|
|
/** |
|
82
|
|
|
* Return the scheme of a table. |
|
83
|
|
|
* |
|
84
|
|
|
* @param string $table |
|
85
|
|
|
* |
|
86
|
|
|
* @return array |
|
87
|
|
|
*/ |
|
88
|
|
|
abstract protected function getTableFields($table); |
|
89
|
|
|
} |
|
90
|
|
|
|