Skip to content

Commit

Permalink
[10.x] Use method on UploadedFile to validate image dimensions (larav…
Browse files Browse the repository at this point in the history
…el#46912)

* imageSize method on uploadedfile

* formatting

* fix variable

---------

Co-authored-by: Taylor Otwell <taylor@laravel.com>
  • Loading branch information
gdebrauwer and taylorotwell authored May 1, 2023
1 parent 8de1aa2 commit a2f35fa
Show file tree
Hide file tree
Showing 3 changed files with 52 additions and 2 deletions.
10 changes: 10 additions & 0 deletions src/Illuminate/Http/FileHelpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -53,4 +53,14 @@ public function hashName($path = null)

return $path.$hash.$extension;
}

/**
* Get the dimensions of the image (if applicable).
*
* @return array|null
*/
public function dimensions()
{
return @getimagesize($this->getRealPath());
}
}
12 changes: 10 additions & 2 deletions src/Illuminate/Validation/Concerns/ValidatesAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -683,13 +683,21 @@ public function validateDimensions($attribute, $value, $parameters)
return true;
}

if (! $this->isValidFileInstance($value) || ! $sizeDetails = @getimagesize($value->getRealPath())) {
if (! $this->isValidFileInstance($value)) {
return false;
}

$dimensions = method_exists($value, 'dimensions')
? $value->dimensions()
: @getimagesize($value->getRealPath());

if (! $dimensions) {
return false;
}

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

[$width, $height] = $sizeDetails;
[$width, $height] = $dimensions;

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

Expand Down
32 changes: 32 additions & 0 deletions tests/Validation/ValidationImageFileRuleTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,20 @@ public function testDimensions()
);
}

public function testDimensionsWithCustomImageSizeMethod()
{
$this->fails(
File::image()->dimensions(Rule::dimensions()->width(100)->height(100)),
new UploadedFileWithCustomImageSizeMethod(stream_get_meta_data($tmpFile = tmpfile())['uri'], 'foo.png'),
['validation.dimensions'],
);

$this->passes(
File::image()->dimensions(Rule::dimensions()->width(200)->height(200)),
new UploadedFileWithCustomImageSizeMethod(stream_get_meta_data($tmpFile = tmpfile())['uri'], 'foo.png'),
);
}

protected function fails($rule, $values, $messages)
{
$this->assertValidationRules($rule, $values, false, $messages);
Expand Down Expand Up @@ -84,3 +98,21 @@ protected function tearDown(): void
Facade::setFacadeApplication(null);
}
}

class UploadedFileWithCustomImageSizeMethod extends UploadedFile
{
public function isValid(): bool
{
return true;
}

public function guessExtension(): string
{
return 'png';
}

public function dimensions()
{
return [200, 200];
}
}

0 comments on commit a2f35fa

Please sign in to comment.