1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Soluble Components (http://belgattitude.github.io/solublecomponents) |
4
|
|
|
* |
5
|
|
|
* @link http://github.com/belgattitude/solublecomponents for the canonical source repository |
6
|
|
|
* @copyright Copyright (c) 2013-2014 Sébastien Vanvelthem |
7
|
|
|
* @license https://github.com/belgattitude/solublecomponents/blob/master/LICENSE.txt MIT License |
8
|
|
|
*/ |
9
|
|
|
|
10
|
|
|
namespace Soluble\Normalist\Synthetic\Table; |
11
|
|
|
|
12
|
|
|
use Soluble\Normalist\Synthetic\Table; |
13
|
|
|
use Soluble\Normalist\Synthetic\Record; |
14
|
|
|
use Soluble\Normalist\Synthetic\Exception; |
15
|
|
|
|
16
|
|
|
class Relation |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* |
20
|
|
|
* @var Table |
21
|
|
|
*/ |
22
|
|
|
protected $table; |
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* |
26
|
|
|
* @param Table $table |
27
|
|
|
*/ |
28
|
5 |
|
public function __construct(Table $table) |
29
|
|
|
{ |
30
|
5 |
|
$this->table = $table; |
31
|
5 |
|
} |
32
|
|
|
|
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Return parent record |
36
|
|
|
* |
37
|
|
|
* @throws Exception\LogicException |
38
|
|
|
* @throws Exception\RelationNotFoundException |
39
|
|
|
* |
40
|
|
|
* @param Record $record |
41
|
|
|
* @param string $parent_table |
42
|
|
|
* @return Record|false |
43
|
|
|
*/ |
44
|
4 |
|
public function getParent(Record $record, $parent_table) |
45
|
|
|
{ |
46
|
4 |
|
if ($record->getState() == Record::STATE_DELETED) { |
47
|
1 |
|
throw new Exception\LogicException(__METHOD__ . ": Logic exception, cannot operate on record that was deleted"); |
48
|
|
|
} |
49
|
|
|
|
50
|
3 |
|
$tableName = $this->table->getTableName(); |
51
|
3 |
|
$relations = $this->table->getTableManager()->metadata()->getForeignKeys($tableName); |
52
|
|
|
//$rels = array(); |
53
|
3 |
|
foreach ($relations as $column => $parent) { |
54
|
3 |
|
if ($parent['referenced_table'] == $parent_table) { |
55
|
|
|
// @todo, check the case when |
56
|
|
|
// table has many relations to the same parent |
57
|
|
|
// we'll have to throw an exception |
58
|
1 |
|
$record = $this->table->getTableManager()->table($parent_table)->findOneBy([ |
59
|
1 |
|
$parent['referenced_column'] => $record->offsetGet($column) |
60
|
1 |
|
]); |
61
|
1 |
|
return $record; |
62
|
|
|
} |
63
|
2 |
|
} |
64
|
2 |
|
throw new Exception\RelationNotFoundException(__METHOD__ . ": Cannot find parent relation between table '$tableName' and '$parent_table'"); |
65
|
|
|
} |
66
|
|
|
} |
67
|
|
|
|