1: <?php
2:
3: namespace PHPixie\ORM\Planners\Planner;
4:
5: class Pivot extends \PHPixie\ORM\Planners\Planner
6: {
7: protected $planners;
8: protected $steps;
9: protected $database;
10:
11: public function __construct($planners, $steps, $database)
12: {
13: $this->planners = $planners;
14: $this->steps = $steps;
15: $this->database = $database;
16: }
17:
18: public function link($pivot, $firstSide, $secondSide, $plan)
19: {
20: $strategy = $this->selectStrategy($pivot, $firstSide, $secondSide);
21: $strategy->link($pivot, $firstSide, $secondSide, $plan);
22: }
23:
24: public function unlink($pivot, $firstSide, $secondSide, $plan)
25: {
26: $this->unlinkSides($pivot, $firstSide, $plan, $secondSide);
27: }
28:
29: public function unlinkAll($pivot, $side, $plan)
30: {
31: $this->unlinkSides($pivot, $side, $plan);
32: }
33:
34: protected function unlinkSides($pivot, $firstSide, $plan, $secondSide = null)
35: {
36: $sides = array($firstSide);
37:
38: if($secondSide !== null) {
39: $sides[]= $secondSide;
40: }
41:
42: $deleteQuery = $pivot->databaseDeleteQuery();
43:
44: foreach ($sides as $side) {
45: $this->planners->in()->itemIds(
46: $deleteQuery,
47: $side->pivotKey(),
48: $side->repository(),
49: $side->items(),
50: $plan
51: );
52: }
53:
54: $deleteStep = $this->steps->query($deleteQuery);
55: $plan->add($deleteStep);
56: }
57:
58: protected function selectStrategy($pivot, $firstSide, $secondSide)
59: {
60: $pivotConnection = $pivot->connection();
61:
62: if (!($pivotConnection instanceof \PHPixie\Database\Type\SQL\Connection)) {
63: return $this->strategy('multiquery');
64: }
65:
66: foreach(array($firstSide, $secondSide) as $side) {
67: if ($side !== null && $side->connection() !== $pivotConnection) {
68: return $this->strategy('multiquery');
69: }
70: }
71:
72: return $this->strategy('sql');
73: }
74:
75: public function pivot($connection, $source)
76: {
77: return new Pivot\Pivot($this->planners->query(), $connection, $source);
78: }
79:
80: public function pivotByConnectionName($connectionName, $source)
81: {
82: $connection = $this->database->connection($connectionName);
83: return $this->pivot($connection, $source);
84: }
85:
86: public function side($items, $repository, $pivotKey)
87: {
88: return new Pivot\Side($items, $repository, $pivotKey);
89: }
90:
91: protected function buildSqlStrategy()
92: {
93: return new \PHPixie\ORM\Planners\Planner\Pivot\Strategy\SQL(
94: $this->planners,
95: $this->steps
96: );
97: }
98:
99: protected function buildMultiqueryStrategy()
100: {
101: return new \PHPixie\ORM\Planners\Planner\Pivot\Strategy\Multiquery(
102: $this->planners,
103: $this->steps
104: );
105: }
106:
107: }
108: