diff --git a/src/Utils/FileSystem.php b/src/Utils/FileSystem.php index 6d34774b1..296175a64 100644 --- a/src/Utils/FileSystem.php +++ b/src/Utils/FileSystem.php @@ -64,11 +64,7 @@ public static function copy(string $origin, string $target, bool $overwrite = tr } } else { static::createDir(dirname($target)); - if ( - ($s = @fopen($origin, 'rb')) - && ($d = @fopen($target, 'wb')) - && @stream_copy_to_stream($s, $d) === false - ) { // @ is escalated to exception + if (@stream_copy_to_stream(static::open($origin, 'rb'), static::open($target, 'wb')) === false) { // @ is escalated to exception throw new Nette\IOException(sprintf( "Unable to copy file '%s' to '%s'. %s", self::normalizePath($origin), @@ -80,6 +76,25 @@ public static function copy(string $origin, string $target, bool $overwrite = tr } + /** + * Opens file and returns resource. + * @return resource + * @throws Nette\IOException on error occurred + */ + public static function open(string $path, string $mode) + { + $f = @fopen($path, $mode); // @ is escalated to exception + if (!$f) { + throw new Nette\IOException(sprintf( + "Unable to open file '%s'. %s", + self::normalizePath($path), + Helpers::getLastError(), + )); + } + return $f; + } + + /** * Deletes a file or an entire directory if exists. If the directory is not empty, it deletes its contents first. * @throws Nette\IOException on error occurred diff --git a/tests/Utils/FileSystem.open.phpt b/tests/Utils/FileSystem.open.phpt new file mode 100644 index 000000000..587721ce8 --- /dev/null +++ b/tests/Utils/FileSystem.open.phpt @@ -0,0 +1,24 @@ + FileSystem::open('missing', 'r'), + Nette\IOException::class, + "Unable to open file 'missing'.%A%", +);