1: <?php
2:
3: namespace PHPixie\ORM\Relationships\Type\Embeds\Type\One;
4:
5: class Handler extends \PHPixie\ORM\Relationships\Type\Embeds\Handler
6: {
7: protected function mapConditionBuilder($builder, $side, $collection, $plan)
8: {
9: $config = $side->config();
10: $builder->startConditionGroup($collection->logic(), $collection->isNegated());
11:
12: $builder->andNot($config->path, null);
13: $container = $builder->addSubdocumentPlaceholder($config->path);
14:
15: $this->mappers->conditions()->map(
16: $container,
17: $config->itemModel,
18: $collection->conditions(),
19: $plan
20: );
21:
22: $builder->endGroup();
23: }
24:
25:
26: public function loadProperty($config, $owner)
27: {
28: $document = $this->getEntityDocument($owner);
29: $item = $this->planners->document()->getDocument($document, $config->path, false);
30:
31: if($item !== null) {
32: $item = $this->models->embedded()->loadEntity($config->itemModel, $item);
33: $item->setOwnerRelationship($owner, $config->ownerItemProperty);
34: }
35: $property = $owner->getRelationshipProperty($config->ownerItemProperty);
36: $property->setValue($item);
37: }
38:
39: public function setItem($entity, $config, $item)
40: {
41: $this->assertModelName($item, $config->itemModel);
42: $this->removeItemFromOwner($item);
43: $this->setItemModel($entity, $config, $item);
44: }
45:
46: public function removeItem($entity, $config)
47: {
48: $property = $entity->getRelationshipProperty($config->ownerItemProperty);
49: $this->unsetCurrentItemOwner($property);
50:
51: list($document, $key) = $this->getParentDocumentAndKey($entity, $config);
52: $document->remove($key);
53: $property->setValue(null);
54: }
55:
56: public function createItem($entity, $config, $data)
57: {
58: $item = $this->models->embedded()->loadEntityFromData($config->itemModel, $data);
59: $this->setItemModel($entity, $config, $item);
60: }
61:
62: protected function setItemModel($entity, $config, $item)
63: {
64: $property = $entity->getRelationshipProperty($config->ownerItemProperty);
65: $this->unsetCurrentItemOwner($property);
66:
67: list($document, $key) = $this->getParentDocumentAndKey($entity, $config);
68: $document->set($key, $item->data()->document());
69: $item->setOwnerRelationship($entity, $config->ownerItemProperty);
70: $property->setValue($item);
71: }
72:
73: protected function unsetCurrentItemOwner($property)
74: {
75: if(!$property->isLoaded())
76: return;
77:
78: $oldItem = $property->value();
79: if($oldItem !== null) {
80: $oldItem->unsetOwnerRelationship();
81: }
82: }
83:
84: protected function getEntityDocument($entity)
85: {
86: return $entity->data()->document();
87: }
88:
89: protected function getParentDocumentAndKey($entity, $config)
90: {
91: $document = $this->getEntityDocument($entity);
92: $documentPlanner = $this->planners->document();
93: return $documentPlanner->getParentDocumentAndKey($document, $config->path, true);
94: }
95:
96: }
97: