Completed
Push — symfony3-fqcn-promotion ( 0dc095...05101d )
by Kamil
16:30
created

BuildProductVariantFormSubscriber   A

Complexity

Total Complexity 5

Size/Duplication

Total Lines 63
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 5

Importance

Changes 0
Metric Value
wmc 5
lcom 1
cbo 5
dl 0
loc 63
rs 10
c 0
b 0
f 0

3 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 5 1
A getSubscribedEvents() 0 6 1
B preSetData() 0 27 3
1
<?php
2
3
/*
4
 * This file is part of the Sylius package.
5
 *
6
 * (c) Paweł Jędrzejewski
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 Sylius\Bundle\ProductBundle\Form\EventSubscriber;
13
14
use Sylius\Bundle\ProductBundle\Form\Type\ProductOptionValueCollectionType;
15
use Sylius\Component\Product\Model\ProductVariantInterface;
16
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
17
use Symfony\Component\Form\FormEvent;
18
use Symfony\Component\Form\FormEvents;
19
use Symfony\Component\Form\FormFactoryInterface;
20
21
/**
22
 * @author Paweł Jędrzejewski <[email protected]>
23
 * @author Łukasz Chruściel <[email protected]>
24
 */
25
final class BuildProductVariantFormSubscriber implements EventSubscriberInterface
26
{
27
    /**
28
     * @var FormFactoryInterface
29
     */
30
    private $factory;
31
32
    /**
33
     * @var bool
34
     */
35
    private $disabled;
36
37
    /**
38
     * @param FormFactoryInterface $factory
39
     * @param bool $disabled
40
     */
41
    public function __construct(FormFactoryInterface $factory, $disabled = false)
42
    {
43
        $this->factory = $factory;
44
        $this->disabled = $disabled;
45
    }
46
47
    /**
48
     * {@inheritdoc}
49
     */
50
    public static function getSubscribedEvents()
51
    {
52
        return [
53
            FormEvents::PRE_SET_DATA => 'preSetData',
54
        ];
55
    }
56
57
    /**
58
     * @param FormEvent $event
59
     */
60
    public function preSetData(FormEvent $event)
61
    {
62
        /** @var ProductVariantInterface $productVariant */
63
        $productVariant = $event->getData();
64
        $form = $event->getForm();
65
66
        if (null === $productVariant) {
67
            return;
68
        }
69
70
        $product = $productVariant->getProduct();
71
72
        if (!$product->hasOptions()) {
73
            return;
74
        }
75
76
        $form->add($this->factory->createNamed(
77
            'optionValues',
78
            ProductOptionValueCollectionType::class,
79
            $productVariant->getOptionValues(),
80
            [
81
                'disabled' => $this->disabled,
82
                'options' => $product->getOptions(),
83
                'auto_initialize' => false,
84
            ]
85
        ));
86
    }
87
}
88