Completed
Pull Request — experimental/sf (#3412)
by Kentaro
14:51 queued 07:29
created

EccubeExtension   A

Complexity

Total Complexity 38

Size/Duplication

Total Lines 306
Duplicated Lines 6.86 %

Coupling/Cohesion

Components 2
Dependencies 6

Test Coverage

Coverage 76.19%

Importance

Changes 0
Metric Value
dl 21
loc 306
ccs 80
cts 105
cp 0.7619
rs 9.36
c 0
b 0
f 0
wmc 38
lcom 2
cbo 6

15 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A getFunctions() 8 16 2
A getFilters() 0 11 1
A getName() 0 4 1
A getActiveMenus() 0 9 2
A getNoImageProduct() 0 4 2
A getDateFormatFilter() 0 8 2
A getPriceFilter() 0 8 1
A getEllipsis() 0 4 1
A getTimeAgo() 0 4 1
A hasErrors() 0 17 4
A getProduct() 0 14 3
A getPhpFunctions() 13 13 2
B getClassCategoriesAsJson() 0 43 11
A getExtensionIcon() 0 44 4

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
/*
4
 * This file is part of EC-CUBE
5
 *
6
 * Copyright(c) LOCKON CO.,LTD. All Rights Reserved.
7
 *
8
 * http://www.lockon.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\Twig\Extension;
15
16
use Eccube\Common\EccubeConfig;
17
use Eccube\Entity\Product;
18
use Eccube\Util\StringUtil;
19
use Symfony\Component\Form\FormView;
20
use Twig\Extension\AbstractExtension;
21
use Twig\TwigFilter;
22
use Twig\TwigFunction;
23
24
class EccubeExtension extends AbstractExtension
0 ignored issues
show
introduced by
Missing class doc comment
Loading history...
25
{
26
    /**
27
     * @var EccubeConfig
28
     */
29
    protected $eccubeConfig;
30
31 468
    public function __construct(EccubeConfig $eccubeConfig)
32
    {
33 468
        $this->eccubeConfig = $eccubeConfig;
34
    }
35
36
    /**
37
     * Returns a list of functions to add to the existing list.
38
     *
39
     * @return array An array of functions
40
     */
41 241
    public function getFunctions()
42
    {
43
        return [
44 241
            new TwigFunction('has_errors', [$this, 'hasErrors']),
45 241
            new TwigFunction('active_menus', [$this, 'getActiveMenus']),
46 241
            new TwigFunction('class_categories_as_json', [$this, 'getClassCategoriesAsJson']),
47 241 View Code Duplication
            new TwigFunction('php_*', function () {
48 10
                $arg_list = func_get_args();
49 10
                $function = array_shift($arg_list);
50 10
                if (is_callable($function)) {
51 10
                    return call_user_func_array($function, $arg_list);
52
                }
53
                trigger_error('Called to an undefined function : php_'.$function, E_USER_WARNING);
54 241
            }, ['pre_escape' => 'html', 'is_safe' => ['html']]),
55
        ];
56
    }
57
58
    /**
59
     * Returns a list of filters.
60
     *
61
     * @return array
62
     */
63 241
    public function getFilters()
64
    {
65
        return [
66 241
            new TwigFilter('no_image_product', [$this, 'getNoImageProduct']),
67 241
            new TwigFilter('date_format', [$this, 'getDateFormatFilter']),
68 241
            new TwigFilter('price', [$this, 'getPriceFilter']),
69 241
            new TwigFilter('ellipsis', [$this, 'getEllipsis']),
70 241
            new TwigFilter('time_ago', [$this, 'getTimeAgo']),
71 241
            new TwigFilter('file_ext_icon', [$this, 'getExtensionIcon'], ['is_safe' => ['html']]),
72
        ];
73
    }
74
75
    /**
76
     * Name of this extension
77
     *
78
     * @return string
79
     */
80
    public function getName()
81
    {
82
        return 'eccube';
83
    }
84
85
    /**
86
     * Name of this extension
87
     *
88
     * @param array $menus
89
     *
90
     * @return array
91
     */
92 151
    public function getActiveMenus($menus = [])
93
    {
94 151
        $count = count($menus);
95 151
        for ($i = $count; $i <= 2; $i++) {
96 111
            $menus[] = '';
97
        }
98
99 151
        return $menus;
100
    }
101
102
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$image" missing
Loading history...
103
     * return No Image filename
104
     *
105
     * @return string
106
     */
107 63
    public function getNoImageProduct($image)
108
    {
109 63
        return empty($image) ? 'no_image_product.jpg' : $image;
110
    }
111
112
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$date" missing
Loading history...
introduced by
Doc comment for parameter "$value" missing
Loading history...
introduced by
Doc comment for parameter "$format" missing
Loading history...
113
     * Name of this extension
114
     *
115
     * @return string
116
     */
117 1
    public function getDateFormatFilter($date, $value = '', $format = 'Y/m/d')
118
    {
119 1
        if (is_null($date)) {
120 1
            return $value;
121
        } else {
122
            return $date->format($format);
123
        }
124
    }
125
126
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$number" missing
Loading history...
introduced by
Doc comment for parameter "$decimals" missing
Loading history...
introduced by
Doc comment for parameter "$decPoint" missing
Loading history...
introduced by
Doc comment for parameter "$thousandsSep" missing
Loading history...
127
     * Name of this extension
128
     *
129
     * @return string
130
     */
131 140
    public function getPriceFilter($number, $decimals = 0, $decPoint = '.', $thousandsSep = ',')
0 ignored issues
show
Unused Code introduced by
The parameter $decimals 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...
Unused Code introduced by
The parameter $decPoint 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...
Unused Code introduced by
The parameter $thousandsSep 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...
132
    {
133 140
        $locale = $this->eccubeConfig['locale'];
134 140
        $currency = $this->eccubeConfig['currency'];
135 140
        $formatter = new \NumberFormatter($locale, \NumberFormatter::CURRENCY);
136
137 140
        return $formatter->formatCurrency($number, $currency);
138
    }
139
140
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$value" missing
Loading history...
introduced by
Doc comment for parameter "$length" missing
Loading history...
introduced by
Doc comment for parameter "$end" missing
Loading history...
141
     * Name of this extension
142
     *
143
     * @return string
144
     */
145
    public function getEllipsis($value, $length = 100, $end = '...')
146
    {
147
        return StringUtil::ellipsis($value, $length, $end);
148
    }
149
150
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$date" missing
Loading history...
151
     * Name of this extension
152
     *
153
     * @return string
154
     */
155
    public function getTimeAgo($date)
156
    {
157
        return StringUtil::timeAgo($date);
158
    }
159
160
    /**
161
     * FormView にエラーが含まれるかを返す.
162
     *
163
     * @return bool
164
     */
165 13
    public function hasErrors()
166
    {
167 13
        $hasErrors = false;
168
169 13
        $views = func_get_args();
170 13
        foreach ($views as $view) {
171 13
            if (!$view instanceof FormView) {
172
                throw new \InvalidArgumentException();
173
            }
174 13
            if (count($view->vars['errors'])) {
175 1
                $hasErrors = true;
176 13
                break;
177
            }
178
        }
179
180 13
        return $hasErrors;
181
    }
182
183
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$id" missing
Loading history...
184
     * product_idで指定したProductを取得
185
     * Productが取得できない場合、または非公開の場合、商品情報は表示させない。
186
     * デバッグ環境以外ではProductが取得できなくでもエラー画面は表示させず無視される。
187
     *
188
     * @param $id
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
189
     *
190
     * @return Product|null
191
     */
192
    public function getProduct($id)
193
    {
194
        try {
195
            $Product = $this->app['eccube.repository.product']->get($id);
196
197
            if ($Product->getStatus()->getId() == Disp::DISPLAY_SHOW) {
198
                return $Product;
199
            }
200
        } catch (\Exception $e) {
201
            return null;
202
        }
203
204
        return null;
205
    }
206
207
    /**
208
     * Twigでphp関数を使用できるようにする。
209
     *
210
     * @return mixed|null
211
     */
212 View Code Duplication
    public function getPhpFunctions()
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...
213
    {
214
        $arg_list = func_get_args();
215
        $function = array_shift($arg_list);
216
217
        if (is_callable($function)) {
218
            return call_user_func_array($function, $arg_list);
219
        }
220
221
        trigger_error('Called to an undefined function : php_'.$function, E_USER_WARNING);
222
223
        return null;
224
    }
225
226
    /**
227
     * Get the ClassCategories as JSON.
228
     *
229
     * @param Product $Product
230
     *
231
     * @return string
232
     */
233 16
    public function getClassCategoriesAsJson(Product $Product)
234
    {
235 16
        $Product->_calc();
236
        $class_categories = [
237
            '__unselected' => [
238
                '__unselected' => [
239 16
                    'name' => trans('product.text.please_select'),
240 16
                    'product_class_id' => '',
241
                ],
242
            ],
243
        ];
244 16
        foreach ($Product->getProductClasses() as $ProductClass) {
245
            /* @var $ProductClass \Eccube\Entity\ProductClass */
246 16
            $ClassCategory1 = $ProductClass->getClassCategory1();
247 16
            $ClassCategory2 = $ProductClass->getClassCategory2();
248 16
            if ($ClassCategory2 && !$ClassCategory2->isVisible()) {
249
                continue;
250
            }
251 16
            $class_category_id1 = $ClassCategory1 ? (string) $ClassCategory1->getId() : '__unselected2';
252 16
            $class_category_id2 = $ClassCategory2 ? (string) $ClassCategory2->getId() : '';
253 16
            $class_category_name2 = $ClassCategory2 ? $ClassCategory2->getName().($ProductClass->getStockFind() ? '' : trans('product.text.out_of_stock')) : '';
254
255 16
            $class_categories[$class_category_id1]['#'] = [
256 16
                'classcategory_id2' => '',
257 16
                'name' => trans('product.text.please_select'),
258 16
                'product_class_id' => '',
259
            ];
260 16
            $class_categories[$class_category_id1]['#'.$class_category_id2] = [
261 16
                'classcategory_id2' => $class_category_id2,
262 16
                'name' => $class_category_name2,
263 16
                'stock_find' => $ProductClass->getStockFind(),
264 16
                'price01' => $ProductClass->getPrice01() === null ? '' : number_format($ProductClass->getPrice01()),
265 16
                'price02' => number_format($ProductClass->getPrice02()),
266 16
                'price01_inc_tax' => $ProductClass->getPrice01() === null ? '' : number_format($ProductClass->getPrice01IncTax()),
267 16
                'price02_inc_tax' => number_format($ProductClass->getPrice02IncTax()),
268 16
                'product_class_id' => (string) $ProductClass->getId(),
269 16
                'product_code' => $ProductClass->getCode() === null ? '' : $ProductClass->getCode(),
270 16
                'sale_type' => (string) $ProductClass->getSaleType()->getId(),
271
            ];
272
        }
273
274 16
        return json_encode($class_categories);
275
    }
276
277
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$ext" missing
Loading history...
introduced by
Doc comment for parameter "$attr" missing
Loading history...
278
     * Display file extension icon
279
     *
280
     * @param $ext
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
281
     * @param $attr
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
282
     *
283
     * @return string
284
     */
285 3
    public function getExtensionIcon($ext, $attr = [])
286
    {
287
        $classes = [
288 3
            'txt' => 'fa-file-text-o',
289
            'rtf' => 'fa-file-text-o',
290
            'pdf' => 'fa-file-pdf-o',
291
            'doc' => 'fa-file-word-o',
292
            'docx' => 'fa-file-word-o',
293
            'csv' => 'fa-file-excel-o',
294
            'xls' => 'fa-file-excel-o',
295
            'xlsx' => 'fa-file-excel-o',
296
            'ppt' => 'fa-file-powerpoint-o',
297
            'pptx' => 'fa-file-powerpoint-o',
298
            'png' => 'fa-file-image-o',
299
            'jpg' => 'fa-file-image-o',
300
            'jpeg' => 'fa-file-image-o',
301
            'bmp' => 'fa-file-image-o',
302
            'gif' => 'fa-file-image-o',
303
            'zip' => 'fa-file-archive-o',
304
            'tar' => 'fa-file-archive-o',
305
            'gz' => 'fa-file-archive-o',
306
            'rar' => 'fa-file-archive-o',
307
            '7zip' => 'fa-file-archive-o',
308
            'mp3' => 'fa-file-audio-o',
309
            'm4a' => 'fa-file-audio-o',
310
            'wav' => 'fa-file-audio-o',
311
            'mp4' => 'fa-file-video-o',
312
            'wmv' => 'fa-file-video-o',
313
            'mov' => 'fa-file-video-o',
314
            'mkv' => 'fa-file-video-o',
315
        ];
316 3
        $class = isset($classes[$ext]) ? $classes[$ext] : 'fa-file-o';
317 3
        $attr['class'] = isset($attr['class'])
318 3
            ? $attr['class']." fa {$class}"
319
            : "fa {$class}";
320
321 3
        $html = '<i ';
322 3
        foreach ($attr as $name => $value) {
323 3
            $html .= "{$name}=\"$value\" ";
324
        }
325 3
        $html .= '></i>';
326
327 3
        return $html;
328
    }
329
}
330