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