Completed
Push — master ( 076975...fbb582 )
by Daniel
03:10 queued 58s
created

GridFactory::createGrid()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 12
rs 9.4285
c 0
b 0
f 0
cc 2
eloc 8
nc 2
nop 2
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Psi\Component\Grid;
6
7
use Metadata\MetadataFactory;
8
use Psi\Component\ObjectAgent\AgentFinder;
9
10
class GridFactory
11
{
12
    private $agentFinder;
13
    private $metadataFactory;
14
    private $actionPerformer;
15
    private $gridViewFactory;
16
17
    public function __construct(
18
        AgentFinder $agentFinder,
19
        MetadataFactory $metadataFactory,
20
        GridViewFactory $gridViewFactory,
21
        ActionPerformer $actionPerformer
22
    ) {
23
        $this->agentFinder = $agentFinder;
24
        $this->metadataFactory = $metadataFactory;
25
        $this->gridViewFactory = $gridViewFactory;
26
        $this->actionPerformer = $actionPerformer;
27
    }
28
29
    public function createGrid(string $classFqn, array $context): Grid
30
    {
31
        $context = new GridContext($classFqn, $context);
32
33
        try {
34
            return $this->doLoadGrid($context);
35
        } catch (\Exception $exception) {
36
            throw new \InvalidArgumentException(sprintf(
37
                'Could not load grid for class "%s"', $classFqn
38
            ), 0, $exception);
39
        }
40
    }
41
42
    private function doLoadGrid(GridContext $context): Grid
43
    {
44
        if (null === $metadata = $this->metadataFactory->getMetadataForClass($context->getClassFqn())) {
45
            throw new \InvalidArgumentException('Could not locate grid metadata');
46
        }
47
48
        // find the agent and get the grid metadata.
49
        $agent = $this->agentFinder->findFor($context->getClassFqn());
50
        $gridMetadata = $this->resolveGridMetadata($metadata->getGrids(), $context->getVariant());
51
52
        return new Grid(
53
            $this->gridViewFactory,
54
            $this->actionPerformer,
55
            $agent,
56
            $context,
57
            $gridMetadata
58
        );
59
    }
60
61
    private function resolveGridMetadata(array $grids, string $variant = null)
62
    {
63
        if (empty($grids)) {
64
            throw new \InvalidArgumentException('No grid variants are available');
65
        }
66
67
        // if no explicit grid variant is requested, return the first one that
68
        // was defined.
69
        if (null === $variant) {
70
            return reset($grids);
71
        }
72
73
        if (!isset($grids[$variant])) {
74
            throw new \InvalidArgumentException(sprintf(
75
                'Unknown grid variant "%s", available variants: "%s"',
76
                implode('", "', array_keys($grids))
77
            ));
78
        }
79
80
        return $grids[$variant];
81
    }
82
}
83