Passed
Push — master ( a0b884...c45d95 )
by Jesse
03:03
created

HasBackReference::hydrating()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Stratadox\Hydration\Mapping\Property\Relationship;
6
7
use Stratadox\HydrationMapping\MapsProperty;
8
use Stratadox\Hydrator\ObservesHydration;
9
10
/**
11
 * Maps a back-reference in a bidirectional relationship.
12
 *
13
 * @package Stratadox\Hydrate
14
 * @author Stratadox
15
 */
16
final class HasBackReference implements MapsProperty, ObservesHydration
17
{
18
    private $name;
19
    private $referenceTo;
20
21
    private function __construct(string $name)
22
    {
23
        $this->name = $name;
24
    }
25
26
    /**
27
     * Create a new mapping that refers back to the "owning" object.
28
     *
29
     * @param string $name The name of both the property.
30
     * @return self        The mapping for the bidirectional relationship.
31
     */
32
    public static function inProperty(string $name) : self
33
    {
34
        return new self($name);
35
    }
36
37
    public function name() : string
38
    {
39
        return $this->name;
40
    }
41
42
    public function hydrating($theInstance) : void
43
    {
44
        $this->referenceTo = $theInstance;
45
    }
46
47
    public function value(array $data, $owner = null)
48
    {
49
        if (!isset($this->referenceTo)) {
50
            throw NoReferrerFound::tryingToHydrateBackReferenceIn($this->name);
51
        }
52
        return $this->referenceTo;
53
    }
54
}
55