|
5 | 5 | namespace Psl\Filesystem;
|
6 | 6 |
|
7 | 7 | use Psl;
|
8 |
| -use Psl\Internal; |
| 8 | +use Psl\File; |
| 9 | +use Psl\IO; |
9 | 10 | use Psl\Str;
|
10 | 11 |
|
11 |
| -use function file_get_contents; |
12 |
| - |
13 | 12 | /**
|
14 | 13 | * Reads entire file into a string.
|
15 | 14 | *
|
|
19 | 18 | *
|
20 | 19 | * @throws Psl\Exception\InvariantViolationException If the file specified by
|
21 | 20 | * $file does not exist, or is not readable.
|
22 |
| - * @throws Exception\RuntimeException If an error |
| 21 | + * @throws Exception\RuntimeException In case of an error. |
23 | 22 | */
|
24 | 23 | function read_file(string $file, int $offset = 0, ?int $length = null): string
|
25 | 24 | {
|
26 |
| - Psl\invariant(exists($file), 'File "%s" does not exist.', $file); |
27 |
| - Psl\invariant(is_file($file), 'File "%s" is not a file.', $file); |
28 |
| - Psl\invariant(is_readable($file), 'File "%s" is not readable.', $file); |
| 25 | + try { |
| 26 | + $handle = File\open_read_only($file); |
| 27 | + $lock = $handle->lock(File\LockType::SHARED); |
29 | 28 |
|
30 |
| - if (null === $length) { |
31 |
| - [$content, $error] = Internal\box( |
32 |
| - static fn() => file_get_contents($file, false, null, $offset) |
33 |
| - ); |
34 |
| - } else { |
35 |
| - [$content, $error] = Internal\box( |
36 |
| - static fn() => file_get_contents($file, false, null, $offset, $length) |
37 |
| - ); |
38 |
| - } |
| 29 | + $handle->seek($offset); |
| 30 | + $content = $handle->readAll($length); |
39 | 31 |
|
40 |
| - // @codeCoverageIgnoreStart |
41 |
| - if (false === $content || null !== $error) { |
| 32 | + $lock->release(); |
| 33 | + $handle->close(); |
| 34 | + |
| 35 | + return $content; |
| 36 | + } catch (File\Exception\ExceptionInterface | IO\Exception\ExceptionInterface $previous) { |
42 | 37 | throw new Exception\RuntimeException(Str\format(
|
43 |
| - 'Failed to read file "%s": %s.', |
| 38 | + 'Failed to read file "%s".', |
44 | 39 | $file,
|
45 |
| - $error ?? 'internal error', |
46 |
| - )); |
| 40 | + ), 0, $previous); |
47 | 41 | }
|
48 |
| - // @codeCoverageIgnoreEnd |
49 |
| - |
50 |
| - return $content; |
51 | 42 | }
|
0 commit comments