-
-
Notifications
You must be signed in to change notification settings - Fork 73
/
Copy pathwrite.php
43 lines (34 loc) · 1.27 KB
/
write.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
<?php
declare(strict_types=1);
namespace Psl\File;
use Psl\File;
use Psl\IO;
use Psl\Str;
use function clearstatcache;
/**
* Write $content to $file.
*
* @param non-empty-string $file
*
* @throws Exception\NotFileException If $file points to a non-file node on the filesystem.
* @throws Exception\AlreadyCreatedException If $file is already created, and $write_mode is {@see WriteMode::MUST_CREATE}.
* @throws Exception\NotFoundException If $file does not exist, and $write_mode is {@see WriteMode::TRUNCATE} or {@see WriteMode::APPEND}.
* @throws Exception\NotWritableException If $file exists, and is non-writable.
* @throws Exception\RuntimeException In case of an error.
*/
function write(string $file, string $content, WriteMode $mode = WriteMode::OpenOrCreate): void
{
clearstatcache();
try {
$handle = File\open_write_only($file, $mode);
$lock = $handle->lock(File\LockType::Exclusive);
$handle->writeAll($content);
$lock->release();
$handle->close();
clearstatcache();
} catch (IO\Exception\ExceptionInterface $previous) {
// @codeCoverageIgnoreStart
throw new Exception\RuntimeException(Str\format('Failed to write to file "%s".', $file), 0, $previous);
// @codeCoverageIgnoreEnd
}
}