phpdoc
[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 $map = $this->mapper->mapOf($this->refClass);
49 $ref = $this->extract($object);
50 if (!$rel = $map->relOf($this->container, $this->refName)) {
51 throw new UnexpectedValueException(
52 sprintf("Unrelated reference from %s to %s with name %s",
53 $this->container->getGateway()->getName(),
54 $map->getGateway()->getName(),
55 $this->refName));
56 }
57 foreach ($rel as $fgn => $col) {
58 foreach ($this->findFieldProperty($col) as $property) {
59 $value = $property->extract($ref);
60 $rowToUpdate->$fgn = $value;
61 }
62 }
63 }
64
65 /**
66 * Find the property exposing $col
67 * @param string $col
68 * @return PropertyInterface[]
69 */
70 private function findFieldProperty($col) {
71 $map = $this->mapper->mapOf($this->refClass);
72 return array_filter($map->getProperties(), function($property) use($col) {
73 return $property->exposes($col);
74 });
75 }
76 }