Completed
Pull Request — master (#36)
by Daniel
02:20
created

ObjectView::buildView()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 9.4285
c 0
b 0
f 0
cc 3
eloc 12
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\View\View;
10
use Psi\Component\ContentType\View\ViewBuilder;
11
use Psi\Component\ContentType\View\ViewInterface;
12
use Symfony\Component\OptionsResolver\OptionsResolver;
13
14
class ObjectView implements ViewInterface
15
{
16
    private $metadataFactory;
17
    private $viewBuilder;
18
19
    public function __construct(
20
        MetadataFactory $metadataFactory,
21
        ViewBuilder $viewBuilder
22
    ) {
23
        $this->metadataFactory = $metadataFactory;
24
        $this->viewBuilder = $viewBuilder;
25
    }
26
27
    public function buildView(View $view, $data, array $options)
28
    {
29
        $classFqn = get_class($data);
30
        $metadata = $this->metadataFactory->getMetadataForClass($classFqn);
31
32
        if ($metadata instanceof NullMetadata) {
33
            throw new \RuntimeException(sprintf(
34
                'Class "%s" is not mapped',
35
                $classFqn
36
            ));
37
        }
38
39
        foreach ($metadata->getPropertyMetadata() as $propertyMetadata) {
40
            $data = $propertyMetadata->getValue($data);
41
            $childView = $this->viewBuilder->createView($propertyMetadata->getType(), $data, $propertyMetadata->getOptions());
42
            $view[$propertyMetadata->getName()] = $childView;
43
        }
44
45
        return $view;
46
    }
47
48
    public function configureOptions(OptionsResolver $options)
49
    {
50
        $options->setDefault('template', 'psi/object');
51
    }
52
}
53