Issues (3627)

FormBundle/Validator/UploadFieldValidator.php (1 issue)

1
<?php
2
3
/*
4
 * @copyright   2014 Mautic Contributors. All rights reserved
5
 * @author      Mautic
6
 *
7
 * @link        http://mautic.org
8
 *
9
 * @license     GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
10
 */
11
12
namespace Mautic\FormBundle\Validator;
13
14
use Mautic\CoreBundle\Exception\FileInvalidException;
15
use Mautic\CoreBundle\Validator\FileUploadValidator;
16
use Mautic\FormBundle\Entity\Field;
17
use Mautic\FormBundle\Exception\FileValidationException;
18
use Mautic\FormBundle\Exception\NoFileGivenException;
19
use Mautic\FormBundle\Form\Type\FormFieldFileType;
20
use Symfony\Component\HttpFoundation\File\UploadedFile;
21
use Symfony\Component\HttpFoundation\Request;
22
23
class UploadFieldValidator
24
{
25
    /**
26
     * @var FileUploadValidator
27
     */
28
    private $fileUploadValidator;
29
30
    public function __construct(FileUploadValidator $fileUploadValidator)
31
    {
32
        $this->fileUploadValidator = $fileUploadValidator;
33
    }
34
35
    /**
36
     * @return UploadedFile
37
     *
38
     * @throws FileValidationException
39
     * @throws NoFileGivenException
40
     */
41
    public function processFileValidation(Field $field, Request $request)
42
    {
43
        $files = $request->files->get('mauticform');
44
45
        if (!$files || !array_key_exists($field->getAlias(), $files)) {
46
            throw new NoFileGivenException();
47
        }
48
49
        /** @var UploadedFile $file */
50
        $file = $files[$field->getAlias()];
51
52
        if (!$file instanceof UploadedFile) {
0 ignored issues
show
$file is always a sub-type of Symfony\Component\HttpFoundation\File\UploadedFile.
Loading history...
53
            throw new NoFileGivenException();
54
        }
55
56
        $properties = $field->getProperties();
57
58
        $maxUploadSize     = $properties[FormFieldFileType::PROPERTY_ALLOWED_FILE_SIZE];
59
        $allowedExtensions = $properties[FormFieldFileType::PROPERTY_ALLOWED_FILE_EXTENSIONS];
60
61
        try {
62
            $this->fileUploadValidator->validate($file->getSize(), $file->getClientOriginalExtension(), $maxUploadSize, $allowedExtensions, 'mautic.form.submission.error.file.extension', 'mautic.form.submission.error.file.size');
63
64
            return $file;
65
        } catch (FileInvalidException $e) {
66
            throw new FileValidationException($e->getMessage());
67
        }
68
    }
69
}
70