Completed
Push — master ( 078f7b...6ad7bc )
by Kentaro
30:09
created

TaxRuleRepository::getByRule()   F

Complexity

Conditions 28
Paths > 20000

Size

Total Lines 145
Code Lines 86

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 47
CRAP Score 51.086
Metric Value
dl 0
loc 145
ccs 47
cts 68
cp 0.6912
rs 2
cc 28
eloc 86
nc 111025
nop 4
crap 51.086

How to fix   Long Method    Complexity   

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
25
namespace Eccube\Repository;
26
27
use Doctrine\ORM\EntityRepository;
28
use Doctrine\ORM\NoResultException;
29
use Eccube\Common\Constant;
30
31
/**
32
 * TaxRuleRepository
33
 *
34
 * This class was generated by the Doctrine ORM. Add your own custom
35
 * repository methods below.
36
 */
37
class TaxRuleRepository extends EntityRepository
38
{
39
    private $rules = array();
40
41
    protected $app;
42
43 533
    public function setApplication($app)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
44
    {
45 533
        $this->app = $app;
46 533
    }
47
48 1
    public function newTaxRule()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
49
    {
50
        $TaxRule = new \Eccube\Entity\TaxRule();
51 1
        $CalcRule = $this->getEntityManager()
52 1
            ->getRepository('Eccube\Entity\Master\Taxrule')
53
            ->find(1);
54
        $TaxRule->setCalcRule($CalcRule);
55
        $TaxRule->setTaxAdjust(0);
56
        $TaxRule->setDelFlg(0);
57
58 1
        return $TaxRule;
59
    }
60
61
    /**
62
     * 現在有効な税率設定情報を返す
63
     *
64
     * @param  int|null|\Eccube\Entity\Product        $Product      商品
65
     * @param  int|null|\Eccube\Entity\ProductClass   $ProductClass 商品規格
66
     * @param  int|null|\Eccube\Entity\Master\Pref    $Pref         都道府県
67
     * @param  int|null|\Eccube\Entity\Master\Country $Country      国
68
     * @return \Eccube\Entity\TaxRule                 税設定情報
69
     *
70
     * @throws NoResultException
71
     */
72 182
    public function getByRule($Product = null, $ProductClass = null, $Pref = null, $Country = null)
73
    {
74 2
        if (!$this->app) {
75
            throw new \LogicException();
76
        }
77
78
        // Pref Country 設定
79
        if (!$Pref && !$Country && $this->app['security']->getToken() && $this->app['security']->isGranted('ROLE_USER')) {
80
            /* @var $Customer \Eccube\Entity\Customer */
81
            $Customer = $this->app['security']->getToken()->getUser();
82
            $Pref = $Customer->getPref();
83
            $Country = $Customer->getCountry();
84
        }
85
86
        // 商品単位税率設定がOFFの場合
87
        /** @var $BaseInfo \Eccube\Entity\BaseInfo */
88
        $BaseInfo = $this->app['eccube.repository.base_info']->get();
89
        if ($BaseInfo->getOptionProductTaxRule() !== Constant::ENABLED) {
90 2
            $Product = null;
91 2
            $ProductClass = null;
92
        }
93
94
        // Cache Key 設定
95 2
        if ($Product instanceof \Eccube\Entity\Product) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\Product does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
96
            $productId = $Product->getId();
97 2
        } elseif ($Product) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $Product of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
98
            $productId = $Product;
99
        } else {
100 2
            $productId = '0';
101 2
        }
102 2
        if ($ProductClass instanceof \Eccube\Entity\ProductClass) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\ProductClass does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
103
            $productClassId = $ProductClass->getId();
104 2
        } else if ($ProductClass instanceof \Eccube\Entity\ShipmentItem) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\ShipmentItem does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
105
            // XXX https://github.com/EC-CUBE/ec-cube/issues/1029
106
            // 注文処理時、TaxRuleEventSubscriber::prePersistからの呼び出しで、
107
            // $ProductClassにShipmentItemがsetされて呼び出されるのに対応
108
            $productClassId = '';
109 2
        } elseif ($ProductClass) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $ProductClass of type integer|null is loosely compared to true; this is ambiguous if the integer can be zero. You might want to explicitly use !== null instead.

In PHP, under loose comparison (like ==, or !=, or switch conditions), values of different types might be equal.

For integer values, zero is a special case, in particular the following results might be unexpected:

0   == false // true
0   == null  // true
123 == false // false
123 == null  // false

// It is often better to use strict comparison
0 === false // false
0 === null  // false
Loading history...
110
            $productClassId = $ProductClass;
111
        } else {
112 2
            $productClassId = '0';
113 1
        }
114 2
        if ($Pref instanceof \Eccube\Entity\Master\Pref) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\Master\Pref does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
115
            $prefId = $Pref->getId();
116 2
        } elseif ($Pref) {
117
            $prefId = $Pref;
118
        } else {
119 2
            $prefId = '0';
120 1
        }
121 2
        if ($Country instanceof \Eccube\Entity\Master\Country) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\Master\Country does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
122
            $countryId = $Country->getId();
123 2
        } elseif ($Country) {
124
            $countryId = $Country;
125
        } else {
126 2
            $countryId = '0';
127 2
        }
128 2
        $cacheKey = $productId.':'.$productClassId.':'.$prefId.':'.$countryId;
129
130
        // すでに取得している場合はキャッシュから
131 2
        if (isset($this->rules[$cacheKey])) {
132 10
            return $this->rules[$cacheKey];
133
        }
134
135 182
        $parameters = array();
136 182
        $qb = $this->createQueryBuilder('t')
137
            ->where('t.apply_date < CURRENT_TIMESTAMP()');
138
139
        // Pref
140 182
        if ($Pref) {
141
            $qb->andWhere('t.Pref IS NULL OR t.Pref = :Pref');
142 26
            $parameters['Pref'] = $Pref;
143
        } else {
144
            $qb->andWhere('t.Pref IS NULL');
145 26
        }
146
147
        // Country
148 182
        if ($Country) {
149
            $qb->andWhere('t.Country IS NULL OR t.Country = :Country');
150 2
            $parameters['Country'] = $Country;
151
        } else {
152
            $qb->andWhere('t.Country IS NULL');
153 2
        }
154
155
        /*
156
         * Product, ProductClass が persist される前に TaxRuleEventSubscriber によってアクセスされる
157
         * 場合があるため、ID の存在もチェックする.
158
         * https://github.com/EC-CUBE/ec-cube/issues/677
159
         */
160
161
        // Product
162 182
        if ($Product && $productId > 0) {
163
            $qb->andWhere('t.Product IS NULL OR t.Product = :Product');
164 2
            $parameters['Product'] = $Product;
165
        } else {
166
            $qb->andWhere('t.Product IS NULL');
167 2
        }
168
169
        // ProductClass
170 182
        if ($ProductClass && $productClassId > 0) {
171
            $qb->andWhere('t.ProductClass IS NULL OR t.ProductClass = :ProductClass');
172 1
            $parameters['ProductClass'] = $ProductClass;
173
        } else {
174
            $qb->andWhere('t.ProductClass IS NULL');
175 1
        }
176
177
        $TaxRules = $qb
178 182
            ->setParameters($parameters)
179 182
            ->orderBy('t.apply_date', 'DESC') // 実際は usort() でソートする
180 182
            ->getQuery()
181
            ->getResult();
182
183
        // 地域設定を優先するが、システムパラメーターなどに設定を持っていくか
184
        // 後に書いてあるほど優先される
185
        $priorityKeys = explode(',', $this->app['config']['tax_rule_priority']);
0 ignored issues
show
Unused Code introduced by
$priorityKeys is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
186 182
        $priorityKeys = array();
187
        foreach (explode(',', $this->app['config']['tax_rule_priority']) as $key) {
188
            $priorityKeys[] = str_replace('_', '', preg_replace('/_id\z/', '', $key));
189
        }
190
191
        foreach ($TaxRules as $TaxRule) {
192 182
            $rank = 0;
193
            foreach ($priorityKeys as $index => $key) {
194
                $arrayProperties = array_change_key_case($TaxRule->toArray());
195
                if ($arrayProperties[$key]) {
196
197
                    // 配列の数値添字を重みとして利用する
198 4
                    $rank += 1 << ($index + 1);
199
                }
200
            }
201
            $TaxRule->setRank($rank);
202
        }
203
204
        // 適用日降順, rank 降順にソートする
205
        usort($TaxRules, function($a, $b) {
206
            return $a->compareTo($b);
207
        });
208
209 182
        if (!empty($TaxRules)) {
210 182
            $this->rules[$cacheKey] = $TaxRules[0];
211
212 182
            return $TaxRules[0];
213
        } else {
214
            throw new NoResultException();
215
        }
216
    }
217
218
    /**
219
     * getList
220
     *
221
     * @return array|null
222
     */
223 3
    public function getList()
224
    {
225 3
        $qb = $this->createQueryBuilder('t')
226 3
            ->orderBy('t.apply_date', 'DESC')
227
            ->where('t.Product IS NULL AND t.ProductClass IS NULL');
228
        $TaxRules = $qb
229 3
            ->getQuery()
230
            ->getResult();
231
232 3
        return $TaxRules;
233
    }
234
235
    /**
236
     * getById
237
     *
238
     * @param  int   $id
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 3 found
Loading history...
239
     * @return array
240
     */
241 1
    public function getById($id)
242
    {
243
        $criteria = array(
244
            'id' => $id,
245 1
        );
246
247
        return $this->findOneBy($criteria);
248
    }
249
250
    /**
251
     * getByTime
252
     *
253
     * @param  string $applyDate
254
     * @return mixed
255
     */
256
    public function getByTime($applyDate)
257
    {
258
        $criteria = array(
259
            'apply_date' => $applyDate,
260
        );
261
262
        return $this->findOneBy($criteria);
263
    }
264
265
    /**
266
     * 税規約の削除.
267
     *
268
     * @param  int|\Eccube\Entity\TaxRule $TaxRule 税規約
269
     * @return void
270
     * @throws NoResultException
271
     */
272 2
    public function delete($TaxRule)
273
    {
274 2
        if (!$TaxRule instanceof \Eccube\Entity\TaxRule) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\TaxRule does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
275
            $TaxRule = $this->find($TaxRule);
276
        }
277 2
        if (!$TaxRule) {
278
            throw new NoResultException;
0 ignored issues
show
introduced by
Use parentheses when instantiating classes
Loading history...
279
        }
280
        $TaxRule->setDelFlg(1);
281
        $em = $this->getEntityManager();
282
        $em->persist($TaxRule);
283
        $em->flush();
284 2
    }
285
286
    /**
287
     * TaxRule のキャッシュをクリアする.
288
     *
289
     * getByRule() をコールすると、結果をキャッシュし、2回目以降はデータベースへアクセスしない.
290
     * このメソッドをコールすると、キャッシュをクリアし、再度データベースを参照して結果を取得する.
291
     */
292 6
    public function clearCache()
293
    {
294 6
        $this->rules = array();
295 6
    }
296
}
297