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