Passed
Pull Request — master (#146)
by
unknown
11:57
created

ConfigHelper::getRequestLimitRuleset()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 15
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 3

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 9
c 1
b 0
f 0
nc 4
nop 1
dl 0
loc 15
ccs 9
cts 9
cp 1
crap 3
rs 9.9666
1
<?php
2
3
namespace hamburgscleanest\LaravelGuzzleThrottle\Helpers;
4
5
use hamburgscleanest\GuzzleAdvancedThrottle\RequestLimitRuleset;
6
use hamburgscleanest\LaravelGuzzleThrottle\Exceptions\DriverNotSetException;
7
use Illuminate\Config\Repository;
8
use Illuminate\Support\Facades\Config;
9
use Illuminate\Support\ServiceProvider;
10
11
class ConfigHelper extends ServiceProvider
12
{
13
    /** @var int */
14
    public const DEFAULT_TTL = 900;
15
16 5
    public static function getRequestLimitRuleset(array $config = null): RequestLimitRuleset
17
    {
18 5
        if ($config === null) {
19 4
            $config = Config::get('laravel-guzzle-throttle');
20
        }
21
22 5
        if (!isset($config['cache']['driver'])) {
23 1
            throw new DriverNotSetException();
24
        }
25
26 4
        return new RequestLimitRuleset(
27 4
            $config['rules'],
28 4
            $config['cache']['strategy'] ?? 'no-cache',
29
            'laravel',
30 4
            new Repository(self::getMiddlewareConfig($config['cache']['driver'], $config['cache']['ttl'] ?? self::DEFAULT_TTL))
31
        );
32
    }
33
34 4
    public static function getMiddlewareConfig(string $driverName, int $ttl): array
35
    {
36 4
        $driverConfig = self::getConfigForDriver($driverName);
37 4
        $driver = $driverConfig['driver'] ?? 'file';
38 4
        unset($driverConfig['driver']);
39
40
        return [
41
            'cache' => [
42
                'driver'  => $driver,
43 4
                'options' => self::_getOptions($driverName, $driverConfig),
44
                'ttl'     => $ttl
45
            ]
46
        ];
47
    }
48
49 4
    public static function getConfigForDriver(string $driverName): array
50
    {
51 4
        return Config::get('cache.stores.' . self::getConfigName($driverName));
52
    }
53
54 4
    public static function getConfigName(string $driverName): string
55
    {
56 4
        return $driverName === 'default' ? Config::get('cache.default') : $driverName;
57
    }
58
59 4
    private static function _getOptions(string $driverName, array $config): array
60
    {
61 4
        if ($driverName !== 'redis') {
62 4
            return $config;
63
        }
64
65
        return ['database' => Config::get('database.redis.' . ($config['connection'] ?? 'default'))];
66
    }
67
}
68