xref: /webtrees/app/Http/RequestHandlers/DataFixUpdateAll.php (revision eb2f4c2a048e609cb67743b72082319664b9b4a2)
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
18declare(strict_types=1);
19
20namespace Fisharebest\Webtrees\Http\RequestHandlers;
21
22use Fisharebest\Webtrees\GedcomRecord;
23use Fisharebest\Webtrees\I18N;
24use Fisharebest\Webtrees\Module\ModuleDataFixInterface;
25use Fisharebest\Webtrees\Services\DataFixService;
26use Fisharebest\Webtrees\Services\ModuleService;
27use Fisharebest\Webtrees\Tree;
28use Illuminate\Support\Collection;
29use Psr\Http\Message\ResponseInterface;
30use Psr\Http\Message\ServerRequestInterface;
31use Psr\Http\Server\RequestHandlerInterface;
32use stdClass;
33
34use function assert;
35use function json_encode;
36use function response;
37
38use const JSON_THROW_ON_ERROR;
39
40/**
41 * Run a data-fix.
42 */
43class DataFixUpdateAll implements RequestHandlerInterface
44{
45    // Process this number of records in each HTTP request
46    private const CHUNK_SIZE = 250;
47
48    /** @var DataFixService */
49    private $data_fix_service;
50
51    /** @var ModuleService */
52    private $module_service;
53
54    /**
55     * DataFix constructor.
56     *
57     * @param DataFixService $data_fix_service
58     * @param ModuleService  $module_service
59     */
60    public function __construct(
61        DataFixService $data_fix_service,
62        ModuleService $module_service
63    ) {
64        $this->data_fix_service = $data_fix_service;
65        $this->module_service   = $module_service;
66    }
67
68    /**
69     * @param ServerRequestInterface $request
70     *
71     * @return ResponseInterface
72     */
73    public function handle(ServerRequestInterface $request): ResponseInterface
74    {
75        $tree = $request->getAttribute('tree');
76        assert($tree instanceof Tree);
77
78        $data_fix = $request->getAttribute('data_fix', '');
79        $module   = $this->module_service->findByName($data_fix);
80        assert($module instanceof ModuleDataFixInterface);
81
82        $params = $request->getQueryParams();
83        $rows   = $module->recordsToFix($tree, $params);
84
85        if ($rows->isEmpty()) {
86            return response([]);
87        }
88
89        $start = $request->getQueryParams()['start'] ?? '';
90        $end   = $request->getQueryParams()['end'] ?? '';
91
92        if ($start === '' || $end === '') {
93            return $this->createUpdateRanges($tree, $module, $rows, $params);
94        }
95
96        /** @var Collection<GedcomRecord> $records */
97        $records = $rows->map(function (stdClass $row) use ($tree): ?GedcomRecord {
98            return $this->data_fix_service->getRecordByType($row->xref, $tree, $row->type);
99        })->filter(static function (?GedcomRecord $record) use ($module, $params): bool {
100            return $record instanceof GedcomRecord && !$record->isPendingDeletion() && $module->doesRecordNeedUpdate($record, $params);
101        });
102
103        foreach ($records as $record) {
104            $module->updateRecord($record, $params);
105        }
106
107        return response();
108    }
109
110    /**
111     * @param Tree                   $tree
112     * @param ModuleDataFixInterface $module
113     * @param Collection<stdClass>   $rows
114     * @param array<string>          $params
115     *
116     * @return ResponseInterface
117     */
118    private function createUpdateRanges(
119        Tree $tree,
120        ModuleDataFixInterface $module,
121        Collection $rows,
122        array $params
123    ): ResponseInterface {
124        $total = $rows->count();
125
126        $updates = $rows
127            ->chunk(self::CHUNK_SIZE)
128            ->map(static function (Collection $chunk) use ($module, $params, $tree, $total): stdClass {
129                static $count = 0;
130
131                $count += $chunk->count();
132
133                $start = $chunk->first()->xref;
134                $end   = $chunk->last()->xref;
135                $url   = route(self::class, [
136                        'tree'     => $tree->name(),
137                        'data_fix' => $module->name(),
138                        'start'    => $start,
139                        'end'      => $end,
140                    ] + $params);
141
142                return (object) [
143                    'url'      => $url,
144                    'percent'  => (100.0 * $count / $total) . '%',
145                    'progress' => I18N::percentage($count / $total, 1),
146                ];
147            })
148            ->all();
149
150        return response(json_encode($updates, JSON_THROW_ON_ERROR));
151    }
152}
153