-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserRepository.php
More file actions
608 lines (555 loc) · 21.2 KB
/
UserRepository.php
File metadata and controls
608 lines (555 loc) · 21.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
<?php
declare(strict_types=1);
namespace AppBundle\Association\Model\Repository;
use AppBundle\Association\MemberType;
use AppBundle\Association\Model\CompanyMember;
use AppBundle\Association\Model\User;
use AppBundle\Event\Model\Badge;
use Aura\SqlQuery\Common\SelectInterface;
use CCMBenchmark\Ting\Driver\Mysqli\Serializer\Boolean;
use CCMBenchmark\Ting\Repository\CollectionInterface;
use CCMBenchmark\Ting\Repository\HydratorSingleObject;
use CCMBenchmark\Ting\Repository\Metadata;
use CCMBenchmark\Ting\Repository\MetadataInitializer;
use CCMBenchmark\Ting\Repository\Repository;
use CCMBenchmark\Ting\Serializer\SerializerFactoryInterface;
use Exception;
use InvalidArgumentException;
use RuntimeException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UserNotFoundException;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\PasswordUpgraderInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Webmozart\Assert\Assert;
/**
* @extends Repository<User>
*/
class UserRepository extends Repository implements MetadataInitializer, UserProviderInterface, PasswordUpgraderInterface
{
public function loadUserByIdentifier(string $identifier): User
{
return $this->loadUserByUsername($identifier);
}
public function loadUserByUsername(string $username): User
{
$queryBuilder = $this->getQueryBuilderWithCompleteUser();
$queryBuilder
->where('app.`login` = :username')
->orWhere('app.`email` = :email')
;
$result = $this
->getPreparedQuery($queryBuilder->getStatement())
->setParams([
'username' => $username,
'email' => $username,
])
->query($this->getCollection($this->getHydratorForUser()));
if ($result->count() === 0) {
throw new UserNotFoundException(sprintf('Could not find the user with login "%s"', $username));
}
return $result->first();
}
/**
* @param User $user
*/
public function upgradePassword(PasswordAuthenticatedUserInterface $user, string $newHashedPassword): void
{
$user->setPassword($newHashedPassword);
$this->save($user);
}
public function loadUserByEmailOrAlternateEmail($email)
{
$queryBuilder = $this->getQueryBuilderWithCompleteUser();
$queryBuilder
->where('app.`email` = :email')
->orWhere('app.`slack_alternate_email` = :slack_alternate_email')
;
$result = $this
->getPreparedQuery($queryBuilder->getStatement())
->setParams([
'email' => $email,
'slack_alternate_email' => $email,
])
->query($this->getCollection($this->getHydratorForUser()));
if ($result->count() === 0) {
throw new UserNotFoundException(sprintf('Could not find the user with email "%s"', $email));
}
return $result->first();
}
public function loadUserByHash($hash)
{
$queryBuilder = $this->getQueryBuilderWithCompleteUser();
$queryBuilder
->having('hash = :hash')
;
$result = $this
->getPreparedQuery($queryBuilder->getStatement())
->setParams([
'hash' => $hash,
])
->query($this->getCollection($this->getHydratorForUser()));
if ($result->count() === 0) {
throw new UserNotFoundException(sprintf('Could not find the user with hash "%s"', $hash));
}
return $result->first();
}
public function loadActiveUsersByCompany(CompanyMember $companyMember)
{
$queryBuilder = $this->getQueryBuilderWithCompleteUser();
$queryBuilder
->where('apm.id = :company')
->where('app.etat = :state')
;
return $this
->getPreparedQuery($queryBuilder->getStatement())
->setParams([
'company' => $companyMember->getId(),
'state' => User::STATUS_ACTIVE,
])
->query($this->getCollection($this->getHydratorForUser()))
;
}
/**
* @return CollectionInterface|User[]
*
* @throws \CCMBenchmark\Ting\Exception
*/
public function loadAll()
{
$queryBuilder = $this->getQueryBuilderWithCompleteUser();
return $this
->getQuery($queryBuilder->getStatement())
->query($this->getCollection($this->getHydratorForUser()))
;
}
public function loadByBadge(Badge $badge)
{
$queryBuilder = $this->getQueryBuilderWithCompleteUser();
$queryBuilder->join('INNER', 'afup_personnes_physiques_badge', 'app.id = afup_personnes_physiques_badge.afup_personne_physique_id');
$queryBuilder->where('afup_personnes_physiques_badge.badge_id = :badge_id');
return $this
->getPreparedQuery($queryBuilder->getStatement())
->setParams(['badge_id' => $badge->getId()])
->query($this->getCollection($this->getHydratorForUser()))
;
}
/**
* Renvoie la liste des personnes physiques
*
* @param bool $onlyActive
* @param string $sort Tri des enregistrements
* @param int|int[] $userId
*
* @return CollectionInterface&iterable<User>
*/
public function search(
$sort = 'lastname',
$direction = 'asc',
$filter = null,
$companyId = null,
$userId = null,
$onlyActive = true,
$isCompanyManager = null,
$needsUptoDateMembership = null,
) {
Assert::inArray($direction, ['asc', 'desc']);
$sorts = [
'lastname' => ['nom', 'prenom'],
'firstname' => ['prenom', 'nom'],
'status' => ['etat','nom', 'prenom'],
];
Assert::keyExists($sorts, $sort);
$queryBuilder = $this->getQueryBuilderWithCompleteUser()
->orderBy(array_map(static fn($field): string => $field . ' ' . $direction, $sorts[$sort]));
// On filtre sur tous les mots possibles. Donc plus on a de mots dans la recherche plus on aura de résultats.
// Mais ça peut aussi permettre de trouver des personnes en entrant par exemple "Prénom email" dans le champ de recherche :
// Même si l'email ne colle pas on pourra trouver la personne.
// C'est un peu barbare mais généralement on ne met qu'un seul terme dans la recherche… du coup c'est pas bien grave.
if ($filter) {
$filters = explode(' ', (string) $filter);
$filters = array_filter(array_map('trim', $filters));
$ors = [];
foreach ($filters as $i => $value) {
$ors[] = "LOWER(app.login) LIKE LOWER(:filter$i) OR LOWER(app.nom) LIKE LOWER(:filter$i) OR LOWER(app.prenom) LIKE LOWER(:filter$i)
OR app.code_postal LIKE :filter$i OR LOWER(app.ville) LIKE LOWER(:filter$i) OR LOWER(app.email) LIKE LOWER(:filter$i)";
$queryBuilder->bindValue('filter' . $i, '%' . $value . '%');
}
$queryBuilder->where('(' . implode(' OR ', $ors) . ')');
}
if ($companyId) {
$queryBuilder->where('app.id_personne_morale = :companyId')
->bindValue('companyId', $companyId);
}
if ($userId) {
if (!is_array($userId)) {
$userId = [$userId];
}
$queryBuilder->where('app.id IN (:userIds)')
->bindValue('userIds', $userId);
}
if ($onlyActive) {
$queryBuilder->where('app.etat = :status')
->bindValue('status', User::STATUS_ACTIVE);
}
if ($isCompanyManager) {
$queryBuilder->where('app.roles LIKE \'%ROLE_COMPANY_MANAGER%\'');
}
if ($needsUptoDateMembership) {
$queryBuilder->where('app.needs_up_to_date_membership = 1');
}
return $this
->getQuery($queryBuilder->getStatement())
->setParams($queryBuilder->getBindValues())
->query($this->getCollection($this->getHydratorForUser()));
}
/**
* Ajoute une personne physique
*/
public function create(User $user): void
{
if ($this->loginExists($user->getUsername())) {
throw new InvalidArgumentException('Il existe déjà un compte pour ce login.');
}
if ($this->emailExists($user->getEmail())) {
throw new InvalidArgumentException('Il existe un compte avec cette adresse email.');
}
if (0 !== $user->getCompanyId() && !$this->companyExists($user->getCompanyId())) {
throw new InvalidArgumentException('La personne morale n\'existe pas.');
}
if (!$this->countryExists($user->getCountry())) {
throw new InvalidArgumentException('Le pays n\'existe pas.');
}
try {
$this->save($user);
} catch (Exception $e) {
throw new RuntimeException("Impossible d'enregistrer l'utilisateur à cause d'une erreur SQL. Veuillez contacter le bureau !", $e->getCode(), $e);
}
}
/**
* @param string $login Person's login
* @param int $id Identifier to ignore
*
* @return bool Login in use (TRUE) or not (FALSE)
*/
public function loginExists($login, $id = 0): bool
{
return 0 < $this->getQuery('SELECT 1 FROM afup_personnes_physiques WHERE login = :login AND id <> :id')
->setParams(['login' => $login, 'id' => $id])
->query()->count();
}
public function edit(User $user): void
{
if ($this->loginExists($user->getUsername(), $user->getId())) {
throw new InvalidArgumentException('Il existe déjà un compte pour ce login.');
}
if (0 !== $user->getCompanyId() && !$this->companyExists($user->getCompanyId())) {
throw new InvalidArgumentException('La personne morale n\'existe pas.');
}
if (!$this->countryExists($user->getCountry())) {
throw new InvalidArgumentException('Le pays n\'existe pas.');
}
$this->save($user);
}
public function remove(User $user): void
{
$nbCotisations = (int) $this->getQuery('SELECT COUNT(*) nb FROM afup_cotisations WHERE type_personne = :memberType AND id_personne = :id')
->setParams(['memberType' => MemberType::MemberPhysical->value, 'id' => $user->getId()])
->query()->first()[0]->nb;
if (0 < $nbCotisations) {
throw new InvalidArgumentException('Impossible de supprimer une personne physique qui a des cotisations');
}
$this->delete($user);
}
/**
* @return CollectionInterface&iterable<User>
*/
public function getAdministrators()
{
$queryBuilder = $this->getQueryBuilderWithCompleteUser()
->where('niveau_modules <> 0 OR niveau = :level')
->orderBy(['nom', 'prenom']);
$queryBuilder->bindValue('level', User::LEVEL_ADMIN);
return $this
->getQuery($queryBuilder->getStatement())
->setParams($queryBuilder->getBindValues())
->query($this->getCollection($this->getHydratorForUser()));
}
/**
* @param string $email Person's email
* @param int $id Identifier to ignore
*
* @return bool TRUE if the email exists, FALSE otherwise
*/
private function emailExists($email, $id = 0): bool
{
return 0 < $this->getQuery('SELECT 1 FROM afup_personnes_physiques WHERE email = :email AND id <> :id')
->setParams(['email' => $email, 'id' => $id])
->query()->count();
}
/**
* @param int $companyId Company's identifier
*
* @return bool TRUE if the company exists, FALSE otherwise
*/
private function companyExists($companyId): bool
{
return 0 < $this->getQuery('SELECT 1 FROM afup_personnes_morales WHERE id = :id')
->setParams(['id' => $companyId])
->query()->count();
}
/**
* @param string $countryId Country's identifier
*
* @return bool TRUE if the country exists, FALSE otherwise
*/
private function countryExists(string $countryId): bool
{
return 0 < $this->getQuery('SELECT 1 FROM afup_pays WHERE id = :id')
->setParams(['id' => $countryId])
->query()->count();
}
/**
* @return SelectInterface
*/
private function getQueryBuilderWithSubscriptions()
{
/**
* @var SelectInterface $queryBuilder
*/
$queryBuilder = $this->getQueryBuilder(self::QUERY_SELECT);
$queryBuilder
->cols([
'app.`id`', 'app.`login`', 'app.`prenom`', 'app.`nom`',
'app.`email`', 'apm.`id`', 'apm.`raison_sociale`', 'apm.`max_members`', 'app.`id_personne_morale`',
])
->from('afup_personnes_physiques app')
->join('LEFT', 'afup_personnes_morales apm', 'apm.id = app.id_personne_morale')
->join('LEFT', 'afup_cotisations ac', 'ac.type_personne = IF(apm.id IS NULL, 0, 1) AND ac.id_personne = IFNULL(apm.id, app.id)')
->groupBy(['app.`id`'])
;
return $queryBuilder;
}
private function getQueryBuilderWithCompleteUser()
{
return $this
->getQueryBuilderWithSubscriptions()
->cols([
'app.`id`', 'app.`id_personne_morale`', 'app.`login`', 'app.`mot_de_passe`', 'app.`niveau`',
'app.`niveau_modules`', 'app.`roles`', 'app.`civilite`', 'app.`nom`', 'app.`prenom`', 'app.`email`',
'app.`adresse`', 'app.`code_postal`', 'app.`ville`', 'app.`id_pays`', 'app.`telephone_fixe`',
'app.`telephone_portable`', 'app.`etat`', 'app.`date_relance`', 'app.`compte_svn`',
'app.`slack_invite_status`', 'app.`slack_alternate_email`', 'app.`needs_up_to_date_membership`',
'app.`nearest_office`',
'MD5(CONCAT(app.`id`, \'_\', app.`email`, \'_\', app.`login`)) as hash',
"MAX(ac.date_fin) AS lastsubcription",
]);
}
/**
* Add a condition about the type of users: physical, legal or all
*
* @param $userType
*/
private function addUserTypeCondition(SelectInterface $queryBuilder, ?MemberType $userType): void
{
if ($userType === MemberType::MemberPhysical) {
$queryBuilder->where('id_personne_morale = 0');
} elseif ($userType === MemberType::MemberCompany) {
$queryBuilder->where('id_personne_morale <> 0');
}
}
private function getHydratorForUser()
{
return (new HydratorSingleObject())
->mapAliasTo('lastsubcription', 'app', 'setLastSubscription')
->mapAliasTo('hash', 'app', 'setHash')
->mapObjectTo('apm', 'app', 'setCompany')
;
}
/**
* Retrieve all users by the date of end of membership.
*
* @return CollectionInterface
*/
public function getActiveMembers()
{
$today = new \DateTimeImmutable();
$queryBuilder = $this->getQueryBuilderWithSubscriptions();
$queryBuilder
->where('app.`etat` = :status')
;
return $this
->getPreparedQuery($queryBuilder->getStatement())
->setParams([
'start' => $today->format('U'),
'status' => User::STATUS_ACTIVE,
])
->query($this->getCollection(new HydratorSingleObject()));
}
/**
* Retrieve all users by the date of end of membership.
*
* @return CollectionInterface
*/
public function getUsersByEndOfMembership(\DateTimeImmutable $endOfSubscription, ?MemberType $userType = null)
{
$startOfDay = $endOfSubscription->setTime(0, 0, 0);
$endOfDay = $endOfSubscription->setTime(23, 59, 59);
$queryBuilder = $this->getQueryBuilderWithSubscriptions();
$queryBuilder
->where('app.`etat` = :status')
->having('MAX(ac.`date_fin`) BETWEEN :start AND :end')
;
$this->addUserTypeCondition($queryBuilder, $userType);
return $this
->getPreparedQuery($queryBuilder->getStatement())
->setParams([
'start' => $startOfDay->format('U'),
'end' => $endOfDay->format('U'),
'status' => User::STATUS_ACTIVE,
])
->query($this->getCollection(new HydratorSingleObject()));
}
public function refreshUser(UserInterface $user): UserInterface
{
if ($this->supportsClass($user::class) === false) {
throw new UnsupportedUserException(sprintf('Instance of %s not supported', $user::class));
}
return $this->loadUserByUsername($user->getUserIdentifier());
}
public function supportsClass(string $class): bool
{
return $class === User::class;
}
/**
* @inheritDoc
*/
public static function initMetadata(SerializerFactoryInterface $serializerFactory, array $options = [])
{
$metadata = new Metadata($serializerFactory);
$metadata->setEntity(User::class);
$metadata->setConnectionName('main');
$metadata->setDatabase($options['database']);
$metadata->setTable('afup_personnes_physiques');
$metadata
->addField([
'columnName' => 'id',
'fieldName' => 'id',
'primary' => true,
'autoincrement' => true,
'type' => 'int',
])
->addField([
'columnName' => 'id_personne_morale',
'fieldName' => 'companyId',
'type' => 'int',
])
->addField([
'columnName' => 'login',
'fieldName' => 'username',
'type' => 'string',
])
->addField([
'columnName' => 'mot_de_passe',
'fieldName' => 'password',
'type' => 'string',
])
->addField([
'columnName' => 'civilite',
'fieldName' => 'civility',
'type' => 'string',
])
->addField([
'columnName' => 'prenom',
'fieldName' => 'firstName',
'type' => 'string',
])
->addField([
'columnName' => 'nom',
'fieldName' => 'lastName',
'type' => 'string',
])
->addField([
'columnName' => 'email',
'fieldName' => 'email',
'type' => 'string',
])
->addField([
'columnName' => 'niveau',
'fieldName' => 'level',
'type' => 'string',
])
->addField([
'columnName' => 'niveau_modules',
'fieldName' => 'levelModules',
'type' => 'string',
])
->addField([
'columnName' => 'roles',
'fieldName' => 'roles',
'type' => 'json',
'serializer_options' => [
'unserialize' => ['assoc' => true],
],
])
->addField([
'columnName' => 'adresse',
'fieldName' => 'address',
'type' => 'string',
])
->addField([
'columnName' => 'code_postal',
'fieldName' => 'zipCode',
'type' => 'string',
])
->addField([
'columnName' => 'ville',
'fieldName' => 'city',
'type' => 'string',
])
->addField([
'columnName' => 'id_pays',
'fieldName' => 'country',
'type' => 'string',
])
->addField([
'columnName' => 'telephone_fixe',
'fieldName' => 'phone',
'type' => 'string',
])
->addField([
'columnName' => 'telephone_portable',
'fieldName' => 'mobilephone',
'type' => 'string',
])
->addField([
'columnName' => 'nearest_office',
'fieldName' => 'nearestOffice',
'type' => 'string',
])
->addField([
'columnName' => 'etat',
'fieldName' => 'status',
'type' => 'int',
])
->addField([
'columnName' => 'slack_invite_status',
'fieldName' => 'slackInviteStatus',
'type' => 'int',
])
->addField([
'columnName' => 'slack_alternate_email',
'fieldName' => 'alternateEmail',
'type' => 'string',
])
->addField([
'columnName' => 'needs_up_to_date_membership',
'fieldName' => 'needsUpToDateMembership',
'type' => 'bool',
'serializer' => Boolean::class,
])
;
return $metadata;
}
}