Test Setup Failed
Pull Request — master (#4268)
by Craig
06:26
created

ParameterHelper::writeEncodedParameters()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 11
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
c 0
b 0
f 0
nc 4
nop 1
dl 0
loc 11
rs 10
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 RandomLib\Factory;
17
use Symfony\Component\Filesystem\Exception\IOException;
18
use Symfony\Component\Filesystem\Exception\IOExceptionInterface;
19
use Symfony\Component\HttpFoundation\RequestStack;
20
use Symfony\Component\Yaml\Yaml;
21
use Zikula\Bundle\CoreBundle\CacheClearer;
22
use Zikula\Bundle\CoreBundle\Helper\LocalDotEnvHelper;
23
use Zikula\Bundle\CoreBundle\HttpKernel\ZikulaHttpKernelInterface;
24
use Zikula\Bundle\CoreBundle\HttpKernel\ZikulaKernel;
25
use Zikula\Bundle\CoreBundle\YamlDumper;
26
use Zikula\Component\Wizard\AbortStageException;
27
use Zikula\ExtensionsModule\Api\ApiInterface\VariableApiInterface;
28
use Zikula\ExtensionsModule\Api\VariableApi;
29
30
class ParameterHelper
31
{
32
    /**
33
     * @var string
34
     */
35
    private $configDir;
36
37
    /**
38
     * @var string
39
     */
40
    private $projectDir;
41
42
    /**
43
     * @var VariableApiInterface
44
     */
45
    private $variableApi;
46
47
    /**
48
     * @var CacheClearer
49
     */
50
    private $cacheClearer;
51
52
    /**
53
     * @var RequestStack
54
     */
55
    private $requestStack;
56
57
    /**
58
     * @var ZikulaHttpKernelInterface
59
     */
60
    private $kernel;
61
62
    /**
63
     * ParameterHelper constructor.
64
     */
65
    public function __construct(
66
        string $projectDir,
67
        VariableApiInterface $variableApi,
68
        CacheClearer $cacheClearer,
69
        RequestStack $requestStack,
70
        ZikulaHttpKernelInterface $kernel
71
    ) {
72
        $this->configDir = $projectDir . '/config';
73
        $this->projectDir = $projectDir;
74
        $this->variableApi = $variableApi;
75
        $this->cacheClearer = $cacheClearer;
76
        $this->requestStack = $requestStack;
77
        $this->kernel = $kernel;
78
    }
79
80
    public function getYamlHelper(bool $initCopy = false): YamlDumper
81
    {
82
        $copyFile = $initCopy ? 'services.yaml' : null;
83
84
        return new YamlDumper($this->configDir, 'services_custom.yaml', $copyFile);
85
    }
86
87
    public function initializeParameters(array $paramsToMerge = []): bool
88
    {
89
        $yamlHelper = $this->getYamlHelper(true);
90
        $params = array_merge($yamlHelper->getParameters(), $paramsToMerge);
91
        $yamlHelper->setParameters($params);
92
        $this->cacheClearer->clear('symfony.config');
93
94
        return true;
95
    }
96
97
    /**
98
     * Load and set new default values from the original services.yaml file into the services_custom.yaml file.
99
     */
100
    public function reInitParameters(): bool
101
    {
102
        $originalParameters = Yaml::parse(file_get_contents($this->kernel->getProjectDir() . '/config/services.yaml'));
103
        $yamlHelper = $this->getYamlHelper();
104
        $yamlHelper->setParameters(array_merge($originalParameters['parameters'], $yamlHelper->getParameters()));
105
        $this->cacheClearer->clear('symfony.config');
106
107
        return true;
108
    }
109
110
    /**
111
     * @throws IOExceptionInterface If .env.local could not be dumped
112
     */
113
    public function finalizeParameters(bool $configureRequestContext = true): bool
114
    {
115
        $yamlHelper = $this->getYamlHelper();
116
        $params = $this->decodeParameters($yamlHelper->getParameters());
117
118
        $this->variableApi->getAll(VariableApi::CONFIG); // forces initialization of API
119
        if (!isset($params['upgrading'])) {
120
            $this->variableApi->set(VariableApi::CONFIG, 'locale', $params['locale']);
121
            // Set the System Identifier as a unique string.
122
            if (!$this->variableApi->get(VariableApi::CONFIG, 'system_identifier')) {
123
                $this->variableApi->set(VariableApi::CONFIG, 'system_identifier', str_replace('.', '', uniqid((string) (random_int(1000000000, 9999999999)), true)));
124
            }
125
            // add admin email as site email
126
            $this->variableApi->set(VariableApi::CONFIG, 'adminmail', $params['email']);
127
        }
128
129
        // add remaining parameters and remove unneeded ones
130
        unset($params['username'], $params['password'], $params['email']);
131
        $params['datadir'] = !empty($params['datadir']) ? $params['datadir'] : 'public/uploads';
132
133
        if ($configureRequestContext) {
134
            // Configure the Request Context
135
            // see http://symfony.com/doc/current/cookbook/console/sending_emails.html#configuring-the-request-context-globally
136
            $request = $this->requestStack->getMasterRequest();
137
            $hostFromRequest = isset($request) ? $request->getHost() : null;
138
            $schemeFromRequest = isset($request) ? $request->getScheme() : 'http';
139
            $basePathFromRequest = isset($request) ? $request->getBasePath() : null;
140
            $params['router.request_context.host'] = $params['router.request_context.host'] ?? $hostFromRequest;
141
            $params['router.request_context.scheme'] = $params['router.request_context.scheme'] ?? $schemeFromRequest;
142
            $params['router.request_context.base_url'] = $params['router.request_context.base_url'] ?? $basePathFromRequest;
143
        }
144
        // store the recent version in a config var for later usage. This enables us to determine the version we are upgrading from
145
        $this->variableApi->set(VariableApi::CONFIG, 'Version_Num', ZikulaKernel::VERSION);
146
147
        if (isset($params['upgrading'])) {
148
            $params['zikula_asset_manager.combine'] = false;
149
150
            // unset start page information to avoid missing module errors
151
            $this->variableApi->set(VariableApi::CONFIG, 'startController_en', '');
152
153
            // on upgrade, if a user doesn't add their custom theme back to the /theme dir, it should be reset to a core theme, if available.
154
            $defaultTheme = (string) $this->variableApi->getSystemVar('Default_Theme');
155
            if (!$this->kernel->isBundle($defaultTheme) && $this->kernel->isBundle('ZikulaBootstrapTheme')) {
156
                $this->variableApi->set(VariableApi::CONFIG, 'Default_Theme', 'ZikulaBootstrapTheme');
157
            }
158
        }
159
160
        // write parameters into config/services_custom.yaml
161
        $yamlHelper->setParameters($params);
162
163
        if (isset($params['upgrading'])) {
164
            unset($params['upgrading']);
165
        } else {
166
            $this->writeEnvVars();
167
        }
168
169
        // clear the cache
170
        $this->cacheClearer->clear('symfony.config');
171
172
        return true;
173
    }
174
175
    private function writeEnvVars()
176
    {
177
        $randomLibFactory = new Factory();
178
        $generator = $randomLibFactory->getMediumStrengthGenerator();
179
        $vars = [
180
            'APP_ENV' => 'prod',
181
            'APP_DEBUG' => 1,
182
            'APP_SECRET' => '\'' . $generator->generateString(50) . '\'',
183
            'ZIKULA_INSTALLED' => '\'' . ZikulaKernel::VERSION . '\''
184
        ];
185
        $helper = new LocalDotEnvHelper($this->projectDir);
186
        $helper->writeLocalEnvVars($vars);
187
    }
188
189
    /**
190
     * Write params to file as encoded values.
191
     *
192
     * @throws AbortStageException
193
     */
194
    public function writeEncodedParameters(array $data): void
195
    {
196
        $yamlHelper = $this->getYamlHelper();
197
        foreach ($data as $k => $v) {
198
            $data[$k] = base64_encode($v); // encode so values are 'safe' for json
199
        }
200
        $params = array_merge($yamlHelper->getParameters(), $data);
201
        try {
202
            $yamlHelper->setParameters($params);
203
        } catch (IOException $exception) {
204
            throw new AbortStageException($this->translator->trans('Cannot write parameters to %fileName% file.', ['%fileName%' => 'services_custom.yaml']));
0 ignored issues
show
Bug Best Practice introduced by
The property translator does not exist on Zikula\Bundle\CoreInstal...\Helper\ParameterHelper. Did you maybe forget to declare it?
Loading history...
205
        }
206
    }
207
208
    /**
209
     * Remove base64 encoding for admin parameters.
210
     */
211
    public function decodeParameters(array $params = []): array
212
    {
213
        if (!empty($params['password'])) {
214
            $params['password'] = base64_decode($params['password']);
215
        }
216
        if (!empty($params['username'])) {
217
            $params['username'] = base64_decode($params['username']);
218
        }
219
        if (!empty($params['email'])) {
220
            $params['email'] = base64_decode($params['email']);
221
        }
222
223
        return $params;
224
    }
225
}
226