RQLService::getProcessor()   A
last analyzed

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2

Importance

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