Skip to content

Commit 680e78c

Browse files
committed
Add isValidImage() validation method
Allows checking if an uploaded file is a valid image before running dimension checks. This enables clearer error messages like "File must be a valid image" instead of confusing dimension errors for non-image uploads. Supports optional array of allowed IMAGETYPE_* constants, defaulting to JPEG, PNG, GIF, and WebP.
1 parent fa867b0 commit 680e78c

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/Model/Validation/ImageValidationTrait.php

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,40 @@
66

77
trait ImageValidationTrait
88
{
9+
/**
10+
* Check if the uploaded file is a valid image.
11+
*
12+
* Use this validation before dimension checks to provide a clear error
13+
* message when non-image files are uploaded.
14+
*
15+
* @param \Psr\Http\Message\UploadedFileInterface|array $check Value to check
16+
* @param array<int> $allowedTypes Allowed image types (IMAGETYPE_* constants). Defaults to JPEG, PNG, GIF, WebP.
17+
*
18+
* @return bool Success
19+
*/
20+
public static function isValidImage($check, array $allowedTypes = []): bool
21+
{
22+
if ($check instanceof UploadedFileInterface) {
23+
$file = $check->getStream()->getMetadata('uri');
24+
} else {
25+
if (!isset($check['tmp_name']) || !strlen($check['tmp_name'])) {
26+
return false;
27+
}
28+
$file = $check['tmp_name'];
29+
}
30+
31+
$imageInfo = @getimagesize($file);
32+
if ($imageInfo === false) {
33+
return false;
34+
}
35+
36+
if (!$allowedTypes) {
37+
$allowedTypes = [IMAGETYPE_JPEG, IMAGETYPE_PNG, IMAGETYPE_GIF, IMAGETYPE_WEBP];
38+
}
39+
40+
return in_array($imageInfo[2], $allowedTypes, true);
41+
}
42+
943
/**
1044
* Check that the file is above the minimum width requirement
1145
*

0 commit comments

Comments
 (0)