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

ReaderFactory   A

Complexity

Total Complexity 8

Size/Duplication

Total Lines 54
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
eloc 23
dl 0
loc 54
rs 10
c 1
b 0
f 0
wmc 8

5 Methods

Rating   Name   Duplication   Size   Complexity  
A detectType() 0 7 2
A __construct() 0 3 1
A get() 0 10 2
A findClass() 0 7 2
A create() 0 5 1
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