xref: /webtrees/app/Http/RequestHandlers/DataFixUpdateAll.php (revision 78606cf427772fbdc5222ff607ee23f43078f94b)
1<?php
2
3/**
4 * webtrees: online genealogy
5 * Copyright (C) 2022 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 Fisharebest\Webtrees\Validator;
29use Illuminate\Support\Collection;
30use Psr\Http\Message\ResponseInterface;
31use Psr\Http\Message\ServerRequestInterface;
32use Psr\Http\Server\RequestHandlerInterface;
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    private DataFixService $data_fix_service;
49
50    private ModuleService $module_service;
51
52    /**
53     * DataFix constructor.
54     *
55     * @param DataFixService $data_fix_service
56     * @param ModuleService  $module_service
57     */
58    public function __construct(
59        DataFixService $data_fix_service,
60        ModuleService $module_service
61    ) {
62        $this->data_fix_service = $data_fix_service;
63        $this->module_service   = $module_service;
64    }
65
66    /**
67     * @param ServerRequestInterface $request
68     *
69     * @return ResponseInterface
70     */
71    public function handle(ServerRequestInterface $request): ResponseInterface
72    {
73        $tree     = Validator::attributes($request)->tree();
74        $data_fix = Validator::attributes($request)->string('data_fix', '');
75        $module   = $this->module_service->findByName($data_fix);
76        assert($module instanceof ModuleDataFixInterface);
77
78        $params = $request->getQueryParams();
79        $rows   = $module->recordsToFix($tree, $params);
80
81        if ($rows->isEmpty()) {
82            return response([]);
83        }
84
85        $start = Validator::queryParams($request)->string('start', '');
86        $end   = Validator::queryParams($request)->string('end', '');
87
88        if ($start === '' || $end === '') {
89            return $this->createUpdateRanges($tree, $module, $rows, $params);
90        }
91
92        /** @var Collection<int,GedcomRecord> $records */
93        $records = $rows->map(function (object $row) use ($tree): ?GedcomRecord {
94            return $this->data_fix_service->getRecordByType($row->xref, $tree, $row->type);
95        })->filter(static function (?GedcomRecord $record) use ($module, $params): bool {
96            return $record instanceof GedcomRecord && !$record->isPendingDeletion() && $module->doesRecordNeedUpdate($record, $params);
97        });
98
99        foreach ($records as $record) {
100            $module->updateRecord($record, $params);
101        }
102
103        return response();
104    }
105
106    /**
107     * @param Tree                   $tree
108     * @param ModuleDataFixInterface $module
109     * @param Collection<int,object> $rows
110     * @param array<string>          $params
111     *
112     * @return ResponseInterface
113     */
114    private function createUpdateRanges(
115        Tree $tree,
116        ModuleDataFixInterface $module,
117        Collection $rows,
118        array $params
119    ): ResponseInterface {
120        $total = $rows->count();
121
122        $updates = $rows
123            ->chunk(self::CHUNK_SIZE)
124            ->map(static function (Collection $chunk) use ($module, $params, $tree, $total): object {
125                static $count = 0;
126
127                $count += $chunk->count();
128
129                $start = $chunk->first()->xref;
130                $end   = $chunk->last()->xref;
131                $url   = route(self::class, [
132                        'tree'     => $tree->name(),
133                        'data_fix' => $module->name(),
134                        'start'    => $start,
135                        'end'      => $end,
136                    ] + $params);
137
138                return (object) [
139                    'url'      => $url,
140                    'percent'  => (100.0 * $count / $total) . '%',
141                    'progress' => I18N::percentage($count / $total, 1),
142                ];
143            })
144            ->all();
145
146        return response(json_encode($updates, JSON_THROW_ON_ERROR));
147    }
148}
149