|
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)) { |
|
|
|
|
|
|
61
|
|
|
throw new UnsupportedFileTypeException("Unsupported file type: \"$type\""); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return static::$knownReaders[$type]; |
|
65
|
|
|
} |
|
66
|
|
|
} |
|
67
|
|
|
|