cleanups
[m6w6/pq-gateway] / lib / pq / Mapper / Property / All.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 All 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 $all = $map->allOf($row, $this->refName, $objects);
25 $this->assign($objectToUpdate, $objects);
26 $map->mapAll($all);
27 }
28 }
29
30 function write($object, Row $rowToUpdate) {
31 $property = $this->findRefProperty($object);
32 $map = $this->mapper->mapOf($this->refClass);
33 $refs = $this->extract($object);
34 foreach ($refs as $ref) {
35 $property->assign($ref, $object);
36 }
37 return function() use($map, $refs) {
38 foreach ($refs as $ref) {
39 $map->unmap($ref);
40 }
41 };
42 }
43
44 private function findRefProperty($object) {
45 $map = $this->mapper->mapOf($this->refClass);
46 $property = array_filter($map->getProperties(), function($property) use($object) {
47 if ($property instanceof RefPropertyInterface) {
48 return $property->references($object) && $property->on($this->refName);
49 }
50 });
51
52 if (1 != count($property)) {
53 // FIXME: move the decl
54 throw new UnexpectedValueException(
55 sprintf("%s does not reference %s exactly once through %s",
56 $this->refClass, $this->container->getClass(), $this->refName));
57 }
58 return current($property);
59 }
60 }