CustomerRepository::getQueryBuilderBySearchData()   F
last analyzed

Complexity

Conditions 41
Paths > 20000

Size

Total Lines 167
Code Lines 116

Duplication

Lines 50
Ratio 29.94 %

Code Coverage

Tests 53
CRAP Score 41

Importance

Changes 0
Metric Value
cc 41
eloc 116
nc 786432
nop 1
dl 50
loc 167
rs 2
c 0
b 0
f 0
ccs 53
cts 53
cp 1
crap 41

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 Eccube\Common\Constant;
29
use Eccube\Entity\Customer;
30
use Eccube\Entity\Master\CustomerStatus;
31
use Eccube\Util\Str;
32
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
33
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
34
use Symfony\Component\Security\Core\User\UserInterface;
35
use Symfony\Component\Security\Core\User\UserProviderInterface;
36
use Symfony\Component\Security\Core\Util\SecureRandom;
37
38
/**
39
 * CustomerRepository
40
 *
41
 * This class was generated by the Doctrine ORM. Add your own custom
42
 * repository methods below.
43
 */
44
class CustomerRepository extends EntityRepository implements UserProviderInterface
45
{
46
    protected $app;
47
48
    public function setApplication($app)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
49
    {
50
        $this->app = $app;
51
    }
52
53 2
    public function newCustomer()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
54
    {
55
        $Customer = new \Eccube\Entity\Customer();
56 2
        $Status = $this->getEntityManager()
57 2
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
58
            ->find(1);
59
60
        $Customer
61 2
            ->setStatus($Status)
62
            ->setDelFlg(0);
63
64 2
        return $Customer;
65
    }
66
67
    /**
68
     * Loads the user for the given username.
69
     *
70
     * This method must throw UsernameNotFoundException if the user is not
71
     * found.
72
     *
73
     * @param string $username The username
74
     *
75
     * @return UserInterface
76
     *
77
     * @see UsernameNotFoundException
78
     *
79
     * @throws UsernameNotFoundException if the user is not found
80
     */
81 7
    public function loadUserByUsername($username)
82
    {
83
        // 本会員ステータスの会員のみ有効.
84 7
        $CustomerStatus = $this
85 7
            ->getEntityManager()
86 7
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
87
            ->find(CustomerStatus::ACTIVE);
88
89 7
        $query = $this->createQueryBuilder('c')
90 7
            ->where('c.email = :email')
91 7
            ->andWhere('c.del_flg = :delFlg')
92 7
            ->andWhere('c.Status =:CustomerStatus')
93
            ->setParameters(array(
94
                'email' => $username,
95 7
                'delFlg' => Constant::DISABLED,
96
                'CustomerStatus' => $CustomerStatus,
97
            ))
98
            ->setMaxResults(1)
99
            ->getQuery();
100 7
        $Customer = $query->getOneOrNullResult();
101
        if (!$Customer) {
102
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
103
        }
104 6
105
        return $Customer;
106
    }
107
108
    /**
109
     * Refreshes the user for the account interface.
110
     *
111
     * It is up to the implementation to decide if the user data should be
112
     * totally reloaded (e.g. from the database), or if the UserInterface
113
     * object can just be merged into some internal array of users / identity
114
     * map.
115
     *
116
     * @param UserInterface $user
117
     *
118
     * @return UserInterface
119
     *
120
     * @throws UnsupportedUserException if the account is not supported
121 5
     */
122 View Code Duplication
    public function refreshUser(UserInterface $user)
123 5
    {
124
        if (!$user instanceof Customer) {
0 ignored issues
show
Bug introduced by
The class Eccube\Entity\Customer 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...
125
            throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user)));
126
        }
127
128 5
        return $this->loadUserByUsername($user->getUsername());
129
    }
130
131
    /**
132
     * Whether this provider supports the given user class.
133
     *
134
     * @param string $class
135
     *
136
     * @return bool
137 1
     */
138
    public function supportsClass($class)
139 1
    {
140
        return $class === 'Eccube\Entity\Customer';
141
    }
142 31
143
    public function getQueryBuilderBySearchData($searchData)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
144 31
    {
145 31
        $qb = $this->createQueryBuilder('c')
146
            ->select('c')
147
            ->andWhere('c.del_flg = 0');
148 21
149
        if (isset($searchData['multi']) && Str::isNotBlank($searchData['multi'])) {
150
            //スペース除去
151
            $clean_key_multi = preg_replace('/\s+|[ ]+/u', '', $searchData['multi']);
152
            $id = preg_match('/^\d+$/', $clean_key_multi) ? $clean_key_multi : null;
153 2
            $qb
154
                ->andWhere('c.id = :customer_id OR CONCAT(c.name01, c.name02) LIKE :name OR CONCAT(c.kana01, c.kana02) LIKE :kana OR c.email LIKE :email')
155
                ->setParameter('customer_id', $id)
156
                ->setParameter('name', '%' . $clean_key_multi . '%')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
157 8
                ->setParameter('kana', '%' . $clean_key_multi . '%')
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
158 8
                ->setParameter('email', '%' . $clean_key_multi . '%');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
159 8
        }
160
161 2
        // Pref
162
        if (!empty($searchData['pref']) && $searchData['pref']) {
163
            $qb
164
                ->andWhere('c.Pref = :pref')
165 31
                ->setParameter('pref', $searchData['pref']->getId());
166
        }
167 1
168
        // sex
169
        if (!empty($searchData['sex']) && count($searchData['sex']) > 0) {
170
            $sexs = array();
171
            foreach ($searchData['sex'] as $sex) {
172 30
                $sexs[] = $sex->getId();
173 1
            }
174 1
175
            $qb
176
                ->andWhere($qb->expr()->in('c.Sex', ':sexs'))
177
                ->setParameter('sexs', $sexs);
178
        }
179
180
        if (!empty($searchData['birth_month']) && $searchData['birth_month']) {
181
            $qb
182
                ->andWhere('EXTRACT(MONTH FROM c.birth) = :birth_month')
183
                ->setParameter('birth_month', $searchData['birth_month']);
184 31
        }
185
186
        // birth
187 View Code Duplication
        if (!empty($searchData['birth_start']) && $searchData['birth_start']) {
188
            $date = $searchData['birth_start']
189
                ->format('Y-m-d H:i:s');
190
            $qb
191
                ->andWhere('c.birth >= :birth_start')
192 31
                ->setParameter('birth_start', $date);
193
        }
194
        if (!empty($searchData['birth_end']) && $searchData['birth_end']) {
195
            $date = clone $searchData['birth_end'];
196 2
            $date = $date
197
                ->modify('+1 days')
198
                ->format('Y-m-d H:i:s');
199 31
            $qb
200 2
                ->andWhere('c.birth < :birth_end')
201
                ->setParameter('birth_end', $date);
202 2
        }
203
204
        // tel
205 2 View Code Duplication
        if (isset($searchData['tel']) && Str::isNotBlank($searchData['tel'])) {
206
            $qb
207
                ->andWhere('CONCAT(c.tel01, c.tel02, c.tel03) LIKE :tel')
208
                ->setParameter('tel', '%' . $searchData['tel'] . '%');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
209
        }
210 30
211
        // buy_total
212 1 View Code Duplication
        if (isset($searchData['buy_total_start']) && Str::isNotBlank($searchData['buy_total_start'])) {
213
            $qb
214
                ->andWhere('c.buy_total >= :buy_total_start')
215
                ->setParameter('buy_total_start', $searchData['buy_total_start']);
216
        }
217 30 View Code Duplication
        if (isset($searchData['buy_total_end']) && Str::isNotBlank($searchData['buy_total_end'])) {
218
            $qb
219 1
                ->andWhere('c.buy_total <= :buy_total_end')
220
                ->setParameter('buy_total_end', $searchData['buy_total_end']);
221
        }
222 30
223
        // buy_times
224 1
        if (!empty($searchData['buy_times_start']) && $searchData['buy_times_start']) {
225
            $qb
226
                ->andWhere('c.buy_times >= :buy_times_start')
227
                ->setParameter('buy_times_start', $searchData['buy_times_start']);
228
        }
229 31
        if (!empty($searchData['buy_times_end']) && $searchData['buy_times_end']) {
230
            $qb
231 1
                ->andWhere('c.buy_times <= :buy_times_end')
232
                ->setParameter('buy_times_end', $searchData['buy_times_end']);
233
        }
234 31
235
        // create_date
236 1 View Code Duplication
        if (!empty($searchData['create_date_start']) && $searchData['create_date_start']) {
237
            $date = $searchData['create_date_start']
238
                ->format('Y-m-d H:i:s');
239
            $qb
240
                ->andWhere('c.create_date >= :create_date_start')
241 31
                ->setParameter('create_date_start', $date);
242
        }
243
        if (!empty($searchData['create_date_end']) && $searchData['create_date_end']) {
244
            $date = clone $searchData['create_date_end'];
245 1
            $date = $date
246
                ->modify('+1 days')
247
                ->format('Y-m-d H:i:s');
248 31
            $qb
249 1
                ->andWhere('c.create_date < :create_date_end')
250
                ->setParameter('create_date_end', $date);
251 1
        }
252
253
        // update_date
254 1 View Code Duplication
        if (!empty($searchData['update_date_start']) && $searchData['update_date_start']) {
255
            $date = $searchData['update_date_start']
256
                ->format('Y-m-d H:i:s');
257
            $qb
258
                ->andWhere('c.update_date >= :update_date_start')
259 31
                ->setParameter('update_date_start', $date);
260
        }
261
        if (!empty($searchData['update_date_end']) && $searchData['update_date_end']) {
262
            $date = clone $searchData['update_date_end'];
263 1
            $date = $date
264
                ->modify('+1 days')
265
                ->format('Y-m-d H:i:s');
266 31
            $qb
267 1
                ->andWhere('c.update_date < :update_date_end')
268
                ->setParameter('update_date_end', $date);
269 1
        }
270
271
        // last_buy
272 1 View Code Duplication
        if (!empty($searchData['last_buy_start']) && $searchData['last_buy_start']) {
273
            $date = $searchData['last_buy_start']
274
                ->format('Y-m-d H:i:s');
275
            $qb
276
                ->andWhere('c.last_buy_date >= :last_buy_start')
277 31
                ->setParameter('last_buy_start', $date);
278
        }
279
        if (!empty($searchData['last_buy_end']) && $searchData['last_buy_end']) {
280
            $date = clone $searchData['last_buy_end'];
281 1
            $date = $date
282
                ->modify('+1 days')
283
                ->format('Y-m-d H:i:s');
284 31
            $qb
285 1
                ->andWhere('c.last_buy_date < :last_buy_end')
286
                ->setParameter('last_buy_end', $date);
287 1
        }
288
289
        // status
290 1
        if (!empty($searchData['customer_status']) && count($searchData['customer_status']) > 0) {
291
            $qb
292
                ->andWhere($qb->expr()->in('c.Status', ':statuses'))
293
                ->setParameter('statuses', $searchData['customer_status']);
294
        }
295 29
296
        // buy_product_name、buy_product_code
297 View Code Duplication
        if (isset($searchData['buy_product_code']) && Str::isNotBlank($searchData['buy_product_code'])) {
298
            $qb
299
                ->leftJoin('c.Orders', 'o')
300
                ->leftJoin('o.OrderDetails', 'od')
301
                ->andWhere('od.product_name LIKE :buy_product_name OR od.product_code LIKE :buy_product_name')
302 30
                ->setParameter('buy_product_name', '%' . $searchData['buy_product_code'] . '%');
0 ignored issues
show
Coding Style introduced by
Concat operator must not be surrounded by spaces
Loading history...
303
        }
304 1
305 1
        // Order By
306 1
        $qb->addOrderBy('c.update_date', 'DESC');
307
308
        return $qb;
309
    }
310
311
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
312
     * ユニークなシークレットキーを返す
313 31
     * @param $app
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
314
     * @return string
315
     */
316 View Code Duplication
    public function getUniqueSecretKey($app)
317
    {
318
        $unique = Str::random(32);
319
        $Customer = $app['eccube.repository.customer']->findBy(array(
320
            'secret_key' => $unique,
321 63
        ));
322
        if (count($Customer) == 0) {
323
            return $unique;
324
        } else {
325
            return $this->getUniqueSecretKey($app);
326
        }
327
    }
328 63
329
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
330
     * ユニークなパスワードリセットキーを返す
331
     * @param $app
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
332
     * @return string
333
     */
334 View Code Duplication
    public function getUniqueResetKey($app)
335
    {
336
        $unique = Str::random(32);
337
        $Customer = $app['eccube.repository.customer']->findBy(array(
338
                        'reset_key' => $unique,
339
        ));
340
        if (count($Customer) == 0) {
341
            return $unique;
342
        } else {
343
            return $this->getUniqueResetKey($app);
344
        }
345
    }
346
347
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$byte" missing
Loading history...
348
     * saltを生成する
349
     *
350
     * @param $byte
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
351
     * @return string
352
     */
353
    public function createSalt($byte)
354
    {
355
        $generator = new SecureRandom();
356
357
        return bin2hex($generator->nextBytes($byte));
358
    }
359
360
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
361
     * 入力されたパスワードをSaltと暗号化する
362
     *
363
     * @param $app
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
364
     * @param  Customer $Customer
365
     * @return mixed
366
     */
367
    public function encryptPassword($app, \Eccube\Entity\Customer $Customer)
368
    {
369
        $encoder = $app['security.encoder_factory']->getEncoder($Customer);
370
371
        return $encoder->encodePassword($Customer->getPassword(), $Customer->getSalt());
372 62
    }
373
374
    public function getNonActiveCustomerBySecretKey($secret_key)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
375
    {
376
        $qb = $this->createQueryBuilder('c')
377 62
            ->where('c.del_flg = 0 AND c.secret_key = :secret_key')
378
            ->leftJoin('c.Status', 's')
379 2
            ->andWhere('s.id = :status')
380
            ->setParameter('secret_key', $secret_key)
381 2
            ->setParameter('status', CustomerStatus::NONACTIVE);
382 2
        $query = $qb->getQuery();
383 2
384 2
        return $query->getSingleResult();
385 2
    }
386
387
    public function getActiveCustomerByEmail($email)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
388
    {
389 1
        $query = $this->createQueryBuilder('c')
390
            ->where('c.email = :email AND c.Status = :status')
391
            ->setParameter('email', $email)
392 1
            ->setParameter('status', CustomerStatus::ACTIVE)
393
            ->setMaxResults(1)
394 1
            ->getQuery();
395 1
396 1
        $Customer = $query->getOneOrNullResult();
397 1
398
        return $Customer;
399
    }
400
401
    public function getActiveCustomerByResetKey($reset_key)
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
402 1
    {
403
        $query = $this->createQueryBuilder('c')
404
            ->where('c.reset_key = :reset_key AND c.Status = :status AND c.reset_expire >= :reset_expire')
405 2
            ->setParameter('reset_key', $reset_key)
406
            ->setParameter('status', CustomerStatus::ACTIVE)
407 2
            ->setParameter('reset_expire', new \DateTime())
408 2
            ->getQuery();
409 2
410 2
        $Customer = $query->getSingleResult();
411
412
        return $Customer;
413
    }
414 1
415
    public function getResetPassword()
0 ignored issues
show
introduced by
Missing function doc comment
Loading history...
416 1
    {
417
        return Str::random(8);
418
    }
419
420
    /**
0 ignored issues
show
introduced by
Doc comment for parameter "$app" missing
Loading history...
introduced by
Doc comment for parameter "$orderStatusId" missing
Loading history...
421
     * 会員の初回購入時間、購入時間、購入回数、購入金額を更新する
422
     *
423
     * @param $app
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
424
     * @param  Customer $Customer
0 ignored issues
show
introduced by
Expected 6 spaces after parameter type; 1 found
Loading history...
425
     * @param  $orderStatusId
0 ignored issues
show
introduced by
Missing parameter name
Loading history...
426
     */
427
    public function updateBuyData($app, Customer $Customer, $orderStatusId)
428
    {
429
        // 会員の場合、初回購入時間・購入時間・購入回数・購入金額を更新
430
431 1
        $arr = array($app['config']['order_new'],
432
                                $app['config']['order_pay_wait'],
433
                                $app['config']['order_back_order'],
434
                                $app['config']['order_deliv'],
435
                                $app['config']['order_pre_end'],
436
                        );
437
438
        $result = $app['eccube.repository.order']->getCustomerCount($Customer, $arr);
439
440
        if (!empty($result)) {
441
            $data = $result[0];
442
443
            $now = new \DateTime();
444
445 1
            $firstBuyDate = $Customer->getFirstBuyDate();
446
            if (empty($firstBuyDate)) {
447
                $Customer->setFirstBuyDate($now);
448
            }
449
450 1
            if ($orderStatusId == $app['config']['order_cancel'] ||
0 ignored issues
show
Unused Code introduced by
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
451
                    $orderStatusId == $app['config']['order_pending'] ||
452
                    $orderStatusId == $app['config']['order_processing']) {
453
                // キャンセル、決済処理中、購入処理中は購入時間は更新しない
454
            } else {
455
                $Customer->setLastBuyDate($now);
456
            }
457
458
            $Customer->setBuyTimes($data['buy_times']);
459
            $Customer->setBuyTotal($data['buy_total']);
460
0 ignored issues
show
Coding Style introduced by
Blank line found at end of control structure
Loading history...
461
        } else {
462
            // 受注データが存在しなければ初期化
463
            $Customer->setFirstBuyDate(null);
464
            $Customer->setLastBuyDate(null);
465
            $Customer->setBuyTimes(0);
466
            $Customer->setBuyTotal(0);
467
        }
468
469
        $app['orm.em']->persist($Customer);
470
        $app['orm.em']->flush();
471 1
    }
472
}
473