Failed Conditions
Pull Request — experimental/3.1 (#2512)
by chihiro
12:14
created

TaxRuleRepository::delete()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 12
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 7
CRAP Score 3.0175

Importance

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