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
|
|
|
public static function get(Builder $builder, string $path): ReaderInterface |
24
|
|
|
{ |
25
|
|
|
$type = static::detectType($path); |
26
|
|
|
$class = static::findClass($type); |
27
|
|
|
|
28
|
|
|
$uniqid = $class . ':' . spl_object_hash($builder); |
29
|
|
|
if (empty(self::$loaders[$uniqid])) { |
30
|
|
|
self::$loaders[$uniqid] = new $class($builder); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
return self::$loaders[$uniqid]; |
34
|
|
|
} |
35
|
|
|
|
36
|
|
|
private static function detectType(string $path): string |
37
|
|
|
{ |
38
|
|
|
if (strncmp(basename($path), '.env.', 5) === 0) { |
39
|
|
|
return 'env'; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return pathinfo($path, PATHINFO_EXTENSION); |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
private static function findClass(string $type): string |
46
|
|
|
{ |
47
|
|
|
if (!array_key_exists($type, static::$knownReaders)) { |
|
|
|
|
48
|
|
|
throw new UnsupportedFileTypeException("Unsupported file type: \"$type\""); |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
return static::$knownReaders[$type]; |
52
|
|
|
} |
53
|
|
|
} |
54
|
|
|
|