-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathFileBootstrapProvider.php
87 lines (79 loc) · 2.36 KB
/
FileBootstrapProvider.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
namespace Unleash\Client\Bootstrap;
use InvalidArgumentException;
use JsonException;
use Override;
use RuntimeException;
use SplFileInfo;
use Throwable;
use Unleash\Client\Exception\InvalidValueException;
final class FileBootstrapProvider implements BootstrapProvider
{
/**
* @readonly
* @var string|\SplFileInfo
*/
private $file;
/**
* @param string|\SplFileInfo $file
*/
public function __construct($file)
{
$this->file = $file;
}
/**
* @throws Throwable
* @throws JsonException
*
* @return array<mixed>
*/
public function getBootstrap(): array
{
$filePath = $this->getFilePath($this->file);
if ($exception = $this->getExceptionForInvalidPath($filePath)) {
throw $exception;
}
$content = @file_get_contents($filePath);
if ($content === false) {
$error = error_get_last();
throw new RuntimeException(sprintf("Failed to read the contents of file '%s': %s", $filePath, $error['message'] ?? 'Unknown error'));
}
$result = @json_decode($content, true);
if (json_last_error()) {
throw new JsonException(json_last_error_msg(), json_last_error());
}
if (!is_array($result)) {
throw new InvalidValueException(sprintf("The file '%s' must contain a valid json object, '%s' given.", $filePath, gettype($result)));
}
return $result;
}
/**
* @param string|\SplFileInfo $file
*/
private function getFilePath($file): string
{
if ($file instanceof SplFileInfo) {
if ($path = $file->getRealPath()) {
return $path;
}
throw new InvalidArgumentException("The file '{$file}' does not exist.");
}
return $file;
}
private function getExceptionForInvalidPath(string $path): ?Throwable
{
if (!fnmatch('*://*', $path)) {
$path = "file://{$path}";
}
if (strncmp($path, 'file://', strlen('file://')) !== 0) {
return null;
}
if (!is_file($path)) {
return new InvalidArgumentException("The file '{$path}' does not exist.");
}
if (!is_readable($path)) {
return new RuntimeException("The file '{$path}' is not readable.");
}
return null;
}
}