Passed
Push — master ( aaef8c...df9ad1 )
by Andrii
14:17 queued 12:18
created

ReaderFactory::findClass()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 8
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 2.032

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 4
c 1
b 0
f 0
nc 2
nop 1
dl 0
loc 8
ccs 4
cts 5
cp 0.8
crap 2.032
rs 10
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Yiisoft\Composer\Config\Reader;
6
7
use Yiisoft\Composer\Config\Builder;
8
use Yiisoft\Composer\Config\Exception\UnsupportedFileTypeException;
9
10
/**
11
 * Reader - helper to load data from files of different types.
12
 */
13
class ReaderFactory
14
{
15
    private static array $loaders = [];
16
17
    private static array $knownReaders = [
18
        'env' => EnvReader::class,
19
        'php' => PhpReader::class,
20
        'json' => JsonReader::class,
21
        'yaml' => YamlReader::class,
22
        'yml' => YamlReader::class,
23
    ];
24
25 1
    public static function get(Builder $builder, string $path): ReaderInterface
26
    {
27 1
        $class = static::findClass($path);
28
29 1
        $uniqid = $class . ':' . spl_object_hash($builder);
30 1
        if (empty(self::$loaders[$uniqid])) {
31 1
            self::$loaders[$uniqid] = new $class($builder);
32
        }
33
34 1
        return self::$loaders[$uniqid];
35
    }
36
37 1
    private static function detectType(string $path): string
38
    {
39 1
        if (strncmp(basename($path), '.env.', 5) === 0) {
40
            return 'env';
41
        }
42
43 1
        return pathinfo($path, PATHINFO_EXTENSION);
44
    }
45
46 1
    private static function findClass(string $path): string
47
    {
48 1
        $type = static::detectType($path);
49 1
        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...
50
            throw new UnsupportedFileTypeException("Unsupported file type for \"$path\".");
51
        }
52
53 1
        return static::$knownReaders[$type];
54
    }
55
}
56