Completed
Pull Request — master (#3735)
by
unknown
06:39
created

CensusAssistantModule::familyMembers()   B

Complexity

Conditions 11
Paths 75

Size

Total Lines 43
Code Lines 27

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 11
eloc 27
nc 75
nop 1
dl 0
loc 43
rs 7.3166
c 0
b 0
f 0

How to fix   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) 2021 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\Census\CensusInterface;
23
use Fisharebest\Webtrees\Functions\Functions;
24
use Fisharebest\Webtrees\Registry;
25
use Fisharebest\Webtrees\I18N;
26
use Fisharebest\Webtrees\Individual;
27
use Fisharebest\Webtrees\Tree;
28
use Illuminate\Support\Collection;
29
use Psr\Http\Message\ResponseInterface;
30
use Psr\Http\Message\ServerRequestInterface;
31
32
use function array_keys;
33
use function assert;
34
use function count;
35
use function e;
36
use function response;
37
use function str_repeat;
38
use function str_replace;
39
use function view;
40
41
/**
42
 * Class CensusAssistantModule
43
 */
44
class CensusAssistantModule extends AbstractModule
45
{
46
    /**
47
     * How should this module be identified in the control panel, etc.?
48
     *
49
     * @return string
50
     */
51
    public function title(): string
52
    {
53
        /* I18N: Name of a module */
54
        return I18N::translate('Census assistant');
55
    }
56
57
    /**
58
     * A sentence describing what this module does.
59
     *
60
     * @return string
61
     */
62
    public function description(): string
63
    {
64
        /* I18N: Description of the “Census assistant” module */
65
        return I18N::translate('An alternative way to enter census transcripts and link them to individuals.');
66
    }
67
68
    /**
69
     * @param ServerRequestInterface $request
70
     *
71
     * @return ResponseInterface
72
     */
73
    public function postCensusHeaderAction(ServerRequestInterface $request): ResponseInterface
74
    {
75
        $params = (array) $request->getParsedBody();
76
77
        $census = $params['census'];
78
79
        $html = $this->censusTableHeader(new $census());
80
81
        return response($html);
82
    }
83
84
    /**
85
     * @param ServerRequestInterface $request
86
     *
87
     * @return ResponseInterface
88
     */
89
    public function postCensusIndividualAction(ServerRequestInterface $request): ResponseInterface
90
    {
91
        $tree = $request->getAttribute('tree');
92
        assert($tree instanceof Tree);
93
94
        $params       = (array) $request->getParsedBody();
95
        $individual   = Registry::individualFactory()->make($params['xref'], $tree);
96
        $head         = Registry::individualFactory()->make($params['head'], $tree);
97
        $census_class = $params['census'];
98
        $census       = new $census_class();
99
100
        // No head of household?  Create a fake one.
101
        $head = $head ?? Registry::individualFactory()->new('X', '0 @X@ INDI', null, $tree);
102
103
        // Generate columns (e.g. relationship name) using the correct language.
104
        I18N::init($census->censusLanguage());
105
106
        if ($individual instanceof Individual && $head instanceof Individual) {
107
            $html = $this->censusTableRow($census, $individual, $head);
108
        } else {
109
            $html = $this->censusTableEmptyRow($census);
110
        }
111
112
        return response($html);
113
    }
114
115
    /**
116
     * @param Individual $individual
117
     *
118
     * @return string
119
     */
120
    public function createCensusAssistant(Individual $individual): string
121
    {
122
        return view('modules/census-assistant', [
123
            'individual' => $individual,
124
            'family'     => $this->familyMembers($individual),
125
        ]);
126
    }
127
128
    /**
129
     * @param ServerRequestInterface $request
130
     * @param Individual             $individual
131
     * @param string                 $fact_id
132
     * @param string                 $newged
133
     * @param bool                   $keep_chan
134
     *
135
     * @return string
136
     */
137
    public function updateCensusAssistant(ServerRequestInterface $request, Individual $individual, string $fact_id, string $newged, bool $keep_chan): string
138
    {
139
        $params = (array) $request->getParsedBody();
140
141
        $ca_title       = $params['ca_title'] ?? '';
142
        $ca_place       = $params['ca_place'] ?? '';
143
        $ca_citation    = $params['ca_citation'] ?? '';
144
        $ca_individuals = $params['ca_individuals'] ?? [];
145
        $ca_notes       = $params['ca_notes'] ?? '';
146
        $ca_census      = $params['ca_census'] ?? '';
147
148
        if ($ca_census !== '' && $ca_individuals !== []) {
149
            $census = new $ca_census();
150
151
            $note_text   = $this->createNoteText($census, $ca_title, $ca_place, $ca_citation, $ca_individuals, $ca_notes);
152
            $note_gedcom = '0 @@ NOTE ' . str_replace("\n", "\n1 CONT ", $note_text);
153
            $note        = $individual->tree()->createRecord($note_gedcom);
154
155
            $newged .= "\n2 NOTE @" . $note->xref() . '@';
156
157
            // Add the census fact to the rest of the household
158
            foreach ($ca_individuals['xref'] ?? [] as $xref) {
159
                if ($xref !== '' && $xref !== $individual->xref()) {
160
                    Registry::individualFactory()->make($xref, $individual->tree())
161
                        ->updateFact($fact_id, $newged, !$keep_chan);
162
                }
163
            }
164
        }
165
166
        return $newged;
167
    }
168
169
    /**
170
     * @param CensusInterface $census
171
     * @param string          $ca_title
172
     * @param string          $ca_place
173
     * @param string          $ca_citation
174
     * @param string[][]      $ca_individuals
175
     * @param string          $ca_notes
176
     *
177
     * @return string
178
     */
179
    private function createNoteText(CensusInterface $census, string $ca_title, string $ca_place, string $ca_citation, array $ca_individuals, string $ca_notes): string
180
    {
181
        $text = $ca_title . "\n" . $ca_citation . "\n" . $ca_place . "\n\n|";
182
183
        foreach ($census->columns() as $column) {
184
            $text .= ' ' . $column->abbreviation() . ' |';
185
        }
186
187
        $text .= "\n|" . str_repeat(' ----- |', count($census->columns()));
188
189
        foreach (array_keys($ca_individuals['xref'] ?? []) as $key) {
190
            $text .= "\n|";
191
192
            foreach ($census->columns() as $n => $column) {
193
                $text .= ' ' . $ca_individuals[$n][$key] . ' |';
194
            }
195
        }
196
197
        return $text . "\n\n" . strtr($ca_notes, ["\r" => '']);
198
    }
199
200
    /**
201
     * Generate an HTML row of data for the census header
202
     * Add prefix cell (store XREF and drag/drop)
203
     * Add suffix cell (delete button)
204
     *
205
     * @param CensusInterface $census
206
     *
207
     * @return string
208
     */
209
    protected function censusTableHeader(CensusInterface $census): string
210
    {
211
        $html = '';
212
        foreach ($census->columns() as $column) {
213
            $html .= '<th class="wt-census-assistant-field" title="' . $column->title() . '">' . $column->abbreviation() . '</th>';
214
        }
215
216
        return '<tr class="wt-census-assistant-row"><th hidden></th>' . $html . '<th></th></tr>';
217
    }
218
219
    /**
220
     * Generate an HTML row of data for the census
221
     * Add prefix cell (store XREF and drag/drop)
222
     * Add suffix cell (delete button)
223
     *
224
     * @param CensusInterface $census
225
     *
226
     * @return string
227
     */
228
    public function censusTableEmptyRow(CensusInterface $census): string
229
    {
230
        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]"></td>';
231
232
        foreach ($census->columns() as $n => $column) {
233
            $html .= '<td class="wt-census-assistant-field p-0"><input class="form-control wt-census-assistant-form-control p-0" type="text" name="ca_individuals[' . $n . '][]"></td>';
234
        }
235
236
        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
237
238
        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
239
    }
240
241
    /**
242
     * Generate an HTML row of data for the census
243
     * Add prefix cell (store XREF and drag/drop)
244
     * Add suffix cell (delete button)
245
     *
246
     * @param CensusInterface $census
247
     * @param Individual      $individual
248
     * @param Individual      $head
249
     *
250
     * @return string
251
     */
252
    public function censusTableRow(CensusInterface $census, Individual $individual, Individual $head): string
253
    {
254
        $html = '<td class="wt-census-assistant-field" hidden><input type="hidden" name="ca_individuals[xref][]" value="' . e($individual->xref()) . '"></td>';
255
256
        foreach ($census->columns() as $n => $column) {
257
            $html .= '<td class="wt-census-assistant-field p-0"><input class="form-control wt-census-assistant-form-control p-0" type="text" value="' . $column->generate($individual, $head) . '" name="ca_individuals[' . $n . '][]"></td>';
258
        }
259
260
        $html .= '<td class="wt-census-assistant-field"><a href="#" title="' . I18N::translate('Remove') . '">' . view('icons/delete') . '</a></td>';
261
262
        return '<tr class="wt-census-assistant-row">' . $html . '</tr>';
263
    }
264
265
    /**
266
     * Produce a list of close family members
267
     * for quick selection
268
     *
269
     * @param Individual $individual
270
     *
271
     * @return string[]
272
     */
273
    private function familyMembers(Individual $individual): array
274
    {
275
        $options  = [];
276
        $tree     = $individual->tree();
277
        $xrefs    = new Collection();
278
        $families = $individual->childFamilies()
279
            ->merge($individual->childStepFamilies())
280
            ->merge($individual->spouseFamilies())
281
            ->merge($individual->spouseStepFamilies());
282
283
        foreach ($families as $family) {
284
            foreach ($family->spouses() as $spouse) {
285
                $xrefs->push($spouse->xref());
286
                foreach ($spouse->childFamilies() as $spouse_child_family) {
287
                    foreach ($spouse_child_family->spouses() as $parent) {
288
                        $xrefs->push($parent->xref());
289
                    }
290
                }
291
            }
292
293
            foreach ($family->children() as $child) {
294
                $xrefs->push($child->xref());
295
                foreach ($child->spouseFamilies() as $in_laws) {
296
                    foreach ($in_laws->spouses() as $sibling_in_law) {
297
                        $xrefs->push($sibling_in_law->xref());
298
                    }
299
                    foreach ($in_laws->children() as $child_in_law) {
300
                        $xrefs->push($child_in_law->xref());
301
                    }
302
                }
303
            }
304
        }
305
306
        foreach ($xrefs->unique() as $xref) {
307
            $indi = Registry::individualFactory()->make($xref, $tree);
308
            if ($indi->canShow()) {
309
                $name           = trim(strip_tags($indi->fullName() . ', ' . $indi->lifespan()));
310
                $relationship   = Functions::getCloseRelationshipName($individual, $indi);
311
                $options[$xref] = $name . ' (' . $relationship . ')';
312
            }
313
        }
314
315
        return $options;
316
    }
317
}
318