Completed
Push — master ( cd03ce...a0b884 )
by Jesse
02:19
created

HasBackReference::value()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 6
nc 3
nop 2
dl 0
loc 10
rs 9.4285
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\Hydration\Hydrates;
8
use Stratadox\Hydration\MapsProperty;
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
17
{
18
    private $name;
19
    private $sourceHydrator;
20
21
    private function __construct(string $name, ?Hydrates $source)
22
    {
23
        $this->name = $name;
24
        $this->sourceHydrator = $source;
25
    }
26
27
    public static function inProperty(string $name, Hydrates $source = null) : self
28
    {
29
        return new self($name, $source);
30
    }
31
32
    /** @inheritdoc */
33
    public function name() : string
34
    {
35
        return $this->name;
36
    }
37
38
    public function setSource(Hydrates $source)
39
    {
40
        $this->sourceHydrator = $source;
41
    }
42
43
    /** @inheritdoc @return mixed|object */
44
    public function value(array $data, $owner = null)
45
    {
46
        if (!isset($this->sourceHydrator)) {
47
            throw NoSourceHydrator::tryingToHydrateBackReferenceIn($this->name);
48
        }
49
        $instance = $this->sourceHydrator->currentInstance();
50
        if (!isset($instance)) {
51
            throw NoReferrerFound::tryingToHydrateBackReferenceIn($this->name);
52
        }
53
        return $instance;
54
    }
55
}
56