10000 [Validator] Migrate File and Image constraints to attributes by derrabus · Pull Request #38410 · symfony/symfony · GitHub
[go: up one dir, main page]

Skip to content

[Validator] Migrate File and Image constraints to attributes #38410

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

Merged
merged 1 commit into from
Oct 6, 2020
Merged
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
57 changes: 54 additions & 3 deletions src/Symfony/Component/Validator/Constraints/File.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
*
* @author Bernhard Schussek <bschussek@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_REPEATABLE)]
class File extends Constraint
{
// Check the Image constraint for clashes if adding new constants here
Expand Down Expand Up @@ -61,10 +62,57 @@ class File extends Constraint

/**
* {@inheritdoc}
*
* @param int|string|null $maxSize
* @param string[]|string|null $mimeTypes
*/
public function __construct($options = null)
{
parent::__construct($options);
public function __construct(
array $options = null,
$maxSize = null,
bool $binaryFormat = null,
$mimeTypes = null,
string $notFoundMessage = null,
string $notReadableMessage = null,
string $maxSizeMessage = null,
string $mimeTypesMessage = null,
string $disallowEmptyMessage = null,

string $uploadIniSizeErrorMessage = null,
string $uploadFormSizeErrorMessage = null,
string $uploadPartialErrorMessage = null,
string $uploadNoFileErrorMessage = null,
string $uploadNoTmpDirErrorMessage = null,
string $uploadCantWriteErrorMessage = null,
string $uploadExtensionErrorMessage = null,
string $uploadErrorMessage = null,
array $groups = null,
$payload = null
) {
if (null !== $maxSize && !\is_int($maxSize) && !\is_string($maxSize)) {
throw new \TypeError(sprintf('"%s": Expected argument $maxSize to be either null, an integer or a string, got "%s".', __METHOD__, get_debug_type($maxSize)));
}
if (null !== $mimeTypes && !\is_array($mimeTypes) && !\is_string($mimeTypes)) {
throw new \TypeError(sprintf('"%s": Expected argument $mimeTypes to be either null, an array or a string, got "%s".', __METHOD__, get_debug_type($mimeTypes)));
}

parent::__construct($options, $groups, $payload);

$this->maxSize = $maxSize ?? $this->maxSize;
$this->binaryFormat = $binaryFormat ?? $this->binaryFormat;
$this->mimeTypes = $mimeTypes ?? $this->mimeTypes;
$this->notFoundMessage = $notFoundMessage ?? $this->notFoundMessage;
$this->notReadableMessage = $notReadableMessage ?? $this->notReadableMessage;
$this->maxSizeMessage = $maxSizeMessage ?? $this->maxSizeMessage;
$this->mimeTypesMessage = $mimeTypesMessage ?? $this->mimeTypesMessage;
$this->disallowEmptyMessage = $disallowEmptyMessage ?? $this->disallowEmptyMessage;
$this->uploadIniSizeErrorMessage = $uploadIniSizeErrorMessage ?? $this->uploadIniSizeErrorMessage;
$this->uploadFormSizeErrorMessage = $uploadFormSizeErrorMessage ?? $this->uploadFormSizeErrorMessage;
$this->uploadPartialErrorMessage = $uploadPartialErrorMessage ?? $this->uploadPartialErrorMessage;
$this->uploadNoFileErrorMessage = $uploadNoFileErrorMessage ?? $this->uploadNoFileErrorMessage;
$this->uploadNoTmpDirErrorMessage = $uploadNoTmpDirErrorMessage ?? $this->uploadNoTmpDirErrorMessage;
$this->uploadCantWriteErrorMessage = $uploadCantWriteErrorMessage ?? $this->uploadCantWriteErrorMessage;
$this->uploadExtensionErrorMessage = $uploadExtensionErrorMessage ?? $this->uploadExtensionErrorMessage;
$this->uploadErrorMessage = $uploadErrorMessage ?? $this->uploadErrorMessage;

if (null !== $this->maxSize) {
$this->normalizeBinaryFormat($this->maxSize);
Expand Down Expand Up @@ -100,6 +148,9 @@ public function __isset(string $option)
return parent::__isset($option);
}

/**
* @param int|string $maxSize
*/
private function normalizeBinaryFormat($maxSize)
{
$factors = [
Expand Down
104 changes: 104 additions & 0 deletions src/Symfony/Component/Validator/Constraints/Image.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
* @author Benjamin Dulau <benjamin.dulau@gmail.com>
* @author Bernhard Schussek <bschussek@gmail.com>
*/
#[\Attribute(\Attribute::TARGET_PROPERTY | \Attribute::TARGET_METHOD | \Attribute::IS_R 10000 EPEATABLE)]
class Image extends File
{
const SIZE_NOT_DETECTED_ERROR = '6d55c3f4-e58e-4fe3-91ee-74b492199956';
Expand Down Expand Up @@ -86,4 +87,107 @@ class Image extends File
public $allowLandscapeMessage = 'The image is landscape oriented ({{ width }}x{{ height }}px). Landscape oriented images are not allowed.';
public $allowPortraitMessage = 'The image is portrait oriented ({{ width }}x{{ height }}px). Portrait oriented images are not allowed.';
public $corruptedMessage = 'The image file is corrupted.';

/**
* {@inheritdoc}
*
* @param int|float $maxRatio
* @param int|float $minRatio
* @param int|float $minPixels
* @param int|float $maxPixels
*/
public function __construct(
array $options = null,
$maxSize = null,
bool $binaryFormat = null,
array $mimeTypes = null,
int $minWidth = null,
int $maxWidth = null,
int $maxHeight = null,
int $minHeight = null,
$maxRatio = null,
$minRatio = null,
$minPixels = null,
$maxPixels = null,
bool $allowSquare = null,
bool $allowLandscape = null,
bool $allowPortrait = null,
bool $detectCorrupted = null,
string $notFoundMessage = null,
string $notReadableMessage = null,
string $maxSizeMessage = null,
string $mimeTypesMessage = null,
string $disallowEmptyMessage = null,
string $uploadIniSizeErrorMessage = null,
string $uploadFormSizeErrorMessage = null,
string $uploadPartialErrorMessage = null,
string $uploadNoFileErrorMessage = null,
string $uploadNoTmpDirErrorMessage = null,
string $uploadCantWriteErrorMessage = null,
string $uploadExtensionErrorMessage = null,
string $uploadErrorMessage = null,
string $sizeNotDetectedMessage = null,
string $maxWidthMessage = null,
string $minWidthMessage = null,
string $maxHeightMessage = null,
string $minHeightMessage = null,
string $minPixelsMessage = null,
string $maxPixelsMessage = null,
string $maxRatioMessage = null,
string $minRatioMessage = null,
string $allowSquareMessage = null,
string $allowLandscapeMessage = null,
string $allowPortraitMessage = null,
string $corruptedMessage = null,
array $groups = null,
$payload = null
) {
parent::__construct(
$options,
$maxSize,
$binaryFormat,
$mimeTypes,
$notFoundMessage,
$notReadableMessage,
$maxSizeMessage,
$mimeTypesMessage,
$disallowEmptyMessage,
$uploadIniSizeErrorMessage,
$uploadFormSizeErrorMessage,
$uploadPartialErrorMessage,
$uploadNoFileErrorMessage,
$uploadNoTmpDirErrorMessage,
$uploadCantWriteErrorMessage,
$uploadExtensionErrorMessage,
$uploadErrorMessage,
$groups,
$payload
);

$this->minWidth = $minWidth ?? $this->minWidth;
$this->maxWidth = $maxWidth ?? $this->maxWidth;
$this->maxHeight = $maxHeight ?? $this->maxHeight;
$this->minHeight = $minHeight ?? $this->minHeight;
$this->maxRatio = $maxRatio ?? $this->maxRatio;
$this->minRatio = $minRatio ?? $this->minRatio;
$this->minPixels = $minPixels ?? $this->minPixels;
$this->maxPixels = $maxPixels ?? $this->maxPixels;
$this->allowSquare = $allowSquare ?? $this->allowSquare;
$this->allowLandscape = $allowLandscape ?? $this->allowLandscape;
$this->allowPortrait = $allowPortrait ?? $this->allowPortrait;
$this->detectCorrupted = $detectCorrupted ?? $this->detectCorrupted;
$this->sizeNotDetectedMessage = $sizeNotDetectedMessage ?? $this->sizeNotDetectedMessage;
$this->maxWidthMessage = $maxWidthMessage ?? $this->maxWidthMessage;
$this->minWidthMessage = $minWidthMessage ?? $this->minWidthMessage;
$this->maxHeightMessage = $maxHeightMessage ?? $this->maxHeightMessage;
$this->minHeightMessage = $minHeightMessage ?? $this->minHeightMessage;
$this->minPixelsMessage = $minPixelsMessage ?? $this->minPixelsMessage;
$this->maxPixelsMessage = $maxPixelsMessage ?? $this->maxPixelsMessage;
$this->maxRatioMessage = $maxRatioMessage ?? $this->maxRatioMessage;
$this->minRatioMessage = $minRatioMessage ?? $this->minRatioMessage;
$this->allowSquareMessage = $allowSquareMessage ?? $this->allowSquareMessage;
$this->allowLandscapeMessage = $allowLandscapeMessage ?? $this->allowLandscapeMessage;
$this->allowPortraitMessage = $allowPortraitMessage ?? $this->allowPortraitMessage;
$this->corruptedMessage = $corruptedMessage ?? $this->corruptedMessage;
}
}
36 changes: 36 additions & 0 deletions src/Symfony/Component/Validator/Tests/Constraints/FileTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@
use PHPUnit\Framework\TestCase;
use Symfony\Component\Validator\Constraints\File;
use Symfony\Component\Validator\Exception\ConstraintDefinitionException;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Mapping\Loader\AnnotationLoader;

class FileTest extends TestCase
{
Expand Down Expand Up @@ -138,4 +140,38 @@ public function provideFormats()
['100Ki', false, false],
];
}

/**
* @requires PHP 8
*/
public function testAttributes()
{
$metadata = new ClassMetadata(FileDummy::class);
self::assertTrue((new AnnotationLoader())->loadClassMetadata($metadata));

list($aConstraint) = $metadata->properties['a']->getConstraints();
self::assertNull($aConstraint->maxSize);

list($bConstraint) = $metadata->properties['b']->getConstraints();
self::assertSame(100, $bConstraint->maxSize);
self::assertSame('myMessage', $bConstraint->notFoundMessage);
self::assertSame(['Default', 'FileDummy'], $bConstraint->groups);

list($cConstraint) = $metadata->properties['c']->getConstraints();
self::assertSame(100000, $cConstraint->maxSize);
self::assertSame(['my_group'], $cConstraint->groups);
self::assertSame('some attached data', $cConstraint->payload);
}
}

class FileDummy
{
#[File]
private $a;

#[File(maxSize: 100, notFoundMessage: 'myMessage')]
private $b;

#[File(maxSize: '100K', groups: ['my_group'], payload: 'some attached data')]
private $c;
}
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,29 @@ public function testBinaryFormat($bytesWritten, $limit, $binaryFormat, $sizeAsSt
->assertRaised();
}

/**
* @requires PHP 8
*/
public function testBinaryFormatNamed()
{
fseek($this->file, 10, \SEEK_SET);
fwrite($this->file, '0');
fclose($this->file);

$constraint = eval('return new \Symfony\Component\Validator\Constraints\File(maxSize: 10, binaryFormat: true, maxSizeMessage: "myMessage");');

$this->validator->validate($this->getFile($this->path), $constraint);

$this->buildViolation('myMessage')
->setParameter('{{ limit }}', '10')
->setParameter('{{ size }}', '11')
->setParameter('{{ suffix }}', 'bytes')
->setParameter('{{ file }}', '"'.$this->path.'"')
->setParameter('{{ name }}', '"'.basename($this->path).'"')
->setCode(File::TOO_LARGE_ERROR)
->assertRaised();
}

public function testValidMimeType()
{
$file = $this
Expand Down Expand Up @@ -329,7 +352,10 @@ public function testValidWildcardMimeType()
$this->assertNoViolation();
}

public function testInvalidMimeType()
/**
* @dataProvider provideMimeTypeConstraints
*/
public function testInvalidMimeType(File $constraint)
{
$file = $this
->getMockBuilder('Symfony\Component\HttpFoundation\File\File')
Expand All @@ -344,11 +370,6 @@ public function testInvalidMimeType()
->method('getMimeType')
->willReturn('application/pdf');

$constraint = new File([
'mimeTypes' => ['image/png', 'image/jpg'],
'mimeTypesMessage' => 'myMessage',
]);

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

$this->buildViolation('myMessage')
Expand All @@ -360,6 +381,20 @@ public function testInvalidMimeType()
->assertRaised();
}

public function provideMimeTypeConstraints(): iterable
{
yield 'Doctrine style' => [new File([
'mimeTypes' => ['image/png', 'image/jpg'],
'mimeTypesMessage' => 'myMessage',
])];

if (\PHP_VERSION_ID >= 80000) {
yield 'named arguments' => [
eval('return new \Symfony\Component\Validator\Constraints\File(mimeTypes: ["image/png", "image/jpg"], mimeTypesMessage: "myMessage");'),
];
}
}

public function testInvalidWildcardMimeType()
{
$file = $this
Expand Down Expand Up @@ -391,14 +426,13 @@ public function testInvalidWildcardMimeType()
->assertRaised();
}

public function testDisallowEmpty()
/**
* @dataProvider provideDisallowEmptyConstraints
*/
public function testDisallowEmpty(File $constraint)
{
ftruncate($this->file, 0);

$constraint = new File([
'disallowEmptyMessage' => 'myMessage',
]);

$this->validator->validate($this->getFile($this->path), $constraint);

$this->buildViolation('myMessage')
Expand All @@ -408,6 +442,19 @@ public function testDisallowEmpty()
->assertRaised();
}

public function provideDisallowEmptyConstraints(): iterable
{
yield 'Doctrine style' => [new File([
'disallowEmptyMessage' => 'myMessage',
])];

if (\PHP_VERSION_ID >= 80000) {
yield 'named arguments' => [
eval('return new \Symfony\Component\Validator\Constraints\File(disallowEmptyMessage: "myMessage");'),
];
}
}

/**
* @dataProvider uploadedFileErrorProvider
*/
Expand Down
Loading
0