1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
|
4
|
|
|
namespace BrowscapPHP\Helper; |
5
|
|
|
|
6
|
|
|
use Symfony\Component\Filesystem\Exception\IOException; |
7
|
|
|
use Symfony\Component\Filesystem\Filesystem as BaseFilesystem; |
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Provides basic utility to manipulate the file system. |
11
|
|
|
*/ |
12
|
|
|
class Filesystem extends BaseFilesystem |
13
|
|
|
{ |
14
|
|
|
/** |
15
|
|
|
* Atomically dumps content into a file. |
16
|
|
|
* |
17
|
|
|
* @param string $filename The file to be written to. |
18
|
|
|
* @param string $content The data to write into the file. |
19
|
|
|
* @param int $mode The file mode (octal). If null, file permissions are not modified |
20
|
|
|
* Deprecated since version 2.3.12, to be removed in 3.0. |
21
|
|
|
* @throws IOException If the file cannot be written to. |
22
|
|
|
*/ |
23
|
|
|
public function dumpFile($filename, $content, $mode = 0666) |
24
|
|
|
{ |
25
|
|
|
$dir = dirname($filename); |
26
|
|
|
|
27
|
|
|
if (!is_dir($dir)) { |
28
|
|
|
$this->mkdir($dir); |
29
|
|
|
} elseif (!is_writable($dir)) { |
30
|
|
|
throw new IOException(sprintf('Unable to write to the "%s" directory.', $dir), 0, null, $dir); |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
// "tempnam" did not work with VFSStream for tests |
34
|
|
|
$tmpFile = dirname($filename) . '/temp_' . md5(time() . basename($filename)); |
35
|
|
|
|
36
|
|
|
if (false === @file_put_contents($tmpFile, $content)) { |
37
|
|
|
throw new IOException(sprintf('Failed to write file "%s".', $filename), 0, null, $filename); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
try { |
41
|
|
|
$this->rename($tmpFile, $filename, true); |
42
|
|
|
} catch (IOException $e) { |
43
|
|
|
unlink($tmpFile); |
44
|
|
|
|
45
|
|
|
throw $e; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if (null !== $mode) { |
49
|
|
|
$this->chmod($filename, $mode); |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|