-
-
Notifications
You must be signed in to change notification settings - Fork 66
/
append_file.php
37 lines (31 loc) 路 971 Bytes
/
append_file.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
<?php
declare(strict_types=1);
namespace Psl\Filesystem;
use Psl;
use Psl\File;
use Psl\IO;
use Psl\Str;
/**
* Append $content to $file.
*
* If $file does not exist, it will be created.
*
* @throws Psl\Exception\InvariantViolationException If the file specified by
* $file is a directory, or is not writeable.
* @throws Exception\RuntimeException In case of an error.
*/
function append_file(string $file, string $content): void
{
try {
$handle = File\open_write_only($file, File\WriteMode::APPEND);
$lock = $handle->lock(File\LockType::EXCLUSIVE);
$handle->writeAll($content);
$lock->release();
$handle->close();
} catch (File\Exception\ExceptionInterface | IO\Exception\ExceptionInterface $previous) {
throw new Exception\RuntimeException(Str\format(
'Failed to write to file "%s".',
$file,
), 0, $previous);
}
}