Passed
Push — ft/pagefield ( db2ad6...f2722b )
by Ben
10:27
created

FieldRepository::find()   A

Complexity

Conditions 4
Paths 6

Size

Total Lines 17
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

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