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