3 namespace pq\Mapper\Property
;
7 use pq\Mapper\PropertyInterface
;
8 use pq\Mapper\RefProperty
;
9 use pq\Mapper\RefPropertyInterface
;
10 use UnexpectedValueException
;
12 class Ref
implements RefPropertyInterface
17 * Create a parent row mapping
18 * @param Mapper $mapper
19 * @param string $property
21 function __construct(Mapper
$mapper, $property) {
22 $this->mapper
= $mapper;
23 $this->property
= $property;
27 * Read the parent object
29 * @param object $objectToUpdate
31 function read(Row
$row, $objectToUpdate) {
32 $val = $this->extract($objectToUpdate);
34 $map = $this->mapper
->mapOf($this->refClass
);
35 $ref = $map->refOf($row, $this->refName
, $objects)->current();
36 $this->assign($objectToUpdate, current($objects));
42 * Write the parent row's foreign key
43 * @param object $object
44 * @param Row $rowToUpdate
45 * @throws UnexpectedValueException
47 function write($object, Row
$rowToUpdate) {
48 if (!$ref = $this->extract($object)) {
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(),
59 foreach ($rel as $fgn => $col) {
60 foreach ($this->findFieldProperty($col) as $property) {
61 $value = $property->extract($ref);
62 $rowToUpdate->$fgn = $value;
68 * Find the property exposing $col
70 * @return PropertyInterface[]
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);