Completed
Pull Request — master (#4433)
by Craig
04:45
created

CoreInstallerExtensionHelper::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 20
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 9
nc 1
nop 9
dl 0
loc 20
rs 9.9666
c 0
b 0
f 0

How to fix   Many Parameters   

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
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 Zikula\Bundle\CoreInstallerBundle\Helper;
15
16
use Doctrine\Persistence\ManagerRegistry;
17
use Symfony\Component\Filesystem\Filesystem;
18
use Symfony\Component\HttpFoundation\Session\SessionInterface;
19
use Symfony\Component\Yaml\Yaml;
20
use Symfony\Contracts\Translation\TranslatorInterface;
21
use Zikula\BlocksModule\Entity\BlockEntity;
22
use Zikula\Bundle\CoreBundle\Configurator;
23
use Zikula\Bundle\CoreBundle\DependencyInjection\Configuration;
24
use Zikula\Bundle\CoreBundle\HttpKernel\ZikulaHttpKernelInterface;
25
use Zikula\Bundle\CoreBundle\HttpKernel\ZikulaKernel;
26
use Zikula\Bundle\CoreBundle\YamlDumper;
27
use Zikula\ExtensionsModule\AbstractExtension;
28
use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
29
use Zikula\ExtensionsModule\Api\VariableApi;
30
use Zikula\ExtensionsModule\Collector\InstallerCollector;
31
use Zikula\ExtensionsModule\Constant;
32
use Zikula\ExtensionsModule\Entity\ExtensionEntity;
33
use Zikula\ExtensionsModule\Helper\BundleSyncHelper;
34
use Zikula\ExtensionsModule\Helper\ExtensionHelper;
35
36
class CoreInstallerExtensionHelper
37
{
38
    /**
39
     * @var ZikulaHttpKernelInterface
40
     */
41
    private $kernel;
42
43
    /**
44
     * @var ManagerRegistry
45
     */
46
    private $managerRegistry;
47
48
    /**
49
     * @var TranslatorInterface
50
     */
51
    private $translator;
52
53
    /**
54
     * @var BundleSyncHelper
55
     */
56
    private $bundleSyncHelper;
57
58
    /**
59
     * @var ExtensionHelper
60
     */
61
    private $extensionHelper;
62
63
    /**
64
     * @var InstallerCollector
65
     */
66
    private $installerCollector;
67
68
    /**
69
     * @var VariableApiInterface
70
     */
71
    private $variableApi;
72
73
    /**
74
     * @var SessionInterface
75
     */
76
    private $session;
77
78
    private $adminCategoryHelper;
79
80
    public function __construct(
81
        ZikulaHttpKernelInterface $kernel,
82
        ManagerRegistry $managerRegistry,
83
        TranslatorInterface $translator,
84
        BundleSyncHelper $bundleSyncHelper,
85
        ExtensionHelper $extensionHelper,
86
        InstallerCollector $installerCollector,
87
        VariableApiInterface $variableApi,
88
        SessionInterface $session,
89
        AdminCategoryHelper $adminCategoryHelper
90
    ) {
91
        $this->kernel = $kernel;
92
        $this->managerRegistry = $managerRegistry;
93
        $this->translator = $translator;
94
        $this->bundleSyncHelper = $bundleSyncHelper;
95
        $this->extensionHelper = $extensionHelper;
96
        $this->installerCollector = $installerCollector;
97
        $this->variableApi = $variableApi;
98
        $this->session = $session;
99
        $this->adminCategoryHelper = $adminCategoryHelper;
100
    }
101
102
    public function install(string $extensionName): bool
103
    {
104
        $extensionBundle = $this->kernel->getModule($extensionName);
105
        /** @var AbstractExtension $extensionBundle */
106
        $className = $extensionBundle->getInstallerClass();
107
        $installer = $this->installerCollector->get($className);
108
109
        if ($installer->install()) {
110
            return true;
111
        }
112
113
        return false;
114
    }
115
116
    /**
117
     * Scan the filesystem and sync the extensions table. Set all system extensions to active state.
118
     */
119
    public function reSyncAndActivate(): bool
120
    {
121
        $extensionsInFileSystem = $this->bundleSyncHelper->scanForBundles(true);
122
        $this->bundleSyncHelper->syncExtensions($extensionsInFileSystem);
123
124
        /** @var ExtensionEntity[] $extensions */
125
        $extensions = $this->managerRegistry->getRepository('ZikulaExtensionsModule:ExtensionEntity')
126
            ->findBy(['name' => array_keys(ZikulaKernel::$coreExtension)]);
127
        foreach ($extensions as $extension) {
128
            $extension->setState(Constant::STATE_ACTIVE);
129
        }
130
        $this->managerRegistry->getManager()->flush();
131
132
        return true;
133
    }
134
135
    /**
136
     * Attempt to upgrade ALL the core extensions. Some will need it, some will not.
137
     * Extensions that do not need upgrading return TRUE as a result of the upgrade anyway.
138
     */
139
    public function upgrade(): bool
140
    {
141
        $coreModulesInPriorityUpgradeOrder = [
142
            'ZikulaExtensionsModule',
143
            'ZikulaUsersModule',
144
            'ZikulaZAuthModule',
145
            'ZikulaGroupsModule',
146
            'ZikulaPermissionsModule',
147
            'ZikulaAdminModule',
148
            'ZikulaBlocksModule',
149
            'ZikulaThemeModule',
150
            'ZikulaSettingsModule',
151
            'ZikulaCategoriesModule',
152
            'ZikulaSecurityCenterModule',
153
            'ZikulaRoutesModule',
154
            'ZikulaMailerModule',
155
            'ZikulaSearchModule',
156
            'ZikulaMenuModule',
157
            'ZikulaBootstrapTheme',
158
            'ZikulaAtomTheme',
159
            'ZikulaRssTheme',
160
            'ZikulaPrinterTheme',
161
        ];
162
        $result = true;
163
        foreach ($coreModulesInPriorityUpgradeOrder as $moduleName) {
164
            $extensionEntity = $this->managerRegistry->getRepository(ExtensionEntity::class)->get($moduleName);
165
            if (isset($extensionEntity)) {
166
                $result = $result && $this->extensionHelper->upgrade($extensionEntity);
167
            }
168
        }
169
170
        return $result;
171
    }
172
173
    public function executeCoreMetaUpgrade($currentCoreVersion): bool
174
    {
175
        /**
176
         * NOTE: There are *intentionally* no `break` statements within each case here so that the process continues
177
         * through each case until the end.
178
         */
179
        switch ($currentCoreVersion) {
180
            case '1.4.3':
181
                $this->install('ZikulaMenuModule');
182
                $this->reSyncAndActivate();
183
                $this->adminCategoryHelper->setCategory('ZikulaMenuModule', $this->translator->trans('Content'));
184
                // no break
185
            case '1.4.4':
186
                // nothing
187
            case '1.4.5':
188
                // Menu module was introduced in 1.4.4 but not installed on upgrade
189
                $schemaManager = $this->managerRegistry->getConnection()->getSchemaManager();
190
                if (!$schemaManager->tablesExist(['menu_items'])) {
191
                    $this->install('ZikulaMenuModule');
192
                    $this->reSyncAndActivate();
193
                    $this->adminCategoryHelper->setCategory('ZikulaMenuModule', $this->translator->trans('Content'));
194
                }
195
                // no break
196
            case '1.4.6':
197
                // nothing needed
198
            case '1.4.7':
199
                // nothing needed
200
            case '1.5.0':
201
                // nothing needed
202
            case '1.9.99':
203
                // upgrades required for 2.0.0
204
                /** @var \Doctrine\DBAL\Driver\PDOConnection $connection */
205
                $connection = $this->managerRegistry->getConnection();
206
                foreach (['objectdata_attributes', 'objectdata_log', 'objectdata_meta', 'workflows', 'categories_mapobj'] as $table) {
207
                    $sql = "DROP TABLE IF EXISTS ${table};";
208
                    $connection->executeQuery($sql);
0 ignored issues
show
Bug introduced by
The method executeQuery() does not exist on Doctrine\DBAL\Driver\PDOConnection. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

208
                    $connection->/** @scrutinizer ignore-call */ 
209
                                 executeQuery($sql);

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
209
                }
210
                $connection->executeQuery(
211
                    "DELETE FROM module_vars WHERE modname LIKE 'systemplugin%'"
212
                );
213
214
                $this->variableApi->del(VariableApi::CONFIG, 'metakeywords');
215
                $this->variableApi->del(VariableApi::CONFIG, 'startpage');
216
                $this->variableApi->del(VariableApi::CONFIG, 'startfunc');
217
                $this->variableApi->del(VariableApi::CONFIG, 'starttype');
218
                $projectDir = $this->kernel->getProjectDir();
219
                if (file_exists($projectDir . '/config/services_custom.yaml')) {
220
                    $fs = new Filesystem();
221
                    $yamlHelper = new YamlDumper($projectDir . '/config', 'services_custom.yaml');
0 ignored issues
show
Deprecated Code introduced by
The class Zikula\Bundle\CoreBundle\YamlDumper has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

221
                    $yamlHelper = /** @scrutinizer ignore-deprecated */ new YamlDumper($projectDir . '/config', 'services_custom.yaml');
Loading history...
222
                    if ('userdata' === $yamlHelper->getParameter('datadir')) {
223
                        try {
224
                            if ($fs->exists($projectDir . '/userdata')) {
225
                                $fs->mirror($projectDir . '/userdata', $projectDir . '/public/uploads');
226
                            }
227
                        } catch (\Exception $exception) {
228
                            $this->session->getFlashBag()->add(
229
                                'info',
230
                                'Attempt to copy files from `userdata` to `public/uploads` failed. You must manually copy the contents.'
231
                            );
232
                        }
233
                    }
234
                }
235
                // remove legacy blocks
236
                $blocksToRemove = $this->managerRegistry->getRepository(BlockEntity::class)->findBy(['blocktype' => ['Extmenu', 'Menutree', 'Menu']]);
237
                foreach ($blocksToRemove as $block) {
238
                    $this->managerRegistry->getManager()->remove($block);
239
                }
240
                $this->managerRegistry->getManager()->flush();
241
                // no break
242
            case '2.0.15':
243
                // nothing
244
            case '3.0.0':
245
                // nothing
246
            case '3.0.99':
247
                $this->migrateParamsAndDynamicConfig();
248
            case '3.1.0':
249
                // current version - cannot perform anything yet
250
        }
251
252
        // always do this
253
        $this->reSyncAndActivate();
254
        // set default themes to ZikulaBootstrapTheme
255
        $this->variableApi->set(VariableApi::CONFIG, 'Default_Theme', 'ZikulaBootstrapTheme');
256
        $this->variableApi->set('ZikulaAdminModule', 'admintheme', '');
257
        // unset start page information to avoid missing module errors
258
        $this->variableApi->set(VariableApi::CONFIG, 'startController_en', []);
259
260
        return true;
261
    }
262
263
    /**
264
     * Migrate all custom values formerly in services_custom.yaml and dynamic/generated.yaml
265
     * to real package config definitions.
266
     * Delete the legacy files.
267
     */
268
    private function migrateParamsAndDynamicConfig(): void
269
    {
270
        $fs = new Filesystem();
271
        $projectDir = $this->kernel->getProjectDir();
272
        if (file_exists($path = $projectDir . '/config/services_custom.yaml')) {
273
            $servicesCustom = Yaml::parse(file_get_contents($path));
274
        }
275
        if (file_exists($path = $projectDir . '/config/dynamic/generated.yaml')) {
276
            $dynamicConfig = Yaml::parse(file_get_contents($path));
277
        }
278
        $configurator = new Configurator($projectDir);
279
        $configurator->loadPackages(['core', 'zikula_routes', 'zikula_security_center', 'zikula_settings', 'zikula_theme']);
280
281
        $configurator->set('core', 'datadir', $servicesCustom['parameters']['datadir'] ?? Configuration::DEFAULT_DATADIR);
282
        $configurator->set('core', 'maker_root_namespace', $dynamicConfig['maker']['root_namespace'] ?? null);
283
        $configurator->set('core', 'multisites', $dynamicConfig['parameters']['multisites'] ?? $configurator->get('core', 'multisites'));
284
285
        $configurator->set('zikula_routes', 'jms_i18n_routing_strategy', $dynamicConfig['jms_i18n_routing']['strategy'] ?? 'prefix_except_default');
286
287
        $configurator->set('zikula_security_center', 'x_frame_options', $servicesCustom['security.x_frame_options'] ?? 'SAMEORIGIN');
288
        $session = [
289
            'name' => $dynamicConfig['parameters']['zikula.session.name'] ?? '_zsid',
290
            'handler_id' => $dynamicConfig['parameters']['zikula.session.handler_id'] ?? 'session.handler.native_file',
291
            'storage_id' => $dynamicConfig['parameters']['zikula.session.storage_id'] ?? 'zikula_core.bridge.http_foundation.zikula_session_storage_file',
292
            'save_path' => $dynamicConfig['parameters']['zikula.session.save_path'] ?? '%kernel.cache_dir%/sessions',
293
            'cookie_secure' => 'auto'
294
        ];
295
        $configurator->set('zikula_security_center', 'session', $session);
296
297
        $configurator->set('zikula_settings', 'locale', $servicesCustom['parameters']['locale'] ?? 'en');
298
        $configurator->set('zikula_settings', 'locales', $dynamicConfig['parameters']['localisation.locales'] ?? ['en']);
299
300
        $configurator->set('zikula_theme', 'script_position', $servicesCustom['parameters']['script_position'] ?? 'foot');
301
        $configurator->set('zikula_theme', 'font_awesome_path', $servicesCustom['parameters']['zikula.stylesheet.fontawesome.min.path'] ?? '/font-awesome/css/all.min.css');
302
        $bootstrap = [
303
            'css_path' => $servicesCustom['parameters']['zikula.javascript.bootstrap.min.path'] ?? '/bootstrap/css/bootstrap.min.css',
304
            'js_path' => $servicesCustom['parameters']['zikula.stylesheet.bootstrap.min.path'] ?? '/bootstrap/js/bootstrap.bundle.min.js'
305
        ];
306
        $configurator->set('zikula_theme', 'bootstrap', $bootstrap);
307
        $assetManager = [
308
            'combine' => $servicesCustom['parameters']['zikula_asset_manager.combine'] ?? false,
309
            'lifetime' => $servicesCustom['parameters']['zikula_asset_manager.lifetime'] ?? '1 day',
310
            'compress' => $servicesCustom['parameters']['zikula_asset_manager.compress'] ?? true,
311
            'minify' => $servicesCustom['parameters']['zikula_asset_manager.minify'] ?? true
312
        ];
313
        $configurator->set('zikula_theme', 'asset_manager', $assetManager);
314
315
        $configurator->write(); // writes nothing when value = default
316
317
        try {
318
            $fs->remove([
319
                $projectDir . '/config/dynamic',
320
                $projectDir . '/config/services_custom.yaml'
321
            ]);
322
        } catch (\Exception $exception) {
323
            // silently fail
324
        }
325
    }
326
}
327