Skip to content

Commit

Permalink
Add openFile() method to FileHelper (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
devanych committed Dec 8, 2020
1 parent 0663107 commit c62d82b
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
28 changes: 28 additions & 0 deletions src/FileHelper.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,34 @@
*/
class FileHelper
{
/**
* Opens a file or URL.
*
* This method is similar to the PHP `fopen()` function, except that it suppresses the `E_WARNING`
* level error and throws the `\RuntimeException` exception if it can't open the file.
*
* @param string $filename The file or URL.
* @param string $mode The type of access.
* @param bool $useIncludePath Whether to search for a file in the include path.
* @param resource|null $context The stream context or `null`.
*
* @throws RuntimeException If the file could not be opened.
*
* @return resource The file pointer resource.
*
* @psalm-suppress PossiblyNullArgument
*/
public static function openFile(string $filename, string $mode, bool $useIncludePath = false, $context = null)
{
$filePointer = @fopen($filename, $mode, $useIncludePath, $context);

if ($filePointer === false) {
throw new RuntimeException("The file \"{$filename}\" could not be opened.");
}

return $filePointer;
}

/**
* Creates a new directory.
*
Expand Down
20 changes: 20 additions & 0 deletions tests/FileHelperTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,26 @@
*/
final class FileHelperTest extends FileSystemTestCase
{
public function testOpenFileWithFile(): void
{
$resource = FileHelper::openFile(tempnam($this->testFilePath, 'test'), 'rb', true);
$this->assertIsResource($resource);
fclose($resource);
}

public function testOpenFileWithUrl(): void
{
$resource = FileHelper::openFile('php://output', 'wb');
$this->assertIsResource($resource);
fclose($resource);
}

public function testOpenFileException(): void
{
$this->expectException(RuntimeException::class);
FileHelper::openFile('invalid://uri', 'rb');
}

public function testCreateDirectory(): void
{
$basePath = $this->testFilePath;
Expand Down

0 comments on commit c62d82b

Please sign in to comment.