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

ObjectView   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 39
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 3
dl 0
loc 39
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 7 1
A buildView() 0 20 3
A configureOptions() 0 4 1
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