Passed
Pull Request — master (#17)
by Dmitriy
07:33
created

FileStorageServiceProvider   A

Complexity

Total Complexity 6

Size/Duplication

Total Lines 41
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 2
Bugs 0 Features 0
Metric Value
eloc 23
c 2
b 0
f 0
dl 0
loc 41
ccs 0
cts 24
cp 0
rs 10
wmc 6

3 Methods

Rating   Name   Duplication   Size   Complexity  
A getDefinitions() 0 3 1
A getExtensions() 0 21 2
A validateAdapter() 0 9 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Yii\Filesystem;
6
7
use League\Flysystem\FilesystemAdapter;
8
use Yiisoft\Di\Container;
9
use Yiisoft\Di\CompositeContainer;
10
use Psr\Container\ContainerInterface;
11
use Yiisoft\Di\Contracts\ServiceProviderInterface;
12
use Yiisoft\Factory\Factory;
13
14
final class FileStorageServiceProvider implements ServiceProviderInterface
15
{
16
    public function getDefinitions(): array
17
    {
18
        return [];
19
    }
20
21
    public function getExtensions(): array
22
    {
23
        return [
24
            ContainerInterface::class => static function (ContainerInterface $container, ContainerInterface $extended) {
25
                $factory = new Factory();
26
                $configs = $extended->get(FileStorageConfigs::class)->getConfigs();
27
28
                $filesystemsDefinitions = [];
29
                foreach ($configs as $alias => $config) {
30
                    $this->validateAdapter($alias, $config);
31
                    $configParams = $config['config'] ?? [];
32
                    $aliases = $config['aliases'] ?? [];
33
                    $adapter = $factory->create($config['adapter']);
34
                    $filesystemsDefinitions[$alias] = fn() => new Filesystem($adapter, $aliases, $configParams);
35
                }
36
                $filesystemsContainer = new Container($filesystemsDefinitions);
37
                $compositeContainer = new CompositeContainer();
38
                $compositeContainer->attach($filesystemsContainer);
39
                $compositeContainer->attach($extended);
40
41
                return $compositeContainer;
42
            }
43
        ];
44
    }
45
46
    private function validateAdapter(string $alias, array $config): void
47
    {
48
        $adapter = $config['adapter']['class'] ?? false;
49
        if (!$adapter) {
50
            throw new \RuntimeException("Adapter is not defined in the \"$alias\" storage config.");
51
        }
52
53
        if (!is_subclass_of($adapter, FilesystemAdapter::class)) {
54
            throw new \RuntimeException('Adapter must implement \League\Flysystem\FilesystemAdapter interface.');
55
        }
56
    }
57
}
58