CustomerRepository::getQueryBuilderBySearchData()   F
last analyzed

Complexity

Conditions 41
Paths > 20000

Size

Total Lines 167

Duplication

Lines 50
Ratio 29.94 %

Importance

Changes 0
Metric Value
cc 41
nc 786432
nop 1
dl 50
loc 167
rs 0
c 0
b 0
f 0

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) EC-CUBE CO.,LTD. All Rights Reserved.
6
 *
7
 * http://www.ec-cube.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)
49
    {
50
        $this->app = $app;
51
    }
52
53
    public function newCustomer()
54
    {
55
        $Customer = new \Eccube\Entity\Customer();
56
        $Status = $this->getEntityManager()
57
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
58
            ->find(1);
59
60
        $Customer
61
            ->setStatus($Status)
62
            ->setDelFlg(0);
63
64
        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
    public function loadUserByUsername($username)
82
    {
83
        // 本会員ステータスの会員のみ有効.
84
        $CustomerStatus = $this
85
            ->getEntityManager()
86
            ->getRepository('Eccube\Entity\Master\CustomerStatus')
87
            ->find(CustomerStatus::ACTIVE);
88
89
        $query = $this->createQueryBuilder('c')
90
            ->where('c.email = :email')
91
            ->andWhere('c.del_flg = :delFlg')
92
            ->andWhere('c.Status =:CustomerStatus')
93
            ->setParameters(array(
94
                'email' => $username,
95
                'delFlg' => Constant::DISABLED,
96
                'CustomerStatus' => $CustomerStatus,
97
            ))
98
            ->setMaxResults(1)
99
            ->getQuery();
100
        $Customer = $query->getOneOrNullResult();
101
        if (!$Customer) {
102
            throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username));
103
        }
104
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
     */
122 View Code Duplication
    public function refreshUser(UserInterface $user)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
123
    {
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
        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
     */
138
    public function supportsClass($class)
139
    {
140
        return $class === 'Eccube\Entity\Customer';
141
    }
142
143
    public function getQueryBuilderBySearchData($searchData)
144
    {
145
        $qb = $this->createQueryBuilder('c')
146
            ->select('c')
147
            ->andWhere('c.del_flg = 0');
148
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
            $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 . '%')
157
                ->setParameter('kana', '%' . $clean_key_multi . '%')
158
                ->setParameter('email', '%' . $clean_key_multi . '%');
159
        }
160
161
        // Pref
162
        if (!empty($searchData['pref']) && $searchData['pref']) {
163
            $qb
164
                ->andWhere('c.Pref = :pref')
165
                ->setParameter('pref', $searchData['pref']->getId());
166
        }
167
168
        // sex
169
        if (!empty($searchData['sex']) && count($searchData['sex']) > 0) {
170
            $sexs = array();
171
            foreach ($searchData['sex'] as $sex) {
172
                $sexs[] = $sex->getId();
173
            }
174
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
        }
185
186
        // birth
187 View Code Duplication
        if (!empty($searchData['birth_start']) && $searchData['birth_start']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
188
            $date = $searchData['birth_start']
189
                ->format('Y-m-d H:i:s');
190
            $qb
191
                ->andWhere('c.birth >= :birth_start')
192
                ->setParameter('birth_start', $date);
193
        }
194
        if (!empty($searchData['birth_end']) && $searchData['birth_end']) {
195
            $date = clone $searchData['birth_end'];
196
            $date = $date
197
                ->modify('+1 days')
198
                ->format('Y-m-d H:i:s');
199
            $qb
200
                ->andWhere('c.birth < :birth_end')
201
                ->setParameter('birth_end', $date);
202
        }
203
204
        // tel
205 View Code Duplication
        if (isset($searchData['tel']) && Str::isNotBlank($searchData['tel'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
206
            $qb
207
                ->andWhere('CONCAT(c.tel01, c.tel02, c.tel03) LIKE :tel')
208
                ->setParameter('tel', '%' . $searchData['tel'] . '%');
209
        }
210
211
        // buy_total
212 View Code Duplication
        if (isset($searchData['buy_total_start']) && Str::isNotBlank($searchData['buy_total_start'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
213
            $qb
214
                ->andWhere('c.buy_total >= :buy_total_start')
215
                ->setParameter('buy_total_start', $searchData['buy_total_start']);
216
        }
217 View Code Duplication
        if (isset($searchData['buy_total_end']) && Str::isNotBlank($searchData['buy_total_end'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
218
            $qb
219
                ->andWhere('c.buy_total <= :buy_total_end')
220
                ->setParameter('buy_total_end', $searchData['buy_total_end']);
221
        }
222
223
        // buy_times
224
        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
        if (!empty($searchData['buy_times_end']) && $searchData['buy_times_end']) {
230
            $qb
231
                ->andWhere('c.buy_times <= :buy_times_end')
232
                ->setParameter('buy_times_end', $searchData['buy_times_end']);
233
        }
234
235
        // create_date
236 View Code Duplication
        if (!empty($searchData['create_date_start']) && $searchData['create_date_start']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
                ->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
            $date = $date
246
                ->modify('+1 days')
247
                ->format('Y-m-d H:i:s');
248
            $qb
249
                ->andWhere('c.create_date < :create_date_end')
250
                ->setParameter('create_date_end', $date);
251
        }
252
253
        // update_date
254 View Code Duplication
        if (!empty($searchData['update_date_start']) && $searchData['update_date_start']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
                ->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
            $date = $date
264
                ->modify('+1 days')
265
                ->format('Y-m-d H:i:s');
266
            $qb
267
                ->andWhere('c.update_date < :update_date_end')
268
                ->setParameter('update_date_end', $date);
269
        }
270
271
        // last_buy
272 View Code Duplication
        if (!empty($searchData['last_buy_start']) && $searchData['last_buy_start']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
                ->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
            $date = $date
282
                ->modify('+1 days')
283
                ->format('Y-m-d H:i:s');
284
            $qb
285
                ->andWhere('c.last_buy_date < :last_buy_end')
286
                ->setParameter('last_buy_end', $date);
287
        }
288
289
        // status
290
        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
296
        // buy_product_name、buy_product_code
297 View Code Duplication
        if (isset($searchData['buy_product_code']) && Str::isNotBlank($searchData['buy_product_code'])) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
                ->setParameter('buy_product_name', '%' . $searchData['buy_product_code'] . '%');
303
        }
304
305
        // Order By
306
        $qb->addOrderBy('c.update_date', 'DESC');
307
308
        return $qb;
309
    }
310
311
    /**
312
     * ユニークなシークレットキーを返す
313
     * @param $app
314
     * @return string
315
     */
316 View Code Duplication
    public function getUniqueSecretKey($app)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
317
    {
318
        $unique = Str::random(32);
319
        $Customer = $app['eccube.repository.customer']->findBy(array(
320
            'secret_key' => $unique,
321
        ));
322
        if (count($Customer) == 0) {
323
            return $unique;
324
        } else {
325
            return $this->getUniqueSecretKey($app);
326
        }
327
    }
328
329
    /**
330
     * ユニークなパスワードリセットキーを返す
331
     * @param $app
332
     * @return string
333
     */
334 View Code Duplication
    public function getUniqueResetKey($app)
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
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
    /**
348
     * saltを生成する
349
     *
350
     * @param $byte
351
     * @return string
352
     */
353
    public function createSalt($byte)
354
    {
355
        $generator = new SecureRandom();
356
357
        return bin2hex($generator->nextBytes($byte));
358
    }
359
360
    /**
361
     * 入力されたパスワードをSaltと暗号化する
362
     *
363
     * @param $app
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
    }
373
374
    public function getNonActiveCustomerBySecretKey($secret_key)
375
    {
376
        $qb = $this->createQueryBuilder('c')
377
            ->where('c.del_flg = 0 AND c.secret_key = :secret_key')
378
            ->leftJoin('c.Status', 's')
379
            ->andWhere('s.id = :status')
380
            ->setParameter('secret_key', $secret_key)
381
            ->setParameter('status', CustomerStatus::NONACTIVE);
382
        $query = $qb->getQuery();
383
384
        return $query->getSingleResult();
385
    }
386
387
    public function getActiveCustomerByEmail($email)
388
    {
389
        $query = $this->createQueryBuilder('c')
390
            ->where('c.email = :email AND c.Status = :status')
391
            ->setParameter('email', $email)
392
            ->setParameter('status', CustomerStatus::ACTIVE)
393
            ->setMaxResults(1)
394
            ->getQuery();
395
396
        $Customer = $query->getOneOrNullResult();
397
398
        return $Customer;
399
    }
400
401
    public function getActiveCustomerByResetKey($reset_key)
402
    {
403
        $query = $this->createQueryBuilder('c')
404
            ->where('c.reset_key = :reset_key AND c.Status = :status AND c.reset_expire >= :reset_expire')
405
            ->setParameter('reset_key', $reset_key)
406
            ->setParameter('status', CustomerStatus::ACTIVE)
407
            ->setParameter('reset_expire', new \DateTime())
408
            ->getQuery();
409
410
        $Customer = $query->getSingleResult();
411
412
        return $Customer;
413
    }
414
415
    public function getResetPassword()
416
    {
417
        return Str::random(8);
418
    }
419
420
    /**
421
     * 会員の初回購入時間、購入時間、購入回数、購入金額を更新する
422
     *
423
     * @param $app
424
     * @param  Customer $Customer
425
     * @param  $orderStatusId
426
     */
427
    public function updateBuyData($app, Customer $Customer, $orderStatusId)
428
    {
429
        // 会員の場合、初回購入時間・購入時間・購入回数・購入金額を更新
430
431
        $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
            $firstBuyDate = $Customer->getFirstBuyDate();
446
            if (empty($firstBuyDate)) {
447
                $Customer->setFirstBuyDate($now);
448
            }
449
450
            if ($orderStatusId == $app['config']['order_cancel'] ||
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
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
    }
472
}
473