Completed
Pull Request — master (#29)
by Daniel
02:17
created

PropertyColumn::createHeader()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

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