-
-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathDiscoveredConventions.php
More file actions
107 lines (81 loc) · 2.47 KB
/
DiscoveredConventions.php
File metadata and controls
107 lines (81 loc) · 2.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
<?php
/**
* This file is part of the Nette Framework (https://nette.org)
* Copyright (c) 2004 David Grudl (https://davidgrudl.com)
*/
namespace Nette\Database\Conventions;
use Nette\Database\IConventions;
use Nette\Database\IStructure;
/**
* Conventions based on database structure.
*/
class DiscoveredConventions implements IConventions
{
/** @var IStructure */
protected $structure;
public function __construct(IStructure $structure)
{
$this->structure = $structure;
}
public function getPrimary($table)
{
return $this->structure->getPrimaryKey($table);
}
public function getForeign($table, $key)
{
return $this->structure->getForeignKey($table, $key);
}
public function getHasManyReference($nsTable, $key)
{
$candidates = $columnCandidates = [];
$targets = $this->structure->getHasManyReference($nsTable);
$table = preg_replace('#^(.*\.)?(.*)$#', '$2', $nsTable);
foreach ($targets as $targetNsTable => $targetColumns) {
$targetTable = preg_replace('#^(.*\.)?(.*)$#', '$2', $targetNsTable);
if (stripos($targetNsTable, $key) === FALSE) {
continue;
}
foreach ($targetColumns as $targetColumn) {
if (stripos($targetColumn, $table) !== FALSE) {
$columnCandidates[] = $candidate = [$targetNsTable, $targetColumn];
if (strcmp($targetTable, $key) === 0 || strcmp($targetNsTable, $key) === 0) {
return $candidate;
}
}
$candidates[] = [$targetTable, [$targetNsTable, $targetColumn]];
}
}
if (count($columnCandidates) === 1) {
return $columnCandidates[0];
} elseif (count($candidates) === 1) {
return $candidates[0][1];
}
foreach ($candidates as $candidate) {
if (strtolower($candidate[0]) === strtolower($key)) {
return $candidate[1];
}
}
if (!empty($candidates)) {
throw new AmbiguousReferenceKeyException('Ambiguous joining column in related call.');
}
if ($this->structure->isRebuilt()) {
return NULL;
}
$this->structure->rebuild();
return $this->getHasManyReference($nsTable, $key);
}
public function getBelongsToReference($table, $key)
{
$tableColumns = $this->structure->getBelongsToReference($table);
foreach ($tableColumns as $column => $targetTable) {
if (stripos($column, $key) !== FALSE || stripos($targetTable, $key) !== FALSE) { //also check if any reference exists
return [$targetTable, $column];
}
}
if ($this->structure->isRebuilt()) {
return NULL;
}
$this->structure->rebuild();
return $this->getBelongsToReference($table, $key);
}
}