AbstractIndividualListModule::handle()   F
last analyzed

Complexity

Conditions 62
Paths > 20000

Size

Total Lines 346
Code Lines 263

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 62
eloc 263
c 2
b 0
f 0
nc 8290473
nop 1
dl 0
loc 346
rs 0

How to fix   Long Method    Complexity   

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
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2025 webtrees development team
6
 * This program is free software: you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation, either version 3 of the License, or
9
 * (at your option) any later version.
10
 * This program is distributed in the hope that it will be useful,
11
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
 * GNU General Public License for more details.
14
 * You should have received a copy of the GNU General Public License
15
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
16
 */
17
18
declare(strict_types=1);
19
20
namespace Fisharebest\Webtrees\Module;
21
22
use Fig\Http\Message\StatusCodeInterface;
23
use Fisharebest\Webtrees\Auth;
24
use Fisharebest\Webtrees\DB;
25
use Fisharebest\Webtrees\Family;
26
use Fisharebest\Webtrees\FlashMessages;
27
use Fisharebest\Webtrees\I18N;
28
use Fisharebest\Webtrees\Individual;
29
use Fisharebest\Webtrees\Registry;
30
use Fisharebest\Webtrees\Session;
31
use Fisharebest\Webtrees\Tree;
32
use Fisharebest\Webtrees\Validator;
33
use Illuminate\Database\Query\Builder;
34
use Illuminate\Database\Query\Expression;
35
use Illuminate\Database\Query\JoinClause;
36
use Illuminate\Support\Collection;
37
use Psr\Http\Message\ResponseInterface;
38
use Psr\Http\Message\ServerRequestInterface;
39
use Psr\Http\Server\RequestHandlerInterface;
40
41
use function app;
42
use function array_filter;
43
use function array_key_exists;
44
use function array_keys;
45
use function array_map;
46
use function array_merge;
47
use function array_sum;
48
use function array_values;
49
use function assert;
50
use function e;
51
use function implode;
52
use function ob_get_clean;
53
use function ob_start;
54
use function route;
55
use function uksort;
56
use function usort;
57
use function view;
58
59
use const ARRAY_FILTER_USE_KEY;
60
61
/**
62
 * Common logic for individual and family lists.
63
 */
64
abstract class AbstractIndividualListModule extends AbstractModule implements ModuleListInterface, RequestHandlerInterface
65
{
66
    use ModuleListTrait;
67
68
    // The individual list and family list use the same code/logic.
69
    // They just display different lists.
70
    abstract protected function showFamilies(): bool;
71
72
    abstract protected function routeUrl(): string;
73
74
    /**
75
     * Initialization.
76
     */
77
    public function boot(): void
78
    {
79
        Registry::routeFactory()->routeMap()->get(static::class, $this->routeUrl(), $this);
80
    }
81
82
    /**
83
     * @param array<bool|int|string|array<string>|null> $parameters
84
     */
85
    public function listUrl(Tree $tree, array $parameters = []): string
86
    {
87
        $request = app(ServerRequestInterface::class);
88
        assert($request instanceof ServerRequestInterface);
89
90
        $xref = Validator::attributes($request)->isXref()->string('xref', '');
91
92
        if ($xref !== '') {
93
            $individual = Registry::individualFactory()->make($xref, $tree);
94
95
            if ($individual instanceof Individual && $individual->canShow()) {
96
                $primary_name = $individual->getPrimaryName();
97
98
                $parameters['surname'] ??= $individual->getAllNames()[$primary_name]['surn'] ?? null;
99
            }
100
        }
101
102
        $parameters['tree'] = $tree->name();
103
104
        return route(static::class, $parameters);
105
    }
106
107
    /**
108
     * @return array<string>
109
     */
110
    public function listUrlAttributes(): array
111
    {
112
        return [];
113
    }
114
115
    public function handle(ServerRequestInterface $request): ResponseInterface
116
    {
117
        $tree = Validator::attributes($request)->tree();
118
        $user = Validator::attributes($request)->user();
119
120
        Auth::checkComponentAccess($this, ModuleListInterface::class, $tree, $user);
121
122
        // All individuals with this surname
123
        $surname_param = Validator::queryParams($request)->string('surname', '');
124
        $surname       = I18N::strtoupper(I18N::language()->normalize($surname_param));
125
126
        // All surnames beginning with this letter, where "@" is unknown and "," is none
127
        $alpha = Validator::queryParams($request)->string('alpha', '');
128
129
        // All first names beginning with this letter where "@" is unknown
130
        $falpha = Validator::queryParams($request)->string('falpha', '');
131
132
        // What type of list to display, if any
133
        $show = Validator::queryParams($request)->string('show', 'surn');
134
135
        // All individuals
136
        $show_all = Validator::queryParams($request)->string('show_all', '');
137
138
        // Include/exclude married names
139
        $show_marnm = Validator::queryParams($request)->string('show_marnm', '');
140
141
        // Break long lists down by given name
142
        $show_all_firstnames = Validator::queryParams($request)->string('show_all_firstnames', '');
143
144
        $params = [
145
            'alpha'               => $alpha,
146
            'falpha'              => $falpha,
147
            'show'                => $show,
148
            'show_all'            => $show_all,
149
            'show_all_firstnames' => $show_all_firstnames,
150
            'show_marnm'          => $show_marnm,
151
            'surname'             => $surname,
152
        ];
153
154
        if ($surname_param !== $surname) {
155
            return Registry::responseFactory()
156
                ->redirectUrl($this->listUrl($tree, $params), StatusCodeInterface::STATUS_MOVED_PERMANENTLY);
157
        }
158
159
        // Make sure parameters are consistent with each other.
160
        if ($show_all_firstnames === 'yes') {
161
            $falpha = '';
162
        }
163
164
        if ($show_all === 'yes') {
165
            $alpha   = '';
166
            $surname = '';
167
        }
168
169
        if ($surname !== '') {
170
            $alpha = I18N::language()->initialLetter($surname);
171
        }
172
173
        $surname_data     = $this->surnameData($tree, $show_marnm === 'yes', $this->showFamilies());
174
        $all_surns        = $this->allSurns($surname_data);
175
        $all_surnames     = $this->allSurnames($surname_data);
176
        $surname_initials = $this->surnameInitials($surname_data);
177
178
        // We've requested a surname that doesn't currently exist.
179
        if ($surname !== '' && !array_key_exists($surname, $all_surns)) {
180
            $message = I18N::translate('There are no individuals with the surname “%s”', e($surname));
181
            FlashMessages::addMessage($message);
182
183
            return Registry::responseFactory()
184
                ->redirectUrl($this->listUrl($tree));
185
        }
186
187
        // Make sure selections are consistent.
188
        // i.e. can’t specify show_all and surname at the same time.
189
        if ($show_all === 'yes') {
190
            if ($show_all_firstnames === 'yes') {
191
                $legend = I18N::translate('All');
192
                $params = ['tree' => $tree->name(), 'show_all' => 'yes', 'show_marnm' => $show_marnm];
193
                $show   = 'indi';
194
            } elseif ($falpha !== '') {
195
                $legend = I18N::translate('All') . ', ' . e($falpha) . '…';
196
                $params = ['tree' => $tree->name(), 'show_all' => 'yes', 'show_marnm' => $show_marnm];
197
                $show   = 'indi';
198
            } else {
199
                $legend = I18N::translate('All');
200
                $params = ['tree' => $tree->name(), 'show_all' => 'yes', 'show_marnm' => $show_marnm];
201
            }
202
        } elseif ($surname !== '') {
203
            $show_all = 'no';
204
            $show   = 'indi'; // The surname list makes no sense with only one surname.
205
            $params = ['tree' => $tree->name(), 'surname' => $surname, 'falpha' => $falpha, 'show_marnm' => $show_marnm];
206
207
            if ($surname === Individual::NOMEN_NESCIO) {
208
                $legend = I18N::translateContext('Unknown surname', '…');
209
            } else {
210
                // The surname parameter is a root/canonical form. Display the actual surnames found.
211
                $variants = array_keys($all_surnames[$surname] ?? [$surname => $surname]);
212
                usort($variants, I18N::comparator());
213
                $variants = array_map(static fn (string $x): string => $x === '' ? I18N::translate('No surname') : $x, $variants);
214
                $legend   = implode('/', $variants);
215
            }
216
217
            switch ($falpha) {
218
                case '':
219
                    break;
220
                case '@':
221
                    $legend .= ', ' . I18N::translateContext('Unknown given name', '…');
222
                    break;
223
                default:
224
                    $legend .= ', ' . e($falpha) . '…';
225
                    break;
226
            }
227
        } elseif ($alpha === '@') {
228
            $show_all = 'no';
229
            $legend   = I18N::translateContext('Unknown surname', '…');
230
            $params   = ['alpha' => $alpha, 'tree' => $tree->name(), 'show_marnm' => $show_marnm];
231
            $surname  = Individual::NOMEN_NESCIO;
232
            $show     = 'indi'; // SURN list makes no sense here
233
        } elseif ($alpha === ',') {
234
            $show_all = 'no';
235
            $legend   = I18N::translate('No surname');
236
            $params   = ['alpha' => $alpha, 'tree' => $tree->name(), 'show_marnm' => $show_marnm];
237
            $show     = 'indi'; // SURN list makes no sense here
238
        } elseif ($alpha !== '') {
239
            $show_all = 'no';
240
            $legend   = e($alpha) . '…';
241
            $params   = ['alpha' => $alpha, 'tree' => $tree->name(), 'show_marnm' => $show_marnm];
242
        } else {
243
            $show_all = 'no';
244
            $legend   = '…';
245
            $params   = ['tree' => $tree->name(), 'show_marnm' => $show_marnm];
246
            $show     = 'none'; // Don't show lists until something is chosen
247
        }
248
        $legend = '<bdi>' . $legend . '</bdi>';
249
250
        if ($this->showFamilies()) {
251
            $title = I18N::translate('Families') . ' — ' . $legend;
252
        } else {
253
            $title = I18N::translate('Individuals') . ' — ' . $legend;
254
        }
255
256
        ob_start(); ?>
257
        <div class="d-flex flex-column wt-page-options wt-page-options-individual-list d-print-none">
258
            <ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-surname">
259
260
                <?php foreach ($surname_initials as $letter => $count) : ?>
261
                    <li class="wt-initials-list-item d-flex">
262
                        <?php if ($count > 0) : ?>
263
                            <a href="<?= e($this->listUrl($tree, ['alpha' => $letter, 'show_marnm' => $show_marnm, 'tree' => $tree->name()])) ?>" class="wt-initial px-1<?= $letter === $alpha ? ' active' : '' ?> '" title="<?= I18N::number($count) ?>"><?= $this->displaySurnameInitial((string) $letter) ?></a>
264
                        <?php else : ?>
265
                            <span class="wt-initial px-1 text-muted"><?= $this->displaySurnameInitial((string) $letter) ?></span>
266
267
                        <?php endif ?>
268
                    </li>
269
                <?php endforeach ?>
270
271
                <?php if (Session::has('initiated')) : ?>
272
                    <!-- Search spiders don't get the "show all" option as the other links give them everything. -->
273
                    <li class="wt-initials-list-item d-flex">
274
                        <a class="wt-initial px-1<?= $show_all === 'yes' ? ' active' : '' ?>" href="<?= e($this->listUrl($tree, ['show_all' => 'yes'] + $params)) ?>"><?= I18N::translate('All') ?></a>
275
                    </li>
276
                <?php endif ?>
277
            </ul>
278
279
            <!-- Search spiders don't get an option to show/hide the surname sublists, nor does it make sense on the all/unknown/surname views -->
280
            <?php if ($show !== 'none' && Session::has('initiated')) : ?>
281
                <?php if ($show_marnm === 'yes') : ?>
282
                    <p>
283
                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'no'] + $params)) ?>">
284
                            <?= I18N::translate('Exclude individuals with “%s” as a married name', $legend) ?>
285
                        </a>
286
                    </p>
287
                <?php else : ?>
288
                    <p>
289
                        <a href="<?= e($this->listUrl($tree, ['show' => $show, 'show_marnm' => 'yes'] + $params)) ?>">
290
                            <?= I18N::translate('Include individuals with “%s” as a married name', $legend) ?>
291
                        </a>
292
                    </p>
293
                <?php endif ?>
294
295
                <?php if ($alpha !== '@' && $alpha !== ',' && $surname === '') : ?>
296
                    <?php if ($show === 'surn') : ?>
297
                        <p>
298
                            <a href="<?= e($this->listUrl($tree, ['show' => 'indi'] + $params)) ?>">
299
                                <?= I18N::translate('Show the list of individuals') ?>
300
                            </a>
301
                        </p>
302
                    <?php else : ?>
303
                        <p>
304
                            <a href="<?= e($this->listUrl($tree, ['show' => 'surn'] + $params)) ?>">
305
                                <?= I18N::translate('Show the list of surnames') ?>
306
                            </a>
307
                        </p>
308
                    <?php endif ?>
309
                <?php endif ?>
310
            <?php endif ?>
311
        </div>
312
313
        <div class="wt-page-content">
314
            <?php if ($show === 'indi' || $show === 'surn') {
315
                switch ($alpha) {
316
                    case '@':
317
                        $filter = static fn (string $x): bool => $x === Individual::NOMEN_NESCIO;
318
                        break;
319
                    case ',':
320
                        $filter = static fn (string $x): bool => $x === '';
321
                        break;
322
                    case '':
323
                        if ($show_all === 'yes') {
324
                            $filter = static fn (string $x): bool => $x !== '' && $x !== Individual::NOMEN_NESCIO;
325
                        } else {
326
                            $filter = static fn (string $x): bool => $x === $surname;
327
                        }
328
                        break;
329
                    default:
330
                        if ($surname === '') {
331
                            $filter = static fn (string $x): bool => I18N::language()->initialLetter($x) === $alpha;
332
                        } else {
333
                            $filter = static fn (string $x): bool => $x === $surname;
334
                        }
335
                        break;
336
                }
337
338
                $all_surnames = array_filter($all_surnames, $filter, ARRAY_FILTER_USE_KEY);
339
340
                if ($show === 'surn') {
341
                    // Show the surname list
342
                    switch ($tree->getPreference('SURNAME_LIST_STYLE')) {
343
                        case 'style1':
344
                            echo view('lists/surnames-column-list', [
345
                                'module'   => $this,
346
                                'params'   => ['show' => 'indi', 'show_all' => null] + $params,
347
                                'surnames' => $all_surnames,
348
                                'totals'   => true,
349
                                'tree'     => $tree,
350
                            ]);
351
                            break;
352
                        case 'style3':
353
                            echo view('lists/surnames-tag-cloud', [
354
                                'module'   => $this,
355
                                'params'   => ['show' => 'indi', 'show_all' => null] + $params,
356
                                'surnames' => $all_surnames,
357
                                'totals'   => true,
358
                                'tree'     => $tree,
359
                            ]);
360
                            break;
361
                        case 'style2':
362
                        default:
363
                            echo view('lists/surnames-table', [
364
                                'families' => $this->showFamilies(),
365
                                'module'   => $this,
366
                                'order'    => [[0, 'asc']],
367
                                'params'   => ['show' => 'indi', 'show_all' => null] + $params,
368
                                'surnames' => $all_surnames,
369
                                'tree'     => $tree,
370
                            ]);
371
                            break;
372
                    }
373
                } else {
374
                    // Show the list
375
                    $count = array_sum(array_map(static fn (array $x): int => array_sum($x), $all_surnames));
376
377
                    // Don't sublist short lists.
378
                    $sublist_threshold = (int) $tree->getPreference('SUBLIST_TRIGGER_I');
379
                    if ($sublist_threshold === 0 || $count < $sublist_threshold) {
380
                        $falpha = '';
381
                    } else {
382
                        // Break long lists by initial letter of given name
383
                        $all_surnames  = array_values(array_map(static fn ($x): array => array_keys($x), $all_surnames));
384
                        $all_surnames  = array_merge(...$all_surnames);
385
                        $givn_initials = $this->givenNameInitials($tree, $all_surnames, $show_marnm === 'yes', $this->showFamilies());
386
387
                        if ($surname !== '' || $show_all === 'yes') {
388
                            echo '<h2 class="wt-page-title">', I18N::translate('Given names'), '</h2>';
389
                            // Don't show the list until we have some filter criteria
390
                            $show = $falpha !== '' || $show_all_firstnames === 'yes' ? 'indi' : 'none';
391
                            echo '<ul class="d-flex flex-wrap list-unstyled justify-content-center wt-initials-list wt-initials-list-given-names">';
392
                            foreach ($givn_initials as $givn_initial => $given_count) {
393
                                echo '<li class="wt-initials-list-item d-flex">';
394
                                if ($given_count > 0) {
395
                                    if ($show === 'indi' && $givn_initial === $falpha && $show_all_firstnames !== 'yes') {
396
                                        echo '<a class="wt-initial px-1 active" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->displayGivenNameInitial((string) $givn_initial) . '</a>';
397
                                    } else {
398
                                        echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['falpha' => $givn_initial] + $params)) . '" title="' . I18N::number($given_count) . '">' . $this->displayGivenNameInitial((string) $givn_initial) . '</a>';
399
                                    }
400
                                } else {
401
                                    echo '<span class="wt-initial px-1 text-muted">' . $this->displayGivenNameInitial((string) $givn_initial) . '</span>';
402
                                }
403
                                echo '</li>';
404
                            }
405
                            // Search spiders don't get the "show all" option as the other links give them everything.
406
                            if (Session::has('initiated')) {
407
                                echo '<li class="wt-initials-list-item d-flex">';
408
                                if ($show_all_firstnames === 'yes') {
409
                                    echo '<span class="wt-initial px-1 active">' . I18N::translate('All') . '</span>';
410
                                } else {
411
                                    echo '<a class="wt-initial px-1" href="' . e($this->listUrl($tree, ['show_all_firstnames' => 'yes'] + $params)) . '" title="' . I18N::number($count) . '">' . I18N::translate('All') . '</a>';
412
                                }
413
                                echo '</li>';
414
                            }
415
                            echo '</ul>';
416
                        }
417
                    }
418
                    if ($show === 'indi') {
419
                        if ($alpha === '@') {
420
                            $surns_to_show = ['@N.N.'];
421
                        } elseif ($alpha === ',') {
422
                            $surns_to_show = [''];
423
                        } elseif ($surname !== '') {
424
                            $surns_to_show = $all_surns[$surname];
425
                        } elseif ($alpha !== '') {
426
                            $tmp = array_filter(
427
                                $all_surns,
428
                                static fn (string $x): bool => I18N::language()->initialLetter($x) === $alpha,
429
                                ARRAY_FILTER_USE_KEY
430
                            );
431
432
                            $surns_to_show = array_merge(...array_values($tmp));
433
                        } else {
434
                            $surns_to_show = [];
435
                        }
436
437
                        if ($this->showFamilies()) {
438
                            echo view('lists/families-table', [
439
                                'families' => $this->families($tree, $surns_to_show, $falpha, $show_marnm === 'yes'),
440
                                'tree'     => $tree,
441
                            ]);
442
                        } else {
443
                            echo view('lists/individuals-table', [
444
                                'individuals' => $this->individuals($tree, $surns_to_show, $falpha, $show_marnm === 'yes', false),
445
                                'sosa'        => false,
446
                                'tree'        => $tree,
447
                            ]);
448
                        }
449
                    }
450
                }
451
            } ?>
452
        </div>
453
        <?php
454
455
        $html = ob_get_clean();
456
457
        return $this->viewResponse('modules/individual-list/page', [
458
            'content' => $html,
459
            'title'   => $title,
460
            'tree'    => $tree,
461
        ]);
462
    }
463
464
    /**
465
     * Some initial letters have a special meaning
466
     */
467
    protected function displayGivenNameInitial(string $initial): string
468
    {
469
        if ($initial === '@') {
470
            return I18N::translateContext('Unknown given name', '…');
471
        }
472
473
        return e($initial);
474
    }
475
476
    /**
477
     * Some initial letters have a special meaning
478
     */
479
    protected function displaySurnameInitial(string $initial): string
480
    {
481
        if ($initial === '@') {
482
            return I18N::translateContext('Unknown surname', '…');
483
        }
484
485
        if ($initial === ',') {
486
            return I18N::translate('No surname');
487
        }
488
489
        return e($initial);
490
    }
491
492
    /**
493
     * Restrict a query to individuals that are a spouse in a family record.
494
     */
495
    protected function whereFamily(bool $fams, Builder $query): void
496
    {
497
        if ($fams) {
498
            $query->join('link', static function (JoinClause $join): void {
499
                $join
500
                    ->on('l_from', '=', 'n_id')
501
                    ->on('l_file', '=', 'n_file')
502
                    ->where('l_type', '=', 'FAMS');
503
            });
504
        }
505
    }
506
507
    /**
508
     * Restrict a query to include/exclude married names.
509
     */
510
    protected function whereMarriedName(bool $marnm, Builder $query): void
511
    {
512
        if (!$marnm) {
513
            $query->where('n_type', '<>', '_MARNM');
514
        }
515
    }
516
517
    /**
518
     * Get a count of individuals with each initial letter
519
     *
520
     * @param array<string> $surns if set, only consider people with this surname
521
     * @param bool          $marnm if set, include married names
522
     * @param bool          $fams  if set, only consider individuals with FAMS records
523
     *
524
     * @return array<int>
525
     */
526
    public function givenNameInitials(Tree $tree, array $surns, bool $marnm, bool $fams): array
527
    {
528
        $initials = [];
529
530
        // Ensure our own language comes before others.
531
        foreach (I18N::language()->alphabet() as $initial) {
532
            $initials[$initial] = 0;
533
        }
534
535
        $query = DB::table('name')
536
            ->where('n_file', '=', $tree->id());
537
538
        $this->whereFamily($fams, $query);
539
        $this->whereMarriedName($marnm, $query);
540
541
        if ($surns !== []) {
542
            $query->whereIn('n_surn', $surns);
543
        }
544
545
        $query
546
            ->select([$this->binaryColumn('n_givn', 'n_givn'), new Expression('COUNT(*) AS count')])
547
            ->groupBy([$this->binaryColumn('n_givn')]);
548
549
        foreach ($query->get() as $row) {
550
            $initial = I18N::language()->initialLetter(I18N::language()->normalize(I18N::strtoupper($row->n_givn)));
551
552
            $initials[$initial] ??= 0;
553
            $initials[$initial] += (int) $row->count;
554
        }
555
556
        $count_unknown = $initials['@'] ?? 0;
557
558
        if ($count_unknown > 0) {
559
            unset($initials['@']);
560
            $initials['@'] = $count_unknown;
561
        }
562
563
        return $initials;
564
    }
565
566
    /**
567
     * @return array<object{n_surn:string,n_surname:string,total:int}>
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<object{n_surn:stri...name:string,total:int}> at position 2 could not be parsed: Expected '>' at position 2, but found 'object'.
Loading history...
568
     */
569
    private function surnameData(Tree $tree, bool $marnm, bool $fams): array
570
    {
571
        $query = DB::table('name')
572
            ->where('n_file', '=', $tree->id())
573
            ->whereNotNull('n_surn') // Filters old records for sources, repositories, etc.
574
            ->whereNotNull('n_surname')
575
            ->select([
576
                $this->binaryColumn('n_surn', 'n_surn'),
577
                $this->binaryColumn('n_surname', 'n_surname'),
578
                new Expression('COUNT(*) AS total'),
579
            ]);
580
581
        $this->whereFamily($fams, $query);
582
        $this->whereMarriedName($marnm, $query);
583
584
        $query->groupBy([
585
            $this->binaryColumn('n_surn'),
586
            $this->binaryColumn('n_surname'),
587
        ]);
588
589
        return $query
590
            ->get()
591
            ->map(static fn (object $x): object => (object) ['n_surn' => $x->n_surn, 'n_surname' => $x->n_surname, 'total' => (int) $x->total])
592
            ->all();
593
    }
594
595
    /**
596
     * Group n_surn values, based on collation rules for the current language.
597
     * We need them to find the individuals with this n_surn.
598
     *
599
     * @param array<object{n_surn:string,n_surname:string,total:int}> $surname_data
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<object{n_surn:stri...name:string,total:int}> at position 2 could not be parsed: Expected '>' at position 2, but found 'object'.
Loading history...
600
     *
601
     * @return array<array<int,string>>
602
     */
603
    protected function allSurns(array $surname_data): array
604
    {
605
        $list = [];
606
607
        foreach ($surname_data as $row) {
608
            $normalized = I18N::strtoupper(I18N::language()->normalize($row->n_surn));
609
            $list[$normalized][] = $row->n_surn;
610
        }
611
612
        uksort($list, I18N::comparator());
613
614
        return $list;
615
    }
616
617
    /**
618
     * Group n_surname values, based on collation rules for each n_surn.
619
     * We need them to show counts of individuals with each surname.
620
     *
621
     * @param array<object{n_surn:string,n_surname:string,total:int}> $surname_data
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<object{n_surn:stri...name:string,total:int}> at position 2 could not be parsed: Expected '>' at position 2, but found 'object'.
Loading history...
622
     *
623
     * @return array<array<int>>
624
     */
625
    protected function allSurnames(array $surname_data): array
626
    {
627
        $list = [];
628
629
        foreach ($surname_data as $row) {
630
            $n_surn = $row->n_surn === '' ? $row->n_surname : $row->n_surn;
631
            $n_surn = I18N::strtoupper(I18N::language()->normalize($n_surn));
632
633
            $list[$n_surn][$row->n_surname] ??= 0;
634
            $list[$n_surn][$row->n_surname] += $row->total;
635
        }
636
637
        uksort($list, I18N::comparator());
638
639
        return $list;
640
    }
641
642
    /**
643
     * Extract initial letters and counts for all surnames.
644
     *
645
     * @param array<object{n_surn:string,n_surname:string,total:int}> $surname_data
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<object{n_surn:stri...name:string,total:int}> at position 2 could not be parsed: Expected '>' at position 2, but found 'object'.
Loading history...
646
     *
647
     * @return array<int>
648
     */
649
    protected function surnameInitials(array $surname_data): array
650
    {
651
        $initials = [];
652
653
        // Ensure our own language comes before others.
654
        foreach (I18N::language()->alphabet() as $initial) {
655
            $initials[$initial] = 0;
656
        }
657
658
        foreach ($surname_data as $row) {
659
            $initial = I18N::language()->initialLetter(I18N::language()->normalize(I18N::strtoupper($row->n_surn)));
660
661
            $initials[$initial] ??= 0;
662
            $initials[$initial] += $row->total;
663
        }
664
665
        // Move specials to the end
666
        $count_none = $initials[''] ?? 0;
667
668
        if ($count_none > 0) {
669
            unset($initials['']);
670
            $initials[','] = $count_none;
671
        }
672
673
        $count_unknown = $initials['@'] ?? 0;
674
675
        if ($count_unknown > 0) {
676
            unset($initials['@']);
677
            $initials['@'] = $count_unknown;
678
        }
679
680
        return $initials;
681
    }
682
683
    /**
684
     * Fetch a list of individuals with specified names
685
     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
686
     * To search for names with no surnames, use $salpha=","
687
     *
688
     * @param array<string> $surns_to_show if set, only fetch people with this n_surn
689
     * @param string        $galpha        if set, only fetch given names starting with this letter
690
     * @param bool          $marnm         if set, include married names
691
     * @param bool          $fams          if set, only fetch individuals with FAMS records
692
     *
693
     * @return Collection<int,Individual>
694
     */
695
    protected function individuals(Tree $tree, array $surns_to_show, string $galpha, bool $marnm, bool $fams): Collection
696
    {
697
        $query = DB::table('individuals')
698
            ->join('name', static function (JoinClause $join): void {
699
                $join
700
                    ->on('n_id', '=', 'i_id')
701
                    ->on('n_file', '=', 'i_file');
702
            })
703
            ->where('i_file', '=', $tree->id())
704
            ->select(['i_id AS xref', 'i_gedcom AS gedcom', 'n_givn', 'n_surn']);
705
706
        $this->whereFamily($fams, $query);
707
        $this->whereMarriedName($marnm, $query);
708
709
        if ($surns_to_show === []) {
710
            $query->whereNotIn('n_surn', ['', '@N.N.']);
711
        } else {
712
            $query->whereIn($this->binaryColumn('n_surn'), $surns_to_show);
713
        }
714
715
        $individuals = new Collection();
716
717
        foreach ($query->get() as $row) {
718
            $individual = Registry::individualFactory()->make($row->xref, $tree, $row->gedcom);
719
            assert($individual instanceof Individual);
720
721
            // The name from the database may be private - check the filtered list...
722
            foreach ($individual->getAllNames() as $n => $name) {
723
                if ($name['givn'] === $row->n_givn && $name['surn'] === $row->n_surn) {
724
                    if ($galpha === '' || I18N::language()->initialLetter(I18N::language()->normalize(I18N::strtoupper($row->n_givn))) === $galpha) {
725
                        $individual->setPrimaryName($n);
726
                        // We need to clone $individual, as we may have multiple references to the
727
                        // same individual in this list, and the "primary name" would otherwise
728
                        // be shared amongst all of them.
729
                        $individuals->push(clone $individual);
730
                        break;
731
                    }
732
                }
733
            }
734
        }
735
736
        return $individuals;
737
    }
738
739
    /**
740
     * Fetch a list of families with specified names
741
     * To search for unknown names, use $surn="@N.N.", $salpha="@" or $galpha="@"
742
     * To search for names with no surnames, use $salpha=","
743
     *
744
     * @param array<string> $surnames if set, only fetch people with this n_surname
745
     * @param string        $galpha   if set, only fetch given names starting with this letter
746
     * @param bool          $marnm    if set, include married names
747
     *
748
     * @return Collection<int,Family>
749
     */
750
    protected function families(Tree $tree, array $surnames, string $galpha, bool $marnm): Collection
751
    {
752
        $families = new Collection();
753
754
        foreach ($this->individuals($tree, $surnames, $galpha, $marnm, true) as $indi) {
755
            foreach ($indi->spouseFamilies() as $family) {
756
                $families->push($family);
757
            }
758
        }
759
760
        return $families->unique();
761
    }
762
763
    /**
764
     * This module assumes the database will use binary collation on the name columns.
765
     * Until we convert MySQL databases to use utf8_bin, we need to do this at run-time.
766
     *
767
     * @param string      $column
768
     * @param string|null $alias
769
     *
770
     * @return Expression
771
     */
772
    private function binaryColumn(string $column, ?string $alias = null): Expression
773
    {
774
        if (DB::connection()->getDriverName() === 'mysql') {
775
            $sql = 'CAST(' . $column . ' AS binary)';
776
        } else {
777
            $sql = $column;
778
        }
779
780
        if ($alias !== null) {
781
            $sql .= ' AS ' . $alias;
782
        }
783
784
        return new Expression($sql);
785
    }
786
}
787