Completed
Pull Request — 4.0 (#4625)
by Kentaro
04:48
created

ComposerApiService::dropTableToExtra()   B

Complexity

Conditions 7
Paths 6

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 56

Importance

Changes 0
Metric Value
cc 7
nc 6
nop 1
dl 0
loc 21
ccs 0
cts 0
cp 0
crap 56
rs 8.6506
c 0
b 0
f 0
1
<?php
2
3
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) EC-CUBE CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.ec-cube.co.jp/
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 Eccube\Service\Composer;
15
16
use Composer\Console\Application;
17
use Eccube\Common\EccubeConfig;
18
use Eccube\Entity\BaseInfo;
19
use Eccube\Exception\PluginException;
20
use Eccube\Repository\BaseInfoRepository;
21
use Eccube\Service\SchemaService;
22
use Symfony\Component\Console\Input\ArrayInput;
23
use Symfony\Component\Console\Output\BufferedOutput;
24
use Symfony\Component\Console\Output\OutputInterface;
25
26
27
/**
28
 * Class ComposerApiService
29
 */
30
class ComposerApiService implements ComposerServiceInterface
31
{
32
    /**
33
     * @var EccubeConfig
34
     */
35
    protected $eccubeConfig;
36
37
    /**
38
     * @var Application
39
     */
40
    private $consoleApplication;
41
42
    private $workingDir;
43
    /**
44
     * @var BaseInfoRepository
45
     */
46
    private $baseInfoRepository;
47
48
    /** @var SchemaService */
49
    private $schemaService;
50
51
    public function __construct(
52
        EccubeConfig $eccubeConfig,
53
        BaseInfoRepository $baseInfoRepository,
54
        SchemaService $schemaService
55
    )
56
    {
57
        $this->eccubeConfig = $eccubeConfig;
58
        $this->schemaService = $schemaService;
59
        $this->baseInfoRepository = $baseInfoRepository;
60
    }
61
62
    /**
63
     * Run get info command
64
     *
65
     * @param string $pluginName format foo/bar or foo/bar:1.0.0 or "foo/bar 1.0.0"
66
     * @param string|null $version
67
     *
68
     * @return array
69
     *
70
     * @throws PluginException
71
     * @throws \Doctrine\ORM\NoResultException
72
     * @throws \Doctrine\ORM\NonUniqueResultException
73
     */
74
    public function execInfo($pluginName, $version)
75
    {
76
        $output = $this->runCommand([
77
            'command' => 'info',
78
            'package' => $pluginName,
79
            'version' => $version,
80
            '--available' => true,
81
        ]);
82
83
        return OutputParser::parseInfo($output);
84
    }
85
86
    /**
87
     * Run execute command
88
     *
89
     * @param string $packageName format "foo/bar foo/bar:1.0.0"
90
     * @param null|OutputInterface $output
91
     *
92
     * @return string
93
     *
94
     * @throws PluginException
95
     * @throws \Doctrine\ORM\NoResultException
96
     * @throws \Doctrine\ORM\NonUniqueResultException
97
     */
98
    public function execRequire($packageName, $output = null)
99
    {
100
        $packageName = explode(' ', trim($packageName));
101
102
        return $this->runCommand([
103
            'command' => 'require',
104
            'packages' => $packageName,
105
            '--no-interaction' => true,
106
            '--profile' => true,
107
            '--prefer-dist' => true,
108
            '--ignore-platform-reqs' => true,
109
            '--update-with-dependencies' => true,
110
            '--no-scripts' => true,
111
        ], $output);
112
    }
113
114
    /**
115
     * Run remove command
116
     *
117
     * @param string $packageName format "foo/bar foo/bar:1.0.0"
118
     * @param null|OutputInterface $output
119
     *
120
     * @return string
121
     *
122
     * @throws PluginException
123
     * @throws \Doctrine\ORM\NoResultException
124
     * @throws \Doctrine\ORM\NonUniqueResultException
125
     */
126
    public function execRemove($packageName, $output = null)
127
    {
128
        $this->dropTableToExtra($packageName);
129
130
        $packageName = explode(' ', trim($packageName));
131
        return $this->runCommand([
132
            'command' => 'remove',
133
            'packages' => $packageName,
134
            '--ignore-platform-reqs' => true,
135
            '--no-interaction' => true,
136
            '--profile' => true,
137
            '--no-scripts' => true,
138
        ], $output);
139
    }
140
141
    /**
142
     * Run update command
143
     *
144
     * @param boolean $dryRun
145
     * @param null|OutputInterface $output
146
     *
147
     * @throws PluginException
148
     * @throws \Doctrine\ORM\NoResultException
149
     * @throws \Doctrine\ORM\NonUniqueResultException
150
     */
151 View Code Duplication
    public function execUpdate($dryRun, $output = null)
0 ignored issues
show
Duplication introduced by
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...
152
    {
153
        $this->runCommand([
154
            'command' => 'update',
155
            '--no-interaction' => true,
156
            '--profile' => true,
157
            '--no-scripts' => true,
158
            '--dry-run' => (bool) $dryRun,
159
        ], $output);
160
    }
161
162
    /**
163
     * Run install command
164
     *
165
     * @param boolean $dryRun
166
     * @param null|OutputInterface $output
167
     *
168
     * @throws PluginException
169
     * @throws \Doctrine\ORM\NoResultException
170
     * @throws \Doctrine\ORM\NonUniqueResultException
171
     */
172 View Code Duplication
    public function execInstall($dryRun, $output = null)
0 ignored issues
show
Duplication introduced by
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
        $this->runCommand([
175
            'command' => 'install',
176
            '--no-interaction' => true,
177
            '--profile' => true,
178
            '--no-scripts' => true,
179
            '--dry-run' => (bool) $dryRun,
180
        ], $output);
181
    }
182
183
    /**
184
     * Get require
185
     *
186
     * @param string $packageName
187
     * @param string|null $version
188
     * @param string $callback
189
     * @param null $typeFilter
190
     * @param int $level
191
     *
192
     * @throws PluginException
193
     * @throws \Doctrine\ORM\NoResultException
194
     * @throws \Doctrine\ORM\NonUniqueResultException
195
     */
196
    public function foreachRequires($packageName, $version, $callback, $typeFilter = null, $level = 0)
197
    {
198
        if (strpos($packageName, '/') === false) {
199
            return;
200
        }
201
        $info = $this->execInfo($packageName, $version);
202
        if (isset($info['requires'])) {
203
            foreach ($info['requires'] as $name => $version) {
0 ignored issues
show
Bug introduced by
The expression $info['requires'] of type array|null is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
204
                if (isset($info['type']) && $info['type'] === $typeFilter) {
205
                    $this->foreachRequires($name, $version, $callback, $typeFilter, $level + 1);
206
                    if (isset($info['descrip.'])) {
207
                        $info['description'] = $info['descrip.'];
208
                    }
209
                    if ($level) {
210
                        $callback($info);
211
                    }
212
                }
213
            }
214
        }
215
    }
216
217
    /**
218
     * Run get config information
219
     *
220
     * @param string $key
221
     * @param null $value
222
     *
223
     * @return array|mixed
224
     *
225
     * @throws PluginException
226
     * @throws \Doctrine\ORM\NoResultException
227
     * @throws \Doctrine\ORM\NonUniqueResultException
228
     */
229
    public function execConfig($key, $value = null)
230
    {
231
        $commands = [
232
            'command' => 'config',
233
            'setting-key' => $key,
234
            'setting-value' => $value,
235
        ];
236
        if ($value) {
237
            $commands['setting-value'] = $value;
238
        }
239
        $output = $this->runCommand($commands, null, false);
240
241
        return OutputParser::parseConfig($output);
242
    }
243
244
    /**
245
     * Get config list
246
     *
247
     * @return array
248
     *
249
     * @throws PluginException
250
     * @throws \Doctrine\ORM\NoResultException
251
     * @throws \Doctrine\ORM\NonUniqueResultException
252
     */
253
    public function getConfig()
254
    {
255
        $output = $this->runCommand([
256
            'command' => 'config',
257
            '--list' => true,
258
        ], null, false);
259
260
        return OutputParser::parseList($output);
261
    }
262
263
    /**
264
     * Set work dir
265
     *
266
     * @param string $workingDir
267
     */
268
    public function setWorkingDir($workingDir)
269
    {
270
        $this->workingDir = $workingDir;
271
    }
272
273
    /**
274
     * Run composer command
275
     *
276
     * @param array $commands
277
     * @param null|OutputInterface $output
278
     * @param bool $init
279
     *
280
     * @return string
281
     *
282
     * @throws PluginException
283
     * @throws \Doctrine\ORM\NoResultException
284
     * @throws \Doctrine\ORM\NonUniqueResultException
285
     * @throws \Exception
286
     */
287
    public function runCommand($commands, $output = null, $init = true)
288
    {
289
        if ($init) {
290
            $this->init();
291
        }
292
        $commands['--working-dir'] = $this->workingDir;
293
        $commands['--no-ansi'] = true;
294
        $input = new ArrayInput($commands);
295
        $useBufferedOutput = $output === null;
296
297
        if ($useBufferedOutput) {
298
            $output = new BufferedOutput();
299
            ob_start(function ($buffer) use ($output) {
300
                $output->write($buffer);
301
302
                return null;
303
            });
304
        }
305
306
        $exitCode = $this->consoleApplication->run($input, $output);
307
308
        if ($useBufferedOutput) {
309
            ob_end_clean();
310
            $log = $output->fetch();
311
            if ($exitCode) {
312
                log_error($log);
313
                throw new PluginException($log);
314
            }
315
            log_info($log, $commands);
316
317
            return $log;
318
        } elseif ($exitCode) {
319
            throw new PluginException();
320
        }
321
322
        return null;
323
    }
324
325
    /**
326
     * Init composer console application
327
     *
328
     * @param BaseInfo|null $BaseInfo
329
     *
330
     * @throws PluginException
331
     * @throws \Doctrine\ORM\NoResultException
332
     * @throws \Doctrine\ORM\NonUniqueResultException
333
     */
334
    private function init($BaseInfo = null)
335
    {
336
        $BaseInfo = $BaseInfo ?: $this->baseInfoRepository->get();
337
338
        set_time_limit(0);
339
340
        $composerMemory = $this->eccubeConfig['eccube_composer_memory_limit'];
341
        ini_set('memory_limit', $composerMemory);
342
343
        // Config for some environment
344
        putenv('COMPOSER_HOME='.$this->eccubeConfig['plugin_realdir'].'/.composer');
345
        $this->initConsole();
346
        $this->workingDir = $this->workingDir ? $this->workingDir : $this->eccubeConfig['kernel.project_dir'];
347
        $url = $this->eccubeConfig['eccube_package_api_url'];
348
        $json = json_encode([
349
            'type' => 'composer',
350
            'url' => $url,
351
            'options' => [
352
                'http' => [
353
                    'header' => ['X-ECCUBE-KEY: '.$BaseInfo->getAuthenticationKey()],
354
                ],
355
            ],
356
        ]);
357
        $this->execConfig('repositories.eccube', [$json]);
358
        if (strpos($url, 'http://') === 0) {
359
            $this->execConfig('secure-http', ['false']);
360
        }
361
        $this->initConsole();
362
    }
363
364
    private function initConsole()
365
    {
366
        $consoleApplication = new Application();
367
        $consoleApplication->resetComposer();
368
        $consoleApplication->setAutoExit(false);
369
        $this->consoleApplication = $consoleApplication;
370
    }
371
372
    /**
373
     * @param BaseInfo $BaseInfo
374
     *
375
     * @throws PluginException
376
     * @throws \Doctrine\ORM\NoResultException
377
     * @throws \Doctrine\ORM\NonUniqueResultException
378
     */
379
    public function configureRepository(BaseInfo $BaseInfo)
380
    {
381
        $this->init($BaseInfo);
382
    }
383
384
    private function dropTableToExtra($packageNames)
385
    {
386
        $projectRoot = $this->eccubeConfig->get('kernel.project_dir');
387
        foreach (explode(' ', trim($packageNames)) as $packageName) {
388
            $pluginCode = basename($packageName);
389
            $composerJsonPath = $projectRoot.'/app/Plugin/'.$pluginCode.'/composer.json';
390
            if (file_exists($composerJsonPath) === false) {
391
                throw new PluginException("${composerJsonPath} not found.");
392
            }
393
            $json = json_decode(file_get_contents($composerJsonPath), true);
394
            if ($json === null) {
395
                throw new PluginException("Invalid json format. [${composerJsonPath}]");
396
            }
397
398
            if (array_key_exists('entity-namespaces', $json['extra']) && is_array($json['extra']['entity-namespaces'])) {
399
                foreach ($json['extra']['entity-namespaces'] as $namespace) {
400
                    $this->schemaService->dropTable($namespace);
401
                }
402
            }
403
        }
404
    }
405
}
406