Completed
Push — master ( 63b171...e81574 )
by Ryo
132:48 queued 127:16
created

TemplateController::add()   C

Complexity

Conditions 8
Paths 18

Size

Total Lines 100
Code Lines 54

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 46.7792

Importance

Changes 2
Bugs 0 Features 1
Metric Value
cc 8
eloc 54
c 2
b 0
f 1
nc 18
nop 2
dl 0
loc 100
ccs 8
cts 52
cp 0.1538
crap 46.7792
rs 5.2676

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
 * 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\Util\Str;
30
use Symfony\Component\Filesystem\Filesystem;
31
use Symfony\Component\Finder\Finder;
32
use Symfony\Component\Form\FormError;
33
use Symfony\Component\HttpFoundation\Request;
34
use Symfony\Component\HttpFoundation\Response;
35
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
36
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
37
use Symfony\Component\Yaml\Yaml;
38
39
class TemplateController extends AbstractController
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
40
{
41
42
    /**
43
     * テンプレート一覧画面
44
     *
45
     * @param Application $app
46
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
47
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
48 1
    public function index(Application $app, Request $request)
49
    {
50
51 1
        $DeviceType = $app['eccube.repository.master.device_type']
52 1
            ->find(DeviceType::DEVICE_TYPE_PC);
53
54 1
        $Templates = $app['eccube.repository.template']
55 1
            ->findBy(array('DeviceType' => $DeviceType));
56
57 1
        $form = $app->form()
58 1
            ->add('selected', 'hidden')
59 1
            ->getForm();
60
61 1
        if ('POST' === $request->getMethod()) {
62
            $form->handleRequest($request);
63
            if ($form->isValid()) {
64
                $Template = $app['eccube.repository.template']
65
                    ->find($form['selected']->getData());
66
67
                // path.(yml|php)の再構築
68
                $file = $app['config']['root_dir'].'/app/config/eccube/path';
69 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...
70
                    $config = require $file.'.php';
71
                } elseif (file_exists($file.'.yml')) {
72
                    $config = Yaml::parse(file_get_contents($file.'.yml'));
73
                }
74
75
                $templateCode = $Template->getCode();
76
                $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...
77
                $config['template_realdir'] = $config['root_dir'].'/app/template/'.$templateCode;
78
                $config['template_html_realdir'] = $config['public_path_realdir'].'/template/'.$templateCode;
79
                $config['front_urlpath'] = $config['root_urlpath'].RELATIVE_PUBLIC_DIR_PATH.'/template/'.$templateCode;
80
                $config['block_realdir'] =$config['template_realdir'].'/Block';
81
82 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...
83
                    file_put_contents($file.'.php', sprintf('<?php return %s', var_export($config, true)).';');
84
                }
85
                if (file_exists($file.'.yml')) {
86
                    file_put_contents($file.'.yml', Yaml::dump($config));
87
                }
88
89
                $app->addSuccess('admin.content.template.save.complete', 'admin');
90
91
                return $app->redirect($app->url('admin_store_template'));
92
            }
93
        }
94
95 1
        return $app->render('Store/template.twig', array(
96 1
            'form' => $form->createView(),
97 1
            'Templates' => $Templates,
98
        ));
99
    }
100
101
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
102
     * テンプレート一覧からのダウンロード
103
     *
104
     * @param Application $app
105
     * @param Request $request
0 ignored issues
show
introduced by
Expected 5 spaces after parameter type; 1 found
Loading history...
106
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
107
     */
0 ignored issues
show
introduced by
Missing @return tag in function comment
Loading history...
108
    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...
109
    {
110
        /** @var $Template \Eccube\Entity\Template */
111
        $Template = $app['eccube.repository.template']->find($id);
112
113
        if (!$Template) {
114
            throw new NotFoundHttpException();
115
        }
116
117
        // 該当テンプレートのディレクトリ
118
        $config = $app['config'];
119
        $templateCode = $Template->getCode();
120
        $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...
121
        $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...
122
123
        // 一時ディレクトリ
124
        $uniqId = sha1(Str::random(32));
125
        $tmpDir = $config['template_temp_realdir'] . '/' . $uniqId;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
126
        $appDir = $tmpDir . '/app';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
127
        $htmlDir = $tmpDir . '/html';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
128
129
        // ファイル名
130
        $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...
131
        $tarGzFile = $tarFile . '.gz';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
132
        $downloadFileName = $Template->getCode() . '.tar.gz';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
133
134
        // 該当テンプレートを一時ディレクトリへコピーする.
135
        $fs = new Filesystem();
136
        $fs->mkdir(array($appDir, $htmlDir));
137
        $fs->mirror($targetRealDir, $appDir);
138
        $fs->mirror($targetHtmlRealDir, $htmlDir);
139
140
        // tar.gzファイルに圧縮する.
141
        $phar = new \PharData($tarFile);
142
        $phar->buildFromDirectory($tmpDir);
143
        // appディレクトリがない場合は, 空ディレクトリを追加
144
        // @see https://github.com/EC-CUBE/ec-cube/issues/742
145
        if (empty($phar['app'])) {
146
            $phar->addEmptyDir('app');
147
        }
148
        $phar->compress(\Phar::GZ);
149
150
        // ダウンロード完了後にファイルを削除する.
151
        // http://stackoverflow.com/questions/15238897/removing-file-after-delivering-response-with-silex-symfony
152
        $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...
153
            $tmpDir,
154
            $tarFile,
155
            $tarGzFile
156
        ) {
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...
157
            $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...
158
            $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...
159
            $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...
160
            $fs = new Filesystem();
161
            $fs->remove($tmpDir);
162
            $fs->remove($tarFile);
163
            $fs->remove($tarGzFile);
164
        });
165
166
        return $app
167
            ->sendFile($tarGzFile)
168
            ->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT, $downloadFileName);
169
    }
170
171
    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...
172
    {
173
        $this->isTokenValid($app);
174
175
        /** @var $Template \Eccube\Entity\Template */
176
        $Template = $app['eccube.repository.template']->find($id);
177
178
        if (!$Template) {
179
            $app->deleteMessage();
180
            return $app->redirect($app->url('admin_store_template'));
0 ignored issues
show
introduced by
Missing blank line before return statement
Loading history...
181
        }
182
183
        // デフォルトテンプレート
184
        if ($Template->isDefaultTemplate()) {
185
            $app->addError('admin.content.template.delete.default.error', 'admin');
186
187
            return $app->redirect($app->url('admin_store_template'));
188
        }
189
190
        // 設定中のテンプレート
191
        if ($app['config']['template_code'] === $Template->getCode()) {
192
            $app->addError('admin.content.template.delete.current.error', 'admin');
193
194
            return $app->redirect($app->url('admin_store_template'));
195
        }
196
197
        // テンプレートディレクトリの削除
198
        $config = $app['config'];
199
        $templateCode = $Template->getCode();
200
        $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...
201
        $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...
202
203
        $fs = new Filesystem();
204
        $fs->remove($targetRealDir);
205
        $fs->remove($targetHtmlRealDir);
206
207
        // テーブルからも削除
208
        $app['orm.em']->remove($Template);
209
        $app['orm.em']->flush();
210
211
        $app->addSuccess('admin.content.template.delete.complete', 'admin');
212
213
        return $app->redirect($app->url('admin_store_template'));
214
    }
215
216 1
    public function add(Application $app, Request $request)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
217
    {
218
        /** @var $Template \Eccube\Entity\Template */
219 1
        $Template = new \Eccube\Entity\Template();
220
221 1
        $form = $app['form.factory']
222 1
            ->createBuilder('admin_template', $Template)
223 1
            ->getForm();
224
225 1
        if ('POST' === $request->getMethod()) {
226
            $form->handleRequest($request);
227
228
            if ($form->isValid()) {
229
230
                /** @var $Template \Eccube\Entity\Template */
231
                $tem = $app['eccube.repository.template']
232
                    ->findByCode($form['code']->getData());
233
234
                // テンプレートコードの重複チェック.
235
                if ($tem) {
236
                    $form['code']->addError(new FormError('すでに登録されているテンプレートコードです。'));
237
238
                    return false;
239
                }
240
241
                // 該当テンプレートのディレクトリ
242
                $config = $app['config'];
243
                $templateCode = $Template->getCode();
244
                $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...
245
                $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...
246
247
                // 一時ディレクトリ
248
                $uniqId = sha1(Str::random(32));
249
                $tmpDir = $config['template_temp_realdir'] . '/' . $uniqId;
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
250
                $appDir = $tmpDir . '/app';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
251
                $htmlDir = $tmpDir . '/html';
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
252
253
                $formFile = $form['file']->getData();
254
                // ファイル名
255
                $archive = $templateCode . '.' . $formFile->getClientOriginalExtension();
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
256
257
                // ファイルを一時ディレクトリへ移動.
258
                $formFile->move($tmpDir, $archive);
259
260
                // 一時ディレクトリへ解凍する.
261
                try {
262
                    if ($formFile->getClientOriginalExtension() == 'zip') {
263
                        $zip = new \ZipArchive();
264
                        $zip->open($tmpDir . '/' . $archive);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
265
                        $zip->extractTo($tmpDir);
266
                        $zip->close();
267
                    } else {
268
                        $phar = new \PharData($tmpDir . '/' . $archive);
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
269
                        $phar->extractTo($tmpDir, null, true);
270
                    }
271
                } catch (\Exception $e) {
272
                    $form['file']->addError(new FormError('アップロードに失敗しました。圧縮ファイルを確認してください。'));
273
274
                    return $app->render('Store/template_add.twig', array(
275
                        'form' => $form->createView(),
276
                    ));
277
                }
278
279
                $fs = new Filesystem();
280
281
                // appディレクトリの存在チェック.
282
                if (!file_exists($appDir)) {
283
                    $fs->mkdir($appDir);
284
                }
285
286
                // htmlディレクトリの存在チェック.
287
                if (!file_exists($htmlDir)) {
288
                    $fs->mkdir($htmlDir);
289
                }
290
291
                // 一時ディレクトリから該当テンプレートのディレクトリへコピーする.
292
                $fs->mirror($appDir, $targetRealDir);
293
                $fs->mirror($htmlDir, $targetHtmlRealDir);
294
295
                // 一時ディレクトリを削除.
296
                $fs->remove($tmpDir);
297
298
                $DeviceType = $app['eccube.repository.master.device_type']
299
                    ->find(DeviceType::DEVICE_TYPE_PC);
300
301
                $Template->setDeviceType($DeviceType);
302
303
                $app['orm.em']->persist($Template);
304
                $app['orm.em']->flush();
305
306
                $app->addSuccess('admin.content.template.add.complete', 'admin');
307
308
                return $app->redirect($app->url('admin_store_template'));
309
            }
310
        }
311
312 1
        return $app->render('Store/template_add.twig', array(
313 1
            'form' => $form->createView(),
314
        ));
315
    }
316
317
}
318