Completed
Pull Request — master (#28)
by Daniel
03:48 queued 01:45
created

PropertyColumn::configureOptions()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 14
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 14
c 0
b 0
f 0
rs 9.4285
cc 2
eloc 9
nc 1
nop 1
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Grid\Column;
6
7
use Psi\Component\Grid\CellInterface;
8
use Psi\Component\Grid\ColumnInterface;
9
use Psi\Component\Grid\RowData;
10
use Psi\Component\Grid\View\Cell as Cell;
11
use Symfony\Component\OptionsResolver\OptionsResolver;
12
use Symfony\Component\PropertyAccess\PropertyAccess;
13
use Symfony\Component\PropertyAccess\PropertyAccessorInterface;
14
15
class PropertyColumn implements ColumnInterface
16
{
17
    private $accessor;
18
19
    public function __construct(PropertyAccessorInterface $propertyAccessor = null)
20
    {
21
        $this->accessor = $propertyAccessor ?: PropertyAccess::createPropertyAccessor();
22
    }
23
24
    public function createCell(RowData $data, array $options): CellInterface
25
    {
26
        $property = $options['property'];
27
        $value = $this->accessor->getValue($data->getObject(), $property);
28
29
        return new Cell\ScalarCell($options['variant'], $value);
30
    }
31
32
    public function configureOptions(OptionsResolver $options)
33
    {
34
        $options->setDefault('variant', null);
35
        $options->setDefault('property', null);
36
        $options->setAllowedTypes('property', ['string', 'null']);
37
        $options->setAllowedTypes('variant', ['string', 'null']);
38
        $options->setNormalizer('property', function (OptionsResolver $options, $value) {
39
            if (null !== $value) {
40
                return $value;
41
            }
42
43
            return $options['column_name'];
44
        });
45
    }
46
}
47