FileNameTypeExtension::onPostSubmit()   B
last analyzed

Complexity

Conditions 8
Paths 6

Size

Total Lines 20
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 20
rs 7.7777
c 0
b 0
f 0
cc 8
eloc 12
nc 6
nop 1
1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: sanbright
5
 * Date: 23.08.16
6
 * Time: 18:56
7
 */
8
9
namespace Fenrizbes\UploadableBundle\Form\Extension;
10
11
12
use Symfony\Component\Form\AbstractTypeExtension;
13
use Symfony\Component\Form\Extension\Core\Type\FileType;
14
use Symfony\Component\Form\FormEvents;
15
use Symfony\Component\Form\FormEvent;
16
use Symfony\Component\Form\FormView;
17
use Symfony\Component\Form\FormBuilderInterface;
18
use Symfony\Component\HttpFoundation\File\UploadedFile;
19
20
use Symfony\Component\Form\FormInterface;
21
22
class FileNameTypeExtension extends AbstractTypeExtension
23
{
24
    public function getExtendedType() {
25
        if(static::isLegacy()) {
26
            return FileType::class;
27
        }
28
        else {
29
            return 'file';
30
        }
31
    }
32
33
    public function buildForm(FormBuilderInterface $builder, array $options) {
34
        parent::buildForm($builder, $options); // TODO: Change the autogenerated stub
35
        $builder->addEventListener(FormEvents::POST_SUBMIT, [
36
            $this,
37
            'onPostSubmit'
38
        ]);
39
    }
40
41
    public function onPostSubmit(FormEvent $event) {
42
        $fieldName = $event->getForm()->getName();
43
        $fileData = $event->getData();
44
45
        $object = $event->getForm()->getParent()->getData();
46
        if(!$event->getForm()->getConfig()->getOption('multiple')) {
47
            if(method_exists($object, 'setOriginalFileName') && $fileData instanceof UploadedFile) {
48
                $object->setOriginalFileName($fieldName, $fileData->getClientOriginalName());
49
            }
50
        }
51
        else {
52
            if(is_array($event->getForm()->getData())) {
53
                foreach($event->getForm()->getData() as $key => $item) {
54
                    if(method_exists($item, 'setOriginalFileName') && $fileData[$key] instanceof UploadedFile) {
55
                        $item->setOriginalFileName($fieldName, $fileData[$key]->getClientOriginalName()); //$item->getClientOriginalName()
56
                    }
57
                }
58
            }
59
        }
60
    }
61
62
    public static function isLegacy() {
63
        return !method_exists('Symfony\Component\Form\AbstractType', 'getBlockPrefix');
64
    }
65
66
}