Failed Conditions
Pull Request — experimental/3.1 (#2304)
by Kiyotaka
39:27
created

TaxRuleRepository::delete()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 4
CRAP Score 3.072

Importance

Changes 0
Metric Value
cc 3
eloc 9
nc 4
nop 1
dl 0
loc 13
ccs 4
cts 5
cp 0.8
crap 3.072
rs 9.4285
c 0
b 0
f 0
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\NoResultException;
28
use Eccube\Common\Constant;
29
30
/**
31
 * TaxRuleRepository
32
 *
33
 * This class was generated by the Doctrine ORM. Add your own custom
34
 * repository methods below.
35
 */
36
class TaxRuleRepository extends AbstractRepository
37
{
38
    private $rules = array();
39
40
    public function newTaxRule()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
41
    {
42
        $TaxRule = new \Eccube\Entity\TaxRule();
43 1179
        $CalcRule = $this->getEntityManager()
44
            ->getRepository('Eccube\Entity\Master\Taxrule')
45 1179
            ->find(1);
46
        $TaxRule->setCalcRule($CalcRule);
47
        $TaxRule->setTaxAdjust(0);
48 11
        $TaxRule->setDelFlg(0);
49
50 11
        return $TaxRule;
51 11
    }
52 11
53 11
    /**
54 11
     * 現在有効な税率設定情報を返す
55 11
     *
56 11
     * @param  int|null|\Eccube\Entity\Product        $Product      商品
57
     * @param  int|null|\Eccube\Entity\ProductClass   $ProductClass 商品規格
58 11
     * @param  int|null|\Eccube\Entity\Master\Pref    $Pref         都道府県
59
     * @param  int|null|\Eccube\Entity\Master\Country $Country      国
60
     * @return \Eccube\Entity\TaxRule                 税設定情報
61
     *
62
     * @throws NoResultException
63
     */
64
    public function getByRule($Product = null, $ProductClass = null, $Pref = null, $Country = null)
65
    {
66
        if (!$this->app) {
67
            throw new \LogicException();
68
        }
69
70
        // Pref Country 設定
71
        if (!$Pref && !$Country && $this->app['security.token_storage']->getToken() && $this->app['security.authorization_checker']->isGranted('ROLE_USER')) {
72 342
            /* @var $Customer \Eccube\Entity\Customer */
73
            $Customer = $this->app->user();
74 342
            $Pref = $Customer->getPref();
75
            $Country = $Customer->getCountry();
76
        }
77
78
        // 商品単位税率設定がOFFの場合
79 342
        /** @var $BaseInfo \Eccube\Entity\BaseInfo */
80
        $BaseInfo = $this->app['eccube.repository.base_info']->get();
81 51
        if ($BaseInfo->getOptionProductTaxRule() !== Constant::ENABLED) {
82 51
            $Product = null;
83 51
            $ProductClass = null;
84
        }
85
86
        // Cache Key 設定
87
        if ($Product instanceof \Eccube\Entity\Product) {
88 342
            $productId = $Product->getId();
89 342
        } 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...
90 320
            $productId = $Product;
91 320
        } else {
92
            $productId = '0';
93
        }
94
        if ($ProductClass instanceof \Eccube\Entity\ProductClass) {
95 342
            $productClassId = $ProductClass->getId();
96 26
        } 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...
97 320
            $productClassId = $ProductClass;
98
        } else {
99
            $productClassId = '0';
100 320
        }
101
        if ($Pref instanceof \Eccube\Entity\Master\Pref) {
102 342
            $prefId = $Pref->getId();
103 25
        } elseif ($Pref) {
104 320
            $prefId = $Pref;
105
        } else {
106
            $prefId = '0';
107 320
        }
108
        if ($Country instanceof \Eccube\Entity\Master\Country) {
109 342
            $countryId = $Country->getId();
110 52
        } elseif ($Country) {
111 292
            $countryId = $Country;
112
        } else {
113
            $countryId = '0';
114 292
        }
115
        $cacheKey = $productId.':'.$productClassId.':'.$prefId.':'.$countryId;
116 342
117 2
        // すでに取得している場合はキャッシュから
118 342
        if (isset($this->rules[$cacheKey])) {
119
            return $this->rules[$cacheKey];
120
        }
121 342
122
        $parameters = array();
123 342
        $qb = $this->createQueryBuilder('t')
124
            ->where('t.apply_date < :apply_date');
125
        $parameters[':apply_date'] = new \DateTime();
126 342
127 340
        // Pref
128
        if ($Pref) {
129
            $qb->andWhere('t.Pref IS NULL OR t.Pref = :Pref');
130 342
            $parameters['Pref'] = $Pref;
131 342
        } else {
132 342
            $qb->andWhere('t.Pref IS NULL');
133 342
        }
134
135
        // Country
136 342
        if ($Country) {
137 52
            $qb->andWhere('t.Country IS NULL OR t.Country = :Country');
138 52
            $parameters['Country'] = $Country;
139
        } else {
140 292
            $qb->andWhere('t.Country IS NULL');
141
        }
142
143
        /*
144 342
         * Product, ProductClass が persist される前に TaxRuleEventSubscriber によってアクセスされる
145 2
         * 場合があるため、ID の存在もチェックする.
146 2
         * https://github.com/EC-CUBE/ec-cube/issues/677
147
         */
148 342
149
        // Product
150
        if ($Product && $productId > 0) {
151
            $qb->andWhere('t.Product IS NULL OR t.Product = :Product');
152
            $parameters['Product'] = $Product;
153
        } else {
154
            $qb->andWhere('t.Product IS NULL');
155
        }
156
157
        // ProductClass
158 342
        if ($ProductClass && $productClassId > 0) {
159 26
            $qb->andWhere('t.ProductClass IS NULL OR t.ProductClass = :ProductClass');
160 26
            $parameters['ProductClass'] = $ProductClass;
161
        } else {
162 323
            $qb->andWhere('t.ProductClass IS NULL');
163
        }
164
165
        $TaxRules = $qb
166 342
            ->setParameters($parameters)
167 25
            ->orderBy('t.apply_date', 'DESC') // 実際は usort() でソートする
168 25
            ->getQuery()
169
            ->getResult();
170 338
171
        // 地域設定を優先するが、システムパラメーターなどに設定を持っていくか
172
        // 後に書いてあるほど優先される
173
        $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...
174 342
        $priorityKeys = array();
175 342
        foreach (explode(',', $this->app['config']['tax_rule_priority']) as $key) {
176 342
            $priorityKeys[] = str_replace('_', '', preg_replace('/_id\z/', '', $key));
177 342
        }
178
179
        foreach ($TaxRules as $TaxRule) {
180
            $rank = 0;
181 342
            foreach ($priorityKeys as $index => $key) {
182 342
                $arrayProperties = array_change_key_case($TaxRule->toArray());
183 342
                if ($arrayProperties[$key]) {
0 ignored issues
show
Coding Style introduced by
Blank line found at start of control structure
Loading history...
184 342
185
                    // 配列の数値添字を重みとして利用する
186
                    $rank += 1 << ($index + 1);
187 342
                }
188 342
            }
189 342
            $TaxRule->setRank($rank);
190 342
        }
191 342
192
        // 適用日降順, rank 降順にソートする
193
        usort($TaxRules, function($a, $b) {
0 ignored issues
show
Coding Style introduced by
Expected 1 space after FUNCTION keyword; 0 found
Loading history...
194 342
            return $a->compareTo($b);
195
        });
196
197 342
        if (!empty($TaxRules)) {
198
            $this->rules[$cacheKey] = $TaxRules[0];
199
200
            return $TaxRules[0];
201 342
        } else {
202 8
            throw new NoResultException();
203 342
        }
204
    }
205 342
206 342
    /**
207
     * getList
208 342
     *
209
     * @return array|null
210
     */
211
    public function getList()
212
    {
213
        $qb = $this->createQueryBuilder('t')
214
            ->orderBy('t.apply_date', 'DESC')
215
            ->where('t.Product IS NULL AND t.ProductClass IS NULL');
216
        $TaxRules = $qb
217
            ->getQuery()
218
            ->getResult();
219 5
220
        return $TaxRules;
221 5
    }
222 5
223 5
    /**
224
     * getById
225 5
     * @deprecated Use TaxRuleRepository::find()
226 5
     *
227
     * @param  int   $id
0 ignored issues
show
introduced by
Expected 1 spaces after parameter type; 3 found
Loading history...
228 5
     * @return array
229
     */
230
    public function getById($id)
231
    {
232
        $criteria = array(
233
            'id' => $id,
234
        );
235
236
        return $this->findOneBy($criteria);
237 1
    }
238
239
    /**
240 1
     * getByTime
241
     *
242
     * @deprecated Use magic finder methods. TaxRuleRepository::findOneByApplyDate()
243 1
     * @param  string $applyDate
244
     * @return mixed
245
     */
246
    public function getByTime($applyDate)
247
    {
248
        $criteria = array(
249
            'apply_date' => $applyDate,
250
        );
251
252
        return $this->findOneBy($criteria);
253
    }
254
255
    /**
256
     * 税規約の削除.
257
     *
258
     * @param  int|\Eccube\Entity\TaxRule $TaxRule 税規約
259
     * @return void
260
     * @throws NoResultException
261
     */
262
    public function delete($TaxRule)
263
    {
264
        if (!$TaxRule instanceof \Eccube\Entity\TaxRule) {
265
            $TaxRule = $this->find($TaxRule);
266
        }
267
        if (!$TaxRule) {
268 3
            throw new NoResultException;
0 ignored issues
show
introduced by
Use parentheses when instantiating classes
Loading history...
269
        }
270 3
        $TaxRule->setDelFlg(1);
271 1
        $em = $this->getEntityManager();
272
        $em->persist($TaxRule);
273 3
        $em->flush();
274
    }
275
276 3
    /**
277 3
     * TaxRule のキャッシュをクリアする.
278 3
     *
279 3
     * getByRule() をコールすると、結果をキャッシュし、2回目以降はデータベースへアクセスしない.
280
     * このメソッドをコールすると、キャッシュをクリアし、再度データベースを参照して結果を取得する.
281
     */
282
    public function clearCache()
283
    {
284
        $this->rules = array();
285
    }
286
}
287