Passed
Push — main ( b8537a...489945 )
by Greg
07:15
created

TopSurnamesModule::binaryColumn()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 13
Code Lines 7

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 7
nc 4
nop 2
dl 0
loc 13
rs 10
c 0
b 0
f 0
1
<?php
2
3
/**
4
 * webtrees: online genealogy
5
 * Copyright (C) 2023 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 Fisharebest\Webtrees\Auth;
23
use Fisharebest\Webtrees\DB;
24
use Fisharebest\Webtrees\I18N;
25
use Fisharebest\Webtrees\Individual;
26
use Fisharebest\Webtrees\Services\ModuleService;
27
use Fisharebest\Webtrees\Tree;
28
use Fisharebest\Webtrees\Validator;
29
use Illuminate\Database\Query\Expression;
30
use Illuminate\Support\Str;
31
use Psr\Http\Message\ServerRequestInterface;
32
33
use function array_slice;
34
use function array_sum;
35
use function count;
36
use function extract;
37
use function uasort;
38
use function uksort;
39
use function view;
40
41
use const EXTR_OVERWRITE;
42
43
/**
44
 * Class TopSurnamesModule
45
 */
46
class TopSurnamesModule extends AbstractModule implements ModuleBlockInterface
47
{
48
    use ModuleBlockTrait;
49
50
    // Default values for new blocks.
51
    private const DEFAULT_NUMBER = '10';
52
    private const DEFAULT_STYLE  = 'table';
53
54
    private ModuleService $module_service;
55
56
    /**
57
     * @param ModuleService $module_service
58
     */
59
    public function __construct(ModuleService $module_service)
60
    {
61
        $this->module_service = $module_service;
62
    }
63
64
    /**
65
     * How should this module be identified in the control panel, etc.?
66
     *
67
     * @return string
68
     */
69
    public function title(): string
70
    {
71
        /* I18N: Name of a module. Top=Most common */
72
        return I18N::translate('Top surnames');
73
    }
74
75
    /**
76
     * A sentence describing what this module does.
77
     *
78
     * @return string
79
     */
80
    public function description(): string
81
    {
82
        /* I18N: Description of the “Top surnames” module */
83
        return I18N::translate('A list of the most popular surnames.');
84
    }
85
86
    /**
87
     * Generate the HTML content of this block.
88
     *
89
     * @param Tree                 $tree
90
     * @param int                  $block_id
91
     * @param string               $context
92
     * @param array<string,string> $config
93
     *
94
     * @return string
95
     */
96
    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
97
    {
98
        $num        = (int) $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
99
        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
100
101
        extract($config, EXTR_OVERWRITE);
102
103
        $query = DB::table('name')
104
            ->where('n_file', '=', $tree->id())
105
            ->where('n_type', '<>', '_MARNM')
106
            ->where('n_surn', '<>', '')
107
            ->where('n_surn', '<>', Individual::NOMEN_NESCIO)
108
            ->select([
109
                DB::binaryColumn('n_surn', 'n_surn'),
110
                DB::binaryColumn('n_surname', 'n_surname'),
111
                new Expression('COUNT(*) AS total'),
112
            ])
113
            ->groupBy([
114
                DB::binaryColumn('n_surn'),
115
                DB::binaryColumn('n_surname'),
116
            ]);
117
118
        /** @var array<array<int>> $top_surnames */
119
        $top_surnames = [];
120
121
        foreach ($query->get() as $row) {
122
            $row->n_surn = $row->n_surn === '' ? $row->n_surname : $row->n_surn;
123
            $row->n_surn = I18N::strtoupper(I18N::language()->normalize($row->n_surn));
124
125
            $top_surnames[$row->n_surn][$row->n_surname] ??= 0;
126
            $top_surnames[$row->n_surn][$row->n_surname] += (int) $row->total;
127
        }
128
129
        uasort($top_surnames, static fn (array $x, array $y): int => array_sum($y) <=> array_sum($x));
130
131
        $top_surnames = array_slice($top_surnames, 0, $num, true);
132
133
        // Find a module providing individual lists.
134
        $module = $this->module_service
135
            ->findByComponent(ModuleListInterface::class, $tree, Auth::user())
136
                // The family list extends the individual list
137
            ->first(static fn (ModuleInterface $module): bool => $module instanceof IndividualListModule && !$module instanceof FamilyListModule);
138
139
        switch ($info_style) {
140
            case 'tagcloud':
141
                uksort($top_surnames, I18N::comparator());
142
                $content = view('lists/surnames-tag-cloud', [
143
                    'module'   => $module,
144
                    'params'   => [],
145
                    'surnames' => $top_surnames,
146
                    'totals'   => true,
147
                    'tree'     => $tree,
148
                ]);
149
                break;
150
151
            case 'list':
152
                $content = view('lists/surnames-bullet-list', [
153
                    'module'   => $module,
154
                    'params'   => [],
155
                    'surnames' => $top_surnames,
156
                    'totals'   => true,
157
                    'tree'     => $tree,
158
                ]);
159
                break;
160
161
            case 'array':
162
                $content = view('lists/surnames-compact-list', [
163
                    'module'   => $module,
164
                    'params'   => [],
165
                    'surnames' => $top_surnames,
166
                    'totals'   => true,
167
                    'tree'     => $tree,
168
                ]);
169
                break;
170
171
            case 'table':
172
            default:
173
                uksort($top_surnames, I18N::comparator());
174
                $content = view('lists/surnames-table', [
175
                    'families' => false,
176
                    'module'   => $module,
177
                    'order'    => [[1, 'desc']],
178
                    'params'   => [],
179
                    'surnames' => $top_surnames,
180
                    'tree'     => $tree,
181
                ]);
182
                break;
183
        }
184
185
        if ($context !== self::CONTEXT_EMBED) {
186
            $num = count($top_surnames);
187
            if ($num === 1) {
188
                // I18N: i.e. most popular surname.
189
                $title = I18N::translate('Top surname');
190
            } else {
191
                // I18N: Title for a list of the most common surnames, %s is a number. Note that a separate translation exists when %s is 1
192
                $title = I18N::plural('Top %s surname', 'Top %s surnames', $num, I18N::number($num));
193
            }
194
195
            return view('modules/block-template', [
196
                'block'      => Str::kebab($this->name()),
197
                'id'         => $block_id,
198
                'config_url' => $this->configUrl($tree, $context, $block_id),
199
                'title'      => $title,
200
                'content'    => $content,
201
            ]);
202
        }
203
204
        return $content;
205
    }
206
207
    /**
208
     * Should this block load asynchronously using AJAX?
209
     *
210
     * Simple blocks are faster in-line, more complex ones can be loaded later.
211
     *
212
     * @return bool
213
     */
214
    public function loadAjax(): bool
215
    {
216
        return false;
217
    }
218
219
    /**
220
     * Can this block be shown on the user’s home page?
221
     *
222
     * @return bool
223
     */
224
    public function isUserBlock(): bool
225
    {
226
        return true;
227
    }
228
229
    /**
230
     * Can this block be shown on the tree’s home page?
231
     *
232
     * @return bool
233
     */
234
    public function isTreeBlock(): bool
235
    {
236
        return true;
237
    }
238
239
    /**
240
     * Update the configuration for a block.
241
     *
242
     * @param ServerRequestInterface $request
243
     * @param int     $block_id
244
     *
245
     * @return void
246
     */
247
    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
248
    {
249
        $num        = Validator::parsedBody($request)->integer('num');
250
        $info_style = Validator::parsedBody($request)->string('infoStyle');
251
252
        $this->setBlockSetting($block_id, 'num', (string) $num);
253
        $this->setBlockSetting($block_id, 'infoStyle', $info_style);
254
    }
255
256
    /**
257
     * An HTML form to edit block settings
258
     *
259
     * @param Tree $tree
260
     * @param int  $block_id
261
     *
262
     * @return string
263
     */
264
    public function editBlockConfiguration(Tree $tree, int $block_id): string
265
    {
266
        $num        = $this->getBlockSetting($block_id, 'num', self::DEFAULT_NUMBER);
267
        $info_style = $this->getBlockSetting($block_id, 'infoStyle', self::DEFAULT_STYLE);
268
269
        $info_styles = [
270
            /* I18N: An option in a list-box */
271
            'list'     => I18N::translate('bullet list'),
272
            /* I18N: An option in a list-box */
273
            'array'    => I18N::translate('compact list'),
274
            /* I18N: An option in a list-box */
275
            'table'    => I18N::translate('table'),
276
            /* I18N: An option in a list-box */
277
            'tagcloud' => I18N::translate('tag cloud'),
278
        ];
279
280
        return view('modules/top10_surnames/config', [
281
            'num'         => $num,
282
            'info_style'  => $info_style,
283
            'info_styles' => $info_styles,
284
        ]);
285
    }
286
}
287