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