Skip to content

Commit a2f35fa

Browse files
[10.x] Use method on UploadedFile to validate image dimensions (#46912)
* imageSize method on uploadedfile * formatting * fix variable --------- Co-authored-by: Taylor Otwell <[email protected]>
1 parent 8de1aa2 commit a2f35fa

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

src/Illuminate/Http/FileHelpers.php

+10
Original file line numberDiff line numberDiff line change
@@ -53,4 +53,14 @@ public function hashName($path = null)
5353

5454
return $path.$hash.$extension;
5555
}
56+
57+
/**
58+
* Get the dimensions of the image (if applicable).
59+
*
60+
* @return array|null
61+
*/
62+
public function dimensions()
63+
{
64+
return @getimagesize($this->getRealPath());
65+
}
5666
}

src/Illuminate/Validation/Concerns/ValidatesAttributes.php

+10-2
Original file line numberDiff line numberDiff line change
@@ -683,13 +683,21 @@ public function validateDimensions($attribute, $value, $parameters)
683683
return true;
684684
}
685685

686-
if (! $this->isValidFileInstance($value) || ! $sizeDetails = @getimagesize($value->getRealPath())) {
686+
if (! $this->isValidFileInstance($value)) {
687+
return false;
688+
}
689+
690+
$dimensions = method_exists($value, 'dimensions')
691+
? $value->dimensions()
692+
: @getimagesize($value->getRealPath());
693+
694+
if (! $dimensions) {
687695
return false;
688696
}
689697

690698
$this->requireParameterCount(1, $parameters, 'dimensions');
691699

692-
[$width, $height] = $sizeDetails;
700+
[$width, $height] = $dimensions;
693701

694702
$parameters = $this->parseNamedParameters($parameters);
695703

tests/Validation/ValidationImageFileRuleTest.php

+32
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,20 @@ public function testDimensions()
3030
);
3131
}
3232

33+
public function testDimensionsWithCustomImageSizeMethod()
34+
{
35+
$this->fails(
36+
File::image()->dimensions(Rule::dimensions()->width(100)->height(100)),
37+
new UploadedFileWithCustomImageSizeMethod(stream_get_meta_data($tmpFile = tmpfile())['uri'], 'foo.png'),
38+
['validation.dimensions'],
39+
);
40+
41+
$this->passes(
42+
File::image()->dimensions(Rule::dimensions()->width(200)->height(200)),
43+
new UploadedFileWithCustomImageSizeMethod(stream_get_meta_data($tmpFile = tmpfile())['uri'], 'foo.png'),
44+
);
45+
}
46+
3347
protected function fails($rule, $values, $messages)
3448
{
3549
$this->assertValidationRules($rule, $values, false, $messages);
@@ -84,3 +98,21 @@ protected function tearDown(): void
8498
Facade::setFacadeApplication(null);
8599
}
86100
}
101+
102+
class UploadedFileWithCustomImageSizeMethod extends UploadedFile
103+
{
104+
public function isValid(): bool
105+
{
106+
return true;
107+
}
108+
109+
public function guessExtension(): string
110+
{
111+
return 'png';
112+
}
113+
114+
public function dimensions()
115+
{
116+
return [200, 200];
117+
}
118+
}

0 commit comments

Comments
 (0)