1: <?php
2:
3: namespace PHPixie\ORM\Relationships\Type\OneTo\Type\One;
4:
5: class Handler extends \PHPixie\ORM\Relationships\Type\OneTo\Handler
6: {
7: public function loadProperty($side, $related)
8: {
9: $value = parent::loadSingleProperty($side, $related);
10:
11: if($value === null) {
12: $this->unlinkProperties($side, $related);
13:
14: }elseif($side->type() === 'owner') {
15: $this->linkProperties($side->config(), $value, $related);
16:
17: }else{
18: $this->linkProperties($side->config(), $related, $value);
19: }
20: }
21:
22: public function linkPlan($config, $owner, $item)
23: {
24: $unlinkPlan = $this->getUnlinkPlan($config, true, $owner, true, $item, 'or');
25: $linkPlan = parent::linkPlan($config, $owner, $item);
26:
27: $plan = $this->plans->steps();
28:
29: $plan->appendPlan($unlinkPlan);
30: $plan->appendPlan($linkPlan);
31:
32: return $plan;
33: }
34:
35: public function unlinkPlan($side, $items)
36: {
37: $config = $side->config();
38:
39: if($side->type() === 'owner') {
40: return $this->getUnlinkPlan($config, false, null, true, $items);
41: }else{
42: return $this->getUnlinkPlan($config, true, $items, false, null);
43: }
44: }
45:
46: public function linkProperties($config, $owner, $item)
47: {
48: $this->processProperty('item', $config, $owner, 'set', $item);
49: $this->processProperty('owner', $config, $item, 'set', $owner);
50: }
51:
52:
53: protected function processProperty($type, $config, $entity, $action, $value = null, $unsetRelated = true)
54: {
55: if(!$this->isEntityValue($entity))
56: return;
57:
58: if($type === 'owner') {
59: $propertyName = $config->itemOwnerProperty;
60: $opposing = 'item';
61: }else{
62: $propertyName = $config->ownerItemProperty;
63: $opposing = 'owner';
64: }
65:
66: $property = $entity->getRelationshipProperty($propertyName);
67:
68: if($unsetRelated) {
69: if($property->isLoaded() && $property->value() !== null) {
70: $this->processProperty($opposing, $config, $property->value(), 'set', null, false);
71: }
72: }
73:
74: if($action === 'set' && !$this->isEntityValue($value))
75: $action = 'reset';
76:
77: if($action === 'reset') {
78: $property->reset();
79: }else{
80: $property->setValue($value);
81: }
82: }
83:
84: public function unlinkProperties($side, $entity)
85: {
86: $this->processProperty($side->type(), $side->config(), $entity, 'set', null);
87: }
88:
89: public function resetProperties($side, $items)
90: {
91: if(!is_array($items))
92: $items = array($items);
93:
94: foreach($items as $item)
95: $this->processProperty($side->type(), $side->config(), $item, 'reset');
96: }
97: }
98: