Passed
Pull Request — master (#6)
by Dmitriy
17:30 queued 02:25
created

ReaderFactory::get()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 5
c 0
b 0
f 0
nc 2
nop 2
dl 0
loc 10
rs 10
1
<?php
2
3
namespace Yiisoft\Composer\Config\Readers;
4
5
use Yiisoft\Composer\Config\Builder;
6
use Yiisoft\Composer\Config\Exceptions\UnsupportedFileTypeException;
7
8
/**
9
 * Reader - helper to load data from files of different types.
10
 */
11
class ReaderFactory
12
{
13
    private static array $loaders = [];
14
15
    private static array $knownReaders = [
16
        'env' => EnvReader::class,
17
        'php' => PhpReader::class,
18
        'json' => JsonReader::class,
19
        'yaml' => YamlReader::class,
20
        'yml' => YamlReader::class,
21
    ];
22
23
    private Builder $builder;
24
25
    public function __construct(Builder $builder)
26
    {
27
        $this->builder = $builder;
28
    }
29
30
    public static function get(Builder $builder, string $path): ReaderInterface
31
    {
32
        $type = static::detectType($path);
33
        $class = static::findClass($type);
34
35
        if (!array_key_exists($class, self::$loaders)) {
36
            self::$loaders[$class] = static::create($builder, $type);
37
        }
38
39
        return self::$loaders[$class];
40
    }
41
42
    private static function detectType(string $path): string
43
    {
44
        if (strncmp(basename($path), '.env.', 5) === 0) {
45
            return 'env';
46
        }
47
48
        return pathinfo($path, PATHINFO_EXTENSION);
49
    }
50
51
    private static function create(Builder $builder, string $type): ReaderInterface
52
    {
53
        $class = static::findClass($type);
54
55
        return new $class($builder);
56
    }
57
58
    private static function findClass(string $type): string
59
    {
60
        if (!array_key_exists($type, static::$knownReaders)) {
0 ignored issues
show
Bug introduced by
Since $knownReaders is declared private, accessing it with static will lead to errors in possible sub-classes; you can either use self, or increase the visibility of $knownReaders to at least protected.
Loading history...
61
            throw new UnsupportedFileTypeException("Unsupported file type: \"$type\"");
62
        }
63
64
        return static::$knownReaders[$type];
65
    }
66
}
67