Completed
Push — master ( 477ca5...2d5ed5 )
by Daniel
10s
created

ObjectType::createView()   B

Complexity

Conditions 3
Paths 3

Size

Total Lines 30
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 30
rs 8.8571
c 0
b 0
f 0
cc 3
eloc 18
nc 3
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\ContentType\Standard\View;
6
7
use Metadata\MetadataFactory;
8
use Metadata\NullMetadata;
9
use Psi\Component\ContentType\FieldLoader;
10
use Psi\Component\ContentType\View\TypeInterface;
11
use Psi\Component\ContentType\View\ViewFactory;
12
use Psi\Component\ContentType\View\ViewInterface;
13
use Symfony\Component\OptionsResolver\OptionsResolver;
14
15
class ObjectType implements TypeInterface
16
{
17
    private $metadataFactory;
18
    private $fieldLoader;
19
20
    public function __construct(
21
        MetadataFactory $metadataFactory,
22
        FieldLoader $fieldLoader
23
    ) {
24
        $this->metadataFactory = $metadataFactory;
25
        $this->fieldLoader = $fieldLoader;
26
    }
27
28
    public function createView(ViewFactory $factory, $data, array $options): ViewInterface
29
    {
30
        $classFqn = get_class($data);
31
        $metadata = $this->metadataFactory->getMetadataForClass($classFqn);
32
33
        if ($metadata instanceof NullMetadata) {
34
            throw new \RuntimeException(sprintf(
35
                'Class "%s" is not mapped',
36
                $classFqn
37
            ));
38
        }
39
40
        $map = [];
41
        foreach ($metadata->getPropertyMetadata() as $propertyMetadata) {
42
            $map[$propertyMetadata->getName()] = function () use ($propertyMetadata, $factory, $data) {
43
                $field = $this->fieldLoader->load(
44
                    $propertyMetadata->getType(),
45
                    $propertyMetadata->getOptions()
46
                );
47
48
                return $factory->create(
49
                    $field->getInnerField()->getViewType(),
50
                    $propertyMetadata->getValue($data),
51
                    $field->getViewOptions()
52
                );
53
            };
54
        }
55
56
        return new ObjectView($options['template'], $map);
57
    }
58
59
    public function configureOptions(OptionsResolver $options)
60
    {
61
        $options->setDefault('template', 'psi/object');
62
    }
63
}
64