Passed
Push — master ( 0de292...c7f65a )
by Christian
02:22
created

ImageTypeExtension::getExtendedType()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 2
nc 2
nop 0
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * (c) Christian Gripp <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
namespace Core23\Form\Extension;
13
14
use Symfony\Component\Form\AbstractTypeExtension;
15
use Symfony\Component\Form\Extension\Core\Type\FileType;
16
use Symfony\Component\Form\FormBuilderInterface;
17
use Symfony\Component\Form\FormInterface;
18
use Symfony\Component\Form\FormView;
19
use Symfony\Component\OptionsResolver\OptionsResolver;
20
use Symfony\Component\PropertyAccess\PropertyAccess;
21
use Symfony\Component\PropertyAccess\PropertyPath;
22
23
final class ImageTypeExtension extends AbstractTypeExtension
24
{
25
    /**
26
     * {@inheritdoc}
27
     */
28
    public function configureOptions(OptionsResolver $resolver): void
29
    {
30
        $resolver
31
            ->setDefaults([
32
                'image_path' => null,
33
            ])
34
            ->setAllowedTypes('image_path', ['null', 'string'])
35
        ;
36
    }
37
38
    /**
39
     * {@inheritdoc}
40
     */
41
    public function buildForm(FormBuilderInterface $builder, array $options): void
42
    {
43
        if (null !== $options['image_path']) {
44
            $builder->setAttribute('image_path', $options['image_path']);
45
        }
46
    }
47
48
    /**
49
     * {@inheritdoc}
50
     */
51
    public function buildView(FormView $view, FormInterface $form, array $options): void
52
    {
53
        if (null !== $options['image_path'] && null !== $form->getParent()) {
54
            $parentData = $form->getParent()->getData();
55
56
            if (null !== $parentData) {
57
                $propertyAccessor = PropertyAccess::createPropertyAccessor();
58
                $propertyPath     = new PropertyPath($options['image_path']);
59
60
                $imageUrl = $propertyAccessor->getValue($parentData, $propertyPath);
61
            } else {
62
                $imageUrl = null;
63
            }
64
            $view->vars['image_url'] = $imageUrl;
65
        }
66
    }
67
68
    /**
69
     * {@inheritdoc}
70
     */
71
    public function getExtendedType()
72
    {
73
        foreach (static::getExtendedTypes() as $extendedType) {
74
            return $extendedType;
75
        }
76
    }
77
78
    /**
79
     * {@inheritdoc}
80
     */
81
    public static function getExtendedTypes(): iterable
82
    {
83
        return [
84
            FileType::class,
85
        ];
86
    }
87
}
88