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