Passed
Pull Request — master (#26)
by Dmitriy
46:44 queued 36:08
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
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 5
rs 10
c 0
b 0
f 0
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
    public static function get(Builder $builder, string $path): ReaderInterface
24
    {
25
        $type = static::detectType($path);
26
        $class = static::findClass($type);
27
28
        $uniqid = $class . ':' . spl_object_hash($builder);
29
        if (empty(self::$loaders[$uniqid])) {
30
            self::$loaders[$uniqid] = new $class($builder);
31
        }
32
33
        return self::$loaders[$uniqid];
34
    }
35
36
    private static function detectType(string $path): string
37
    {
38
        if (strncmp(basename($path), '.env.', 5) === 0) {
39
            return 'env';
40
        }
41
42
        return pathinfo($path, PATHINFO_EXTENSION);
43
    }
44
45
    private static function findClass(string $type): string
46
    {
47
        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...
48
            throw new UnsupportedFileTypeException("Unsupported file type: \"$type\"");
49
        }
50
51
        return static::$knownReaders[$type];
52
    }
53
}
54