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