Passed
Pull Request — master (#22)
by Dmitriy
37:40 queued 22:25
created

ReaderFactory::create()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 2
dl 0
loc 5
c 0
b 0
f 0
rs 10
cc 1
nc 1
nop 2
1
<?php
2
3
namespace Yiisoft\Composer\Config\Reader;
4
5
use Yiisoft\Composer\Config\Builder;
6
use Yiisoft\Composer\Config\Exception\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
        $uniqid = $class . ':' . spl_object_hash($builder);
36
        if (empty(self::$loaders[$uniqid])) {
37
            self::$loaders[$uniqid] = static::create($builder, $type);
38
        }
39
40
        return self::$loaders[$uniqid];
41
    }
42
43
    private static function detectType(string $path): string
44
    {
45
        if (strncmp(basename($path), '.env.', 5) === 0) {
46
            return 'env';
47
        }
48
49
        return pathinfo($path, PATHINFO_EXTENSION);
50
    }
51
52
    private static function create(Builder $builder, string $type): ReaderInterface
53
    {
54
        $class = static::findClass($type);
55
56
        return new $class($builder);
57
    }
58
59
    private static function findClass(string $type): string
60
    {
61
        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...
62
            throw new UnsupportedFileTypeException("Unsupported file type: \"$type\"");
63
        }
64
65
        return static::$knownReaders[$type];
66
    }
67
}
68