1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Yiisoft\Composer\Config\Reader; |
4
|
|
|
|
5
|
|
|
use Yiisoft\Composer\Config\Builder; |
6
|
|
|
use Yiisoft\Composer\Config\Exception\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
|
|
|
$uniqid = $class . ':' . spl_object_hash($builder); |
36
|
|
|
if (empty(self::$loaders[$uniqid])) { |
37
|
|
|
self::$loaders[$uniqid] = static::create($builder, $type); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return self::$loaders[$uniqid]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
private static function detectType(string $path): string |
44
|
|
|
{ |
45
|
|
|
if (strncmp(basename($path), '.env.', 5) === 0) { |
46
|
|
|
return 'env'; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
return pathinfo($path, PATHINFO_EXTENSION); |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
private static function create(Builder $builder, string $type): ReaderInterface |
53
|
|
|
{ |
54
|
|
|
$class = static::findClass($type); |
55
|
|
|
|
56
|
|
|
return new $class($builder); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
private static function findClass(string $type): string |
60
|
|
|
{ |
61
|
|
|
if (!array_key_exists($type, static::$knownReaders)) { |
|
|
|
|
62
|
|
|
throw new UnsupportedFileTypeException("Unsupported file type: \"$type\""); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
return static::$knownReaders[$type]; |
66
|
|
|
} |
67
|
|
|
} |
68
|
|
|
|