Completed
Pull Request — 3.x (#601)
by Jordi Sala
08:17
created

SonataNewsExtension::load()   C

Complexity

Conditions 9
Paths 60

Size

Total Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 84
rs 6.7935
c 0
b 0
f 0
cc 9
nc 60
nop 2

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Sonata Project package.
7
 *
8
 * (c) Thomas Rabaix <[email protected]>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Sonata\NewsBundle\DependencyInjection;
15
16
use Sonata\Doctrine\Mapper\Builder\OptionsBuilder;
17
use Sonata\Doctrine\Mapper\DoctrineCollector;
18
use Sonata\EasyExtendsBundle\Mapper\DoctrineCollector as DeprecatedDoctrineCollector;
19
use Symfony\Component\Config\Definition\Processor;
20
use Symfony\Component\Config\FileLocator;
21
use Symfony\Component\DependencyInjection\ContainerBuilder;
22
use Symfony\Component\DependencyInjection\Definition;
23
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
24
use Symfony\Component\DependencyInjection\Reference;
25
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
26
27
/**
28
 * @author Thomas Rabaix <[email protected]>
29
 */
30
class SonataNewsExtension extends Extension
31
{
32
    /**
33
     * @throws \InvalidArgumentException
34
     */
35
    public function load(array $configs, ContainerBuilder $container)
36
    {
37
        $processor = new Processor();
38
        $configuration = new Configuration();
39
        $config = $processor->processConfiguration($configuration, $configs);
40
        $bundles = $container->getParameter('kernel.bundles');
41
42
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
43
        $loader->load('actions.xml');
44
        $loader->load('twig.xml');
45
        $loader->load('form.xml');
46
        $loader->load('core.xml');
47
        $loader->load('serializer.xml');
48
        $loader->load('command.xml');
49
50
        if (isset($bundles['SonataBlockBundle'])) {
51
            $loader->load('block.xml');
52
        }
53
54
        if (isset($bundles['FOSRestBundle'], $bundles['NelmioApiDocBundle'])) {
55
            $loader->load(sprintf('api_form_%s.xml', $config['db_driver']));
56
            if ('doctrine_orm' === $config['db_driver']) {
57
                $loader->load('api_controllers.xml');
58
            }
59
        }
60
61
        $loader->load(sprintf('%s.xml', $config['db_driver']));
62
63
        if (isset($bundles['SonataAdminBundle'])) {
64
            $loader->load(sprintf('%s_admin.xml', $config['db_driver']));
65
        }
66
67
        if (!isset($config['salt'])) {
68
            throw new \InvalidArgumentException(
69
                'The configuration node "salt" is not set for the SonataNewsBundle (sonata_news)'
70
            );
71
        }
72
73
        if (!isset($config['comment'])) {
74
            throw new \InvalidArgumentException(
75
                'The configuration node "comment" is not set for the SonataNewsBundle (sonata_news)'
76
            );
77
        }
78
79
        $container->getDefinition('sonata.news.hash.generator')
80
            ->replaceArgument(0, $config['salt']);
81
82
        $container->getDefinition('sonata.news.permalink.date')
83
            ->replaceArgument(0, $config['permalink']['date']);
84
85
        $container->setAlias('sonata.news.permalink.generator', $config['permalink_generator']);
86
87
        $container->setDefinition('sonata.news.blog', new Definition('Sonata\NewsBundle\Model\Blog', [
88
            $config['title'],
89
            $config['link'],
90
            $config['description'],
91
            new Reference('sonata.news.permalink.generator'),
92
        ]));
93
94
        $container->getDefinition('sonata.news.hash.generator')
95
            ->replaceArgument(0, $config['salt']);
96
97
        $container->getDefinition('sonata.news.mailer')
98
            ->replaceArgument(5, [
99
                'notification' => $config['comment']['notification'],
100
            ]);
101
102
        if ('doctrine_orm' === $config['db_driver']) {
103
            if (isset($bundles['SonataDoctrineBundle'])) {
104
                $this->registerSonataDoctrineMapping($config);
105
            } else {
106
                // NEXT MAJOR: Throw error when not registering SonataDoctrineBundle
107
                @trigger_error(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
108
                    'Using SonataEasyExtendsBundle is deprecated since sonata-project/dashboard-bundle 0.x. Please register SonataDoctrineBundle as a bundle instead.',
109
                    E_USER_DEPRECATED
110
                );
111
112
                $this->registerDoctrineMapping($config);
113
            }
114
        }
115
116
        $this->configureClass($config, $container);
117
        $this->configureAdmin($config, $container);
118
    }
119
120
    /**
121
     * @param array $config
122
     */
123
    public function configureClass($config, ContainerBuilder $container)
124
    {
125
        // admin configuration
126
        $container->setParameter('sonata.news.admin.post.entity', $config['class']['post']);
127
        $container->setParameter('sonata.news.admin.comment.entity', $config['class']['comment']);
128
129
        // manager configuration
130
        $container->setParameter('sonata.news.manager.post.entity', $config['class']['post']);
131
        $container->setParameter('sonata.news.manager.comment.entity', $config['class']['comment']);
132
    }
133
134
    /**
135
     * @param array $config
136
     */
137
    public function configureAdmin($config, ContainerBuilder $container)
138
    {
139
        $container->setParameter('sonata.news.admin.post.class', $config['admin']['post']['class']);
140
        $container->setParameter('sonata.news.admin.post.controller', $config['admin']['post']['controller']);
141
        $container->setParameter('sonata.news.admin.post.translation_domain', $config['admin']['post']['translation']);
142
143
        $container->setParameter('sonata.news.admin.comment.class', $config['admin']['comment']['class']);
144
        $container->setParameter('sonata.news.admin.comment.controller', $config['admin']['comment']['controller']);
145
        $container->setParameter('sonata.news.admin.comment.translation_domain', $config['admin']['comment']['translation']);
146
    }
147
148
    public function registerDoctrineMapping(array $config)
149
    {
150
        $collector = DeprecatedDoctrineCollector::getInstance();
151
152
        foreach ($config['class'] as $type => $class) {
153
            if (!class_exists($class)) {
154
                /*
155
                 * NEXT_MAJOR:
156
                 * Throw an exception if the class is not defined
157
                 */
158
                @trigger_error(sprintf(
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
159
                    'The "%s" class is not defined or does not exist. This is tolerated now but will be forbidden in 4.0',
160
                    $class
161
                ), E_USER_DEPRECATED);
162
163
                return;
164
            }
165
        }
166
167
        $collector->addAssociation($config['class']['post'], 'mapOneToMany', [
168
            'fieldName' => 'comments',
169
            'targetEntity' => $config['class']['comment'],
170
            'cascade' => [
171
                    0 => 'remove',
172
                    1 => 'persist',
173
                ],
174
            'mappedBy' => 'post',
175
            'orphanRemoval' => true,
176
            'orderBy' => [
177
                    'createdAt' => 'DESC',
178
                ],
179
        ]);
180
181
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
182
            'fieldName' => 'image',
183
            'targetEntity' => $config['class']['media'],
184
            'cascade' => [
185
                    0 => 'remove',
186
                    1 => 'persist',
187
                    2 => 'refresh',
188
                    3 => 'merge',
189
                    4 => 'detach',
190
                ],
191
            'mappedBy' => null,
192
            'inversedBy' => null,
193
            'joinColumns' => [
194
                    [
195
                        'name' => 'image_id',
196
                        'referencedColumnName' => 'id',
197
                    ],
198
                ],
199
            'orphanRemoval' => false,
200
        ]);
201
202
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
203
            'fieldName' => 'author',
204
            'targetEntity' => $config['class']['user'],
205
            'cascade' => [
206
                    1 => 'persist',
207
                ],
208
            'mappedBy' => null,
209
            'inversedBy' => null,
210
            'joinColumns' => [
211
                    [
212
                        'name' => 'author_id',
213
                        'referencedColumnName' => 'id',
214
                    ],
215
                ],
216
            'orphanRemoval' => false,
217
        ]);
218
219
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
220
            'fieldName' => 'collection',
221
            'targetEntity' => $config['class']['collection'],
222
            'cascade' => [
223
                    1 => 'persist',
224
                ],
225
            'mappedBy' => null,
226
            'inversedBy' => null,
227
            'joinColumns' => [
228
                    [
229
                        'name' => 'collection_id',
230
                        'referencedColumnName' => 'id',
231
                    ],
232
                ],
233
            'orphanRemoval' => false,
234
        ]);
235
236
        $collector->addAssociation($config['class']['post'], 'mapManyToMany', [
237
            'fieldName' => 'tags',
238
            'targetEntity' => $config['class']['tag'],
239
            'cascade' => [
240
                    1 => 'persist',
241
                ],
242
            'joinTable' => [
243
                    'name' => $config['table']['post_tag'],
244
                    'joinColumns' => [
245
                            [
246
                                'name' => 'post_id',
247
                                'referencedColumnName' => 'id',
248
                            ],
249
                        ],
250
                    'inverseJoinColumns' => [
251
                            [
252
                                'name' => 'tag_id',
253
                                'referencedColumnName' => 'id',
254
                            ],
255
                        ],
256
                ],
257
        ]);
258
259
        $collector->addAssociation($config['class']['comment'], 'mapManyToOne', [
260
            'fieldName' => 'post',
261
            'targetEntity' => $config['class']['post'],
262
            'cascade' => [
263
            ],
264
            'mappedBy' => null,
265
            'inversedBy' => 'comments',
266
            'joinColumns' => [
267
                    [
268
                        'name' => 'post_id',
269
                        'referencedColumnName' => 'id',
270
                        'nullable' => false,
271
                    ],
272
                ],
273
            'orphanRemoval' => false,
274
        ]);
275
    }
276
277
    private function registerSonataDoctrineMapping(array $config): void
278
    {
279
        foreach ($config['class'] as $type => $class) {
280
            if (!class_exists($class)) {
281
                return;
282
            }
283
        }
284
285
        $collector = DoctrineCollector::getInstance();
286
287
        $commentsOptions = OptionsBuilder::createOneToMany('comments', $config['class']['comment'])
288
            ->cascade(['remove', 'persist'])
289
            ->mappedBy('post')
290
            ->orphanRemoval()
291
            ->addOrder('createdAt', 'DESC');
292
293
        $imageOptions = OptionsBuilder::createManyToOne('image', $config['class']['media'])
294
            ->cascade(['remove', 'persist', 'refresh', 'merge', 'detach'])
295
            ->addJoin([
296
                'name' => 'image_id',
297
                'referencedColumnName' => 'id',
298
            ]);
299
300
        $authorOptions = OptionsBuilder::createManyToOne('author', $config['class']['user'])
301
            ->cascade(['persist'])
302
            ->addJoin([
303
                'name' => 'author_id',
304
                'referencedColumnName' => 'id',
305
            ]);
306
307
        $collectionOptions = OptionsBuilder::createManyToOne('collection', $config['class']['collection'])
308
            ->cascade(['persist'])
309
            ->addJoin([
310
                'name' => 'collection_id',
311
                'referencedColumnName' => 'id',
312
            ]);
313
314
        $tagsOptions = OptionsBuilder::createManyToOne('tags', $config['class']['tag'])
315
            ->cascade(['persist'])
316
            ->addJoinTable($config['table']['post_tag'], [[
317
                'name' => 'post_id',
318
                'referencedColumnName' => 'id',
319
            ]], [[
320
                'name' => 'tag_id',
321
                'referencedColumnName' => 'id',
322
            ]]);
323
324
        $postOptions = OptionsBuilder::createManyToOne('post', $config['class']['post'])
325
            ->inversedBy('comments')
326
            ->addJoin([
327
                'name' => 'post_id',
328
                'referencedColumnName' => 'id',
329
                'nullable' => false,
330
            ]);
331
332
        $collector->addAssociation($config['class']['post'], 'mapOneToMany', $commentsOptions);
333
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', $imageOptions);
334
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', $authorOptions);
335
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', $collectionOptions);
336
        $collector->addAssociation($config['class']['post'], 'mapManyToMany', $tagsOptions);
337
        $collector->addAssociation($config['class']['comment'], 'mapManyToOne', $postOptions);
338
    }
339
}
340