Failed Conditions
Branch master (116909)
by Guilherme
08:28
created

PersonRepository::getCountByState()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 23
Code Lines 18

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
cc 1
eloc 18
nc 1
nop 0
dl 0
loc 23
ccs 0
cts 18
cp 0
crap 2
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 Egulias\EmailValidator\EmailValidator;
15
16
class PersonRepository extends EntityRepository
17
{
18
19
    public function findAllPendingCPF()
20
    {
21
        return $this->getEntityManager()
22
                ->createQuery('SELECT p FROM LoginCidadaoCoreBundle:Person p WHERE p.cpf IS NULL')
23
                ->getResult();
24
    }
25
26
    public function findUnconfirmedEmailUntilDate(\DateTime $dateLimit)
27
    {
28
        return $this->getEntityManager()
29
            ->createQuery(
30
                'SELECT p FROM LoginCidadaoCoreBundle:Person p WHERE p.emailConfirmedAt IS NULL AND p.emailExpiration <= :date'
31
            )
32
                ->setParameter('date', $dateLimit)
33
                ->getResult();
34
    }
35
36
    public function getFindAuthorizedByClientIdQuery($clientId)
37
    {
38
        return $this->createQueryBuilder('p')
39
            ->innerJoin(
40
                'LoginCidadaoCoreBundle:Authorization',
41
                'a',
42
                'WITH',
43
                'a.person = p'
44
            )
45
            ->innerJoin(
46
                'LoginCidadaoOAuthBundle:Client',
47
                'c',
48
                'WITH',
49
                'a.client = c'
50
            )
51
                ->andWhere('c.id = :clientId')
52
            ->setParameter('clientId', $clientId);
53
    }
54
55
    public function getCountByCountry()
56
    {
57
        $qb = $this->getEntityManager()->createQueryBuilder();
58
59
        return $qb
60
                ->select('count(p.country) AS qty, c.name')
61
                ->from('LoginCidadaoCoreBundle:Person', 'p')
62
            ->innerJoin(
63
                'LoginCidadaoCoreBundle:Country',
64
                'c',
65
                'WITH',
66
                'p.country = c'
67
            )
68
                ->where('p.country IS NOT NULL')
69
                ->groupBy('p.country, c.name')
70
                ->orderBy('qty', 'DESC')
71
                ->getQuery()->getResult();
72
    }
73
74
    public function getCountByState()
75
    {
76
        $qb = $this->getEntityManager()->createQueryBuilder();
77
78
        return $qb
79
                ->select('count(p.state) AS qty, s.id, s.name, c.name AS country')
80
                ->from('LoginCidadaoCoreBundle:Person', 'p')
81
            ->innerJoin(
82
                'LoginCidadaoCoreBundle:State',
83
                's',
84
                'WITH',
85
                'p.state = s'
86
            )
87
            ->innerJoin(
88
                'LoginCidadaoCoreBundle:Country',
89
                'c',
90
                'WITH',
91
                's.country = c'
92
            )
93
                ->where('p.state IS NOT NULL')
94
                ->groupBy('p.state, s.name, country, s.id')
95
                ->orderBy('qty', 'DESC')
96
                ->getQuery()->getResult();
97
    }
98
99
    public function getCountByCity($stateId)
100
    {
101
        $qb = $this->getEntityManager()->createQueryBuilder();
102
103
        return $qb
104
                ->select('count(p.city) AS qty, c.name')
105
                ->from('LoginCidadaoCoreBundle:Person', 'p')
106
            ->innerJoin(
107
                'LoginCidadaoCoreBundle:City',
108
                'c',
109
                'WITH',
110
                'p.city = c'
111
            )
112
            ->innerJoin(
113
                'LoginCidadaoCoreBundle:State',
114
                's',
115
                'WITH',
116
                'c.state = s'
117
            )
118
                ->where('p.city IS NOT NULL')
119
                ->andWhere('s.id = :stateId')
120
                ->groupBy('p.city, c.name')
121
                ->orderBy('qty', 'DESC')
122
                ->setParameter('stateId', $stateId)
123
                ->getQuery()->getResult();
124
    }
125
126
    public function getCountAll()
127
    {
128
        $qb = $this->getEntityManager()->createQueryBuilder();
129
130
        return $qb
131
                ->select('count(p.id) AS qty')
132
                ->from('LoginCidadaoCoreBundle:Person', 'p')
133
                ->orderBy('qty', 'DESC')
134
                ->getQuery()->getSingleResult();
135
    }
136
137
    public function getUserSearchQuery($query)
138
    {
139
        return $this->createQueryBuilder('p')
140
            ->where(
141
                'p.cpf LIKE :query OR p.username LIKE :query OR p.email LIKE :query OR p.firstName LIKE :query OR p.surname LIKE :query'
142
            )
143
                ->setParameter('query', '%'.addcslashes($query, '\\%_').'%')
144
                ->addOrderBy('p.id', 'DESC');
145
    }
146
147
    public function getFindByIdIn($ids)
148
    {
149
        return $this->createQueryBuilder('p')
150
                ->where('p.id in(:ids)')
151
                ->setParameters(compact('ids'))
152
                ->addOrderBy('p.id', 'desc');
153
    }
154
155
    public function findOneByEmail($email)
156
    {
157
        return $this->createQueryBuilder('p')
158
            ->where('p.email = :email')
159
            ->orWhere('p.emailCanonical = :email')
160
            ->setParameter('email', $email)
161
            ->getQuery()->getOneOrNullResult();
162
    }
163
164
    /**
165
     * @return \Doctrine\ORM\QueryBuilder
166
     */
167
    private function getBaseSearchQuery()
168
    {
169
        return $this->createQueryBuilder('p')
170
            ->addOrderBy('p.id', 'DESC');
171
    }
172
173
    public function getCpfSearchQuery($cpf)
174
    {
175
        return $this->getBaseSearchQuery()
176
            ->where('p.cpf = :cpf')
177
            ->setParameter('cpf', $cpf);
178
    }
179
180
    public function getEmailSearchQuery($email)
181
    {
182
        return $this->getBaseSearchQuery()
183
            ->where('p.emailCanonical = LOWER(:email)')
184
            ->setParameter('email', $email);
185
    }
186
187
    public function getNameSearchQuery($name)
188
    {
189
        $sanitized = addcslashes($name, "%_");
190
191
        return $this->getBaseSearchQuery()
192
            ->where('LowerUnaccent(p.username) LIKE LowerUnaccent(:name)')
193
            ->orWhere('LowerUnaccent(p.firstName) LIKE LowerUnaccent(:name)')
194
            ->orWhere('LowerUnaccent(p.surname) LIKE LowerUnaccent(:name)')
195
            ->setParameter('name', "%{$sanitized}%");
196
    }
197
198
    /**
199
     * This will return the appropriate query for the input given.
200
     * @param $query
201
     * @return \Doctrine\ORM\QueryBuilder
202
     */
203
    public function getSmartSearchQuery($query)
204
    {
205
        $query = trim($query);
206
207
        if (strlen($query) == 0) {
208
            return $this->getBaseSearchQuery();
209
        }
210
211
        $cpfRegex = '/^(?:\d{3}\.?){2}\d{3}-?\d{2}$/';
212
        // Check CPF
213
        if (preg_match($cpfRegex, $query) === 1) {
214
            $cpf = str_replace(['.', '-'], '', $query);
215
216
            return $this->getCpfSearchQuery($cpf);
217
        }
218
219
        // Check email
220
        $emailValidator = new EmailValidator();
221
        if ($emailValidator->isValid($query)) {
222
            return $this->getEmailSearchQuery($query);
223
        }
224
225
        // Defaults to name search
226
        return $this->getNameSearchQuery($query);
227
    }
228
}
229