Failed Conditions
Push — master ( 371c79...c194c4 )
by Sylvain
07:44
created

Importer::insertBookables()   B

Complexity

Conditions 4
Paths 8

Size

Total Lines 76
Code Lines 56

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 20

Importance

Changes 0
Metric Value
cc 4
eloc 56
nc 8
nop 0
dl 0
loc 76
ccs 0
cts 60
cp 0
crap 20
rs 8.9599
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
3
declare(strict_types=1);
4
5
namespace Application\Service;
6
7
use Doctrine\DBAL\Driver\PDOConnection;
8
use Doctrine\ORM\EntityManager;
9
use Interop\Container\ContainerInterface;
10
11
class Importer
12
{
13
    /**
14
     * @var ContainerInterface
15
     */
16
    private $container;
17
18
    /**
19
     * @var EntityManager
20
     */
21
    private $entityManager;
22
23
    /**
24
     * @var PDOConnection
25
     */
26
    private $filemaker;
27
28
    /**
29
     * @var PDOConnection
30
     */
31
    private $typo3;
32
33
    /**
34
     * @var array
35
     */
36
    private $members = [];
37
38
    /**
39
     * @var array
40
     */
41
    private $users = [];
42
43
    /**
44
     * Storage requests
45
     *
46
     * @var array
47
     */
48
    private $storage = [];
49
50
    /**
51
     * Allocated storage
52
     * [idBookable] => number of bookings
53
     *
54
     * @var array
55
     */
56
    private $storageAllocated = [];
57
58
    /**
59
     * Import constructor
60
     */
61
    public function __construct(ContainerInterface $container, EntityManager $entityManager)
62
    {
63
        $this->container = $container;
64
        $this->entityManager = $entityManager;
65
    }
66
67
    /**
68
     * Import the members from FileMaker and TYPO3
69
     */
70
    public function import(): void
71
    {
72
        $this->loadMembers();
73
        $this->loadPeople();
74
//        $this->deleteTestUsers();
75
        $this->loadStorageRequests();
76
        $this->insertBookables();
77
        $this->insertUsers();
78
        $this->insertBookings();
79
    }
80
81
    /**
82
     * @return PDOConnection
83
     */
84
    private function connectFileMaker(): PDOConnection
85
    {
86
        if ($this->filemaker) {
87
            return $this->filemaker;
88
        }
89
        $config = $this->container->get('config');
90
91
        $dsn = sprintf('odbc:Driver={%s};Server=%s;Database=%s;charset=UTF-8', $config['filemaker']['driver'], $config['filemaker']['host'], $config['filemaker']['dbname']);
92
        $this->filemaker = new PDOConnection($dsn, $config['filemaker']['user'], $config['filemaker']['password']);
93
94
        return $this->filemaker;
95
    }
96
97
    /**
98
     * @return PDOConnection
99
     */
100
    private function connectTypo3(): PDOConnection
101
    {
102
        if ($this->typo3) {
103
            return $this->typo3;
104
        }
105
        $config = $this->container->get('config');
106
107
        $this->typo3 = new PDOConnection(sprintf('mysql:host=%s;port=%u;dbname=%s', $config['typo3']['host'], $config['typo3']['port'], $config['typo3']['dbname']), $config['typo3']['user'], $config['typo3']['password']);
108
109
        return $this->typo3;
110
    }
111
112
    /**
113
     * Load members from FileMaker "ichtus" table into memory
114
     */
115
    private function loadMembers(): void
116
    {
117
        $this->connectFileMaker();
118
        $query = <<<EOT
119
          SELECT ID_membre,
120
               "nom_prénom",
121
               "date_entrée ichtus",
122
               remarques,
123
               "liens de famille",
124
               "date_séance d'accueil",
125
               "date_formulaire_adhésion",
126
               membre_new,
127
               membre_actif,
128
               membre_suspension,
129
               "membre_archivé",
130
               assurances,
131
               envoi_papier
132
          FROM ichtus
133
          WHERE ((membre_new>0 AND "date_formulaire_adhésion">=DATE '2018-10-01') OR membre_actif>0 OR membre_suspension>0) AND "membre_archivé"=0 AND remarques NOT LIKE '%Ignorer%'
134
EOT;
135
        $statement = $this->filemaker->prepare(trim($query));
136
        if ($statement->execute()) {
137
            echo sprintf('%u membres à importer...', $statement->rowCount()) . PHP_EOL;
138
            foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $member) {
139
                foreach ($member as $fieldName => $fieldValue) {
140
                    $member[$fieldName] = $this->fromMacRoman($fieldValue);
141
                }
142
                $this->members[$member['ID_membre']] = $member;
143
                echo sprintf('Membre %u importé', $member['ID_membre']) . PHP_EOL;
144
            }
145
        }
146
    }
147
148
    /**
149
     * Load people from TYPO3 fe_users into memory
150
     */
151
    private function loadPeople(): void
152
    {
153
        $this->connectTypo3();
154
        $query = <<<EOT
155
          SELECT *
156
          FROM fe_users
157
          WHERE FIND_IN_SET(CAST(family_uid as char), :members) AND status_archived=0;
158
EOT;
159
        $statement = $this->typo3->prepare($query);
160
        $statement->bindValue(':members', implode(',', array_keys($this->members)));
161
162
        if ($statement->execute()) {
163
            echo sprintf('%u individus à importer...', $statement->rowCount()) . PHP_EOL;
164
            $withoutLoginCount = 0;
165
            foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $user) {
166
                if (($user['family_status'] === 'chef de famille' || $user['family_status'] === 'chef(fe) de famille') && $user['uid'] !== $user['family_uid']) {
167
                    echo sprintf('WARN: utilisateur %u ne devrait pas être de chef de la famille %u', $user['uid'], $user['family_uid']) . PHP_EOL;
168
                }
169
                if (empty($user['new_username'])) {
170
                    echo sprintf("WARN: utilisateur %u (%s %s) n'a pas de login MyIchtus", $user['uid'], $user['first_name'], $user['last_name']) . PHP_EOL;
171
                    ++$withoutLoginCount;
172
                }
173
                $this->users[$user['uid']] = $user;
174
                echo sprintf('Individu %u importé', $user['uid']) . PHP_EOL;
175
            }
176
            if ($withoutLoginCount > 0) {
177
                echo sprintf('%u individus sans login MyIchtus', $withoutLoginCount) . PHP_EOL;
178
            }
179
        }
180
    }
181
182
    /**
183
     * Create users
184
     */
185
    private function insertUsers(): void
186
    {
187
        $conn = $this->entityManager->getConnection();
188
189
        $insert = <<<EOT
190
                INSERT INTO user(
191
                  id,
192
                  login,
193
                  first_name,
194
                  last_name,
195
                  birthday,
196
                  sex,
197
                  email,
198
                  street,
199
                  postcode,
200
                  locality,
201
                  country_id,
202
                  mobile_phone,
203
                  phone,
204
                  internal_remarks,
205
                  iban,
206
                  has_insurance,
207
                  swiss_sailing,
208
                  swiss_sailing_type,
209
                  swiss_windsurf_type,
210
                  receives_newsletter,
211
                  role,
212
                  family_relationship,
213
                  billing_type,
214
                  welcome_session_date,
215
                  status,
216
                  creation_date
217
                ) VALUES (
218
                  :id,
219
                  :login,
220
                  :first_name,
221
                  :last_name,
222
                  :birthday,
223
                  :sex,
224
                  :email,
225
                  :street,
226
                  :postcode,
227
                  :locality,
228
                  :country_id,
229
                  :mobile_phone,
230
                  :phone,
231
                  :remarks,
232
                  :iban,
233
                  :has_insurance,
234
                  :swiss_sailing,
235
                  :swiss_sailing_type,
236
                  :swiss_windsurf_type,
237
                  :receives_newsletter,
238
                  :role,
239
                  :family_relationship,
240
                  :billing_type,
241
                  :welcome_session_date,
242
                  :status,
243
                  :creation_date
244
                )
245
EOT;
246
        $insert = $conn->prepare($insert);
247
248
        $createAccount = <<<EOT
249
                INSERT INTO account(
250
                  owner_id,
251
                  creation_date,
252
                  balance,
253
                  name,
254
                  parent_id,
255
                  type,
256
                  code
257
                ) VALUES (
258
                  :owner,
259
                  NOW(),
260
                  :balance,
261
                  :name,
262
                  10011, -- Passifs -> 2030 Acomptes de clients
263
                  'liability',
264
                  :code
265
                )
266
EOT;
267
        $createAccount = $conn->prepare($createAccount);
268
269
        $linkToTag = $conn->prepare('INSERT INTO user_tag_user(user_tag_id, user_id) VALUES (:user_tag_id, :user_id)');
270
271
        foreach ($this->users as $user) {
272
            echo sprintf('Insert user %u (%s %s)', $user['uid'], $user['first_name'], $user['last_name']) . PHP_EOL;
273
            $insert->bindValue(':id', $user['uid']);
274
            $insert->bindValue(':login', $user['new_username']);
275
            $insert->bindValue(':first_name', $user['first_name']);
276
            $insert->bindValue(':last_name', $user['last_name']);
277
            $insert->bindValue(':birthday', $user['date_birth'] !== null && $user['date_birth'] !== '0000-00-00' ? $user['date_birth'] : null);
278
            $insert->bindValue(':sex', $user['sexe'] === 'F' ? 2 : 1);
279
            $insert->bindValue(':email', !empty($user['email']) ? $user['email'] : null);
280
            $insert->bindValue(':street', $user['address']);
281
            $insert->bindValue(':postcode', $user['zip']);
282
            $insert->bindValue(':locality', $user['city']);
283
284
            switch ($user['country']) {
285
                case 'CH': $country_id = 1;
286
287
break;
288
                case 'FR': $country_id = 2;
289
290
break;
291
                case 'DE': $country_id = 10;
292
293
break;
294
                case 'CA': $country_id = 6;
295
296
break;
297
                case 'NL': $country_id = 19;
298
299
break;
300
                default:
301
                    $country_id = null;
302
                    echo sprintf("WARN: pas de correspondance pour le code pays %s de l\\'individu %u (%s &s)", $user['country'], $user['uid'], $user['first_name'], $user['last_name']) . PHP_EOL;
303
            }
304
            $insert->bindValue(':country_id', $country_id);
305
306
            $insert->bindValue(':mobile_phone', !empty($user['natel']) ? $user['natel'] : '');
307
            $insert->bindValue(':phone', $user['telephone']);
308
309
            if ($user['uid'] === $user['family_uid']) {
310
                // Si responsable de l'adhésion, fusionne les notes au niveau du membre et de l'individu
311
                $remarks = implode(PHP_EOL, [$this->members[$user['family_uid']]['remarques'], $user['notes']]);
312
            } else {
313
                $remarks = !empty($user['notes']) ? $user['notes'] : '';
314
            }
315
316
            $insert->bindValue(':remarks', $remarks);
317
            $insert->bindValue(':iban', !empty($user['IBAN']) ? $user['IBAN'] : '');
318
319
            $hasInsurance = false;
320
            if (empty($this->members[$user['family_uid']]['assurances'])) {
321
                echo sprintf('WARN: membre %u n\'a aucune assurance', $user['family_uid']) . PHP_EOL;
322
            } elseif (mb_strpos($this->members[$user['family_uid']]['assurances'], 'RC privée') !== false) {
323
                $hasInsurance = true;
324
            }
325
            $insert->bindValue(':has_insurance', $hasInsurance);
326
327
            $insert->bindValue(':swiss_sailing', !empty($user['ichtus_swiss_sailing']) ? $user['ichtus_swiss_sailing'] : '');
328
            switch ($user['ichtus_swiss_sailing_type']) {
329
                case 'A': $swissSailingType = 'active';
330
331
break;
332
                case 'P': $swissSailingType = 'passive';
333
334
break;
335
                case 'J': $swissSailingType = 'junior';
336
337
break;
338
                default: $swissSailingType = null;
339
            }
340
            $insert->bindValue(':swiss_sailing_type', $swissSailingType);
341
342
            switch ($user['ichtus_swiss_windsurf_type']) {
343
                case 'A': $swissWindsurfType = 'active';
344
345
break;
346
                case 'P': $swissWindsurfType = 'passive';
347
348
break;
349
                default: $swissWindsurfType = null;
350
            }
351
            $insert->bindValue(':swiss_windsurf_type', $swissWindsurfType);
352
353
            $insert->bindValue(':receives_newsletter', !empty($user['email']) ? 1 : 0);
354
355
            switch ($user['family_status']) {
356
                case 'chef de famille':
357
                    $relationship = 'householder';
358
                    $role = 'member';
359
360
                    break;
361
                case 'chef(fe) de famille':
362
                    $relationship = 'householder';
363
                    $role = 'member';
364
365
                    break;
366
                case 'conjoint':
367
                    $relationship = 'partner';
368
                    $role = 'individual';
369
370
                    break;
371
                case 'enfant':
372
                    $relationship = 'child';
373
                    $role = 'individual';
374
375
                    break;
376
                case 'parent':
377
                    $relationship = 'parent';
378
                    $role = 'individual';
379
380
                    break;
381
                case 'soeur':
382
                    $relationship = 'sister';
383
                    $role = 'individual';
384
385
                    break;
386
                case 'frère':
387
                    $relationship = 'brother';
388
                    $role = 'individual';
389
390
                    break;
391
                case 'beau-frère':
392
                    $relationship = 'brother';
393
                    $role = 'individual';
394
395
                    break;
396
                default:
397
                    $relationship = 'householder';
398
                    $role = 'individual';
399
                    echo sprintf("WARN: individu %u (%s %s) n'a pas de statut familial", $user['uid'], $user['first_name'], $user['last_name']) . PHP_EOL;
400
            }
401
            if (in_array((int) $user['uid'], [1057, 2738], true)) {
402
                $role = 'administrator';
403
            } elseif (!empty($user['ichtus_comite_fonction'])) {
404
                $role = 'responsible';
405
            }
406
            $insert->bindValue(':role', $role);
407
            $insert->bindValue(':family_relationship', $relationship);
408
409
            if ($this->members[$user['family_uid']]['envoi_papier'] && empty($user['email'])) {
410
                $insert->bindValue(':billing_type', 'paper');
411
            } else {
412
                $insert->bindValue(':billing_type', 'electronic');
413
            }
414
            $insert->bindValue(':welcome_session_date', $this->members[$user['family_uid']]["date_séance d'accueil"]);
415
416
            $userStatus = 'new';
417
            if ($user['status_new'] + $user['status_actif'] + $user['status_archived'] > 1) {
418
                echo sprintf('WARN individu %u (%s %s) a plus d\' un statut actif à la fois', $user['uid'], $user['first_name'], $user['last_name']) . PHP_EOL;
419
            }
420
            if ($user['status_actif']) {
421
                $userStatus = 'active';
422
            } elseif ($user['status_archived']) {
423
                $userStatus = 'archived';
424
            }
425
            $insert->bindValue(':status', $userStatus);
426
427
            $insert->bindValue(':creation_date', $this->members[$user['family_uid']]['date_entrée ichtus']);
428
429
            if ($insert->execute() === false) {
430
                echo sprintf('ERROR: création de l\'individu %u (%s %s)', $user['uid'], $user['first_name'], $user['last_name']) . PHP_EOL;
431
432
                continue;
433
            }
434
435
            // Crée un compte débiteur pour le membre
436
            $createAccount->bindValue(':owner', $user['uid']);
437
            $createAccount->bindValue(':name', implode(' ', [$user['first_name'], $user['last_name']]));
438
            $accountNumber = sprintf('2030%04u', $user['uid']); // 2030 (Acomptes de client) & ID User = numéro de compte unique
439
            $createAccount->bindValue(':code', $accountNumber);
440
            $createAccount->bindValue(':balance', 0.00); // Importer le solde des comptes 2018 ?
441
            if ($createAccount->execute() === false) {
442
                echo sprintf('ERROR: échec de création de compte débiteur n°%u pour l\'utilisateur %u (%s %s)', $accountNumber, $user['uid'], $user['first_name'], $user['last_name']) . PHP_EOL;
443
            }
444
445
            // Assigne les tags au membre
446
            if (!empty($user['ichtus_comite_fonction'])) {
447
                $userTagId = $this->insertUserTag($user['ichtus_comite_fonction']);
448
                $linkToTag->bindValue(':user_id', $user['uid']);
449
                $linkToTag->bindValue(':user_tag_id', $userTagId);
450
                $linkToTag->execute();
451
            }
452
        }
453
454
        $updateOwner = $conn->prepare('UPDATE user SET owner_id=:owner WHERE id=:id');
455
        foreach ($this->users as $user) {
456
            if ($user['family_uid'] && $user['family_uid'] !== $user['uid']) {
457
                // Update family ownership
458
                $updateOwner->bindValue(':owner', $user['family_uid']);
459
                $updateOwner->bindValue(':id', $user['uid']);
460
                $updateOwner->execute();
461
            }
462
        }
463
    }
464
465
    public function loadStorageRequests(): void
466
    {
467
        $this->connectTypo3();
468
        $query = 'SELECT * FROM tx_speciality_storage_places';
469
        $statement = $this->typo3->prepare($query);
470
471
        if ($statement->execute()) {
472
            echo sprintf('%u demandes d\'emplacement de stockage à importer...', $statement->rowCount()) . PHP_EOL;
473
            foreach ($statement->fetchAll(\PDO::FETCH_ASSOC) as $request) {
474
                if (!array_key_exists($request['uid_link'], $this->members)) {
475
                    echo sprintf('WARN: demande de stockage %u pour membre %u (%s %s) introuvable', $request['uid'], $request['uid_link'], $request['first_name'], $request['last_name']) . PHP_EOL;
476
                }
477
                $this->storage[$request['uid_link']] = $request;
478
            }
479
        }
480
    }
481
482
    /**
483
     * Create bookables (storage lockers, cabinets, space for boats)
484
     */
485
    private function insertBookables(): void
486
    {
487
        $conn = $this->entityManager->getConnection();
488
489
        $insert = <<<EOT
490
                INSERT INTO bookable(
491
                  code,
492
                  name,
493
                  description,
494
                  initial_price,
495
                  periodic_price,
496
                  simultaneous_booking_maximum,
497
                  booking_type,
498
                  creation_date
499
                ) VALUES (
500
                  :code,
501
                  :name,
502
                  :description,
503
                  :initial_price,
504
                  :periodic_price,
505
                  :simultaneous_booking_maximum,
506
                  :booking_type,
507
                  NOW()
508
                )
509
EOT;
510
511
        $insert = $conn->prepare($insert);
512
513
        $linkToTag = $conn->prepare('INSERT INTO bookable_tag_bookable(bookable_tag_id, bookable_id) VALUES (:bookable_tag_id, :bookable_id)');
514
515
        // Armoires
516
        $insert->bindValue(':initial_price', 0);
517
        $insert->bindValue(':periodic_price', 50);
518
        // Une armoire peut être partagée entre 2 ou 3 membres
519
        $insert->bindValue(':simultaneous_booking_maximum', 3);
520
521
        /*
522
         * admin_only, because l'attribution d'un casier particulier est faite par l'admin,
523
         * bien que le membre demande un "Casier" il ne doit pas pouvoir réserver "Casier 26"
524
         */
525
        $insert->bindValue(':booking_type', 'admin_only');
526
527
        $insert->bindValue(':description', 'Armoire (50 x 200 x 70 cm)');
528
        $linkToTag->bindValue(':bookable_tag_id', $this->insertBookableTag('Armoire'));
529
        for ($i = 1; $i <= 120; ++$i) {
530
            $insert->bindValue(':name', sprintf('Armoire %u', $i));
531
            $insert->bindValue(':code', sprintf('STVA%u', $i));
532
            $insert->execute();
533
            $linkToTag->bindValue(':bookable_id', $conn->lastInsertId());
534
            $linkToTag->execute();
535
        }
536
537
        // Casiers
538
        $insert->bindValue(':periodic_price', 30);
539
        $insert->bindValue(':simultaneous_booking_maximum', 1);
540
        $insert->bindValue(':description', 'Casier (50 x 50 x 70 cm)');
541
        $linkToTag->bindValue(':bookable_tag_id', $this->insertBookableTag('Casier'));
542
        for ($i = 1; $i <= 36; ++$i) {
543
            $insert->bindValue(':name', sprintf('Casier %u', $i));
544
            $insert->bindValue(':code', sprintf('STVC%u', $i));
545
            $insert->execute();
546
            $linkToTag->bindValue(':bookable_id', $conn->lastInsertId());
547
            $linkToTag->execute();
548
        }
549
550
        // Stockage flotteurs
551
        $insert->bindValue(':periodic_price', 50);
552
        $insert->bindValue(':simultaneous_booking_maximum', -1);
553
        $insert->bindValue(':description', 'Stockage sous le local pour un flotteur');
554
        $linkToTag->bindValue(':bookable_tag_id', $this->insertBookableTag('Flotteurs'));
555
        for ($i = 1; $i <= 80; ++$i) {
556
            $insert->bindValue(':name', sprintf('Stockage flotteur %u', $i));
557
            $insert->bindValue(':code', sprintf('STVF%u', $i));
558
            $insert->execute();
559
            $linkToTag->bindValue(':bookable_id', $conn->lastInsertId());
560
            $linkToTag->execute();
561
        }
562
    }
563
564
    /**
565
     * Create periodic bookings for all members
566
     */
567
    private function insertBookings(): void
568
    {
569
        $conn = $this->entityManager->getConnection();
570
571
        $insert = <<<EOT
572
                INSERT INTO booking(
573
                  owner_id,
574
                  creation_date,
575
                  status,
576
                  participant_count,
577
                  start_date,
578
                  bookable_id
579
                ) VALUES (
580
                  :owner,
581
                  NOW(),
582
                  :status,
583
                  :participant_count,
584
                  NOW(),
585
                  :bookable
586
                )
587
EOT;
588
589
        $insert = $conn->prepare($insert);
590
591
        foreach ($this->members as $idMember => $member) {
592
            // Cotisation annuelle
593
            $insert->bindValue(':owner', $idMember);
594
            $insert->bindValue(':status', 'booked');
595
            $insert->bindValue(':participant_count', 1);
596
            $insert->bindValue(':bookable', 3006); // Cotisation annuelle
597
            $insert->execute();
598
599
            // Fond de réparation (optionnel)
600
            if (!empty($member['assurances']) && mb_strpos($member['assurances'], 'Fonds réparation') !== false) {
601
                $insert->bindValue(':bookable', 3026); // Fonds de réparation interne
602
                $insert->execute();
603
            }
604
605
            // Adhésion NFT (optionnel)
606
            if (!empty($this->users[$idMember]['ichtus_NFT'])) {
607
                $insert->bindValue(':bookable', 3004); // Cotisation NFT
608
                $insert->execute();
609
            }
610
        }
611
612
        // Attribution des emplacements de stockage
613
        $selectBookableByName = $conn->prepare('SELECT id, name, simultaneous_booking_maximum FROM bookable WHERE name=:name');
614
        foreach ($this->storage as $request) {
615
            if (empty($request['uid_link']) || !array_key_exists($request['uid_link'], $this->members)) {
616
                echo sprintf('ERROR: UID membre de %s %s inconnu dans fichier de demande de stockage', $request['first_name'], $request['last_name']) . PHP_EOL;
617
618
                continue;
619
            }
620
            $insert->bindValue(':owner', $request['uid_link']);
621
            foreach ([1 => 'Armoire %u', 2 => 'Armoire %u', 3 => 'Casier %u', 4 => 'Stockage floteur %u'] as $index => $bookableName) {
622
                if ($request["materiel{$index}"] > 0 && !empty($request["materiel{$index}attrib"])) {
623
                    $selectBookableByName->bindValue(':name', sprintf($bookableName, $request["materiel{$index}attrib"]));
624
                    $bookable = null;
625
                    if ($selectBookableByName->execute() && $selectBookableByName->rowCount() === 1) {
626
                        $bookable = $selectBookableByName->fetch(\PDO::FETCH_ASSOC);
627
                    }
628
                    if ($bookable) {
629
                        $insert->bindValue(':bookable', $bookable['id']);
630
                        $insert->execute();
631
                        if (!array_key_exists($bookable['id'], $this->storageAllocated)) {
632
                            $this->storageAllocated[$bookable['id']] = 1;
633
                        } else {
634
                            $this->storageAllocated[$bookable['id']] += 1;
635
                        }
636
                        echo sprintf('%s attribué à %s %s', $bookable['name'], $this->users[$request['uid_link']]['first_name'], $this->users[$request['uid_link']]['last_name']) . PHP_EOL;
637
                        if ($this->storageAllocated[$bookable['id']] > $bookable['simultaneous_booking_maximum']) {
638
                            echo sprintf('WARN: %s attribué %u fois dépassant la limite de %u', $bookable['name'], $this->storageAllocated[$bookable], $bookable['simultaneous_booking_maximum']) . PHP_EOL;
639
                        }
640
                    } else {
641
                        echo sprintf("ERROR: cannot find $bookableName in bookables", $request["materiel{$index}attrib"]) . PHP_EOL;
642
                    }
643
                }
644
            }
645
        }
646
    }
647
648
    /**
649
     * Insert or find an user tag by name
650
     *
651
     * @param string $name
652
     *
653
     * @return int ID of the existing or newly tag
654
     */
655
    private function insertUserTag(string $name): int
656
    {
657
        $conn = $this->entityManager->getConnection();
658
659
        $existing = $conn->prepare('SELECT id FROM user_tag WHERE name = :name');
660
        $existing->bindValue(':name', $name);
661
        $existing->execute();
662
        if ($existing->rowCount()) {
663
            return (int) $existing->fetchColumn();
664
        }
665
666
        $insert = $conn->prepare('INSERT INTO user_tag(creation_date, name) VALUES (NOW(), :name)');
667
        $insert->bindValue(':name', $name);
668
        if ($insert->execute()) {
669
            return (int) $conn->lastInsertId();
670
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 668 is false. This is incompatible with the type-hinted return integer. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
671
    }
672
673
    /**
674
     * Insert or find a bookable tag by name
675
     *
676
     * @param string $name
677
     *
678
     * @return int ID of the existing or newly tag
679
     */
680
    private function insertBookableTag(string $name): int
681
    {
682
        $conn = $this->entityManager->getConnection();
683
684
        $existing = $conn->prepare('SELECT id FROM bookable_tag WHERE name = :name');
685
        $existing->bindValue(':name', $name);
686
        $existing->execute();
687
        if ($existing->rowCount()) {
688
            return (int) $existing->fetchColumn();
689
        }
690
691
        $insert = $conn->prepare('INSERT INTO bookable_tag(creation_date, name) VALUES (NOW(), :name)');
692
        $insert->bindValue(':name', $name);
693
        if ($insert->execute()) {
694
            return (int) $conn->lastInsertId();
695
        }
0 ignored issues
show
Bug Best Practice introduced by
The function implicitly returns null when the if condition on line 693 is false. This is incompatible with the type-hinted return integer. Consider adding a return statement or allowing null as return value.

For hinted functions/methods where all return statements with the correct type are only reachable via conditions, ?null? gets implicitly returned which may be incompatible with the hinted type. Let?s take a look at an example:

interface ReturnsInt {
    public function returnsIntHinted(): int;
}

class MyClass implements ReturnsInt {
    public function returnsIntHinted(): int
    {
        if (foo()) {
            return 123;
        }
        // here: null is implicitly returned
    }
}
Loading history...
696
    }
697
698
    /**
699
     * Convert MacRoman string to UTF-8
700
     *
701
     * @param mixed $string
702
     *
703
     * @return string
704
     */
705
    private function fromMacRoman($string): ?string
706
    {
707
        return !empty($string) ? iconv('MacRoman', 'UTF-8', $string) : $string;
708
    }
709
710
    /**
711
     * Delete existing test users prior importing to prevent an ID collision
712
     */
713
    private function deleteTestUsers(): void
714
    {
715
        $conn = $this->entityManager->getConnection();
716
        $result = $conn->executeQuery('SELECT id FROM account a where a.owner_id < 0');
717
        $accounts = $result->fetchAll(\PDO::FETCH_COLUMN);
718
        $stmt = $conn->prepare('DELETE tl, t FROM transaction_line tl JOIN transaction t ON tl.transaction_id = t.id WHERE FIND_IN_SET(CAST(tl.debit_id as char), :accounts) OR FIND_IN_SET(CAST(tl.credit_id as char), :accounts)');
719
        $stmt->bindValue('accounts', implode(',', $accounts));
720
        $stmt->execute();
721
        $stmt = $conn->prepare('DELETE FROM account WHERE FIND_IN_SET(CAST(id as char), :accounts)');
722
        $stmt->bindValue('accounts', implode(',', $accounts));
723
        $stmt->execute();
724
        $stmt = $conn->prepare('DELETE FROM message WHERE creator_id < 0 OR owner_id < 0');
725
        $stmt->execute();
726
        $stmt = $conn->prepare('DELETE FROM user_tag WHERE creator_id < 0 OR owner_id < 0');
727
        $stmt->execute();
728
        $stmt = $conn->prepare('DELETE FROM user_tag WHERE creator_id < 0 OR owner_id < 0');
729
        $stmt->execute();
730
        $stmt = $conn->prepare('DELETE FROM expense_claim WHERE creator_id < 0 OR owner_id < 0');
731
        $stmt->execute();
732
        $stmt = $conn->prepare('DELETE FROM booking WHERE creator_id < 0 OR owner_id < 0');
733
        $stmt->execute();
734
        $stmt = $conn->prepare('UPDATE user set owner_id = NULL WHERE id < 0');
735
        $stmt->execute();
736
        $stmt = $conn->prepare('DELETE FROM user WHERE id < 0');
737
        $stmt->execute();
738
    }
739
}
740