ReaderFactory   A
last analyzed

Complexity

Total Complexity 6

Size/Duplication

Total Lines 44
Duplicated Lines 0 %

Test Coverage

Coverage 86.67%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 6
eloc 20
c 1
b 0
f 0
dl 0
loc 44
ccs 13
cts 15
cp 0.8667
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A get() 0 12 2
A findClass() 0 8 2
A detectType() 0 7 2
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
    /** @psalm-var array<string, ReaderInterface> */
16
    private static array $loaders = [];
17
18
    private static array $knownReaders = [
19
        'env' => EnvReader::class,
20
        'php' => PhpReader::class,
21
        'json' => JsonReader::class,
22
        'yaml' => YamlReader::class,
23
        'yml' => YamlReader::class,
24
    ];
25
26 4
    public static function get(Builder $builder, string $path): ReaderInterface
27
    {
28 4
        $class = static::findClass($path);
29
30 4
        $uniqid = $class . ':' . spl_object_hash($builder);
31 4
        if (empty(self::$loaders[$uniqid])) {
32
            /** @psalm-var ReaderInterface */
33 4
            self::$loaders[$uniqid] = new $class($builder);
34
        }
35
36
        /** @psalm-var ReaderInterface */
37 4
        return self::$loaders[$uniqid];
38
    }
39
40 4
    private static function detectType(string $path): string
41
    {
42 4
        if (strncmp(basename($path), '.env.', 5) === 0) {
43
            return 'env';
44
        }
45
46 4
        return pathinfo($path, PATHINFO_EXTENSION);
0 ignored issues
show
Bug Best Practice introduced by
The expression return pathinfo($path, Y...der\PATHINFO_EXTENSION) could return the type array which is incompatible with the type-hinted return string. Consider adding an additional type-check to rule them out.
Loading history...
47
    }
48
49 4
    private static function findClass(string $path): string
50
    {
51 4
        $type = static::detectType($path);
52 4
        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...
53
            throw new UnsupportedFileTypeException("Unsupported file type for \"$path\".");
54
        }
55
56 4
        return static::$knownReaders[$type];
57
    }
58
}
59