|
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
|
7 |
|
public static function getRequestLimitRuleset(array $config = null): RequestLimitRuleset |
|
17
|
|
|
{ |
|
18
|
7 |
|
if ($config === null) { |
|
19
|
6 |
|
$config = Config::get('laravel-guzzle-throttle'); |
|
20
|
|
|
} |
|
21
|
|
|
|
|
22
|
7 |
|
if (!isset($config['cache']['driver'])) { |
|
23
|
1 |
|
throw new DriverNotSetException(); |
|
24
|
|
|
} |
|
25
|
|
|
|
|
26
|
6 |
|
return new RequestLimitRuleset( |
|
27
|
6 |
|
$config['rules'], |
|
28
|
6 |
|
$config['cache']['strategy'] ?? 'no-cache', |
|
29
|
6 |
|
'laravel', |
|
30
|
6 |
|
new Repository(self::getMiddlewareConfig($config['cache']['driver'], $config['cache']['ttl'] ?? self::DEFAULT_TTL)) |
|
31
|
|
|
); |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
6 |
|
public static function getMiddlewareConfig(string $driverName, int $ttl): array |
|
35
|
|
|
{ |
|
36
|
6 |
|
$driverConfig = self::getConfigForDriver($driverName); |
|
37
|
6 |
|
$driver = $driverConfig['driver'] ?? 'file'; |
|
38
|
6 |
|
unset($driverConfig['driver']); |
|
39
|
|
|
|
|
40
|
|
|
return [ |
|
41
|
|
|
'cache' => [ |
|
42
|
6 |
|
'driver' => $driver, |
|
43
|
6 |
|
'options' => self::_getOptions($driverName, $driverConfig), |
|
44
|
6 |
|
'ttl' => $ttl |
|
45
|
|
|
] |
|
46
|
|
|
]; |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
6 |
|
public static function getConfigForDriver(string $driverName): array |
|
50
|
|
|
{ |
|
51
|
6 |
|
return Config::get('cache.stores.' . self::getConfigName($driverName)); |
|
52
|
|
|
} |
|
53
|
|
|
|
|
54
|
6 |
|
public static function getConfigName(string $driverName): string |
|
55
|
|
|
{ |
|
56
|
6 |
|
return $driverName === 'default' ? Config::get('cache.default') : $driverName; |
|
57
|
|
|
} |
|
58
|
|
|
|
|
59
|
6 |
|
private static function _getOptions(string $driverName, array $config): array |
|
60
|
|
|
{ |
|
61
|
6 |
|
if ($driverName !== 'redis') { |
|
62
|
4 |
|
return $config; |
|
63
|
|
|
} |
|
64
|
|
|
|
|
65
|
2 |
|
return ['database' => Config::get('database.redis.' . ($config['connection'] ?? 'default'))]; |
|
66
|
|
|
} |
|
67
|
|
|
} |
|
68
|
|
|
|