Completed
Push — master ( 1de9b7...830752 )
by Kristof
38:46 queued 24:09
created

DependencyInjection/KunstmaanAdminExtension.php (9 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
namespace Kunstmaan\AdminBundle\DependencyInjection;
4
5
use FOS\UserBundle\Form\Type\ResettingFormType;
6
use InvalidArgumentException;
7
use Kunstmaan\AdminBundle\Helper\Menu\MenuAdaptorInterface;
8
use Symfony\Component\Config\FileLocator;
9
use Symfony\Component\DependencyInjection\ContainerBuilder;
10
use Symfony\Component\DependencyInjection\Definition;
11
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
12
use Symfony\Component\DependencyInjection\Loader;
13
use Symfony\Component\DependencyInjection\Reference;
14
use Symfony\Component\HttpKernel\DependencyInjection\Extension;
15
16
/**
17
 * This is the class that loads and manages your bundle configuration
18
 *
19
 * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
20
 */
21
class KunstmaanAdminExtension extends Extension implements PrependExtensionInterface
22
{
23
    /**
24
     * Loads a specific configuration.
25
     *
26
     * @param array            $configs   An array of configuration values
27
     * @param ContainerBuilder $container A ContainerBuilder instance
28
     *
29
     * @throws InvalidArgumentException When provided tag is not defined in this extension
30
     */
31
    public function load(array $configs, ContainerBuilder $container)
32
    {
33
        $container->setParameter('version_checker.url', 'https://bundles.kunstmaan.be/version-check');
34
        $container->setParameter('version_checker.timeframe', 60 * 60 * 24);
35
        $container->setParameter('version_checker.enabled', true);
36
37
        $configuration = new Configuration();
38
        $config = $this->processConfiguration($configuration, $configs);
39
40
        if (array_key_exists('dashboard_route', $config)) {
41
            $container->setParameter('kunstmaan_admin.dashboard_route', $config['dashboard_route']);
42
        }
43
        if (array_key_exists('admin_password', $config)) {
44
            $container->setParameter('kunstmaan_admin.admin_password', $config['admin_password']);
45
        }
46
        $container->setParameter('kunstmaan_admin.admin_locales', $config['admin_locales']);
47
        $container->setParameter('kunstmaan_admin.default_admin_locale', $config['default_admin_locale']);
48
49
        $container->setParameter('kunstmaan_admin.session_security.ip_check', $config['session_security']['ip_check']);
50
        $container->setParameter('kunstmaan_admin.session_security.user_agent_check', $config['session_security']['user_agent_check']);
51
52
        $container->setParameter('kunstmaan_admin.admin_prefix', $this->normalizeUrlSlice($config['admin_prefix']));
53
54
        $container->setParameter('kunstmaan_admin.admin_exception_excludes', $config['admin_exception_excludes']);
55
56
        $container->setParameter('kunstmaan_admin.google_signin.enabled', $config['google_signin']['enabled']);
57
        $container->setParameter('kunstmaan_admin.google_signin.client_id', $config['google_signin']['client_id']);
58
        $container->setParameter('kunstmaan_admin.google_signin.client_secret', $config['google_signin']['client_secret']);
59
        $container->setParameter('kunstmaan_admin.google_signin.hosted_domains', $config['google_signin']['hosted_domains']);
60
61
        $container->setParameter('kunstmaan_admin.password_restrictions.min_digits', $config['password_restrictions']['min_digits']);
62
        $container->setParameter('kunstmaan_admin.password_restrictions.min_uppercase', $config['password_restrictions']['min_uppercase']);
63
        $container->setParameter('kunstmaan_admin.password_restrictions.min_special_characters', $config['password_restrictions']['min_special_characters']);
64
        $container->setParameter('kunstmaan_admin.password_restrictions.min_length', $config['password_restrictions']['min_length']);
65
        $container->setParameter('kunstmaan_admin.password_restrictions.max_length', $config['password_restrictions']['max_length']);
66
        $container->setParameter('kunstmaan_admin.enable_toolbar_helper', $config['enable_toolbar_helper']);
67
        $container->setParameter('kunstmaan_admin.toolbar_firewall_names', !empty($config['provider_keys']) ? $config['provider_keys'] : $config['toolbar_firewall_names']);
68
        $container->setParameter('kunstmaan_admin.admin_firewall_name', $config['admin_firewall_name']);
69
70
        $container->registerForAutoconfiguration(MenuAdaptorInterface::class)
71
            ->addTag('kunstmaan_admin.menu.adaptor');
72
73
        $loader = new Loader\YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
74
        $loader->load('services.yml');
75
        $loader->load('commands.yml');
76
77
        if (!empty($config['enable_console_exception_listener']) && $config['enable_console_exception_listener']) {
78
            $loader->load('console_listener.yml');
79
        }
80
81
        if (0 !== count($config['menu_items'])) {
82
            $this->addSimpleMenuAdaptor($container, $config['menu_items']);
83
        }
84
85
        $this->addWebsiteTitleParameter($container, $config);
86
        $this->addMultiLanguageParameter($container, $config);
87
        $this->addRequiredLocalesParameter($container, $config);
88
        $this->addDefaultLocaleParameter($container, $config);
89
    }
90
91
    public function prepend(ContainerBuilder $container)
92
    {
93
        $knpMenuConfig['twig'] = true; // set to false to disable the Twig extension and the TwigRenderer
94
        $knpMenuConfig['templating'] = false; // if true, enables the helper for PHP templates
95
        $knpMenuConfig['default_renderer'] = 'twig'; // The renderer to use, list is also available by default
96
        $container->prependExtensionConfig('knp_menu', $knpMenuConfig);
97
98
        $fosUserConfig['db_driver'] = 'orm'; // other valid values are 'mongodb', 'couchdb'
99
        $fosUserConfig['from_email']['address'] = '[email protected]';
100
        $fosUserConfig['from_email']['sender_name'] = 'KunstmaanCMS';
101
        $fosUserConfig['firewall_name'] = 'main';
102
        $fosUserConfig['user_class'] = 'Kunstmaan\AdminBundle\Entity\User';
103
        $fosUserConfig['group']['group_class'] = 'Kunstmaan\AdminBundle\Entity\Group';
104
        $fosUserConfig['resetting']['token_ttl'] = 86400;
105
        // Use this node only if you don't want the global email address for the resetting email
106
        $fosUserConfig['resetting']['email']['from_email']['address'] = '[email protected]';
107
        $fosUserConfig['resetting']['email']['from_email']['sender_name'] = 'KunstmaanCMS';
108
        $fosUserConfig['resetting']['email']['template'] = 'FOSUserBundle:Resetting:email.txt.twig';
109
        $fosUserConfig['resetting']['form']['type'] = ResettingFormType::class;
110
        $fosUserConfig['resetting']['form']['name'] = 'fos_user_resetting_form';
111
        $fosUserConfig['resetting']['form']['validation_groups'] = ['ResetPassword'];
112
        $container->prependExtensionConfig('fos_user', $fosUserConfig);
113
114
        $monologConfig['handlers']['main']['type'] = 'rotating_file';
115
        $monologConfig['handlers']['main']['path'] = sprintf('%s/%s', $container->getParameter('kernel.logs_dir'), $container->getParameter('kernel.environment'));
116
        $monologConfig['handlers']['main']['level'] = 'debug';
117
        $container->prependExtensionConfig('monolog', $monologConfig);
118
119
        $twigConfig['paths'][] = ['value' => dirname(__DIR__).'/Resources/views', 'namespace' => 'FOSUser'];
0 ignored issues
show
Coding Style Comprehensibility introduced by
$twigConfig was never initialized. Although not strictly required by PHP, it is generally a good practice to add $twigConfig = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
120
        $container->prependExtensionConfig('twig', $twigConfig);
121
122
        $configs = $container->getExtensionConfig($this->getAlias());
123
        $this->processConfiguration(new Configuration(), $configs);
124
    }
125
126
    /**
127
     * {@inheritdoc}
128
     */
129
    public function getNamespace()
130
    {
131
        return 'http://bundles.kunstmaan.be/schema/dic/admin';
132
    }
133
134
    /**
135
     * {@inheritdoc}
136
     */
137
    public function getXsdValidationBasePath()
138
    {
139
        return __DIR__.'/../Resources/config/schema';
140
    }
141
142
    private function addSimpleMenuAdaptor(ContainerBuilder $container, array $menuItems)
143
    {
144
        $definition = new Definition('Kunstmaan\AdminBundle\Helper\Menu\SimpleMenuAdaptor', [
145
            new Reference('security.authorization_checker'),
146
            $menuItems,
147
        ]);
148
        $definition->addTag('kunstmaan_admin.menu.adaptor');
149
150
        $container->setDefinition('kunstmaan_admin.menu.adaptor.simple', $definition);
151
    }
152
153
    /**
154
     * @param string $urlSlice
155
     *
156
     * @return string
157
     */
158
    protected function normalizeUrlSlice($urlSlice)
159
    {
160
        /* Get rid of exotic characters that would break the url */
161
        $urlSlice = filter_var($urlSlice, FILTER_SANITIZE_URL);
162
163
        /* Remove leading and trailing slashes */
164
        $urlSlice = trim($urlSlice, '/');
165
166
        /* Make sure our $urlSlice is literally used in our regex */
167
        $urlSlice = preg_quote($urlSlice);
168
169
        return $urlSlice;
170
    }
171
172 View Code Duplication
    private function addWebsiteTitleParameter(ContainerBuilder $container, array $config)
0 ignored issues
show
This method seems to be duplicated in 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...
173
    {
174
        $websiteTitle = $config['website_title'];
175
        if (null === $config['website_title']) {
176
            @trigger_error('Not providing a value for the "kunstmaan_admin.website_title" config is deprecated since KunstmaanAdminBundle 5.2, this config value will be required in KunstmaanAdminBundle 6.0.', E_USER_DEPRECATED);
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...
177
178
            $websiteTitle = $container->hasParameter('websitetitle') ? $container->getParameter('websitetitle') : '';
179
        }
180
181
        $container->setParameter('kunstmaan_admin.website_title', $websiteTitle);
182
    }
183
184 View Code Duplication
    private function addMultiLanguageParameter(ContainerBuilder $container, array $config)
0 ignored issues
show
This method seems to be duplicated in 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...
185
    {
186
        $multilanguage = $config['multi_language'];
187
        if (null === $multilanguage) {
188
            @trigger_error('Not providing a value for the "kunstmaan_admin.multi_language" config is deprecated since KunstmaanAdminBundle 5.2, this config value will be required in KunstmaanAdminBundle 6.0.', E_USER_DEPRECATED);
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...
189
190
            $multilanguage = $container->hasParameter('multilanguage') ? $container->getParameter('multilanguage') : '';
191
        }
192
193
        $container->setParameter('kunstmaan_admin.multi_language', $multilanguage);
194
    }
195
196 View Code Duplication
    private function addRequiredLocalesParameter(ContainerBuilder $container, array $config)
0 ignored issues
show
This method seems to be duplicated in 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...
197
    {
198
        $requiredLocales = $config['required_locales'];
199
        if (null === $config['required_locales']) {
200
            @trigger_error('Not providing a value for the "kunstmaan_admin.required_locales" config is deprecated since KunstmaanAdminBundle 5.2, this config value will be required in KunstmaanAdminBundle 6.0.', E_USER_DEPRECATED);
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...
201
202
            $requiredLocales = $container->hasParameter('requiredlocales') ? $container->getParameter('requiredlocales') : '';
203
        }
204
205
        $container->setParameter('kunstmaan_admin.required_locales', $requiredLocales);
206
        $container->setParameter('requiredlocales', $requiredLocales); //Keep old parameter for to keep BC with routing config
207
    }
208
209 View Code Duplication
    private function addDefaultLocaleParameter(ContainerBuilder $container, array $config)
0 ignored issues
show
This method seems to be duplicated in 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...
210
    {
211
        $defaultLocale = $config['default_locale'];
212
        if (null === $config['default_locale']) {
213
            @trigger_error('Not providing a value for the "kunstmaan_admin.default_locale" config is deprecated since KunstmaanAdminBundle 5.2, this config value will be required in KunstmaanAdminBundle 6.0.', E_USER_DEPRECATED);
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...
214
215
            $defaultLocale = $container->hasParameter('defaultlocale') ? $container->getParameter('defaultlocale') : '';
216
        }
217
218
        $container->setParameter('kunstmaan_admin.default_locale', $defaultLocale);
219
    }
220
}
221