Completed
Push — master ( 5d51b4...87fdd9 )
by Paul
10s
created

ArticleType::buildForm()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 41
Code Lines 30

Duplication

Lines 13
Ratio 31.71 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
c 2
b 0
f 0
dl 13
loc 41
rs 8.8571
cc 1
eloc 30
nc 1
nop 2
1
<?php
2
3
namespace Victoire\Bundle\BlogBundle\Form;
4
5
use A2lix\TranslationFormBundle\Form\Type\TranslationsType;
6
use Doctrine\ORM\EntityManager;
7
use Symfony\Component\Form\AbstractType;
8
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
9
use Symfony\Component\Form\FormBuilderInterface;
10
use Symfony\Component\Form\FormEvent;
11
use Symfony\Component\Form\FormEvents;
12
use Symfony\Component\OptionsResolver\OptionsResolver;
13
use Victoire\Bundle\BlogBundle\Entity\Blog;
14
use Victoire\Bundle\BlogBundle\Repository\ArticleTemplateRepository;
15
use Victoire\Bundle\BlogBundle\Repository\TagRepository;
16
use Victoire\Bundle\CoreBundle\DataTransformer\ViewToIdTransformer;
17
use Victoire\Bundle\MediaBundle\Form\Type\MediaType;
18
19
class ArticleType extends AbstractType
20
{
21
    private $entityManager;
22
23
    /**
24
     * Constructor.
25
     */
26
    public function __construct(EntityManager $entityManager)
0 ignored issues
show
Bug introduced by
You have injected the EntityManager via parameter $entityManager. This is generally not recommended as it might get closed and become unusable. Instead, it is recommended to inject the ManagerRegistry and retrieve the EntityManager via getManager() each time you need it.

The EntityManager might become unusable for example if a transaction is rolled back and it gets closed. Let’s assume that somewhere in your application, or in a third-party library, there is code such as the following:

function someFunction(ManagerRegistry $registry) {
    $em = $registry->getManager();
    $em->getConnection()->beginTransaction();
    try {
        // Do something.
        $em->getConnection()->commit();
    } catch (\Exception $ex) {
        $em->getConnection()->rollback();
        $em->close();

        throw $ex;
    }
}

If that code throws an exception and the EntityManager is closed. Any other code which depends on the same instance of the EntityManager during this request will fail.

On the other hand, if you instead inject the ManagerRegistry, the getManager() method guarantees that you will always get a usable manager instance.

Loading history...
27
    {
28
        $this->entityManager = $entityManager;
29
    }
30
31
    /**
32
     * define form fields.
33
     *
34
     * @param FormBuilderInterface $builder
35
     * @param array                $options
36
     */
37
    public function buildForm(FormBuilderInterface $builder, array $options)
38
    {
39
        $viewToIdTransformer = new ViewToIdTransformer($this->entityManager);
40
41
        $builder
42
            ->add($builder
43
                ->create('blog', HiddenType::class, ['label' => 'form.article.blog.label'])
44
                ->addModelTransformer($viewToIdTransformer))
45
            ->add('template')
46
            ->add('tags', TagsType::class, [
47
                'required' => false,
48
                'multiple' => true,
49
            ])
50
            ->remove('visibleOnFront');
51
52 View Code Duplication
        $builder->get('blog')->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
53
            $data = $event->getData();
54
            $parent = $event->getForm()->getParent();
55
            $this->manageCategories($data, $parent);
56
            $this->manageTemplate($data, $parent);
57
            $this->manageLocales($data, $parent);
58
        });
59
60 View Code Duplication
        $builder->get('blog')->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
61
            $data = $event->getData();
62
            $parent = $event->getForm()->getParent();
63
            $this->manageCategories($data, $parent);
64
            $this->manageLocales($data, $parent);
65
        });
66
67
        $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
68
            $data = $event->getData();
69
            $form = $event->getForm();
70
            $this->manageTags($data, $form);
71
        });
72
        $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
73
            $form = $event->getForm();
74
            $data = $form->getData();
75
            $this->manageTags($data, $form);
76
        });
77
    }
78
79
    /**
80
     * @param \Symfony\Component\Form\FormInterface $form
81
     */
82
    protected function manageTags($data, $form)
83
    {
84
        $form->add('tags', TagsType::class, [
85
            'required'      => false,
86
            'multiple'      => true,
87
            'query_builder' => function (TagRepository $er) use ($data) {
88
                $qb = $er->filterByBlog($data->getBlog())->getInstance();
89
                $er->clearInstance();
90
91
                return $qb;
92
            },
93
        ]);
94
    }
95
96
    /**
97
     * @param \Symfony\Component\Form\FormInterface|null $form
98
     *
99
     * @throws \Symfony\Component\Form\Exception\AlreadySubmittedException
100
     */
101
    protected function manageLocales($blog, $form)
102
    {
103
        if (!$blog instanceof Blog) {
104
            $blog = $this->entityManager->getRepository('VictoireBlogBundle:Blog')->findOneById($blog);
105
        }
106
        $translations = $blog->getTranslations();
107
        $availableLocales = [];
108
        foreach ($translations as $translation) {
109
            $availableLocales[] = $translation->getLocale();
110
        }
111
        $form->add('translations', TranslationsType::class, [
0 ignored issues
show
Bug introduced by
It seems like $form is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
112
            'required_locales' => $availableLocales,
113
            'locales'          => $availableLocales,
114
            'fields'           => [
115
                'name' => [
116
                    'label' => 'form.article.name.label',
117
                ],
118
                'image' => [
119
                    'label'      => 'form.article.image.label',
120
                    'field_type' => MediaType::class,
121
                    'required'   => false,
122
                ],
123
124
            ],
125
        ]);
126
    }
127
128
    /**
129
     * @param \Symfony\Component\Form\FormInterface|null $form
130
     */
131
    protected function manageCategories($blogId, $form)
132
    {
133
        $categoryRepo = $this->entityManager->getRepository('Victoire\Bundle\BlogBundle\Entity\Category');
134
135
        if ($blogId) {
136
            $queryBuilder = $categoryRepo->getOrderedCategories($blogId)->getInstance();
137
            $categoryRepo->clearInstance();
138
        } else {
139
            $queryBuilder = $categoryRepo->getAll()->getInstance();
140
            $categoryRepo->clearInstance();
141
        }
142
143
        $form->add('category', HierarchyTreeType::class, [
0 ignored issues
show
Bug introduced by
It seems like $form is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
144
            'required'      => false,
145
            'label'         => 'form.article.category.label',
146
            'class'         => 'Victoire\\Bundle\\BlogBundle\\Entity\\Category',
147
            'query_builder' => $queryBuilder,
148
            'placeholder'   => 'form.article.category.placeholder',
149
        ]);
150
    }
151
152
    /**
153
     * @param \Symfony\Component\Form\FormInterface|null $form
154
     */
155
    protected function manageTemplate($blog_id, $form)
156
    {
157
        $articleTemplateRepo = $this->entityManager->getRepository('VictoireBlogBundle:ArticleTemplate');
158
159
        if (!$form->getData()->getTemplate()) {
160
            if ($articleTemplateRepo->filterByBlog($blog_id)->getCount('parent')->run('getSingleScalarResult') > 1) {
161
                $articleTemplates = function (ArticleTemplateRepository $repo) use ($blog_id) {
162
                    return $repo->filterByBlog($blog_id)->getInstance();
163
                };
164
                $form->add('template', null, [
0 ignored issues
show
Bug introduced by
It seems like $form is not always an object, but can also be of type null. Maybe add an additional type check?

If a variable is not always an object, we recommend to add an additional type check to ensure your method call is safe:

function someFunction(A $objectMaybe = null)
{
    if ($objectMaybe instanceof A) {
        $objectMaybe->doSomething();
    }
}
Loading history...
165
                    'label'         => 'form.article.type.template.label',
166
                    'property'      => 'backendName',
167
                    'required'      => true,
168
                    'query_builder' => $articleTemplates,
169
                ]);
170
            } else {
171
                $form->add('template', ArticleTemplateType::class, [
172
                    'data_class' => null,
173
                    'data'       => $articleTemplateRepo->filterByBlog($blog_id)->run('getSingleResult'),
174
                ]);
175
            }
176
        } else {
177
            $form->remove('template');
178
        }
179
    }
180
181
    /**
182
     * bind to Page entity.
183
     *
184
     * @param OptionsResolver $resolver
185
     */
186
    public function configureOptions(OptionsResolver $resolver)
187
    {
188
        $resolver->setDefaults([
189
                'data_class'         => 'Victoire\Bundle\BlogBundle\Entity\Article',
190
                'translation_domain' => 'victoire',
191
            ]);
192
    }
193
}
194