-
-
Notifications
You must be signed in to change notification settings - Fork 9.6k
[Validator] Add the DataUri
constraint for validating Data URI content
#58201
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
symfonyaml
wants to merge
2
commits into
symfony:7.2
from
symfonyaml:feature-validator-datauri-constraint
Closed
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,46 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\Validator\Constraints; | ||
|
||
use Symfony\Component\Validator\Constraint; | ||
|
||
/** | ||
* Validates that a value is a valid data URI string. | ||
* | ||
* @author Kev <https://github.com/symfonyaml> | ||
*/ | ||
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)] | ||
class DataUri extends Constraint | ||
{ | ||
public const INVALID_DATA_URI_ERROR = 'b9e175d1-8d7a-4e28-bf65-ad2448a3b3cf'; | ||
|
||
protected const ERROR_NAMES = [ | ||
self::INVALID_DATA_URI_ERROR => 'INVALID_DATA_URI_ERROR', | ||
]; | ||
|
||
public string $message = 'This value is not a valid data URI.'; | ||
|
||
/** | ||
* @param array<string,mixed>|null $options | ||
* @param string[]|null $groups | ||
*/ | ||
public function __construct( | ||
?array $options = null, | ||
?string $message = null, | ||
?array $groups = null, | ||
mixed $payload = null, | ||
) { | ||
parent::__construct($options ?? [], $groups, $payload); | ||
|
||
$this->message = $message ?? $this->message; | ||
} | ||
} |
69 changes: 69 additions & 0 deletions
69
src/Symfony/Component/Validator/Constraints/DataUriValidator.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,69 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\Validator\Constraints; | ||
|
||
use Symfony\Component\Validator\Constraint; | ||
use Symfony\Component\Validator\ConstraintValidator; | ||
use Symfony\Component\Validator\Exception\UnexpectedTypeException; | ||
use Symfony\Component\Validator\Exception\UnexpectedValueException; | ||
|
||
/** | ||
* @author Kev <https://github.com/symfonyaml> | ||
* | ||
* @see https://datatracker.ietf.org/doc/html/rfc2397 | ||
*/ | ||
class DataUriValidator extends ConstraintValidator | ||
{ | ||
/** maximum number of characters allowed in a error message */ | ||
private const MAX_MESSAGE_VALUE_LENGTH = 30; | ||
/** data-uri regexp */ | ||
public const PATTERN = '~^ | ||
data: | ||
(?:\w+\/(?:(?!;).)+)? # MIME-type | ||
(?:;[\w\W]*?[^;])* # parameters | ||
(;base64)? # encoding | ||
, | ||
[^$]+ # data | ||
$~ixuD'; | ||
|
||
public function validate(mixed $value, Constraint $constraint): void | ||
{ | ||
if (!$constraint instanceof DataUri) { | ||
throw new UnexpectedTypeException($constraint, DataUri::class); | ||
} | ||
|
||
if (null === $value || '' === $value) { | ||
return; | ||
} | ||
|
||
if (!\is_scalar($value) && !$value instanceof \Stringable) { | ||
throw new UnexpectedValueException($value, 'string'); | ||
} | ||
|
||
$value = (string) $value; | ||
if ('' === $value) { | ||
return; | ||
} | ||
|
||
if (!preg_match(static::PATTERN, $value)) { | ||
if (\strlen($value) > self::MAX_MESSAGE_VALUE_LENGTH) { | ||
$value = \sprintf('%s (truncated)', $this->formatValue(substr($value, 0, self::MAX_MESSAGE_VALUE_LENGTH).'...')); | ||
} else { | ||
$value = $this->formatValue($value); | ||
} | ||
$this->context->buildViolation($constraint->message) | ||
->setParameter('{{ value }}', $value) | ||
->setCode(DataUri::INVALID_DATA_URI_ERROR) | ||
->addViolation(); | ||
} | ||
} | ||
} |
99 changes: 99 additions & 0 deletions
99
src/Symfony/Component/Validator/Tests/Constraints/DataUriValidatorTest.php
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
<?php | ||
|
||
/* | ||
* This file is part of the Symfony package. | ||
* | ||
* (c) Fabien Potencier <fabien@symfony.com> | ||
* | ||
* For the full copyright and license information, please view the LICENSE | ||
* file that was distributed with this source code. | ||
*/ | ||
|
||
namespace Symfony\Component\Validator\Tests\Constraints; | ||
|
||
use Symfony\Component\Validator\Constraints\DataUri; | ||
use Symfony\Component\Validator\Constraints\DataUriValidator; | ||
use Symfony\Component\Validator\Test\ConstraintValidatorTestCase; | ||
|
||
/** | ||
* @author Kev <https://github.com/symfonyaml> | ||
*/ | ||
class DataUriValidatorTest extends ConstraintValidatorTestCase | ||
{ | ||
protected function createValidator(): DataUriValidator | ||
{ | ||
return new DataUriValidator(); | ||
} | ||
|
||
public function testNullIsValid() | ||
{ | ||
$this->validator->validate(null, new DataUri()); | ||
|
||
$this->assertNoViolation(); | ||
} | ||
|
||
public function testBlankIsValid() | ||
{ | ||
$this->validator->validate('', new DataUri()); | ||
|
||
$this->assertNoViolation(); | ||
} | ||
|
||
/** | ||
* @dataProvider getValidValues | ||
*/ | ||
public function testValidValues(string $value) | ||
{ | ||
$this->validator->validate($value, new DataUri()); | ||
|
||
$this->assertNoViolation(); | ||
} | ||
|
||
public static function getValidValues() | ||
{ | ||
return [ | ||
'mime type is omitted' => ['data:,FooBar'], | ||
'just charset' => ['data:;charset=UTF-8,FooBar'], | ||
'plain text' => ['data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=='], | ||
'text html' => ['data:text/html,%3Ch1%3EHello%2C%20World%21%3C%2Fh1%3E'], | ||
'plain text with charset' => ['data:text/plain;charset=UTF-8,the%20data:1234,5678'], | ||
'with meta key=value' => ['data:image/jpeg;key=value;base64,UEsDBBQAAAAI'], | ||
'without base64 key name' => ['data:image/jpeg;key=value,UEsDBBQAAAAI'], | ||
'jpeg image' => ['data:image/jpeg;base64,/9j/4AAQSkZJRgABAgAAZABkAAD'], | ||
'png image' => ['data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='], | ||
'gif image' => ['data:image/gif;base64,R0lGODlhyAAiALM...DfD0QAADs='], | ||
'svg' => ['data:image/svg+xml,%3Csvg%20version%3D%221.1%22%3E%3C%2Fsvg%3E'], | ||
'networking applications' => ['data:application/vnd-xxx-query,select_vcount,fcol_from_fieldtable/local,123456789'], | ||
]; | ||
} | ||
|
||
/** | ||
* @dataProvider getInvalidValues | ||
*/ | ||
public function testInvalidValues($value, $valueAsString) | ||
{ | ||
$constraint = new DataUri([ | ||
'message' => 'myMessage', | ||
]); | ||
|
||
$this->validator->validate($value, $constraint); | ||
|
||
$this->buildViolation('myMessage') | ||
->setParameter('{{ value }}', $valueAsString) | ||
->setCode(DataUri::INVALID_DATA_URI_ERROR) | ||
->assertRaised(); | ||
} | ||
|
||
public static function getInvalidValues() | ||
{ | ||
return [ | ||
'random string' => ['foobar', '"foobar"'], | ||
'zero' => [0, '"0"'], | ||
'integer' => [1234, '"1234"'], | ||
'truncated invalid value' => [ | ||
'1234567890123456789012345678901', // 31 chars | ||
'"123456789012345678901234567890..." (truncated)', | ||
], | ||
]; | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't think this is correct: the data part cannot be "anything-but-$"
Here is another regexp for your consideration:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@nicolas-grekas thank you so much, I'll have a go...
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note that I'm not sure my regexp is correct. I often see data URI with html tags in them and this wouldn't be allowed. Looks like carefully reading the RFC might be needed :)