cleanups
[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 use UnexpectedValueException;
10
11 class Ref implements RefPropertyInterface
12 {
13 use RefProperty;
14
15 function __construct(Mapper $mapper, $property) {
16 $this->mapper = $mapper;
17 $this->property = $property;
18 }
19
20 function read(Row $row, $objectToUpdate) {
21 $val = $this->extract($objectToUpdate);
22 if (!isset($val)) {
23 $map = $this->mapper->mapOf($this->refClass);
24 $ref = $map->refOf($row, $this->refName, $objects)->current();
25 $this->assign($objectToUpdate, current($objects));
26 $map->map($ref);
27 }
28 }
29
30 function write($object, Row $rowToUpdate) {
31 $map = $this->mapper->mapOf($this->refClass);
32 $ref = $this->extract($object);
33 if (!$rel = $map->relOf($this->container, $this->refName)) {
34 throw new UnexpectedValueException(
35 sprintf("Unrelated reference from %s to %s with name %s",
36 $this->container->getGateway()->getName(),
37 $map->getGateway()->getName(),
38 $this->refName));
39 }
40 foreach ($rel as $fgn => $col) {
41 foreach ($this->findFieldProperty($col) as $property) {
42 $value = $property->extract($ref);
43 $rowToUpdate->$fgn = $value;
44 }
45 }
46 }
47
48 private function findFieldProperty($col) {
49 $map = $this->mapper->mapOf($this->refClass);
50 return array_filter($map->getProperties(), function($property) use($col) {
51 return $property->exposes($col);
52 });
53 }
54 }