Skip to content

Commit 319f561

Browse files
committed
Disallow empty file in FileValidator
1 parent e81249a commit 319f561

File tree

4 files changed

+26
-2
lines changed

4 files changed

+26
-2
lines changed

CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,11 @@
11
CHANGELOG
22
=========
33

4+
2.6.0
5+
-----
6+
7+
* [BC BREAK] `FileValidator` disallow empty files
8+
49
2.5.0
510
-----
611

Constraints/File.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ class File extends Constraint
2929
public $notReadableMessage = 'The file is not readable.';
3030
public $maxSizeMessage = 'The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.';
3131
public $mimeTypesMessage = 'The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.';
32+
public $disallowEmptyMessage = 'An empty file is not allowed.';
3233

3334
public $uploadIniSizeErrorMessage = 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.';
3435
public $uploadFormSizeErrorMessage = 'The file is too large.';

Constraints/FileValidator.php

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -121,8 +121,10 @@ public function validate($value, Constraint $constraint)
121121
return;
122122
}
123123

124-
if ($constraint->maxSize) {
125-
$sizeInBytes = filesize($path);
124+
$sizeInBytes = filesize($path);
125+
if (0 === $sizeInBytes) {
126+
$this->context->addViolation($constraint->disallowEmptyMessage);
127+
} elseif ($constraint->maxSize) {
126128
$limitInBytes = (int) $constraint->maxSize;
127129

128130
if (preg_match('/^\d++k$/', $constraint->maxSize)) {

Tests/Constraints/FileValidatorTest.php

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ protected function setUp()
2929
$this->validator->initialize($this->context);
3030
$this->path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'FileValidatorTest';
3131
$this->file = fopen($this->path, 'w');
32+
fwrite($this->file, ' ', 1);
3233
}
3334

3435
protected function tearDown()
@@ -319,6 +320,21 @@ public function testInvalidWildcardMimeType()
319320
$this->validator->validate($file, $constraint);
320321
}
321322

323+
public function testDisallowEmpty()
324+
{
325+
ftruncate($this->file, 0);
326+
327+
$constraint = new File(array(
328+
'disallowEmptyMessage' => 'myMessage',
329+
));
330+
331+
$this->context->expects($this->once())
332+
->method('addViolation')
333+
->with('myMessage');
334+
335+
$this->validator->validate($this->getFile($this->path), $constraint);
336+
}
337+
322338
/**
323339
* @dataProvider uploadedFileErrorProvider
324340
*/

0 commit comments

Comments
 (0)