Passed
Push — master ( 0b9717...65bc60 )
by noitran
05:28
created

RQLService::createFilterSpecResolver()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 3
CRAP Score 1

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 4
ccs 3
cts 3
cp 1
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
crap 1
1
<?php
2
3
namespace Noitran\RQL\Services;
4
5
use Noitran\RQL\Contracts\Processor\ProcessorInterface;
6
use Illuminate\Contracts\Config\Repository as Config;
7
use Noitran\RQL\Contracts\Resolver\ResolverInterface;
8
use Noitran\RQL\Exceptions\RuntimeException;
9
use Noitran\RQL\Processors\FilterSpecResolver;
10
11
/**
12
 * Class RQLService
13
 */
14
class RQLService
15
{
16
    /**
17
     * @var ProcessorInterface|null
18
     */
19
    protected $processor;
20
21
    /**
22
     * @var Config
23
     */
24
    protected $config;
25
26
    /**
27
     * RQLService constructor.
28
     *
29
     * @param Config $config
30
     */
31 12
    public function __construct(Config $config)
32
    {
33 12
        $this->config = $config;
34 12
    }
35
36
    /**
37
     * @return ProcessorInterface
38
     */
39 12
    public function getProcessor(): ProcessorInterface
40
    {
41 12
        if (! $this->processor) {
42 12
            $this->processor = $this->createProcessor();
43
        }
44
45 12
        return $this->processor;
46
    }
47
48
    /**
49
     * @return ProcessorInterface
50
     */
51 12
    protected function createProcessor(): ProcessorInterface
52
    {
53 12
        $name = $this->config->get('rql.default_processor', 'eloquent');
54 12
        $class = config("rql.processors.{$name}.class");
55
56 12
        if (! class_exists($class)) {
57
            throw new RuntimeException('Processor class "' . $class . '" does not exist!');
58
        }
59
60 12
        $resolver = $this->createFilterSpecResolver($this->getConfig($name));
61
62 12
        return new $class($resolver);
63
    }
64
65
    /**
66
     * @param array $config
67
     *
68
     * @return ResolverInterface
69
     */
70 12
    protected function createFilterSpecResolver(array $config): ResolverInterface
71
    {
72 12
        return (new FilterSpecResolver())
73 12
            ->registerAll($config['filter_specs']);
74
    }
75
76
    /**
77
     * @param string $processorName
78
     *
79
     * @return array
80
     */
81 12
    protected function getConfig(string $processorName = 'eloquent'): array
82
    {
83 12
        $config = (array) $this->config->get('rql');
84
85 12
        if (empty($config)) {
86
            throw new RuntimeException('RQL config does not exist.');
87
        }
88
89 12
        return $config['processors'][$processorName];
90
    }
91
}
92