Completed
Pull Request — master (#42)
by Daniel
10:35 queued 08:29
created

QueryFactory::createQuery()   B

Complexity

Conditions 3
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.9713
c 0
b 0
f 0
cc 3
eloc 14
nc 3
nop 2
1
<?php
2
3
namespace Psi\Component\Grid;
4
5
use Psi\Component\ObjectAgent\Query\Converter\ArrayConverter;
6
use Metadata\MetadataFactory;
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
    {
25
        $this->metadataFactory = $metadataFactory;
26
        $this->converter = $converter ?: new ArrayConverter();
27
    }
28
29
    public function createQuery(string $classFqn, string $name)
30
    {
31
        if (null === $metadata = $this->metadataFactory->getMetadataForClass($classFqn)) {
32
            throw new \InvalidArgumentException('Could not locate grid metadata');
33
        }
34
35
        $queries = $metadata->getQueries();
36
        
37
        if (!isset($queries[$name])) {
38
            throw new \InvalidArgumentException(sprintf(
39
                'Query "%s" for "%s" is not known. Known queries: "%s"',
40
                $name, $classFqn, implode('", "', array_keys($queries))
41
            ));
42
        }
43
44
        $query = $queries[$name];
45
46
        return $this->converter->__invoke([
47
            'from' => $classFqn,
48
            'selects' => $query->getSelects(),
49
            'joins' => $query->getJoins(),
50
            'criteria' => $query->getCriteria()
51
        ]);
52
    }
53
}
54