forked from Skillshare/formatphp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileSystemHelper.php
More file actions
276 lines (236 loc) · 7.88 KB
/
FileSystemHelper.php
File metadata and controls
276 lines (236 loc) · 7.88 KB
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
<?php
/**
* This file is part of formatphp/formatphp
*
* formatphp/formatphp is open source software: you can distribute
* it and/or modify it under the terms of the MIT License
* (the "License"). You may not use this file except in
* compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*
* @copyright Copyright (c) Skillshare, Inc. <https://www.skillshare.com>
* @copyright Copyright (c) FormatPHP Contributors <https://formatphp.dev>
* @license https://opensource.org/licenses/MIT MIT License
*/
declare(strict_types=1);
namespace FormatPHP\Util;
use Closure;
use FormatPHP\Exception\ImproperContextException;
use FormatPHP\Exception\InvalidArgumentException;
use FormatPHP\Exception\UnableToProcessFileException;
use FormatPHP\Exception\UnableToWriteFileException;
use JsonException;
use function assert;
use function file_get_contents;
use function file_put_contents;
use function fwrite;
use function get_resource_type;
use function getcwd;
use function gettype;
use function is_callable;
use function is_dir;
use function is_readable;
use function is_resource;
use function is_string;
use function json_decode;
use function json_encode;
use function realpath;
use function sprintf;
use function strlen;
use const JSON_BIGINT_AS_STRING;
use const JSON_INVALID_UTF8_SUBSTITUTE;
use const JSON_PRETTY_PRINT;
use const JSON_THROW_ON_ERROR;
use const JSON_UNESCAPED_SLASHES;
use const JSON_UNESCAPED_UNICODE;
use const PHP_SAPI;
/**
* File and path utilities
*/
class FileSystemHelper
{
private const JSON_DECODE_FLAGS =
JSON_BIGINT_AS_STRING
| JSON_INVALID_UTF8_SUBSTITUTE
| JSON_THROW_ON_ERROR;
private const JSON_ENCODE_FLAGS =
JSON_PRETTY_PRINT
| JSON_UNESCAPED_SLASHES
| JSON_UNESCAPED_UNICODE
| JSON_THROW_ON_ERROR;
private static ?string $currentWorkingDir = null;
/**
* Returns the contents of a file
*
* @throws UnableToProcessFileException
*/
public function getContents(string $filePath): string
{
if (!$this->isReadable($filePath)) {
throw new UnableToProcessFileException(sprintf(
'File does not exist or you do not have permission to read it: "%s".',
$filePath,
));
}
if ($this->isDirectory($filePath)) {
throw new UnableToProcessFileException(sprintf('File path is a directory: "%s".', $filePath));
}
$contents = @file_get_contents($filePath);
if ($contents === false) {
throw new UnableToProcessFileException(sprintf('Could not open file for reading: "%s".', $filePath));
}
return $contents;
}
/**
* @return array<array-key, mixed>
*
* @throws UnableToProcessFileException
*/
public function getJsonContents(string $filePath): array
{
$contents = $this->getContents($filePath);
try {
/** @var array<array-key, mixed> $parsedContents */
$parsedContents = @json_decode($contents, true, 512, self::JSON_DECODE_FLAGS);
return $parsedContents;
} catch (JsonException $exception) {
throw new UnableToProcessFileException(
sprintf('Unable to decode the JSON in the file "%s"', $filePath),
0,
$exception,
);
}
}
/**
* @throws InvalidArgumentException
* @throws UnableToWriteFileException
*/
public function writeContents(mixed $file, string $contents): void
{
if (!is_string($file) && (!is_resource($file) || get_resource_type($file) !== 'stream')) {
throw new InvalidArgumentException(sprintf(
'File must be a string path or a stream resource; received %s.',
gettype($file),
));
}
if (is_resource($file)) {
$bytes = @fwrite($file, $contents);
if ($bytes === false) {
throw new UnableToWriteFileException('Unable to write contents to stream resource.');
}
return;
}
assert(is_string($file));
$bytes = @file_put_contents($file, $contents);
if ($bytes === false) {
throw new UnableToWriteFileException(sprintf('Unable to write contents to file "%s".', $file));
}
}
/**
* @param string | resource | mixed $file
* @param mixed $contents
*
* @throws InvalidArgumentException
* @throws UnableToWriteFileException
*/
public function writeJsonContents($file, $contents): void
{
try {
$encodedContents = @json_encode($contents, self::JSON_ENCODE_FLAGS);
} catch (JsonException $exception) {
throw new InvalidArgumentException('Unable to encode contents as JSON', 0, $exception);
}
$this->writeContents($file, $encodedContents . "\n");
}
/**
* @throws InvalidArgumentException
*/
public function getRealPath(string $path): string
{
$realpath = @realpath($path);
if ($realpath === false) {
throw new InvalidArgumentException(sprintf(
'Unable to find or access the path at "%s"',
$path,
));
}
return $realpath;
}
/**
* Returns `true` if the path is a directory
*/
public function isDirectory(string $path): bool
{
return @is_dir($path);
}
/**
* Returns `true` if the path is readable
*/
public function isReadable(string $path): bool
{
return @is_readable($path);
}
/**
* Returns the current working directory
*
* This is not necessarily the directory from which the script is running,
* nor is it the location of this class file. It is the directory in which
* the process is currently working, which can change if using
* {@link https://www.php.net/chdir chdir()} or `cd` to change the working
* directory.
*/
public function getCurrentWorkingDirectory(): string
{
if (self::$currentWorkingDir === null) {
self::$currentWorkingDir = getcwd() ?: '';
}
return strlen(self::$currentWorkingDir) > 0 ? self::$currentWorkingDir . '/' : '';
}
/**
* Loads a PHP script and returns its Closure
*
* PHP needs a taint mode, so we can determine whether $path might have
* come from external sources. If it did, we don't want to attempt to
* include it here. As a result, we only allow calling this method from a
* CLI SAPI context. Calling from a Web SAPI context is forbidden.
*
* @throws ImproperContextException
*/
public function loadClosureFromScript(string $path): ?Closure
{
if ($this->getSapiName() !== 'cli') {
throw new ImproperContextException(sprintf(
'Method must be called from CLI SAPI context only; called from %s context.',
$this->getSapiName(),
));
}
if (!$this->isReadable($path) || $this->isDirectory($path)) {
return null;
}
/**
* @var Closure | callable | int $closure
*/
$closure = @include $path;
if (!$closure instanceof Closure && is_callable($closure)) {
$closure = Closure::fromCallable($closure);
}
if ($closure instanceof Closure) {
return $closure;
}
return null;
}
/**
* Returns the name of the current SAPI in which PHP is running
*
* This method exists for ease of mocking this value from tests.
*/
protected function getSapiName(): string
{
return PHP_SAPI;
}
}