8000 [Validator] Support SVGs when validating image dimensions by JabriAbdelilah · Pull Request #45486 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Support SVGs when validating image dimensions #45486

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Support SVGs when validating image dimensions
upadte validator changelog

Use Mime Component, Check for corrupted XML
  • Loading branch information
JabriAbdelilah committed Feb 26, 2022
commit a4ace646c5022c9eaaf1a67acb8637b85d8acfaf
3 changes: 2 additions & 1 deletion src/Symfony/Component/Validator/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ CHANGELOG

6.1
---


* Support `SVGs` when validating image dimensions
* Deprecate `Constraint::$errorNames`, use `Constraint::ERROR_NAMES` instead

6.0
Expand Down
57 changes: 56 additions & 1 deletion src/Symfony/Component/Validator/Constraints/ImageValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@

namespace Symfony\Component\Validator\Constraints;

use Symfony\Component\HttpFoundation\File\File as FileObject;
use Symfony\Component\Mime\MimeTypes;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Exception\LogicException;
Expand Down Expand Up @@ -53,7 +55,18 @@ public function validate(mixed $value, Constraint $constraint)
return;
}

$size = @getimagesize($value);
if ($this->isSvg($value)) {
$size = $this->getSvgSize($value);
if (null === $size) {
$this->context->buildViolation($constraint->corruptedMessage)
->setCode(Image::CORRUPTED_IMAGE_ERROR)
->addViolation();

return;
}
} else {
$size = @getimagesize($value);
}

if (empty($size) || (0 === $size[0]) || (0 === $size[1])) {
$this->context->buildViolation($constraint->sizeNotDetectedMessage)
Expand Down Expand Up @@ -234,4 +247,46 @@ public function validate(mixed $value, Constraint $constraint)
imagedestroy($resource);
}
}

/**
* Check whether a value is an SVG image
*
* @param mixed $value
*
* @return bool
* <b>TRUE</b> if <i>value</i> is an SVG, <b>FALSE</b> if it's not, or if we can't detect its MimeType;
*/
private function isSvg(mixed $value)
{
if ($value instanceof FileObject) {
$mime = $value->getMimeType();
} elseif (class_exists(MimeTypes::class)) {
$mime = MimeTypes::getDefault()->guessMimeType($value);
} elseif (!class_exists(FileObject::class)) {
return false;
} else {
$mime = (new FileObject($value))->getMimeType();
}

return 'image/svg+xml' === $mime;
}

/**
* @param mixed $value
*
* @return array|null
* <b>array</b> contains the width and height of the image
* <b>null</b> if the XML is corrupted
*/
private function getSvgSize(mixed $value)
{
if (false === $xmlValue = simplexml_load_file($value)) {
return null;
}
$svgAttributes = $xmlValue->attributes();
$width = intval($svgAttributes->width);
$height = intval($svgAttributes->height);

return [$width, $height];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't know if it's common for others, but I usually work with SVG files and the following is not that uncommon:

  • To not have any width or height attribute and just rely on the viewBox attribute dimensions
  • To have values like 100% in the width or height attributes because those images are embedded in other parent elements with some height/width defined

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree with @javiereguiluz here. Does it mean that this is not that useful? The size of an SVG is not that important anyway, maybe just the ratio? cc @symfony/mergers

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe just the ratio?

I agree this one would be important.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just to be clear, I would only implement the ratio validation for SVGs.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would be fine to also validate width and height if we make sure to skip this validation in case the given width or height are relative values (like mentioned by Javier).

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

But I fail to see how this is useful. A 100x200 SVG file looks perfectly fine at 20x40 or 2000x4000.

}
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ class ImageValidatorTest extends ConstraintValidatorTestCase
protected $image4By3;
protected $imageCorrupted;
protected $notAnImage;
protected $imageSvg;
protected $imageSvgLandscape;
protected $imageSvgPortrait;

protected function createValidator()
{
Expand All @@ -47,6 +50,9 @@ protected function setUp(): void
$this->image16By9 = __DIR__.'/Fixtures/test_16by9.gif';
$this->imageCorrupted = __DIR__.'/Fixtures/test_corrupted.gif';
$this->notAnImage = __DIR__.'/Fixtures/ccc.txt';
$this->imageSvg = __DIR__.'/Fixtures/test_svg.svg';
$this->imageSvgLandscape = __DIR__.'/Fixtures/test_svg_landscape.svg';
$this->imageSvgPortrait = __DIR__.'/Fixtures/test_svg_portrait.svg';
}

public function testNullIsValid()
Expand Down Expand Up @@ -536,6 +542,62 @@ public function testInvalidMimeType()
->assertRaised();
}

public function testSvgSize()
{
$constraint = new Image([
'minWidth' => 1,
'maxWidth' => 2,
'minHeight' => 1,
'maxHeight' => 2,
]);

$this->validator->validate($this->imageSvg, $constraint);

$this->assertNoViolation();
}

/**
* @dataProvider provideAllowSquareConstraints
*/
public function testSquareNotAllowedOnSvg(Image $constraint)
{
$this->validator->validate($this->imageSvg, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ width }}', 1)
->setParameter('{{ height }}', 1)
->setCode(Image::SQUARE_NOT_ALLOWED_ERROR)
->assertRaised();
}

/**
* @dataProvider provideAllowLandscapeConstraints
*/
public function testLandscapeNotAllowedOnSvg(Image $constraint)
{
$this->validator->validate($this->imageSvgLandscape, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ width }}', 2)
->setParameter('{{ height }}', 1)
->setCode(Image::LANDSCAPE_NOT_ALLOWED_ERROR)
->assertRaised();
}

/**
* @dataProvider provideAllowPortraitConstraints
*/
public function testPortraitNotAllowedOnSvg(Image $constraint)
{
$this->validator->validate($this->imageSvgPortrait, $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ width }}', 1)
->setParameter('{{ height }}', 2)
->setCode(Image::PORTRAIT_NOT_ALLOWED_ERROR)
->assertRaised();
}

public function provideDetectCorruptedConstraints(): iterable
{
yield 'Doctrine style' => [new Image([
Expand Down
0