Failed Conditions
Pull Request — experimental/3.1 (#2159)
by Kentaro
88:02
created

TemplateController   A

Complexity

Total Complexity 22

Size/Duplication

Total Lines 279
Duplicated Lines 2.87 %

Coupling/Cohesion

Components 0
Dependencies 11

Test Coverage

Coverage 12.08%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 8
loc 279
ccs 18
cts 149
cp 0.1208
rs 10
c 1
b 0
f 0
wmc 22
lcom 0
cbo 11

4 Methods

Rating   Name   Duplication   Size   Complexity  
B index() 8 52 7
A download() 0 62 3
B delete() 0 44 4
C add() 0 100 8

How to fix   Duplicated Code   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

1
<?php
2
/*
3
 * This file is part of EC-CUBE
4
 *
5
 * Copyright(c) 2000-2015 LOCKON CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.lockon.co.jp/
8
 *
9
 * This program is free software; you can redistribute it and/or
10
 * modify it under the terms of the GNU General Public License
11
 * as published by the Free Software Foundation; either version 2
12
 * of the License, or (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program; if not, write to the Free Software
21
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
22
 */
23
24
namespace Eccube\Controller\Admin\Store;
25
26
use Eccube\Application;
27
use Eccube\Controller\AbstractController;
28
use Eccube\Entity\Master\DeviceType;
29
use Eccube\Form\Type\Admin\TemplateType;
30
use Eccube\Util\Str;
31
use Symfony\Component\Filesystem\Filesystem;
32
use Symfony\Component\Finder\Finder;
33
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
34
use Symfony\Component\Form\FormError;
35
use Symfony\Component\HttpFoundation\Request;
36
use Symfony\Component\HttpFoundation\Response;
37
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
38
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
39
use Symfony\Component\Yaml\Yaml;
40
41
class TemplateController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
42
{
43
44
    /**
45
     * テンプレート一覧画面
46
     *
47
     * @param Application $app
48
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
49
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
50 1
    public function index(Application $app, Request $request)
51
    {
52
53 1
        $DeviceType = $app['eccube.repository.master.device_type']
54 1
            ->find(DeviceType::DEVICE_TYPE_PC);
55
56 1
        $Templates = $app['eccube.repository.template']
57 1
            ->findBy(array('DeviceType' => $DeviceType));
58
59 1
        $form = $app->form()
60 1
            ->add('selected', HiddenType::class)
61 1
            ->getForm();
62
63 1
        if ('POST' === $request->getMethod()) {
64
            $form->handleRequest($request);
65
            if ($form->isValid()) {
66
                $Template = $app['eccube.repository.template']
67
                    ->find($form['selected']->getData());
68
69
                // path.(yml|php)の再構築
70
                $file = $app['config']['root_dir'].'/app/config/eccube/path';
71 View Code Duplication
                if (file_exists($file.'.php')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
72
                    $config = require $file.'.php';
73
                } elseif (file_exists($file.'.yml')) {
74
                    $config = Yaml::parse(file_get_contents($file.'.yml'));
75
                }
76
77
                $templateCode = $Template->getCode();
78
                $config['template_code'] = $templateCode;
0 ignored issues
show
Bug introduced by
The variable $config does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
79
                $config['template_realdir'] = $config['root_dir'].'/app/template/'.$templateCode;
80
                $config['template_html_realdir'] = $config['public_path_realdir'].'/template/'.$templateCode;
81
                $config['front_urlpath'] = $config['root_urlpath'].RELATIVE_PUBLIC_DIR_PATH.'/template/'.$templateCode;
82
                $config['block_realdir'] =$config['template_realdir'].'/Block';
83
84 View Code Duplication
                if (file_exists($file.'.php')) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
85
                    file_put_contents($file.'.php', sprintf('<?php return %s', var_export($config, true)).';');
86
                }
87
                if (file_exists($file.'.yml')) {
88
                    file_put_contents($file.'.yml', Yaml::dump($config));
89
                }
90
91
                $app->addSuccess('admin.content.template.save.complete', 'admin');
92
93
                return $app->redirect($app->url('admin_store_template'));
94
            }
95
        }
96
97 1
        return $app->render('Store/template.twig', array(
98 1
            'form' => $form->createView(),
99 1
            'Templates' => $Templates,
100
        ));
101
    }
102
103
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
104
     * テンプレート一覧からのダウンロード
105
     *
106
     * @param Application $app
107
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
108
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
109
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
110
    public function download(Application $app, Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
111
    {
112
        /** @var $Template \Eccube\Entity\Template */
113
        $Template = $app['eccube.repository.template']->find($id);
114
115
        if (!$Template) {
116
            throw new NotFoundHttpException();
117
        }
118
119
        // 該当テンプレートのディレクトリ
120
        $config = $app['config'];
121
        $templateCode = $Template->getCode();
122
        $targetRealDir = $config['root_dir'] . '/app/template/' . $templateCode;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
123
        $targetHtmlRealDir = $config['root_dir'] . '/html/template/' . $templateCode;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
124
125
        // 一時ディレクトリ
126
        $uniqId = sha1(Str::random(32));
127
        $tmpDir = $config['template_temp_realdir'] . '/' . $uniqId;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
128
        $appDir = $tmpDir . '/app';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
129
        $htmlDir = $tmpDir . '/html';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
130
131
        // ファイル名
132
        $tarFile = $config['template_temp_realdir'] . '/' . $uniqId . '.tar';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
133
        $tarGzFile = $tarFile . '.gz';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
134
        $downloadFileName = $Template->getCode() . '.tar.gz';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
135
136
        // 該当テンプレートを一時ディレクトリへコピーする.
137
        $fs = new Filesystem();
138
        $fs->mkdir(array($appDir, $htmlDir));
139
        $fs->mirror($targetRealDir, $appDir);
140
        $fs->mirror($targetHtmlRealDir, $htmlDir);
141
142
        // tar.gzファイルに圧縮する.
143
        $phar = new \PharData($tarFile);
144
        $phar->buildFromDirectory($tmpDir);
145
        // appディレクトリがない場合は, 空ディレクトリを追加
146
        // @see https://github.com/EC-CUBE/ec-cube/issues/742
147
        if (empty($phar['app'])) {
148
            $phar->addEmptyDir('app');
149
        }
150
        $phar->compress(\Phar::GZ);
151
152
        // ダウンロード完了後にファイルを削除する.
153
        // http://stackoverflow.com/questions/15238897/removing-file-after-delivering-response-with-silex-symfony
154
        $app->finish(function (Request $request, Response $response, \Silex\Application $app) use (
0 ignored issues
show
Coding Style introduced by
Multi-line function declarations must define one parameter per line
Loading history...
155
            $tmpDir,
156
            $tarFile,
157
            $tarGzFile
158
        ) {
0 ignored issues
show
Coding Style introduced by
This line of the multi-line function call does not seem to be indented correctly. Expected 12 spaces, but found 8.
Loading history...
159
            $app['monolog']->addDebug('remove temp file: ' . $tmpDir);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
160
            $app['monolog']->addDebug('remove temp file: ' . $tarFile);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
161
            $app['monolog']->addDebug('remove temp file: ' . $tarGzFile);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
162
            $fs = new Filesystem();
163
            $fs->remove($tmpDir);
164
            $fs->remove($tarFile);
165
            $fs->remove($tarGzFile);
166
        });
167
168
        return $app
169
            ->sendFile($tarGzFile)
170
            ->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $downloadFileName);
171
    }
172
173
    public function delete(Application $app, Request $request, $id)
0 ignored issues
show
Unused Code introduced by
The parameter $request is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
introduced by
Missing function doc comment
Loading history...
174
    {
175
        $this->isTokenValid($app);
176
177
        /** @var $Template \Eccube\Entity\Template */
178
        $Template = $app['eccube.repository.template']->find($id);
179
180
        if (!$Template) {
181
            $app->deleteMessage();
182
            return $app->redirect($app->url('admin_store_template'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
183
        }
184
185
        // デフォルトテンプレート
186
        if ($Template->isDefaultTemplate()) {
187
            $app->addError('admin.content.template.delete.default.error', 'admin');
188
189
            return $app->redirect($app->url('admin_store_template'));
190
        }
191
192
        // 設定中のテンプレート
193
        if ($app['config']['template_code'] === $Template->getCode()) {
194
            $app->addError('admin.content.template.delete.current.error', 'admin');
195
196
            return $app->redirect($app->url('admin_store_template'));
197
        }
198
199
        // テンプレートディレクトリの削除
200
        $config = $app['config'];
201
        $templateCode = $Template->getCode();
202
        $targetRealDir = $config['root_dir'] . '/app/template/' . $templateCode;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
203
        $targetHtmlRealDir = $config['root_dir'] . '/html/template/' . $templateCode;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
204
205
        $fs = new Filesystem();
206
        $fs->remove($targetRealDir);
207
        $fs->remove($targetHtmlRealDir);
208
209
        // テーブルからも削除
210
        $app['orm.em']->remove($Template);
211
        $app['orm.em']->flush();
212
213
        $app->addSuccess('admin.content.template.delete.complete', 'admin');
214
215
        return $app->redirect($app->url('admin_store_template'));
216
    }
217
218 1
    public function add(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
219
    {
220
        /** @var $Template \Eccube\Entity\Template */
221 1
        $Template = new \Eccube\Entity\Template();
222
223 1
        $form = $app['form.factory']
224 1
            ->createBuilder(TemplateType::class, $Template)
225 1
            ->getForm();
226
227 1
        if ('POST' === $request->getMethod()) {
228
            $form->handleRequest($request);
229
230
            if ($form->isValid()) {
231
232
                /** @var $Template \Eccube\Entity\Template */
233
                $tem = $app['eccube.repository.template']
234
                    ->findByCode($form['code']->getData());
235
236
                // テンプレートコードの重複チェック.
237
                if ($tem) {
238
                    $form['code']->addError(new FormError('すでに登録されているテンプレートコードです。'));
239
240
                    return false;
241
                }
242
243
                // 該当テンプレートのディレクトリ
244
                $config = $app['config'];
245
                $templateCode = $Template->getCode();
246
                $targetRealDir = $config['root_dir'] . '/app/template/' . $templateCode;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
247
                $targetHtmlRealDir = $config['root_dir'] . '/html/template/' . $templateCode;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
248
249
                // 一時ディレクトリ
250
                $uniqId = sha1(Str::random(32));
251
                $tmpDir = $config['template_temp_realdir'] . '/' . $uniqId;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
252
                $appDir = $tmpDir . '/app';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
253
                $htmlDir = $tmpDir . '/html';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
254
255
                $formFile = $form['file']->getData();
256
                // ファイル名
257
                $archive = $templateCode . '.' . $formFile->getClientOriginalExtension();
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
258
259
                // ファイルを一時ディレクトリへ移動.
260
                $formFile->move($tmpDir, $archive);
261
262
                // 一時ディレクトリへ解凍する.
263
                try {
264
                    if ($formFile->getClientOriginalExtension() == 'zip') {
265
                        $zip = new \ZipArchive();
266
                        $zip->open($tmpDir . '/' . $archive);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
267
                        $zip->extractTo($tmpDir);
268
                        $zip->close();
269
                    } else {
270
                        $phar = new \PharData($tmpDir . '/' . $archive);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
271
                        $phar->extractTo($tmpDir, null, true);
272
                    }
273
                } catch (\Exception $e) {
274
                    $form['file']->addError(new FormError('アップロードに失敗しました。圧縮ファイルを確認してください。'));
275
276
                    return $app->render('Store/template_add.twig', array(
277
                        'form' => $form->createView(),
278
                    ));
279
                }
280
281
                $fs = new Filesystem();
282
283
                // appディレクトリの存在チェック.
284
                if (!file_exists($appDir)) {
285
                    $fs->mkdir($appDir);
286
                }
287
288
                // htmlディレクトリの存在チェック.
289
                if (!file_exists($htmlDir)) {
290
                    $fs->mkdir($htmlDir);
291
                }
292
293
                // 一時ディレクトリから該当テンプレートのディレクトリへコピーする.
294
                $fs->mirror($appDir, $targetRealDir);
295
                $fs->mirror($htmlDir, $targetHtmlRealDir);
296
297
                // 一時ディレクトリを削除.
298
                $fs->remove($tmpDir);
299
300
                $DeviceType = $app['eccube.repository.master.device_type']
301
                    ->find(DeviceType::DEVICE_TYPE_PC);
302
303
                $Template->setDeviceType($DeviceType);
304
305
                $app['orm.em']->persist($Template);
306
                $app['orm.em']->flush();
307
308
                $app->addSuccess('admin.content.template.add.complete', 'admin');
309
310
                return $app->redirect($app->url('admin_store_template'));
311
            }
312
        }
313
314
        return $app->render('Store/template_add.twig', array(
315
            'form' => $form->createView(),
316
        ));
317
    }
318
319
}
320