Passed
Push — ft/fragments ( 6fc2e4...3b32df )
by Ben
11:43
created

FieldRepository   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 27
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 5
eloc 11
c 1
b 0
f 0
dl 0
loc 27
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A find() 0 17 4
1
<?php
2
declare(strict_types=1);
3
4
namespace Thinktomorrow\Chief\Fields;
5
6
use Thinktomorrow\Chief\Fields\Types\Field;
7
use Thinktomorrow\Chief\Fragments\FragmentField;
8
use Thinktomorrow\Chief\Management\Managers;
9
10
class FieldRepository
11
{
12
    /** @var Managers */
13
    private $managers;
14
15
    public function __construct(Managers $managers)
16
    {
17
        $this->managers = $managers;
18
    }
19
20
    public function find(FieldReference $reference): Field
21
    {
22
        $manager = $this->managers->findByKey($reference->getManagerKey());
23
24
        $field = $manager->fields()[($reference->hasFragmentKey() ? $reference->getFragmentKey() : $reference->getFieldKey())];
25
26
        if($reference->hasFragmentKey()) {
27
            if(!$field instanceof FragmentField) {
28
                throw new \RuntimeException('Field ' . $field->getKey() . ' was expected to be a fragmentfield but its not.');
29
            }
30
31
            $firstFragment = $field->getFragments()[0];
32
33
            return $firstFragment->getFields()[$reference->getFieldKey()];
34
        }
35
36
        return $field;
37
    }
38
}
39