Completed
Pull Request — master (#36)
by Daniel
02:23
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
namespace Psi\Component\ContentType\Standard\View;
4
5
use Metadata\MetadataFactory;
6
use Psi\Component\ContentType\View\ViewBuilder;
7
use Psi\Component\ContentType\View\ViewInterface;
8
use Psi\Component\ContentType\View\View;
9
use Symfony\Component\OptionsResolver\OptionsResolver;
10
use Metadata\NullMetadata;
11
12
class ObjectView implements ViewInterface
13
{
14
    private $metadataFactory;
15
    private $viewBuilder;
16
17
    public function __construct(
18
        MetadataFactory $metadataFactory,
19
        ViewBuilder $viewBuilder
20
    ) 
21
    {
22
        $this->metadataFactory = $metadataFactory;
23
        $this->viewBuilder = $viewBuilder;
24
    }
25
26
    public function buildView(View $view, $data, array $options)
27
    {
28
        $classFqn = get_class($data);
29
        $metadata = $this->metadataFactory->getMetadataForClass($classFqn);
30
31
        if ($metadata instanceof NullMetadata) {
32
            throw new \RuntimeException(sprintf(
33
                'Class "%s" is not mapped',
34
                $classFqn
35
            ));
36
        }
37
38
        foreach ($metadata->getPropertyMetadata() as $propertyMetadata) {
39
            $data = $propertyMetadata->getValue($data);
40
            $childView = $this->viewBuilder->createView($propertyMetadata->getType(), $data, $propertyMetadata->getOptions());
41
            $view[$propertyMetadata->getName()] = $childView;
42
        }
43
44
        return $view;
45
    }
46
47
    public function configureOptions(OptionsResolver $options)
48
    {
49
        $options->setDefault('template', 'psi/object');
50
    }
51
}
52