use cache library out of laravel framework
1<?php
2
3namespace Company;
4
5
6use Illuminate\Cache\CacheManager;
7use Illuminate\Container\Container;
8use Illuminate\Filesystem\Filesystem;
9
10class FileCache {
11
12
13 private $cacheManager;
14 private $cache;
15
16 private function __construct()
17 {
18 $container = new Container();
19 $container['config'] = [
20 'cache.default' => 'file',
21 'cache.stores.file' => [
22 'driver' => 'file',
23 'path' => __DIR__ . '/../../../storage/framework/cache'
24 ]
25 ];
26
27 $container['files'] = new Filesystem();
28 $this->cacheManager = new CacheManager($container);
29 $this->cache = $this->cacheManager->store();
30 }
31
32 public static function rememberForever($key, callable $callBack) {
33 return (new static())
34 ->cache
35 ->rememberForever($key, $callBack);
36 }
37}
use file cache get AWS SecretsManager item
1<?php
2
3namespace Company;
4
5use Aws\Exception\AwsException;
6use Aws\SecretsManager\SecretsManagerClient;
7
8class Configuration
9{
10
11 private const SECRET_PATTERN = '#/secretsmanager/[^\s\n]+#';
12
13 public static function wrapEnv(string $key): string
14 {
15 $value = Env($key, '');
16 if (preg_match(static::SECRET_PATTERN, $value)) {
17 return FileCache::rememberForever("AWS:SM:".$key, function() use($value) {
18 return Configuration::fetchFromSM($value);
19 });
20 }
21
22 return $value;
23 }
24
25 public static function fetchFromSM(string $key): string
26 {
27 $args = [
28 'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
29 'version' => '2017-10-17',
30 ];
31 if (!empty(env('AWS_MOCK_SM_URL', ''))) {
32 $args['endpoint'] = env('AWS_MOCK_SM_URL');
33 }
34 $client = new SecretsManagerClient($args);
35 try {
36 $result = $client->getSecretValue(['SecretId' => $key,]);
37 } catch (AwsException $ex) {
38 throw $ex;
39 }
40
41 if (isset($result['SecretString'])) {
42 $value = $result['SecretString'];
43 } else {
44 $value = base64_decode($result['SecretString']);
45 }
46
47 return $value;
48 }
49
50}