Completed
Push — 4.0 ( e4f725...acc402 )
by Kiyotaka
35s
created

EccubeExtension::getExtensionIcon()   B

Complexity

Conditions 5
Paths 10

Size

Total Lines 51

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 8
CRAP Score 7.5412

Importance

Changes 0
Metric Value
cc 5
nc 10
nop 3
dl 0
loc 51
ccs 8
cts 15
cp 0.5333
crap 7.5412
rs 8.7579
c 0
b 0
f 0

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