Completed
Pull Request — experimental/sf (#3376)
by
unknown
136:36 queued 129:56
created

EccubeExtension::getFunctions()   A

Complexity

Conditions 2
Paths 1

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 2.0014

Importance

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