Completed
Push — master ( b1eb14...1aaaec )
by Grégoire
12s queued 10s
created

SonataNewsExtension::configureStringExtension()   A

Complexity

Conditions 3
Paths 2

Size

Total Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 9
rs 9.9666
c 0
b 0
f 0
cc 3
nc 2
nop 1
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): void
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('The configuration node "salt" is not set for the SonataNewsBundle (sonata_news)');
68
        }
69
70
        if (!isset($config['comment'])) {
71
            throw new \InvalidArgumentException('The configuration node "comment" is not set for the SonataNewsBundle (sonata_news)');
72
        }
73
74
        $container->getDefinition('sonata.news.hash.generator')
75
            ->replaceArgument(0, $config['salt']);
76
77
        $container->getDefinition('sonata.news.permalink.date')
78
            ->replaceArgument(0, $config['permalink']['date']);
79
80
        $container->setAlias('sonata.news.permalink.generator', $config['permalink_generator']);
81
82
        $container->setDefinition('sonata.news.blog', new Definition('Sonata\NewsBundle\Model\Blog', [
83
            $config['title'],
84
            $config['link'],
85
            $config['description'],
86
            new Reference('sonata.news.permalink.generator'),
87
        ]));
88
89
        $container->getDefinition('sonata.news.hash.generator')
90
            ->replaceArgument(0, $config['salt']);
91
92
        $container->getDefinition('sonata.news.mailer')
93
            ->replaceArgument(5, [
94
                'notification' => $config['comment']['notification'],
95
            ]);
96
97
        if ('doctrine_orm' === $config['db_driver']) {
98
            $this->registerDoctrineMapping($config);
99
        }
100
101
        $this->configureClass($config, $container);
102
        $this->configureAdmin($config, $container);
103
        $this->configureStringExtension($container);
104
    }
105
106
    /**
107
     * @param array $config
108
     */
109
    public function configureClass($config, ContainerBuilder $container): void
110
    {
111
        // admin configuration
112
        $container->setParameter('sonata.news.admin.post.entity', $config['class']['post']);
113
        $container->setParameter('sonata.news.admin.comment.entity', $config['class']['comment']);
114
115
        // manager configuration
116
        $container->setParameter('sonata.news.manager.post.entity', $config['class']['post']);
117
        $container->setParameter('sonata.news.manager.comment.entity', $config['class']['comment']);
118
    }
119
120
    /**
121
     * @param array $config
122
     */
123
    public function configureAdmin($config, ContainerBuilder $container): void
124
    {
125
        $container->setParameter('sonata.news.admin.post.class', $config['admin']['post']['class']);
126
        $container->setParameter('sonata.news.admin.post.controller', $config['admin']['post']['controller']);
127
        $container->setParameter('sonata.news.admin.post.translation_domain', $config['admin']['post']['translation']);
128
129
        $container->setParameter('sonata.news.admin.comment.class', $config['admin']['comment']['class']);
130
        $container->setParameter('sonata.news.admin.comment.controller', $config['admin']['comment']['controller']);
131
        $container->setParameter('sonata.news.admin.comment.translation_domain', $config['admin']['comment']['translation']);
132
    }
133
134
    public function registerDoctrineMapping(array $config): void
135
    {
136
        $collector = DoctrineCollector::getInstance();
137
138
        foreach ($config['class'] as $type => $class) {
139
            if (!class_exists($class)) {
140
                /*
141
                 * NEXT_MAJOR:
142
                 * Throw an exception if the class is not defined
143
                 */
144
                @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...
145
                    'The "%s" class is not defined or does not exist. This is tolerated now but will be forbidden in 4.0',
146
                    $class
147
                ), E_USER_DEPRECATED);
148
149
                return;
150
            }
151
        }
152
153
        $collector->addAssociation($config['class']['post'], 'mapOneToMany', [
154
            'fieldName' => 'comments',
155
            'targetEntity' => $config['class']['comment'],
156
            'cascade' => [
157
                    0 => 'remove',
158
                    1 => 'persist',
159
                ],
160
            'mappedBy' => 'post',
161
            'orphanRemoval' => true,
162
            'orderBy' => [
163
                    'createdAt' => 'DESC',
164
                ],
165
        ]);
166
167
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
168
            'fieldName' => 'image',
169
            'targetEntity' => $config['class']['media'],
170
            'cascade' => [
171
                    0 => 'remove',
172
                    1 => 'persist',
173
                    2 => 'refresh',
174
                    3 => 'merge',
175
                    4 => 'detach',
176
                ],
177
            'mappedBy' => null,
178
            'inversedBy' => null,
179
            'joinColumns' => [
180
                    [
181
                        'name' => 'image_id',
182
                        'referencedColumnName' => 'id',
183
                    ],
184
                ],
185
            'orphanRemoval' => false,
186
        ]);
187
188
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
189
            'fieldName' => 'author',
190
            'targetEntity' => $config['class']['user'],
191
            'cascade' => [
192
                    1 => 'persist',
193
                ],
194
            'mappedBy' => null,
195
            'inversedBy' => null,
196
            'joinColumns' => [
197
                    [
198
                        'name' => 'author_id',
199
                        'referencedColumnName' => 'id',
200
                    ],
201
                ],
202
            'orphanRemoval' => false,
203
        ]);
204
205
        $collector->addAssociation($config['class']['post'], 'mapManyToOne', [
206
            'fieldName' => 'collection',
207
            'targetEntity' => $config['class']['collection'],
208
            'cascade' => [
209
                    1 => 'persist',
210
                ],
211
            'mappedBy' => null,
212
            'inversedBy' => null,
213
            'joinColumns' => [
214
                    [
215
                        'name' => 'collection_id',
216
                        'referencedColumnName' => 'id',
217
                    ],
218
                ],
219
            'orphanRemoval' => false,
220
        ]);
221
222
        $collector->addAssociation($config['class']['post'], 'mapManyToMany', [
223
            'fieldName' => 'tags',
224
            'targetEntity' => $config['class']['tag'],
225
            'cascade' => [
226
                    1 => 'persist',
227
                ],
228
            'joinTable' => [
229
                    'name' => $config['table']['post_tag'],
230
                    'joinColumns' => [
231
                            [
232
                                'name' => 'post_id',
233
                                'referencedColumnName' => 'id',
234
                            ],
235
                        ],
236
                    'inverseJoinColumns' => [
237
                            [
238
                                'name' => 'tag_id',
239
                                'referencedColumnName' => 'id',
240
                            ],
241
                        ],
242
                ],
243
        ]);
244
245
        $collector->addAssociation($config['class']['comment'], 'mapManyToOne', [
246
            'fieldName' => 'post',
247
            'targetEntity' => $config['class']['post'],
248
            'cascade' => [
249
            ],
250
            'mappedBy' => null,
251
            'inversedBy' => 'comments',
252
            'joinColumns' => [
253
                    [
254
                        'name' => 'post_id',
255
                        'referencedColumnName' => 'id',
256
                        'nullable' => false,
257
                    ],
258
                ],
259
            'orphanRemoval' => false,
260
        ]);
261
    }
262
263
    private function configureStringExtension(ContainerBuilder $container): void
264
    {
265
        if (!$container->hasDefinition('twig.extension.string') || !is_a($container->getDefinition('twig.extension.string')->getClass(), StringExtension::class)) {
266
            $definition = new Definition(StringExtension::class);
267
            $definition->addTag('twig.extension');
268
269
            $container->setDefinition(StringExtension::class, $definition);
270
        }
271
    }
272
}
273