Failed Conditions
Push — issue#702 ( 91bd46...0b5bf0 )
by Guilherme
19:37 queued 12:15
created

PersonRepository   A

Complexity

Total Complexity 20

Size/Duplication

Total Lines 223
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 0
Metric Value
dl 0
loc 223
ccs 0
cts 133
cp 0
rs 10
c 0
b 0
f 0
wmc 20

15 Methods

Rating   Name   Duplication   Size   Complexity  
A getUserSearchQuery() 0 8 1
A countByPhone() 0 14 3
A getNameSearchQuery() 0 9 1
A getFindAuthorizedByClientIdQuery() 0 17 1
B getSmartSearchQuery() 0 24 4
A findUnconfirmedEmailUntilDate() 0 8 1
A getFindByIdIn() 0 6 1
A getCpfSearchQuery() 0 5 1
A getBaseSearchQuery() 0 4 1
A getEmailSearchQuery() 0 5 1
A findAllPendingCPF() 0 5 1
A getCountByState() 0 23 1
B getCountByCity() 0 25 1
A getCountAll() 0 9 1
A getCountByCountry() 0 17 1
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
    /**
161
     * @param PhoneNumber $phone
162
     * @return int
163
     */
164
    public function countByPhone(PhoneNumber $phone)
165
    {
166
        try {
167
            $phoneUtil = PhoneNumberUtil::getInstance();
168
169
            return $this->createQueryBuilder('p')
170
                ->select('COUNT(p)')
171
                ->where('p.mobile = :mobile')
172
                ->setParameter('mobile', $phoneUtil->format($phone, PhoneNumberFormat::E164))
173
                ->getQuery()->getSingleScalarResult();
174
        } catch (NoResultException $e) {
175
            return 0;
176
        } catch (NonUniqueResultException $e) {
177
            return 0;
178
        }
179
    }
180
181
    /**
182
     * @return \Doctrine\ORM\QueryBuilder
183
     */
184
    private function getBaseSearchQuery()
185
    {
186
        return $this->createQueryBuilder('p')
187
            ->addOrderBy('p.id', 'DESC');
188
    }
189
190
    public function getCpfSearchQuery($cpf)
191
    {
192
        return $this->getBaseSearchQuery()
193
            ->where('p.cpf = :cpf')
194
            ->setParameter('cpf', $cpf);
195
    }
196
197
    public function getEmailSearchQuery($email)
198
    {
199
        return $this->getBaseSearchQuery()
200
            ->where('p.emailCanonical = LOWER(:email)')
201
            ->setParameter('email', $email);
202
    }
203
204
    public function getNameSearchQuery($name)
205
    {
206
        $sanitized = addcslashes($name, "%_");
207
208
        return $this->getBaseSearchQuery()
209
            ->where('LowerUnaccent(p.username) LIKE LowerUnaccent(:name)')
210
            ->orWhere('LowerUnaccent(p.firstName) LIKE LowerUnaccent(:name)')
211
            ->orWhere('LowerUnaccent(p.surname) LIKE LowerUnaccent(:name)')
212
            ->setParameter('name', "%{$sanitized}%");
213
    }
214
215
    /**
216
     * This will return the appropriate query for the input given.
217
     * @param $query
218
     * @return \Doctrine\ORM\QueryBuilder
219
     */
220
    public function getSmartSearchQuery($query)
221
    {
222
        $query = trim($query);
223
224
        if (strlen($query) == 0) {
225
            return $this->getBaseSearchQuery();
226
        }
227
228
        $cpfRegex = '/^(?:\d{3}\.?){2}\d{3}-?\d{2}$/';
229
        // Check CPF
230
        if (preg_match($cpfRegex, $query) === 1) {
231
            $cpf = str_replace(['.', '-'], '', $query);
232
233
            return $this->getCpfSearchQuery($cpf);
234
        }
235
236
        // Check email
237
        $emailValidator = new EmailValidator();
238
        if ($emailValidator->isValid($query)) {
239
            return $this->getEmailSearchQuery($query);
240
        }
241
242
        // Defaults to name search
243
        return $this->getNameSearchQuery($query);
244
    }
245
}
246