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

ObjectView   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 40
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 3

Importance

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

3 Methods

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