Completed
Pull Request — master (#4433)
by Craig
05:13
created

migrateParamsAndDynamicConfig()   A

Complexity

Conditions 4
Paths 8

Size

Total Lines 55
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 40
c 0
b 0
f 0
nc 8
nop 0
dl 0
loc 55
rs 9.28

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 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
                // no break
249
            case '3.1.0':
250
                // current version - cannot perform anything yet
251
        }
252
253
        // always do this
254
        $this->reSyncAndActivate();
255
        // set default themes to ZikulaBootstrapTheme
256
        $this->variableApi->set(VariableApi::CONFIG, 'Default_Theme', 'ZikulaBootstrapTheme');
257
        $this->variableApi->set('ZikulaAdminModule', 'admintheme', '');
258
        // unset start page information to avoid missing module errors
259
        $this->variableApi->set(VariableApi::CONFIG, 'startController_en', []);
260
261
        return true;
262
    }
263
264
    /**
265
     * Migrate all custom values formerly in services_custom.yaml and dynamic/generated.yaml
266
     * to real package config definitions.
267
     * Delete the legacy files.
268
     */
269
    private function migrateParamsAndDynamicConfig(): void
270
    {
271
        $fs = new Filesystem();
272
        $projectDir = $this->kernel->getProjectDir();
273
        if (file_exists($path = $projectDir . '/config/services_custom.yaml')) {
274
            $servicesCustom = Yaml::parse(file_get_contents($path));
275
        }
276
        if (file_exists($path = $projectDir . '/config/dynamic/generated.yaml')) {
277
            $dynamicConfig = Yaml::parse(file_get_contents($path));
278
        }
279
        $configurator = new Configurator($projectDir);
280
        $configurator->loadPackages(['core', 'zikula_routes', 'zikula_security_center', 'zikula_settings', 'zikula_theme']);
281
282
        $configurator->set('core', 'datadir', $servicesCustom['parameters']['datadir'] ?? Configuration::DEFAULT_DATADIR);
283
        $configurator->set('core', 'maker_root_namespace', $dynamicConfig['maker']['root_namespace'] ?? null);
284
        $configurator->set('core', 'multisites', $dynamicConfig['parameters']['multisites'] ?? $configurator->get('core', 'multisites'));
285
286
        $configurator->set('zikula_routes', 'jms_i18n_routing_strategy', $dynamicConfig['jms_i18n_routing']['strategy'] ?? 'prefix_except_default');
287
288
        $configurator->set('zikula_security_center', 'x_frame_options', $servicesCustom['security.x_frame_options'] ?? 'SAMEORIGIN');
289
        $session = [
290
            'name' => $dynamicConfig['parameters']['zikula.session.name'] ?? '_zsid',
291
            'handler_id' => $dynamicConfig['parameters']['zikula.session.handler_id'] ?? 'session.handler.native_file',
292
            'storage_id' => $dynamicConfig['parameters']['zikula.session.storage_id'] ?? 'zikula_core.bridge.http_foundation.zikula_session_storage_file',
293
            'save_path' => $dynamicConfig['parameters']['zikula.session.save_path'] ?? '%kernel.cache_dir%/sessions',
294
            'cookie_secure' => 'auto'
295
        ];
296
        $configurator->set('zikula_security_center', 'session', $session);
297
298
        $configurator->set('zikula_settings', 'locale', $servicesCustom['parameters']['locale'] ?? 'en');
299
        $configurator->set('zikula_settings', 'locales', $dynamicConfig['parameters']['localisation.locales'] ?? ['en']);
300
301
        $configurator->set('zikula_theme', 'script_position', $servicesCustom['parameters']['script_position'] ?? 'foot');
302
        $configurator->set('zikula_theme', 'font_awesome_path', $servicesCustom['parameters']['zikula.stylesheet.fontawesome.min.path'] ?? '/font-awesome/css/all.min.css');
303
        $bootstrap = [
304
            'css_path' => $servicesCustom['parameters']['zikula.javascript.bootstrap.min.path'] ?? '/bootstrap/css/bootstrap.min.css',
305
            'js_path' => $servicesCustom['parameters']['zikula.stylesheet.bootstrap.min.path'] ?? '/bootstrap/js/bootstrap.bundle.min.js'
306
        ];
307
        $configurator->set('zikula_theme', 'bootstrap', $bootstrap);
308
        $assetManager = [
309
            'combine' => $servicesCustom['parameters']['zikula_asset_manager.combine'] ?? false,
310
            'lifetime' => $servicesCustom['parameters']['zikula_asset_manager.lifetime'] ?? '1 day',
311
            'compress' => $servicesCustom['parameters']['zikula_asset_manager.compress'] ?? true,
312
            'minify' => $servicesCustom['parameters']['zikula_asset_manager.minify'] ?? true
313
        ];
314
        $configurator->set('zikula_theme', 'asset_manager', $assetManager);
315
316
        $configurator->write(); // writes nothing when value = default
317
318
        try {
319
            $fs->remove([
320
                $projectDir . '/config/dynamic',
321
                $projectDir . '/config/services_custom.yaml'
322
            ]);
323
        } catch (\Exception $exception) {
324
            // silently fail
325
        }
326
    }
327
}
328