data mapper POC
[m6w6/pq-gateway] / lib / pq / Mapper / Property / Ref.php
1 <?php
2
3 namespace pq\Mapper\Property;
4
5 use pq\Gateway\Row;
6 use pq\Mapper\Mapper;
7 use pq\Mapper\RefProperty;
8 use pq\Mapper\RefPropertyInterface;
9
10 class Ref implements RefPropertyInterface
11 {
12 use RefProperty;
13
14 function __construct(Mapper $mapper, $property) {
15 $this->mapper = $mapper;
16 $this->property = $property;
17 }
18
19 function read(Row $row, $objectToUpdate) {
20 $val = $this->extract($objectToUpdate);
21 if (!isset($val)) {
22 $map = $this->mapper->mapOf($this->refClass);
23 $ref = $map->refOf($row, $this->refName, $objects)->current();
24 $this->assign($objectToUpdate, current($objects));
25 $map->map($ref);
26 }
27 }
28
29 function write($object, Row $rowToUpdate) {
30 $map = $this->mapper->mapOf($this->refClass);
31 $ref = $this->extract($object);
32 $rel = $map->relOf($this->container, $this->refName);
33 foreach ($rel as $fgn => $col) {
34 foreach ($this->findFieldProperty($col) as $property) {
35 $value = $property->extract($ref);
36 $rowToUpdate->$fgn = $value;
37 }
38 }
39 }
40
41 private function findFieldProperty($col) {
42 $map = $this->mapper->mapOf($this->refClass);
43 return array_filter($map->getProperties(), function($property) use($col) {
44 return $property->exposes($col);
45 });
46 }
47
48
49 function read2(RowGateway $row) {
50 #echo __METHOD__." ".$this;
51 $map = $this->getRefMap();
52 $rel = $this->container->getGateway()->getRelation(
53 $map->getGateway()->getName(), $this->refName);
54 $key = array_combine($rel->referencedColumns, array_map(function($c) use($row) {
55 return $row->$c->get();
56 }, $rel->foreignColumns));
57 if (($obj = $this->mapper->objectOfRowId($this->refClass, $key))) {
58 yield $this->property => $obj;
59 } else foreach ($map->getGateway()->by($row, $this->refName) as $row) {
60 yield $this->property => $this->mapper->objectOf($this->refClass, $row);
61 }
62 }
63
64 function write2($object) {
65 #echo __METHOD__." ".$this;
66 $map = $this->getRefMap();
67 $rel = $this->container->getGateway()->getRelation(
68 $map->getGateway()->getName(), $this->refName);
69 $ref = $this->extract($object);
70 foreach ($rel as $fgn => $col) {
71 $fld = $map->getFieldMapping($col);
72 yield $fgn => $fld->extract($ref);
73 }
74 }
75 }