4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Validator\Constraints;
14 use Symfony\Component\HttpFoundation\File\File as FileObject;
15 use Symfony\Component\HttpFoundation\File\UploadedFile;
16 use Symfony\Component\Validator\Constraint;
17 use Symfony\Component\Validator\ConstraintValidator;
18 use Symfony\Component\Validator\Exception\UnexpectedTypeException;
21 * @author Bernhard Schussek <bschussek@gmail.com>
23 class FileValidator extends ConstraintValidator
25 const KB_BYTES = 1000;
26 const MB_BYTES = 1000000;
27 const KIB_BYTES = 1024;
28 const MIB_BYTES = 1048576;
30 private static $suffices = array(
32 self::KB_BYTES => 'kB',
33 self::MB_BYTES => 'MB',
34 self::KIB_BYTES => 'KiB',
35 self::MIB_BYTES => 'MiB',
41 public function validate($value, Constraint $constraint)
43 if (!$constraint instanceof File) {
44 throw new UnexpectedTypeException($constraint, __NAMESPACE__.'\File');
47 if (null === $value || '' === $value) {
51 if ($value instanceof UploadedFile && !$value->isValid()) {
52 switch ($value->getError()) {
53 case UPLOAD_ERR_INI_SIZE:
54 $iniLimitSize = UploadedFile::getMaxFilesize();
55 if ($constraint->maxSize && $constraint->maxSize < $iniLimitSize) {
56 $limitInBytes = $constraint->maxSize;
57 $binaryFormat = $constraint->binaryFormat;
59 $limitInBytes = $iniLimitSize;
60 $binaryFormat = null === $constraint->binaryFormat ? true : $constraint->binaryFormat;
63 list($sizeAsString, $limitAsString, $suffix) = $this->factorizeSizes(0, $limitInBytes, $binaryFormat);
64 $this->context->buildViolation($constraint->uploadIniSizeErrorMessage)
65 ->setParameter('{{ limit }}', $limitAsString)
66 ->setParameter('{{ suffix }}', $suffix)
67 ->setCode(UPLOAD_ERR_INI_SIZE)
71 case UPLOAD_ERR_FORM_SIZE:
72 $this->context->buildViolation($constraint->uploadFormSizeErrorMessage)
73 ->setCode(UPLOAD_ERR_FORM_SIZE)
77 case UPLOAD_ERR_PARTIAL:
78 $this->context->buildViolation($constraint->uploadPartialErrorMessage)
79 ->setCode(UPLOAD_ERR_PARTIAL)
83 case UPLOAD_ERR_NO_FILE:
84 $this->context->buildViolation($constraint->uploadNoFileErrorMessage)
85 ->setCode(UPLOAD_ERR_NO_FILE)
89 case UPLOAD_ERR_NO_TMP_DIR:
90 $this->context->buildViolation($constraint->uploadNoTmpDirErrorMessage)
91 ->setCode(UPLOAD_ERR_NO_TMP_DIR)
95 case UPLOAD_ERR_CANT_WRITE:
96 $this->context->buildViolation($constraint->uploadCantWriteErrorMessage)
97 ->setCode(UPLOAD_ERR_CANT_WRITE)
101 case UPLOAD_ERR_EXTENSION:
102 $this->context->buildViolation($constraint->uploadExtensionErrorMessage)
103 ->setCode(UPLOAD_ERR_EXTENSION)
108 $this->context->buildViolation($constraint->uploadErrorMessage)
109 ->setCode($value->getError())
116 if (!is_scalar($value) && !$value instanceof FileObject && !(\is_object($value) && method_exists($value, '__toString'))) {
117 throw new UnexpectedTypeException($value, 'string');
120 $path = $value instanceof FileObject ? $value->getPathname() : (string) $value;
122 if (!is_file($path)) {
123 $this->context->buildViolation($constraint->notFoundMessage)
124 ->setParameter('{{ file }}', $this->formatValue($path))
125 ->setCode(File::NOT_FOUND_ERROR)
131 if (!is_readable($path)) {
132 $this->context->buildViolation($constraint->notReadableMessage)
133 ->setParameter('{{ file }}', $this->formatValue($path))
134 ->setCode(File::NOT_READABLE_ERROR)
140 $sizeInBytes = filesize($path);
142 if (0 === $sizeInBytes) {
143 $this->context->buildViolation($constraint->disallowEmptyMessage)
144 ->setParameter('{{ file }}', $this->formatValue($path))
145 ->setCode(File::EMPTY_ERROR)
151 if ($constraint->maxSize) {
152 $limitInBytes = $constraint->maxSize;
154 if ($sizeInBytes > $limitInBytes) {
155 list($sizeAsString, $limitAsString, $suffix) = $this->factorizeSizes($sizeInBytes, $limitInBytes, $constraint->binaryFormat);
156 $this->context->buildViolation($constraint->maxSizeMessage)
157 ->setParameter('{{ file }}', $this->formatValue($path))
158 ->setParameter('{{ size }}', $sizeAsString)
159 ->setParameter('{{ limit }}', $limitAsString)
160 ->setParameter('{{ suffix }}', $suffix)
161 ->setCode(File::TOO_LARGE_ERROR)
168 if ($constraint->mimeTypes) {
169 if (!$value instanceof FileObject) {
170 $value = new FileObject($value);
173 $mimeTypes = (array) $constraint->mimeTypes;
174 $mime = $value->getMimeType();
176 foreach ($mimeTypes as $mimeType) {
177 if ($mimeType === $mime) {
181 if ($discrete = strstr($mimeType, '/*', true)) {
182 if (strstr($mime, '/', true) === $discrete) {
188 $this->context->buildViolation($constraint->mimeTypesMessage)
189 ->setParameter('{{ file }}', $this->formatValue($path))
190 ->setParameter('{{ type }}', $this->formatValue($mime))
191 ->setParameter('{{ types }}', $this->formatValues($mimeTypes))
192 ->setCode(File::INVALID_MIME_TYPE_ERROR)
197 private static function moreDecimalsThan($double, $numberOfDecimals)
199 return \strlen((string) $double) > \strlen(round($double, $numberOfDecimals));
203 * Convert the limit to the smallest possible number
204 * (i.e. try "MB", then "kB", then "bytes").
206 private function factorizeSizes($size, $limit, $binaryFormat)
209 $coef = self::MIB_BYTES;
210 $coefFactor = self::KIB_BYTES;
212 $coef = self::MB_BYTES;
213 $coefFactor = self::KB_BYTES;
216 $limitAsString = (string) ($limit / $coef);
218 // Restrict the limit to 2 decimals (without rounding! we
219 // need the precise value)
220 while (self::moreDecimalsThan($limitAsString, 2)) {
221 $coef /= $coefFactor;
222 $limitAsString = (string) ($limit / $coef);
225 // Convert size to the same measure, but round to 2 decimals
226 $sizeAsString = (string) round($size / $coef, 2);
228 // If the size and limit produce the same string output
229 // (due to rounding), reduce the coefficient
230 while ($sizeAsString === $limitAsString) {
231 $coef /= $coefFactor;
232 $limitAsString = (string) ($limit / $coef);
233 $sizeAsString = (string) round($size / $coef, 2);
236 return array($sizeAsString, $limitAsString, self::$suffices[$coef]);