Completed
Pull Request — 3.x (#607)
by Grégoire
08:46
created

SonataNewsExtension   A

Complexity

Total Complexity 16

Size/Duplication

Total Lines 248
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 9

Importance

Changes 0
Metric Value
wmc 16
lcom 1
cbo 9
dl 0
loc 248
rs 10
c 0
b 0
f 0

5 Methods

Rating   Name   Duplication   Size   Complexity  
B load() 0 75 8
B registerDoctrineMapping() 0 128 3
A configureClass() 0 10 1
A configureAdmin() 0 10 1
A configureStringExtension() 0 9 3
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\EasyExtendsBundle\Mapper\DoctrineCollector;
17
use Symfony\Component\Config\Definition\Processor;
18
use Symfony\Component\Config\FileLocator;
19
use Symfony\Component\DependencyInjection\ContainerBuilder;
20
use Symfony\Component\DependencyInjection\Definition;
21
use Symfony\Component\DependencyInjection\Loader\XmlFileLoader;
22
use Symfony\Component\DependencyInjection\Reference;
23
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
24
use Twig\Extra\String\StringExtension;
25
26
/**
27
 * @author Thomas Rabaix <[email protected]>
28
 */
29
class SonataNewsExtension extends Extension
30
{
31
    /**
32
     * @throws \InvalidArgumentException
33
     */
34
    public function load(array $configs, ContainerBuilder $container)
35
    {
36
        $processor = new Processor();
37
        $configuration = new Configuration();
38
        $config = $processor->processConfiguration($configuration, $configs);
39
        $bundles = $container->getParameter('kernel.bundles');
40
41
        $loader = new XmlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
42
        $loader->load('actions.xml');
43
        $loader->load('twig.xml');
44
        $loader->load('form.xml');
45
        $loader->load('core.xml');
46
        $loader->load('serializer.xml');
47
        $loader->load('command.xml');
48
49
        if (isset($bundles['SonataBlockBundle'])) {
50
            $loader->load('block.xml');
51
        }
52
53
        if (isset($bundles['FOSRestBundle'], $bundles['NelmioApiDocBundle'])) {
54
            $loader->load(sprintf('api_form_%s.xml', $config['db_driver']));
55
            if ('doctrine_orm' === $config['db_driver']) {
56
                $loader->load('api_controllers.xml');
57
            }
58
        }
59
60
        $loader->load(sprintf('%s.xml', $config['db_driver']));
61
62
        if (isset($bundles['SonataAdminBundle'])) {
63
            $loader->load(sprintf('%s_admin.xml', $config['db_driver']));
64
        }
65
66
        if (!isset($config['salt'])) {
67
            throw new \InvalidArgumentException(
68
                'The configuration node "salt" is not set for the SonataNewsBundle (sonata_news)'
69
            );
70
        }
71
72
        if (!isset($config['comment'])) {
73
            throw new \InvalidArgumentException(
74
                'The configuration node "comment" is not set for the SonataNewsBundle (sonata_news)'
75
            );
76
        }
77
78
        $container->getDefinition('sonata.news.hash.generator')
79
            ->replaceArgument(0, $config['salt']);
80
81
        $container->getDefinition('sonata.news.permalink.date')
82
            ->replaceArgument(0, $config['permalink']['date']);
83
84
        $container->setAlias('sonata.news.permalink.generator', $config['permalink_generator']);
85
86
        $container->setDefinition('sonata.news.blog', new Definition('Sonata\NewsBundle\Model\Blog', [
87
            $config['title'],
88
            $config['link'],
89
            $config['description'],
90
            new Reference('sonata.news.permalink.generator'),
91
        ]));
92
93
        $container->getDefinition('sonata.news.hash.generator')
94
            ->replaceArgument(0, $config['salt']);
95
96
        $container->getDefinition('sonata.news.mailer')
97
            ->replaceArgument(5, [
98
                'notification' => $config['comment']['notification'],
99
            ]);
100
101
        if ('doctrine_orm' === $config['db_driver']) {
102
            $this->registerDoctrineMapping($config);
103
        }
104
105
        $this->configureClass($config, $container);
106
        $this->configureAdmin($config, $container);
107
        $this->configureStringExtension($container);
108
    }
109
110
    /**
111
     * @param array $config
112
     */
113
    public function configureClass($config, ContainerBuilder $container)
114
    {
115
        // admin configuration
116
        $container->setParameter('sonata.news.admin.post.entity', $config['class']['post']);
117
        $container->setParameter('sonata.news.admin.comment.entity', $config['class']['comment']);
118
119
        // manager configuration
120
        $container->setParameter('sonata.news.manager.post.entity', $config['class']['post']);
121
        $container->setParameter('sonata.news.manager.comment.entity', $config['class']['comment']);
122
    }
123
124
    /**
125
     * @param array $config
126
     */
127
    public function configureAdmin($config, ContainerBuilder $container)
128
    {
129
        $container->setParameter('sonata.news.admin.post.class', $config['admin']['post']['class']);
130
        $container->setParameter('sonata.news.admin.post.controller', $config['admin']['post']['controller']);
131
        $container->setParameter('sonata.news.admin.post.translation_domain', $config['admin']['post']['translation']);
132
133
        $container->setParameter('sonata.news.admin.comment.class', $config['admin']['comment']['class']);
134
        $container->setParameter('sonata.news.admin.comment.controller', $config['admin']['comment']['controller']);
135
        $container->setParameter('sonata.news.admin.comment.translation_domain', $config['admin']['comment']['translation']);
136
    }
137
138
    public function registerDoctrineMapping(array $config)
139
    {
140
        $collector = DoctrineCollector::getInstance();
141
142
        foreach ($config['class'] as $type => $class) {
143
            if (!class_exists($class)) {
144
                /*
145
                 * NEXT_MAJOR:
146
                 * Throw an exception if the class is not defined
147
                 */
148
                @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...
149
                    'The "%s" class is not defined or does not exist. This is tolerated now but will be forbidden in 4.0',
150
                    $class
151
                ), E_USER_DEPRECATED);
152
153
                return;
154
            }
155
        }
156
157
        $collector->addAssociation($config['class']['post'], 'mapOneToMany', [
158
            'fieldName' => 'comments',
159
            'targetEntity' => $config['class']['comment'],
160
            'cascade' => [
161
                    0 => 'remove',
162
                    1 => 'persist',
163
                ],
164
            'mappedBy' => 'post',
165
            'orphanRemoval' => true,
166
            'orderBy' => [
167
                    'createdAt' => 'DESC',
168
                ],
169
        ]);
170
171
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
172
            'fieldName' => 'image',
173
            'targetEntity' => $config['class']['media'],
174
            'cascade' => [
175
                    0 => 'remove',
176
                    1 => 'persist',
177
                    2 => 'refresh',
178
                    3 => 'merge',
179
                    4 => 'detach',
180
                ],
181
            'mappedBy' => null,
182
            'inversedBy' => null,
183
            'joinColumns' => [
184
                    [
185
                        'name' => 'image_id',
186
                        'referencedColumnName' => 'id',
187
                    ],
188
                ],
189
            'orphanRemoval' => false,
190
        ]);
191
192
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
193
            'fieldName' => 'author',
194
            'targetEntity' => $config['class']['user'],
195
            'cascade' => [
196
                    1 => 'persist',
197
                ],
198
            'mappedBy' => null,
199
            'inversedBy' => null,
200
            'joinColumns' => [
201
                    [
202
                        'name' => 'author_id',
203
                        'referencedColumnName' => 'id',
204
                    ],
205
                ],
206
            'orphanRemoval' => false,
207
        ]);
208
209
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
210
            'fieldName' => 'collection',
211
            'targetEntity' => $config['class']['collection'],
212
            'cascade' => [
213
                    1 => 'persist',
214
                ],
215
            'mappedBy' => null,
216
            'inversedBy' => null,
217
            'joinColumns' => [
218
                    [
219
                        'name' => 'collection_id',
220
                        'referencedColumnName' => 'id',
221
                    ],
222
                ],
223
            'orphanRemoval' => false,
224
        ]);
225
226
        $collector->addAssociation($config['class']['post'], 'mapManyToMany', [
227
            'fieldName' => 'tags',
228
            'targetEntity' => $config['class']['tag'],
229
            'cascade' => [
230
                    1 => 'persist',
231
                ],
232
            'joinTable' => [
233
                    'name' => $config['table']['post_tag'],
234
                    'joinColumns' => [
235
                            [
236
                                'name' => 'post_id',
237
                                'referencedColumnName' => 'id',
238
                            ],
239
                        ],
240
                    'inverseJoinColumns' => [
241
                            [
242
                                'name' => 'tag_id',
243
                                'referencedColumnName' => 'id',
244
                            ],
245
                        ],
246
                ],
247
        ]);
248
249
        $collector->addAssociation($config['class']['comment'], 'mapManyToOne', [
250
            'fieldName' => 'post',
251
            'targetEntity' => $config['class']['post'],
252
            'cascade' => [
253
            ],
254
            'mappedBy' => null,
255
            'inversedBy' => 'comments',
256
            'joinColumns' => [
257
                    [
258
                        'name' => 'post_id',
259
                        'referencedColumnName' => 'id',
260
                        'nullable' => false,
261
                    ],
262
                ],
263
            'orphanRemoval' => false,
264
        ]);
265
    }
266
267
    private function configureStringExtension(ContainerBuilder $container): void
268
    {
269
        if (!$container->hasDefinition('twig.extension.string') || !is_a($container->getDefinition('twig.extension.string')->getClass(), StringExtension::class)) {
270
            $definition = new Definition(StringExtension::class);
271
            $definition->addTag('twig.extension');
272
273
            $container->setDefinition(StringExtension::class, $definition);
274
        }
275
    }
276
}
277