Completed
Pull Request — master (#42)
by Daniel
01:54
created

QueryFactory::createQuery()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 24
Code Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 8.6845
c 0
b 0
f 0
cc 4
eloc 14
nc 3
nop 2
1
<?php
2
3
namespace Psi\Component\Grid;
4
5
use Metadata\MetadataFactory;
6
use Psi\Component\ObjectAgent\Query\Converter\ArrayConverter;
7
8
class QueryFactory
9
{
10
    /**
11
     * @var MetadataFactory
12
     */
13
    private $metadataFactory;
14
15
    /**
16
     * @var ArrayConverter
17
     */
18
    private $converter;
19
20
    public function __construct(
21
        MetadataFactory $metadataFactory,
22
        ArrayConverter $converter = null
23
    ) {
24
        $this->metadataFactory = $metadataFactory;
25
        $this->converter = $converter ?: new ArrayConverter();
26
    }
27
28
    public function createQuery(string $classFqn, string $name)
29
    {
30
        if (null === $metadata = $this->metadataFactory->getMetadataForClass($classFqn)) {
31
            throw new \InvalidArgumentException('Could not locate grid metadata');
32
        }
33
34
        $queries = $metadata->getQueries();
35
36
        if (!isset($queries[$name])) {
37
            throw new \InvalidArgumentException(sprintf(
38
                'Query "%s" for "%s" is not known. Known queries: "%s"',
39
                $name, $classFqn, implode('", "', array_keys($queries))
40
            ));
41
        }
42
43
        $query = $queries[$name];
44
45
        return $this->converter->__invoke([
46
            'from' => $classFqn,
47
            'selects' => $query->getSelects(),
48
            'joins' => $query->getJoins(),
49
            'criteria' => $query->getCriteria() ?: null,
50
        ]);
51
    }
52
}
53