CollectionType::createView()   B
last analyzed

Complexity

Conditions 5
Paths 3

Size

Total Lines 25
Code Lines 15

Duplication

Lines 6
Ratio 24 %

Importance

Changes 0
Metric Value
dl 6
loc 25
rs 8.439
c 0
b 0
f 0
cc 5
eloc 15
nc 3
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\ContentType\Standard\View;
6
7
use Psi\Component\ContentType\FieldLoader;
8
use Psi\Component\ContentType\FieldOptions;
9
use Psi\Component\ContentType\View\TypeInterface;
10
use Psi\Component\ContentType\View\ViewFactory;
11
use Psi\Component\ContentType\View\ViewInterface;
12
use Symfony\Component\OptionsResolver\OptionsResolver;
13
14
class CollectionType implements TypeInterface
15
{
16
    private $fieldLoader;
17
18
    public function __construct(FieldLoader $fieldLoader)
19
    {
20
        $this->fieldLoader = $fieldLoader;
21
    }
22
23
    public function createView(ViewFactory $factory, $data, array $options): ViewInterface
24
    {
25 View Code Duplication
        if (!is_array($data) && !$data instanceof \Traversable) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
26
            throw new \InvalidArgumentException(sprintf(
27
                'Data must be traversable or an array, got: "%s"',
28
                is_object($data) ? get_class($data) : gettype($data)
29
            ));
30
        }
31
32
        if (is_array($data)) {
33
            $data = new \ArrayIterator($data);
34
        }
35
36
        $field = $this->fieldLoader->load(
37
            $options['field_type'],
38
            FieldOptions::create($options['field_options'])
39
        );
40
41
        return new CollectionView(
42
            $factory,
43
            $data,
44
            $field->getViewType(),
45
            $field->getViewOptions()
46
        );
47
    }
48
49
    public function configureOptions(OptionsResolver $options)
50
    {
51
        $options->setDefaults([
52
            'field_options' => [],
53
        ]);
54
55
        $options->setRequired([
56
            'field_type',
57
        ]);
58
59
        $options->setAllowedTypes('field_type', ['string']);
60
        $options->setAllowedTypes('field_options', ['array']);
61
    }
62
}
63