Skip to content

Commit

Permalink
added FileSystem::open()
Browse files Browse the repository at this point in the history
  • Loading branch information
dg committed Feb 2, 2023
1 parent f730f7f commit 78ac893
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 5 deletions.
25 changes: 20 additions & 5 deletions src/Utils/FileSystem.php
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -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
Expand Down
24 changes: 24 additions & 0 deletions tests/Utils/FileSystem.open.phpt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
<?php

/**
* Test: Nette\Utils\FileSystem open()
*/

declare(strict_types=1);

use Nette\Utils\FileSystem;
use Tester\Assert;

require __DIR__ . '/../bootstrap.php';


test('open', function () {
$f = FileSystem::open(__FILE__, 'r');
Assert::type('resource', $f);
});

Assert::exception(
fn() => FileSystem::open('missing', 'r'),
Nette\IOException::class,
"Unable to open file 'missing'.%A%",
);

0 comments on commit 78ac893

Please sign in to comment.