Skip to content

Commit aac2936

Browse files
committed
add some check for read stream data
1 parent 1df7b57 commit aac2936

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

src/File.php

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -304,7 +304,9 @@ public static function streamOpen(string $path)
304304
*/
305305
public static function streamWrite($stream, string $content, string $path = ''): void
306306
{
307-
if (($result = @fwrite($stream, $content)) === false || ($result < strlen($content))) {
307+
self::assertWritableStream($stream);
308+
309+
if (($result = fwrite($stream, $content)) === false || ($result < strlen($content))) {
308310
throw new IOException('The file "' . $path . '" could not be written to. Check your disk space and file permissions.');
309311
}
310312
}
@@ -317,6 +319,8 @@ public static function streamWrite($stream, string $content, string $path = ''):
317319
*/
318320
public static function streamRead($stream, int $length = 1024): string
319321
{
322+
self::assertReadableStream($stream);
323+
320324
return (string)fread($stream, $length);
321325
}
322326

@@ -327,6 +331,8 @@ public static function streamRead($stream, int $length = 1024): string
327331
*/
328332
public static function streamReadln($stream): string
329333
{
334+
self::assertReadableStream($stream);
335+
330336
return trim((string)fgets($stream));
331337
}
332338

@@ -339,6 +345,8 @@ public static function streamReadln($stream): string
339345
*/
340346
public static function streamReadAll($stream, int $length = -1, int $offset = -1): string
341347
{
348+
self::assertReadableStream($stream);
349+
342350
return (string)stream_get_contents($stream, $length, $offset);
343351
}
344352

src/Traits/FileSystemFuncTrait.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,21 @@ public static function assertReadableStream($stream): void
8080
}
8181
}
8282

83+
/**
84+
* @param resource $stream
85+
*/
86+
public static function assertWritableStream($stream): void
87+
{
88+
if (!self::isStream($stream)) {
89+
throw new InvalidArgumentException('Expected a valid stream');
90+
}
91+
92+
$meta = stream_get_meta_data($stream);
93+
if (strpos($meta['mode'], 'w') === false && strpos($meta['mode'], '+') === false) {
94+
throw new InvalidArgumentException('Expected a writable stream');
95+
}
96+
}
97+
8398
/**
8499
* @param string $source
85100
* @param string $dest

0 commit comments

Comments
 (0)