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)) { |
|
|
|
|
50
|
|
|
throw new UnsupportedFileTypeException("Unsupported file type for \"$path\"."); |
51
|
|
|
} |
52
|
|
|
|
53
|
1 |
|
return static::$knownReaders[$type]; |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|