UserRepository   A
last analyzed

Complexity

Total Complexity 29

Size/Duplication

Total Lines 198
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 96
dl 0
loc 198
rs 10
c 0
b 0
f 0
wmc 29

14 Methods

Rating   Name   Duplication   Size   Complexity  
A getByEmailAndAuthMethod() 0 14 1
A orderByFromArray() 0 8 2
A count() 0 11 2
B queryBySearchForm() 0 28 8
A paginatedQuery() 0 10 1
A searchActiveUser() 0 15 2
A setApproved() 0 4 1
A makeQueryBuilder() 0 19 4
A query() 0 8 1
A __construct() 0 3 1
A countDuplicateUnames() 0 13 2
A findAllAsIterable() 0 5 1
A findByUids() 0 8 1
A getSearchResults() 0 18 2
1
<?php
2
3
declare(strict_types=1);
4
5
/*
6
 * This file is part of the Zikula package.
7
 *
8
 * Copyright Zikula - https://ziku.la/
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
14
namespace Zikula\UsersBundle\Repository;
15
16
use DateTime;
17
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
18
use Doctrine\Common\Collections\ArrayCollection;
19
use Doctrine\ORM\Query\Expr\OrderBy;
20
use Doctrine\Persistence\ManagerRegistry;
21
use Zikula\CoreBundle\Doctrine\Paginator;
0 ignored issues
show
Bug introduced by
The type Zikula\CoreBundle\Doctrine\Paginator was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
22
use Zikula\CoreBundle\Doctrine\WhereFromFilterTrait;
23
use Zikula\UsersBundle\Entity\User;
24
use Zikula\UsersBundle\UsersConstant;
25
26
class UserRepository extends ServiceEntityRepository implements UserRepositoryInterface
27
{
28
    use WhereFromFilterTrait;
29
30
    public function __construct(ManagerRegistry $registry)
31
    {
32
        parent::__construct($registry, User::class);
33
    }
34
35
    public function findByUids(array $userIds = []): array
36
    {
37
        // using queryBuilder allows to index collection by the uid
38
        $qb = $this->createQueryBuilder('u', 'u.uid')
39
            ->where('u.uid IN (:uids)')
40
            ->setParameter('uids', $userIds);
41
42
        return $qb->getQuery()->getResult();
43
    }
44
45
    public function setApproved(User $user, DateTime $approvedOn, int $approvedBy = null): void
46
    {
47
        $user->setApprovedDate($approvedOn);
48
        $user->setApprovedBy($approvedBy ?? $user->getUid());
0 ignored issues
show
Bug introduced by
The method getUid() does not exist on Zikula\UsersBundle\Entity\User. ( Ignorable by Annotation )

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

48
        $user->setApprovedBy($approvedBy ?? $user->/** @scrutinizer ignore-call */ getUid());

This check looks for calls to methods that do not seem to exist on a given type. It looks for the method on the type itself as well as in inherited classes or implemented interfaces.

This is most likely a typographical error or the method has been renamed.

Loading history...
49
    }
50
51
    public function queryBySearchForm(array $formData = [])
52
    {
53
        $filter = [];
54
        foreach ($formData as $k => $v) {
55
            if (!empty($v)) {
56
                switch ($k) {
57
                    case 'registered_before':
58
                        $filter['registrationDate'] = ['operator' => '<=', 'operand' => $v];
59
                        break;
60
                    case 'registered_after':
61
                        $filter['registrationDate'] = ['operator' => '>=', 'operand' => $v];
62
                        break;
63
                    case 'groups':
64
                        /** @var ArrayCollection $v */
65
                        if (!$v->isEmpty()) {
66
                            $filter['groups'] = ['operator' => 'in', 'operand' => $v->getValues()];
67
                        }
68
                        break;
69
                    case 'activated':
70
                        $filter['activated'] = ['operator' => '=', 'operand' => $v];
71
                        break;
72
                    default:
73
                        $filter[$k] = ['operator' => 'like', 'operand' => '%' . $v . '%'];
74
                }
75
            }
76
        }
77
78
        return $this->query($filter);
79
    }
80
81
    public function getSearchResults(array $words = [])
82
    {
83
        $qb = $this->createQueryBuilder('u')
84
            ->andWhere('u.activated != :activated')
85
            ->setParameter('activated', UsersConstant::ACTIVATED_PENDING_REG);
86
        $where = $qb->expr()->orX();
87
        $i = 1;
88
        foreach ($words as $word) {
89
            $subWhere = $qb->expr()->orX();
90
            $expr = $qb->expr()->like('u.uname', '?' . $i);
91
            $subWhere->add($expr);
92
            $qb->setParameter($i, '%' . $word . '%');
93
            $i++;
94
            $where->add($subWhere);
95
        }
96
        $qb->andWhere($where);
97
98
        return $qb->getQuery()->getResult();
99
    }
100
101
    private function makeQueryBuilder(
102
        array $filter = [],
103
        array $sort = [],
104
        string $exprType = 'and'
105
    ) {
106
        $qb = $this->createQueryBuilder('u')
107
            ->select('u');
108
        if (!empty($filter['groups'])) {
109
            $qb->join('u.groups', 'g');
110
        }
111
        if (!empty($filter)) {
112
            $where = $this->whereFromFilter($qb, $filter, $exprType);
113
            $qb->andWhere($where);
114
        }
115
        if (!empty($sort)) {
116
            $qb->orderBy($this->orderByFromArray($sort));
117
        }
118
119
        return $qb;
120
    }
121
122
    public function query(
123
        array $filter = [],
124
        array $sort = [],
125
        string $exprType = 'and'
126
    ) {
127
        $qb = $this->makeQueryBuilder($filter, $sort, $exprType);
128
129
        return $qb->getQuery()->getResult();
130
    }
131
132
    public function paginatedQuery(
133
        array $filter = [],
134
        array $sort = [],
135
        string $exprType = 'and',
136
        int $page = 1,
137
        int $pageSize = 25
138
    ) {
139
        $qb = $this->makeQueryBuilder($filter, $sort, $exprType);
140
141
        return (new Paginator($qb, $pageSize))->paginate($page);
142
    }
143
144
    public function count(array $filter = [], string $exprType = 'and'): int
145
    {
146
        $qb = $this->createQueryBuilder('u')
147
            ->select('count(u.uid)');
148
        if (!empty($filter)) {
149
            $where = $this->whereFromFilter($qb, $filter, $exprType);
150
            $qb->andWhere($where);
151
        }
152
        $query = $qb->getQuery();
153
154
        return (int) $query->getSingleScalarResult();
155
    }
156
157
    /**
158
     * Construct a QueryBuilder Expr\OrderBy object suitable for use in QueryBuilder->orderBy() from an array.
159
     * sort = [field => dir, field => dir, ...]
160
     */
161
    private function orderByFromArray(array $sort = []): OrderBy
162
    {
163
        $orderBy = new OrderBy();
164
        foreach ($sort as $field => $direction) {
165
            $orderBy->add('u.' . $field, $direction);
166
        }
167
168
        return $orderBy;
169
    }
170
171
    public function findAllAsIterable(): iterable
172
    {
173
        $qb = $this->createQueryBuilder('u');
174
175
        return $qb->getQuery()->toIterable();
176
    }
177
178
    public function searchActiveUser(array $unameFilter = [])
179
    {
180
        if (!count($unameFilter)) {
181
            return [];
182
        }
183
184
        $filter = [
185
            'activated' => ['operator' => 'notIn', 'operand' => [
186
                UsersConstant::ACTIVATED_PENDING_REG,
187
                UsersConstant::ACTIVATED_PENDING_DELETE
188
            ]],
189
            'uname' => $unameFilter
190
        ];
191
192
        return $this->query($filter, ['uname' => 'asc']);
193
    }
194
195
    public function countDuplicateUnames(string $uname, ?int $uid = null): int
196
    {
197
        $qb = $this->createQueryBuilder('u');
198
        $qb->select('count(u.uid)')
199
            ->where($qb->expr()->eq('LOWER(u.uname)', ':uname'))
200
            ->setParameter('uname', mb_strtolower($uname));
201
        // when updating an existing User, the existing Uid must be excluded.
202
        if (isset($uid)) {
203
            $qb->andWhere('u.uid != :excludedUid')
204
                ->setParameter('excludedUid', $uid);
205
        }
206
207
        return (int) $qb->getQuery()->getSingleScalarResult();
208
    }
209
210
    public function getByEmailAndAuthMethod(string $email, string $authMethod): array
211
    {
212
        $qb = $this->createQueryBuilder('u');
213
        $qb->join('u.attributes', 'a')
214
            ->where('u.email = :email')
215
            ->setParameter('email', $email)
216
            ->andWhere($qb->expr()->andX(
217
                $qb->expr()->eq('a.name', ':attributeName'),
218
                $qb->expr()->neq('a.value', ':authMethod')
219
            ))
220
            ->setParameter('attributeName', UsersConstant::AUTHENTICATION_METHOD_ATTRIBUTE_KEY)
0 ignored issues
show
Bug introduced by
The constant Zikula\UsersBundle\Users...ON_METHOD_ATTRIBUTE_KEY was not found. Maybe you did not declare it correctly or list all dependencies?
Loading history...
221
            ->setParameter('authMethod', $authMethod);
222
223
        return $qb->getQuery()->getArrayResult();
224
    }
225
}
226