storage test
[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\PropertyInterface;
8 use pq\Mapper\RefProperty;
9 use pq\Mapper\RefPropertyInterface;
10 use UnexpectedValueException;
11
12 class Ref implements RefPropertyInterface
13 {
14 use RefProperty;
15
16 /**
17 * Create a parent row mapping
18 * @param Mapper $mapper
19 * @param string $property
20 */
21 function __construct(Mapper $mapper, $property) {
22 $this->mapper = $mapper;
23 $this->property = $property;
24 }
25
26 /**
27 * Read the parent object
28 * @param Row $row
29 * @param object $objectToUpdate
30 */
31 function read(Row $row, $objectToUpdate) {
32 $val = $this->extract($objectToUpdate);
33 if (!isset($val)) {
34 $map = $this->mapper->mapOf($this->refClass);
35 $ref = $map->refOf($row, $this->refName, $objects)->current();
36 $this->assign($objectToUpdate, current($objects));
37 $map->map($ref);
38 }
39 }
40
41 /**
42 * Write the parent row's foreign key
43 * @param object $object
44 * @param Row $rowToUpdate
45 * @throws UnexpectedValueException
46 */
47 function write($object, Row $rowToUpdate) {
48 if (!$ref = $this->extract($object)) {
49 return;
50 }
51 $map = $this->mapper->mapOf($this->refClass);
52 if (!$rel = $map->relOf($this->container, $this->refName)) {
53 throw new UnexpectedValueException(
54 sprintf("Unrelated reference from %s to %s with name %s",
55 $this->container->getGateway()->getName(),
56 $map->getGateway()->getName(),
57 $this->refName));
58 }
59 foreach ($rel as $fgn => $col) {
60 foreach ($this->findFieldProperty($col) as $property) {
61 $value = $property->extract($ref);
62 $rowToUpdate->$fgn = $value;
63 }
64 }
65 }
66
67 /**
68 * Find the property exposing $col
69 * @param string $col
70 * @return PropertyInterface[]
71 */
72 private function findFieldProperty($col) {
73 $map = $this->mapper->mapOf($this->refClass);
74 return array_filter($map->getProperties(), function($property) use($col) {
75 return $property->exposes($col);
76 });
77 }
78 }