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

HasBackReference   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 37
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
dl 0
loc 37
rs 10
c 0
b 0
f 0
wmc 6

5 Methods

Rating   Name   Duplication   Size   Complexity  
A inProperty() 0 3 1
A name() 0 3 1
A hydrating() 0 3 1
A __construct() 0 3 1
A value() 0 6 2
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