ray-di /
Ray.Compiler
| 1 | <?php |
||
| 2 | |||
| 3 | declare(strict_types=1); |
||
| 4 | |||
| 5 | namespace Ray\Compiler; |
||
| 6 | |||
| 7 | use Ray\Compiler\Exception\FileNotWritable; |
||
| 8 | |||
| 9 | use function dirname; |
||
| 10 | use function file_put_contents; |
||
| 11 | use function is_dir; |
||
| 12 | use function is_int; |
||
| 13 | use function is_string; |
||
| 14 | use function mkdir; |
||
| 15 | use function rename; |
||
| 16 | use function tempnam; |
||
| 17 | use function unlink; |
||
| 18 | |||
| 19 | final class FilePutContents |
||
| 20 | { |
||
| 21 | public function __invoke(string $filename, string $content): void |
||
| 22 | { |
||
| 23 | $dir = dirname($filename); |
||
| 24 | if (! is_dir($dir)) { |
||
| 25 | mkdir($dir, 0777, true); |
||
| 26 | } |
||
| 27 | |||
| 28 | $tmpFile = tempnam(dirname($filename), 'swap'); |
||
| 29 | if (is_string($tmpFile) && is_int(file_put_contents($tmpFile, $content)) && @rename($tmpFile, $filename)) { |
||
| 30 | return; |
||
| 31 | } |
||
| 32 | |||
| 33 | // @codeCoverageIgnoreStart |
||
| 34 | @unlink((string) $tmpFile); |
||
|
0 ignored issues
–
show
|
|||
| 35 | |||
| 36 | throw new FileNotWritable($filename); |
||
| 37 | // @codeCoverageIgnoreEnd |
||
| 38 | } |
||
| 39 | } |
||
| 40 |
If you suppress an error, we recommend checking for the error condition explicitly: