Failed Conditions
Push — master ( fc54b8...947180 )
by Yangsin
124:44 queued 119:37
created

TaxRuleRepository::newTaxRule()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 12
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 9
CRAP Score 1

Importance

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