Failed Conditions
Push — issue#702_rs ( ed72a1...cdafcf )
by Guilherme
07:33
created

PersonRepository::getCountByState()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 18
nc 1
nop 0
dl 0
loc 23
rs 9.0856
c 0
b 0
f 0
1
<?php
2
/**
3
 * This file is part of the login-cidadao project or it's bundles.
4
 *
5
 * (c) Guilherme Donato <guilhermednt on github>
6
 *
7
 * For the full copyright and license information, please view the LICENSE
8
 * file that was distributed with this source code.
9
 */
10
11
namespace LoginCidadao\CoreBundle\Entity;
12
13
use Doctrine\ORM\EntityRepository;
14
use Doctrine\ORM\NonUniqueResultException;
15
use Doctrine\ORM\NoResultException;
16
use Egulias\EmailValidator\EmailValidator;
17
use libphonenumber\PhoneNumber;
18
use libphonenumber\PhoneNumberFormat;
19
use libphonenumber\PhoneNumberUtil;
20
21
class PersonRepository extends EntityRepository
22
{
23
24
    public function findAllPendingCPF()
25
    {
26
        return $this->getEntityManager()
27
                ->createQuery('SELECT p FROM LoginCidadaoCoreBundle:Person p WHERE p.cpf IS NULL')
28
                ->getResult();
29
    }
30
31
    public function findUnconfirmedEmailUntilDate(\DateTime $dateLimit)
32
    {
33
        return $this->getEntityManager()
34
            ->createQuery(
35
                'SELECT p FROM LoginCidadaoCoreBundle:Person p WHERE p.emailConfirmedAt IS NULL AND p.emailExpiration <= :date'
36
            )
37
                ->setParameter('date', $dateLimit)
38
                ->getResult();
39
    }
40
41
    public function getFindAuthorizedByClientIdQuery($clientId)
42
    {
43
        return $this->createQueryBuilder('p')
44
            ->innerJoin(
45
                'LoginCidadaoCoreBundle:Authorization',
46
                'a',
47
                'WITH',
48
                'a.person = p'
49
            )
50
            ->innerJoin(
51
                'LoginCidadaoOAuthBundle:Client',
52
                'c',
53
                'WITH',
54
                'a.client = c'
55
            )
56
                ->andWhere('c.id = :clientId')
57
            ->setParameter('clientId', $clientId);
58
    }
59
60
    public function getCountByCountry()
61
    {
62
        $qb = $this->getEntityManager()->createQueryBuilder();
63
64
        return $qb
65
                ->select('count(p.country) AS qty, c.name')
66
                ->from('LoginCidadaoCoreBundle:Person', 'p')
67
            ->innerJoin(
68
                'LoginCidadaoCoreBundle:Country',
69
                'c',
70
                'WITH',
71
                'p.country = c'
72
            )
73
                ->where('p.country IS NOT NULL')
74
                ->groupBy('p.country, c.name')
75
                ->orderBy('qty', 'DESC')
76
                ->getQuery()->getResult();
77
    }
78
79
    public function getCountByState()
80
    {
81
        $qb = $this->getEntityManager()->createQueryBuilder();
82
83
        return $qb
84
                ->select('count(p.state) AS qty, s.id, s.name, c.name AS country')
85
                ->from('LoginCidadaoCoreBundle:Person', 'p')
86
            ->innerJoin(
87
                'LoginCidadaoCoreBundle:State',
88
                's',
89
                'WITH',
90
                'p.state = s'
91
            )
92
            ->innerJoin(
93
                'LoginCidadaoCoreBundle:Country',
94
                'c',
95
                'WITH',
96
                's.country = c'
97
            )
98
                ->where('p.state IS NOT NULL')
99
                ->groupBy('p.state, s.name, country, s.id')
100
                ->orderBy('qty', 'DESC')
101
                ->getQuery()->getResult();
102
    }
103
104
    public function getCountByCity($stateId)
105
    {
106
        $qb = $this->getEntityManager()->createQueryBuilder();
107
108
        return $qb
109
                ->select('count(p.city) AS qty, c.name')
110
                ->from('LoginCidadaoCoreBundle:Person', 'p')
111
            ->innerJoin(
112
                'LoginCidadaoCoreBundle:City',
113
                'c',
114
                'WITH',
115
                'p.city = c'
116
            )
117
            ->innerJoin(
118
                'LoginCidadaoCoreBundle:State',
119
                's',
120
                'WITH',
121
                'c.state = s'
122
            )
123
                ->where('p.city IS NOT NULL')
124
                ->andWhere('s.id = :stateId')
125
                ->groupBy('p.city, c.name')
126
                ->orderBy('qty', 'DESC')
127
                ->setParameter('stateId', $stateId)
128
                ->getQuery()->getResult();
129
    }
130
131
    public function getCountAll()
132
    {
133
        $qb = $this->getEntityManager()->createQueryBuilder();
134
135
        return $qb
136
                ->select('count(p.id) AS qty')
137
                ->from('LoginCidadaoCoreBundle:Person', 'p')
138
                ->orderBy('qty', 'DESC')
139
                ->getQuery()->getSingleResult();
140
    }
141
142
    public function getUserSearchQuery($query)
143
    {
144
        return $this->createQueryBuilder('p')
145
            ->where(
146
                'p.cpf LIKE :query OR p.username LIKE :query OR p.email LIKE :query OR p.firstName LIKE :query OR p.surname LIKE :query'
147
            )
148
                ->setParameter('query', '%'.addcslashes($query, '\\%_').'%')
149
                ->addOrderBy('p.id', 'DESC');
150
    }
151
152
    public function getFindByIdIn($ids)
153
    {
154
        return $this->createQueryBuilder('p')
155
                ->where('p.id in(:ids)')
156
                ->setParameters(compact('ids'))
157
                ->addOrderBy('p.id', 'desc');
158
    }
159
160
    public function findOneByEmail($email)
161
    {
162
        return $this->createQueryBuilder('p')
163
            ->where('p.email = :email')
164
            ->orWhere('p.emailCanonical = :email')
165
            ->setParameter('email', $email)
166
            ->getQuery()->getOneOrNullResult();
167
    }
168
169
    /**
170
     * @param PhoneNumber $phone
171
     * @return int
172
     */
173
    public function countByPhone(PhoneNumber $phone)
174
    {
175
        try {
176
            $phoneUtil = PhoneNumberUtil::getInstance();
177
178
            return $this->createQueryBuilder('p')
179
                ->select('COUNT(p)')
180
                ->where('p.mobile = :mobile')
181
                ->setParameter('mobile', $phoneUtil->format($phone, PhoneNumberFormat::E164))
182
                ->getQuery()->getSingleScalarResult();
183
        } catch (NoResultException $e) {
184
            return 0;
185
        } catch (NonUniqueResultException $e) {
186
            return 0;
187
        }
188
    }
189
190
    /**
191
     * @return \Doctrine\ORM\QueryBuilder
192
     */
193
    private function getBaseSearchQuery()
194
    {
195
        return $this->createQueryBuilder('p')
196
            ->addOrderBy('p.id', 'DESC');
197
    }
198
199
    public function getCpfSearchQuery($cpf)
200
    {
201
        return $this->getBaseSearchQuery()
202
            ->where('p.cpf = :cpf')
203
            ->setParameter('cpf', $cpf);
204
    }
205
206
    public function getEmailSearchQuery($email)
207
    {
208
        return $this->getBaseSearchQuery()
209
            ->where('p.emailCanonical = LOWER(:email)')
210
            ->setParameter('email', $email);
211
    }
212
213
    public function getNameSearchQuery($name)
214
    {
215
        $sanitized = addcslashes($name, "%_");
216
217
        return $this->getBaseSearchQuery()
218
            ->where('LowerUnaccent(p.username) LIKE LowerUnaccent(:name)')
219
            ->orWhere('LowerUnaccent(p.firstName) LIKE LowerUnaccent(:name)')
220
            ->orWhere('LowerUnaccent(p.surname) LIKE LowerUnaccent(:name)')
221
            ->setParameter('name', "%{$sanitized}%");
222
    }
223
224
    /**
225
     * This will return the appropriate query for the input given.
226
     * @param $query
227
     * @return \Doctrine\ORM\QueryBuilder
228
     */
229
    public function getSmartSearchQuery($query)
230
    {
231
        $query = trim($query);
232
233
        if (strlen($query) == 0) {
234
            return $this->getBaseSearchQuery();
235
        }
236
237
        $cpfRegex = '/^(?:\d{3}\.?){2}\d{3}-?\d{2}$/';
238
        // Check CPF
239
        if (preg_match($cpfRegex, $query) === 1) {
240
            $cpf = str_replace(['.', '-'], '', $query);
241
242
            return $this->getCpfSearchQuery($cpf);
243
        }
244
245
        // Check email
246
        $emailValidator = new EmailValidator();
247
        if ($emailValidator->isValid($query)) {
0 ignored issues
show
Bug introduced by
The call to Egulias\EmailValidator\EmailValidator::isValid() has too few arguments starting with emailValidation. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

247
        if ($emailValidator->/** @scrutinizer ignore-call */ isValid($query)) {

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
248
            return $this->getEmailSearchQuery($query);
249
        }
250
251
        // Defaults to name search
252
        return $this->getNameSearchQuery($query);
253
    }
254
}
255