LoaderFactory::create()   A
last analyzed

Complexity

Conditions 3
Paths 3

Size

Total Lines 16
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 3
eloc 7
c 1
b 0
f 0
nc 3
nop 2
dl 0
loc 16
rs 10
1
<?php
2
3
namespace Startwind\Forrest\Adapter\Loader;
4
5
use Cache\Adapter\Filesystem\FilesystemCachePool;
6
use GuzzleHttp\Client;
7
use League\Flysystem\Adapter\Local;
8
use League\Flysystem\Filesystem;
9
use Startwind\Forrest\Adapter\Loader\Decorator\CacheDecorator;
10
use Startwind\Forrest\Adapter\Loader\Decorator\WritableCacheDecorator;
11
12
class LoaderFactory
13
{
14
    private const CACHE_DIR = '/tmp/forrest-cache';
15
16
    private static array $loaders = [
17
        'github' => PrivateGitHubLoader::class,
18
        'localFile' => LocalFileLoader::class,
19
        'httpFile' => HttpFileLoader::class
20
    ];
21
22
    /**
23
     * Create a loader depending on a given configuration array.
24
     */
25
    public static function create($config, Client $client): Loader
26
    {
27
        if (!array_key_exists($config['type'], self::$loaders)) {
28
            throw new \RuntimeException('No YAML loader found with the identifier "' . $config['loader']['type'] . '". Known types are ' . implode(', ', array_keys(self::$loaders)) . '.');
29
        }
30
31
        $loaderClass = self::$loaders[$config['type']];
32
33
        /** @var Loader $loader */
34
        $loader = call_user_func([$loaderClass, 'fromConfigArray'], $config['config']);
35
36
        if ($loader instanceof HttpAwareLoader) {
37
            $loader->setClient($client);
38
        }
39
40
        return self::decorateWithCache($loader);
41
    }
42
43
    private static function decorateWithCache(Loader $loader): CacheDecorator
44
    {
45
        $filesystemAdapter = new Local(self::CACHE_DIR);
46
        $filesystem = new Filesystem($filesystemAdapter);
47
        $pool = new FilesystemCachePool($filesystem);
48
49
        if ($loader instanceof WritableLoader) {
50
            $loader = new WritableCacheDecorator($loader, $pool);
51
        } else {
52
            $loader = new CacheDecorator($loader, $pool);
53
        }
54
55
        return $loader;
56
    }
57
}
58