Completed
Push — 3.x ( b308ff...0d24d7 )
by Grégoire
01:35
created

SonataNewsExtension::load()   C

Complexity

Conditions 9
Paths 60

Size

Total Lines 79

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 79
rs 6.9026
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: Remove next line and throw error when not registering SonataDoctrineBundle
107
                $this->registerDoctrineMapping($config);
108
            }
109
        }
110
111
        $this->configureClass($config, $container);
112
        $this->configureAdmin($config, $container);
113
    }
114
115
    /**
116
     * @param array $config
117
     */
118
    public function configureClass($config, ContainerBuilder $container)
119
    {
120
        // admin configuration
121
        $container->setParameter('sonata.news.admin.post.entity', $config['class']['post']);
122
        $container->setParameter('sonata.news.admin.comment.entity', $config['class']['comment']);
123
124
        // manager configuration
125
        $container->setParameter('sonata.news.manager.post.entity', $config['class']['post']);
126
        $container->setParameter('sonata.news.manager.comment.entity', $config['class']['comment']);
127
    }
128
129
    /**
130
     * @param array $config
131
     */
132
    public function configureAdmin($config, ContainerBuilder $container)
133
    {
134
        $container->setParameter('sonata.news.admin.post.class', $config['admin']['post']['class']);
135
        $container->setParameter('sonata.news.admin.post.controller', $config['admin']['post']['controller']);
136
        $container->setParameter('sonata.news.admin.post.translation_domain', $config['admin']['post']['translation']);
137
138
        $container->setParameter('sonata.news.admin.comment.class', $config['admin']['comment']['class']);
139
        $container->setParameter('sonata.news.admin.comment.controller', $config['admin']['comment']['controller']);
140
        $container->setParameter('sonata.news.admin.comment.translation_domain', $config['admin']['comment']['translation']);
141
    }
142
143
    /**
144
     * NEXT_MAJOR: Remove this method.
145
     */
146
    public function registerDoctrineMapping(array $config)
147
    {
148
        @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...
149
            'Using SonataEasyExtendsBundle is deprecated since sonata-project/news-bundle 3.x. Please register SonataDoctrineBundle as a bundle instead.',
150
            E_USER_DEPRECATED
151
        );
152
153
        $collector = DeprecatedDoctrineCollector::getInstance();
154
155
        foreach ($config['class'] as $type => $class) {
156
            if (!class_exists($class)) {
157
                /*
158
                 * NEXT_MAJOR:
159
                 * Throw an exception if the class is not defined
160
                 */
161
                @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...
162
                    'The "%s" class is not defined or does not exist. This is tolerated now but will be forbidden in 4.0',
163
                    $class
164
                ), E_USER_DEPRECATED);
165
166
                return;
167
            }
168
        }
169
170
        $collector->addAssociation($config['class']['post'], 'mapOneToMany', [
171
            'fieldName' => 'comments',
172
            'targetEntity' => $config['class']['comment'],
173
            'cascade' => [
174
                    0 => 'remove',
175
                    1 => 'persist',
176
                ],
177
            'mappedBy' => 'post',
178
            'orphanRemoval' => true,
179
            'orderBy' => [
180
                    'createdAt' => 'DESC',
181
                ],
182
        ]);
183
184
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
185
            'fieldName' => 'image',
186
            'targetEntity' => $config['class']['media'],
187
            'cascade' => [
188
                    0 => 'remove',
189
                    1 => 'persist',
190
                    2 => 'refresh',
191
                    3 => 'merge',
192
                    4 => 'detach',
193
                ],
194
            'mappedBy' => null,
195
            'inversedBy' => null,
196
            'joinColumns' => [
197
                    [
198
                        'name' => 'image_id',
199
                        'referencedColumnName' => 'id',
200
                    ],
201
                ],
202
            'orphanRemoval' => false,
203
        ]);
204
205
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
206
            'fieldName' => 'author',
207
            'targetEntity' => $config['class']['user'],
208
            'cascade' => [
209
                    1 => 'persist',
210
                ],
211
            'mappedBy' => null,
212
            'inversedBy' => null,
213
            'joinColumns' => [
214
                    [
215
                        'name' => 'author_id',
216
                        'referencedColumnName' => 'id',
217
                    ],
218
                ],
219
            'orphanRemoval' => false,
220
        ]);
221
222
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
223
            'fieldName' => 'collection',
224
            'targetEntity' => $config['class']['collection'],
225
            'cascade' => [
226
                    1 => 'persist',
227
                ],
228
            'mappedBy' => null,
229
            'inversedBy' => null,
230
            'joinColumns' => [
231
                    [
232
                        'name' => 'collection_id',
233
                        'referencedColumnName' => 'id',
234
                    ],
235
                ],
236
            'orphanRemoval' => false,
237
        ]);
238
239
        $collector->addAssociation($config['class']['post'], 'mapManyToMany', [
240
            'fieldName' => 'tags',
241
            'targetEntity' => $config['class']['tag'],
242
            'cascade' => [
243
                    1 => 'persist',
244
                ],
245
            'joinTable' => [
246
                    'name' => $config['table']['post_tag'],
247
                    'joinColumns' => [
248
                            [
249
                                'name' => 'post_id',
250
                                'referencedColumnName' => 'id',
251
                            ],
252
                        ],
253
                    'inverseJoinColumns' => [
254
                            [
255
                                'name' => 'tag_id',
256
                                'referencedColumnName' => 'id',
257
                            ],
258
                        ],
259
                ],
260
        ]);
261
262
        $collector->addAssociation($config['class']['comment'], 'mapManyToOne', [
263
            'fieldName' => 'post',
264
            'targetEntity' => $config['class']['post'],
265
            'cascade' => [
266
            ],
267
            'mappedBy' => null,
268
            'inversedBy' => 'comments',
269
            'joinColumns' => [
270
                    [
271
                        'name' => 'post_id',
272
                        'referencedColumnName' => 'id',
273
                        'nullable' => false,
274
                    ],
275
                ],
276
            'orphanRemoval' => false,
277
        ]);
278
    }
279
280
    private function registerSonataDoctrineMapping(array $config): void
281
    {
282
        foreach ($config['class'] as $type => $class) {
283
            if (!class_exists($class)) {
284
                return;
285
            }
286
        }
287
288
        $collector = DoctrineCollector::getInstance();
289
290
        $collector->addAssociation(
291
            $config['class']['post'],
292
            'mapOneToMany',
293
            OptionsBuilder::createOneToMany('comments', $config['class']['comment'])
294
                ->cascade(['remove', 'persist'])
295
                ->mappedBy('post')
296
                ->orphanRemoval()
297
                ->addOrder('createdAt', 'DESC')
298
        );
299
300
        $collector->addAssociation(
301
            $config['class']['post'],
302
            'mapManyToOne',
303
            OptionsBuilder::createManyToOne('image', $config['class']['media'])
304
                ->cascade(['remove', 'persist', 'refresh', 'merge', 'detach'])
305
                ->addJoin([
306
                    'name' => 'image_id',
307
                    'referencedColumnName' => 'id',
308
                ])
309
        );
310
311
        $collector->addAssociation(
312
            $config['class']['post'],
313
            'mapManyToOne',
314
            OptionsBuilder::createManyToOne('author', $config['class']['user'])
315
                ->cascade(['persist'])
316
                ->addJoin([
317
                    'name' => 'author_id',
318
                    'referencedColumnName' => 'id',
319
                ])
320
        );
321
322
        $collector->addAssociation(
323
            $config['class']['post'],
324
            'mapManyToOne',
325
            OptionsBuilder::createManyToOne('collection', $config['class']['collection'])
326
                ->cascade(['persist'])
327
                ->addJoin([
328
                    'name' => 'collection_id',
329
                    'referencedColumnName' => 'id',
330
                ])
331
        );
332
333
        $collector->addAssociation(
334
            $config['class']['post'],
335
            'mapManyToMany',
336
            OptionsBuilder::createManyToMany('tags', $config['class']['tag'])
337
                ->cascade(['persist'])
338
                ->addJoinTable($config['table']['post_tag'], [[
339
                    'name' => 'post_id',
340
                    'referencedColumnName' => 'id',
341
                ]], [[
342
                    'name' => 'tag_id',
343
                    'referencedColumnName' => 'id',
344
                ]])
345
        );
346
347
        $collector->addAssociation(
348
            $config['class']['comment'],
349
            'mapManyToOne',
350
            OptionsBuilder::createManyToOne('post', $config['class']['post'])
351
                ->inversedBy('comments')
352
                ->addJoin([
353
                    'name' => 'post_id',
354
                    'referencedColumnName' => 'id',
355
                    'nullable' => false,
356
                ])
357
        );
358
    }
359
}
360