Skip to content

Commit 935aeb8

Browse files
authored
Fix nonexistent file error handling
1 parent 5b7d548 commit 935aeb8

File tree

2 files changed

+39
-1
lines changed

2 files changed

+39
-1
lines changed

src/Utils/FileUtils.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<?php
2+
23
/**
34
* This file is part of the Cloudinary PHP package.
45
*
@@ -137,7 +138,7 @@ public static function safeFileOpen(string $filename, string $mode, bool $useInc
137138

138139
if (! $fp) {
139140
$err = error_get_last();
140-
throw new GeneralError($err['message']);
141+
throw new GeneralError($err['message'] ?? 'Failed to open file: ' . $filename);
141142
}
142143

143144
return $fp;

tests/Unit/Utils/FileUtilsTest.php

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
<?php
2+
23
/**
34
* This file is part of the Cloudinary PHP package.
45
*
@@ -10,6 +11,7 @@
1011

1112
namespace Cloudinary\Test\Unit\Utils;
1213

14+
use Cloudinary\Api\Exception\GeneralError;
1315
use Cloudinary\FileUtils;
1416
use Cloudinary\Tag\ImageTag;
1517
use PHPUnit\Framework\TestCase;
@@ -64,4 +66,39 @@ public function testSplitFilenameExtension()
6466
self::assertEquals($file[1], FileUtils::splitPathFilenameExtension($file[0]));
6567
}
6668
}
69+
70+
public function testSafeFileOpenWithExistingFile()
71+
{
72+
$existingFile = __DIR__ . '/../../assets/sample.png';
73+
$resource = FileUtils::safeFileOpen($existingFile, 'rb');
74+
75+
self::assertIsResource($resource);
76+
self::assertEquals('stream', get_resource_type($resource));
77+
78+
fclose($resource);
79+
}
80+
81+
public function testSafeFileOpenWithNonExistingFile()
82+
{
83+
$nonExistingFile = __DIR__ . '/../../assets/non_existing_file.txt';
84+
85+
$this->expectException(GeneralError::class);
86+
FileUtils::safeFileOpen($nonExistingFile, 'rb');
87+
}
88+
89+
public function testSafeFileOpenWithNonExistingFolder()
90+
{
91+
$nonExistingFile = 'foo/bar';
92+
93+
$this->expectException(GeneralError::class);
94+
FileUtils::safeFileOpen($nonExistingFile, 'rb');
95+
}
96+
97+
public function testSafeFileOpenWithEmptyPath()
98+
{
99+
$this->expectException(GeneralError::class);
100+
$this->expectExceptionMessage('Path cannot be empty');
101+
102+
FileUtils::safeFileOpen('', 'rb');
103+
}
67104
}

0 commit comments

Comments
 (0)