Disallow empty file in FileValidator

This commit is contained in:
Vyacheslav Salakhutdinov 2014-06-15 13:48:08 +00:00
parent 9e3e89ae33
commit 1b253cb14d
4 changed files with 26 additions and 2 deletions

View File

@ -1,6 +1,11 @@
CHANGELOG
=========
2.6.0
-----
* [BC BREAK] `FileValidator` disallow empty files
2.5.0
-----

View File

@ -29,6 +29,7 @@ class File extends Constraint
public $notReadableMessage = 'The file is not readable.';
public $maxSizeMessage = 'The file is too large ({{ size }} {{ suffix }}). Allowed maximum size is {{ limit }} {{ suffix }}.';
public $mimeTypesMessage = 'The mime type of the file is invalid ({{ type }}). Allowed mime types are {{ types }}.';
public $disallowEmptyMessage = 'An empty file is not allowed.';
public $uploadIniSizeErrorMessage = 'The file is too large. Allowed maximum size is {{ limit }} {{ suffix }}.';
public $uploadFormSizeErrorMessage = 'The file is too large.';

View File

@ -121,8 +121,10 @@ class FileValidator extends ConstraintValidator
return;
}
if ($constraint->maxSize) {
$sizeInBytes = filesize($path);
$sizeInBytes = filesize($path);
if (0 === $sizeInBytes) {
$this->context->addViolation($constraint->disallowEmptyMessage);
} elseif ($constraint->maxSize) {
$limitInBytes = (int) $constraint->maxSize;
if (preg_match('/^\d++k$/', $constraint->maxSize)) {

View File

@ -29,6 +29,7 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
$this->validator->initialize($this->context);
$this->path = sys_get_temp_dir().DIRECTORY_SEPARATOR.'FileValidatorTest';
$this->file = fopen($this->path, 'w');
fwrite($this->file, ' ', 1);
}
protected function tearDown()
@ -319,6 +320,21 @@ abstract class FileValidatorTest extends \PHPUnit_Framework_TestCase
$this->validator->validate($file, $constraint);
}
public function testDisallowEmpty()
{
ftruncate($this->file, 0);
$constraint = new File(array(
'disallowEmptyMessage' => 'myMessage',
));
$this->context->expects($this->once())
->method('addViolation')
->with('myMessage');
$this->validator->validate($this->getFile($this->path), $constraint);
}
/**
* @dataProvider uploadedFileErrorProvider
*/