Passed
Push — main ( 00c5b4...fe37d7 )
by Jonathan
03:49
created
app/Module/GeoDispersion/GeoAnalyses/AllEventsByTypeGeoAnalysis.php 1 patch
Indentation   +45 added lines, -45 removed lines patch added patch discarded remove patch
@@ -26,55 +26,55 @@
 block discarded – undo
26 26
  */
27 27
 class AllEventsByTypeGeoAnalysis implements GeoAnalysisInterface
28 28
 {
29
-    private GeoAnalysisDataService $geoanalysis_data_service;
29
+	private GeoAnalysisDataService $geoanalysis_data_service;
30 30
 
31
-    /**
32
-     * Constructor for AllEventsByTypeGeoAnalysis
33
-     *
34
-     * @param GeoAnalysisDataService $geoanalysis_data_service
35
-     */
36
-    public function __construct(GeoAnalysisDataService $geoanalysis_data_service)
37
-    {
38
-        $this->geoanalysis_data_service = $geoanalysis_data_service;
39
-    }
31
+	/**
32
+	 * Constructor for AllEventsByTypeGeoAnalysis
33
+	 *
34
+	 * @param GeoAnalysisDataService $geoanalysis_data_service
35
+	 */
36
+	public function __construct(GeoAnalysisDataService $geoanalysis_data_service)
37
+	{
38
+		$this->geoanalysis_data_service = $geoanalysis_data_service;
39
+	}
40 40
 
41
-    /**
42
-     * {@inheritDoc}
43
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::title()
44
-     */
45
-    public function title(): string
46
-    {
47
-        return I18N::translate('All events places by event type');
48
-    }
41
+	/**
42
+	 * {@inheritDoc}
43
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::title()
44
+	 */
45
+	public function title(): string
46
+	{
47
+		return I18N::translate('All events places by event type');
48
+	}
49 49
 
50
-    /**
51
-     * {@inheritDoc}
52
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::itemsDescription()
53
-     */
54
-    public function itemsDescription(): callable
55
-    {
56
-        return fn(int $count): string => I18N::plural('event', 'events', $count);
57
-    }
50
+	/**
51
+	 * {@inheritDoc}
52
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::itemsDescription()
53
+	 */
54
+	public function itemsDescription(): callable
55
+	{
56
+		return fn(int $count): string => I18N::plural('event', 'events', $count);
57
+	}
58 58
 
59
-    /**
60
-     * {@inheritDoc}
61
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::results()
62
-     */
63
-    public function results(Tree $tree, int $depth): GeoAnalysisResults
64
-    {
65
-        $results = new GeoAnalysisResults();
59
+	/**
60
+	 * {@inheritDoc}
61
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::results()
62
+	 */
63
+	public function results(Tree $tree, int $depth): GeoAnalysisResults
64
+	{
65
+		$results = new GeoAnalysisResults();
66 66
 
67
-        foreach ($this->geoanalysis_data_service->individualsAndFamilies($tree) as $record) {
68
-            foreach ($record->facts([]) as $fact) {
69
-                $place = new GeoAnalysisPlace($tree, $fact->place(), $depth);
70
-                if ($place->isUnknown()) {
71
-                    continue;
72
-                }
73
-                $results->addPlace($place);
74
-                $results->addPlaceInCategory($fact->label(), 0, $place);
75
-            }
76
-        }
67
+		foreach ($this->geoanalysis_data_service->individualsAndFamilies($tree) as $record) {
68
+			foreach ($record->facts([]) as $fact) {
69
+				$place = new GeoAnalysisPlace($tree, $fact->place(), $depth);
70
+				if ($place->isUnknown()) {
71
+					continue;
72
+				}
73
+				$results->addPlace($place);
74
+				$results->addPlaceInCategory($fact->label(), 0, $place);
75
+			}
76
+		}
77 77
 
78
-        return $results;
79
-    }
78
+		return $results;
79
+	}
80 80
 }
Please login to merge, or discard this patch.
app/Module/GeoDispersion/GeoAnalyses/AllEventsByCenturyGeoAnalysis.php 1 patch
Indentation   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -28,66 +28,66 @@
 block discarded – undo
28 28
  */
29 29
 class AllEventsByCenturyGeoAnalysis implements GeoAnalysisInterface
30 30
 {
31
-    private GeoAnalysisDataService $geoanalysis_data_service;
32
-    private CenturyService $century_service;
31
+	private GeoAnalysisDataService $geoanalysis_data_service;
32
+	private CenturyService $century_service;
33 33
 
34
-    /**
35
-     * Constructor for AllEventsByCenturyGeoAnalysis
36
-     *
37
-     * @param GeoAnalysisDataService $geoanalysis_data_service
38
-     * @param CenturyService $century_service
39
-     */
40
-    public function __construct(GeoAnalysisDataService $geoanalysis_data_service, CenturyService $century_service)
41
-    {
42
-        $this->geoanalysis_data_service = $geoanalysis_data_service;
43
-        $this->century_service = $century_service;
44
-    }
34
+	/**
35
+	 * Constructor for AllEventsByCenturyGeoAnalysis
36
+	 *
37
+	 * @param GeoAnalysisDataService $geoanalysis_data_service
38
+	 * @param CenturyService $century_service
39
+	 */
40
+	public function __construct(GeoAnalysisDataService $geoanalysis_data_service, CenturyService $century_service)
41
+	{
42
+		$this->geoanalysis_data_service = $geoanalysis_data_service;
43
+		$this->century_service = $century_service;
44
+	}
45 45
 
46
-    /**
47
-     * {@inheritDoc}
48
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::title()
49
-     */
50
-    public function title(): string
51
-    {
52
-        return I18N::translate('All events places by century');
53
-    }
46
+	/**
47
+	 * {@inheritDoc}
48
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::title()
49
+	 */
50
+	public function title(): string
51
+	{
52
+		return I18N::translate('All events places by century');
53
+	}
54 54
 
55
-    /**
56
-     * {@inheritDoc}
57
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::itemsDescription()
58
-     */
59
-    public function itemsDescription(): callable
60
-    {
61
-        return fn(int $count): string => I18N::plural('event', 'events', $count);
62
-    }
55
+	/**
56
+	 * {@inheritDoc}
57
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::itemsDescription()
58
+	 */
59
+	public function itemsDescription(): callable
60
+	{
61
+		return fn(int $count): string => I18N::plural('event', 'events', $count);
62
+	}
63 63
 
64
-    /**
65
-     * {@inheritDoc}
66
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::results()
67
-     */
68
-    public function results(Tree $tree, int $depth): GeoAnalysisResults
69
-    {
70
-        $results = new GeoAnalysisResults();
64
+	/**
65
+	 * {@inheritDoc}
66
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::results()
67
+	 */
68
+	public function results(Tree $tree, int $depth): GeoAnalysisResults
69
+	{
70
+		$results = new GeoAnalysisResults();
71 71
 
72
-        foreach ($this->geoanalysis_data_service->individualsAndFamilies($tree) as $record) {
73
-            foreach ($record->facts([]) as $fact) {
74
-                $place = new GeoAnalysisPlace($tree, $fact->place(), $depth);
75
-                if ($place->isUnknown()) {
76
-                    continue;
77
-                }
78
-                $results->addPlace($place);
79
-                $date = $fact->date();
80
-                if ($date->isOK()) {
81
-                    $century = intdiv($date->gregorianYear(), 100);
82
-                    $results->addPlaceInCategory(
83
-                        I18N::translate('%s century', $this->century_service->centuryName($century)),
84
-                        $century,
85
-                        $place
86
-                    );
87
-                }
88
-            }
89
-        }
72
+		foreach ($this->geoanalysis_data_service->individualsAndFamilies($tree) as $record) {
73
+			foreach ($record->facts([]) as $fact) {
74
+				$place = new GeoAnalysisPlace($tree, $fact->place(), $depth);
75
+				if ($place->isUnknown()) {
76
+					continue;
77
+				}
78
+				$results->addPlace($place);
79
+				$date = $fact->date();
80
+				if ($date->isOK()) {
81
+					$century = intdiv($date->gregorianYear(), 100);
82
+					$results->addPlaceInCategory(
83
+						I18N::translate('%s century', $this->century_service->centuryName($century)),
84
+						$century,
85
+						$place
86
+					);
87
+				}
88
+			}
89
+		}
90 90
 
91
-        return $results;
92
-    }
91
+		return $results;
92
+	}
93 93
 }
Please login to merge, or discard this patch.
app/Module/GeoDispersion/PlaceMappers/SimplePlaceMapper.php 1 patch
Indentation   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -24,23 +24,23 @@
 block discarded – undo
24 24
  */
25 25
 class SimplePlaceMapper implements PlaceMapperInterface
26 26
 {
27
-    use PlaceMapperTrait;
27
+	use PlaceMapperTrait;
28 28
 
29
-    /**
30
-     * {@inheritDoc}
31
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::title()
32
-     */
33
-    public function title(): string
34
-    {
35
-        return I18N::translate('Mapping on place name');
36
-    }
29
+	/**
30
+	 * {@inheritDoc}
31
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::title()
32
+	 */
33
+	public function title(): string
34
+	{
35
+		return I18N::translate('Mapping on place name');
36
+	}
37 37
 
38
-    /**
39
-     * {@inheritDoc}
40
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::map()
41
-     */
42
-    public function map(Place $place, string $feature_property): ?string
43
-    {
44
-        return $place->firstParts(1)->first();
45
-    }
38
+	/**
39
+	 * {@inheritDoc}
40
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::map()
41
+	 */
42
+	public function map(Place $place, string $feature_property): ?string
43
+	{
44
+		return $place->firstParts(1)->first();
45
+	}
46 46
 }
Please login to merge, or discard this patch.
app/Module/GeoDispersion/PlaceMappers/SimpleTopFilteredPlaceMapper.php 1 patch
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -28,51 +28,51 @@
 block discarded – undo
28 28
  */
29 29
 class SimpleTopFilteredPlaceMapper extends SimplePlaceMapper implements PlaceMapperInterface
30 30
 {
31
-    use TopFilteredPlaceMapperTrait;
31
+	use TopFilteredPlaceMapperTrait;
32 32
 
33
-    /**
34
-     * {@inheritDoc}
35
-     * @see \MyArtJaub\Webtrees\Module\GeoDispersion\PlaceMappers\SimplePlaceMapper::title()
36
-     */
37
-    public function title(): string
38
-    {
39
-        return I18N::translate('Mapping on place name with filter');
40
-    }
33
+	/**
34
+	 * {@inheritDoc}
35
+	 * @see \MyArtJaub\Webtrees\Module\GeoDispersion\PlaceMappers\SimplePlaceMapper::title()
36
+	 */
37
+	public function title(): string
38
+	{
39
+		return I18N::translate('Mapping on place name with filter');
40
+	}
41 41
 
42
-    /**
43
-     * {@inheritDoc}
44
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::boot()
45
-     */
46
-    public function boot(): void
47
-    {
48
-        parent::boot();
49
-        $top_places = $this->config()->get('topPlaces');
50
-        if (is_array($top_places)) {
51
-            $this->setTopPlaces($top_places);
52
-        }
53
-    }
42
+	/**
43
+	 * {@inheritDoc}
44
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::boot()
45
+	 */
46
+	public function boot(): void
47
+	{
48
+		parent::boot();
49
+		$top_places = $this->config()->get('topPlaces');
50
+		if (is_array($top_places)) {
51
+			$this->setTopPlaces($top_places);
52
+		}
53
+	}
54 54
 
55
-    /**
56
-     * {@inheritDoc}
57
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::config()
58
-     */
59
-    public function config(): PlaceMapperConfigInterface
60
-    {
61
-        if (!(parent::config() instanceof FilteredTopPlaceMapperConfig)) {
62
-            $this->setConfig(app(FilteredTopPlaceMapperConfig::class));
63
-        }
64
-        return parent::config();
65
-    }
55
+	/**
56
+	 * {@inheritDoc}
57
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::config()
58
+	 */
59
+	public function config(): PlaceMapperConfigInterface
60
+	{
61
+		if (!(parent::config() instanceof FilteredTopPlaceMapperConfig)) {
62
+			$this->setConfig(app(FilteredTopPlaceMapperConfig::class));
63
+		}
64
+		return parent::config();
65
+	}
66 66
 
67
-    /**
68
-     * {@inheritDoc}
69
-     * @see \MyArtJaub\Webtrees\Module\GeoDispersion\PlaceMappers\SimplePlaceMapper::map()
70
-     */
71
-    public function map(Place $place, string $feature_property): ?string
72
-    {
73
-        if (!$this->belongsToTopLevels($place)) {
74
-            return null;
75
-        }
76
-        return parent::map($place, $feature_property);
77
-    }
67
+	/**
68
+	 * {@inheritDoc}
69
+	 * @see \MyArtJaub\Webtrees\Module\GeoDispersion\PlaceMappers\SimplePlaceMapper::map()
70
+	 */
71
+	public function map(Place $place, string $feature_property): ?string
72
+	{
73
+		if (!$this->belongsToTopLevels($place)) {
74
+			return null;
75
+		}
76
+		return parent::map($place, $feature_property);
77
+	}
78 78
 }
Please login to merge, or discard this patch.
app/Module/GeoDispersion/PlaceMappers/CoordinatesPlaceMapper.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
         if ($cacheKey === null) {
126 126
             return null;
127 127
         }
128
-        return Registry::cache()->array()->remember($cacheKey, function (): ?array {
128
+        return Registry::cache()->array()->remember($cacheKey, function(): ?array {
129 129
             $map_def = $this->data('map');
130 130
             if (
131 131
                 !$this->setGeometryEngine()
@@ -201,7 +201,7 @@  discard block
 block discarded – undo
201 201
             if ($map_def === null || !($map_def instanceof MapDefinitionInterface)) {
202 202
                 return null;
203 203
             }
204
-            return spl_object_id($this) . '-map-' . $map_def->id();
204
+            return spl_object_id($this).'-map-'.$map_def->id();
205 205
         }
206 206
         return $this->cache_key;
207 207
     }
Please login to merge, or discard this patch.
Indentation   +180 added lines, -180 removed lines patch added patch discarded remove patch
@@ -36,184 +36,184 @@
 block discarded – undo
36 36
  */
37 37
 class CoordinatesPlaceMapper implements PlaceMapperInterface
38 38
 {
39
-    use PlaceMapperTrait;
40
-
41
-    private ?string $cache_key = null;
42
-
43
-    /**
44
-     * {@inheritDoc}
45
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::title()
46
-     */
47
-    public function title(): string
48
-    {
49
-        return I18N::translate('Mapping on place coordinates');
50
-    }
51
-
52
-    /**
53
-     * {@inheritDoc}
54
-     *
55
-     * {@internal The Place is associated to a Point only.
56
-     * PlaceLocation can calculate a BoundingBox.
57
-     * Using a BoundingBox could make the mapping more complex and potentially arbitary.
58
-     * Furthermore, when no coordinate is found for the place or its children, then it bubbles up to the parents.
59
-     * This could create the unwanted side effect of a very large area to consider}
60
-     *
61
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::map()
62
-     */
63
-    public function map(Place $place, string $feature_property): ?string
64
-    {
65
-        $location = new PlaceLocation($place->gedcomName());
66
-        $longitude = $location->longitude();
67
-        $latitude = $location->latitude();
68
-        if ($longitude === null || $latitude === null) {
69
-            return null;
70
-        }
71
-
72
-        $features_index = $this->featuresIndex();
73
-        if ($features_index === null) {
74
-            return null;
75
-        }
76
-
77
-        $place_point = Point::xy($longitude, $latitude, $features_index['SRID']);
78
-        $grid_box = $this->getGridCell(
79
-            $place_point,
80
-            $features_index['map_NE'],
81
-            $features_index['map_SW'],
82
-            $features_index['nb_columns']
83
-        );
84
-        if ($grid_box === null || !$this->setGeometryEngine()) {
85
-            return null;
86
-        }
87
-        $features = $features_index['grid'][$grid_box[0]][$grid_box[1]];
88
-        foreach ($features as $feature) {
89
-            $geometry = $feature->getGeometry();
90
-            if ($geometry !== null && $place_point->SRID() === $geometry->SRID() && $geometry->contains($place_point)) {
91
-                return $feature->getProperty($feature_property);
92
-            }
93
-        }
94
-        return null;
95
-    }
96
-
97
-    /**
98
-     * Return the XY coordinates in a bounded grid of the cell containing a specific point.
99
-     *
100
-     * @param Point $point Point to find
101
-     * @param Point $grid_NE North-East point of the bounded grid
102
-     * @param Point $grid_SW South-West point fo the bounded grid
103
-     * @param int $grid_columns Number of columns/rows in the grid
104
-     * @return int[]|NULL
105
-     */
106
-    protected function getGridCell(Point $point, Point $grid_NE, Point $grid_SW, int $grid_columns): ?array
107
-    {
108
-        list($x, $y) = $point->toArray();
109
-        list($x_max, $y_max) = $grid_NE->toArray();
110
-        list($x_min, $y_min) = $grid_SW->toArray();
111
-
112
-        $x_step = ($x_max - $x_min) / $grid_columns;
113
-        $y_step = ($y_max - $y_min) / $grid_columns;
114
-
115
-        if ($x_min <= $x && $x <= $x_max && $y_min <= $y && $y <= $y_max) {
116
-            return [
117
-                $x === $x_max ? $grid_columns - 1 : intval(($x - $x_min) / $x_step),
118
-                $y === $y_max ? $grid_columns - 1 : intval(($y - $y_min) / $y_step)
119
-            ];
120
-        }
121
-        return null;
122
-    }
123
-
124
-    /**
125
-     * Get an indexed array of the features of the map.
126
-     *
127
-     * {@internal The map is divided in a grid, eacg cell containing the features which bounding box overlaps that cell.
128
-     * The grid is computed once for each map, and cached.}
129
-     *
130
-     * @phpcs:ignore Generic.Files.LineLength.TooLong
131
-     * @return array{grid: array<int, array<int, \Brick\Geo\IO\GeoJSON\Feature[]>>, nb_columns: int, map_NE: \Brick\Geo\Point, map_SW: \Brick\Geo\Point, SRID: int}|NULL
132
-     */
133
-    protected function featuresIndex(): ?array
134
-    {
135
-        $cacheKey = $this->cacheKey();
136
-        if ($cacheKey === null) {
137
-            return null;
138
-        }
139
-        return Registry::cache()->array()->remember($cacheKey, function (): ?array {
140
-            $map_def = $this->data('map');
141
-            if (
142
-                !$this->setGeometryEngine()
143
-                || $map_def === null
144
-                || !($map_def instanceof MapDefinitionInterface)
145
-            ) {
146
-                return null;
147
-            }
148
-            $bounding_boxes = [];
149
-            $map_bounding_box = new BoundingBox();
150
-            $srid = 0;
151
-            foreach ($map_def->features() as $feature) {
152
-                $geometry = $feature->getGeometry();
153
-                if ($geometry === null) {
154
-                    continue;
155
-                }
156
-                $srid = $geometry->SRID();
157
-                $bounding_box = $geometry->getBoundingBox();
158
-                $bounding_boxes[] = [$feature, $bounding_box];
159
-                $map_bounding_box = $map_bounding_box->extendedWithBoundingBox($bounding_box);
160
-            }
161
-            $grid_columns = count($bounding_boxes);
162
-            $grid = array_fill(0, $grid_columns, array_fill(0, $grid_columns, []));
163
-            $map_NE = $map_bounding_box->getNorthEast();
164
-            $map_SW = $map_bounding_box->getSouthWest();
165
-            foreach ($bounding_boxes as $item) {
166
-                $grid_box_SW = $this->getGridCell($item[1]->getSouthWest(), $map_NE, $map_SW, $grid_columns) ?? [1, 1];
167
-                $grid_box_NE = $this->getGridCell($item[1]->getNorthEast(), $map_NE, $map_SW, $grid_columns) ?? [0, 0];
168
-                for ($i = $grid_box_SW[0]; $i <= $grid_box_NE[0]; $i++) {
169
-                    for ($j = $grid_box_SW[1]; $j <= $grid_box_NE[1]; $j++) {
170
-                        $grid[$i][$j][] = $item[0];
171
-                    }
172
-                }
173
-            }
174
-            return [
175
-                'grid'          =>  $grid,
176
-                'nb_columns'    =>  $grid_columns,
177
-                'map_NE'        =>  $map_NE,
178
-                'map_SW'        =>  $map_SW,
179
-                'SRID'          =>  $srid
180
-            ];
181
-        });
182
-    }
183
-
184
-    /**
185
-     * Set the Brick Geo Engine to use the database for geospatial computations.
186
-     * The engine is set only if it has not been set beforehand.
187
-     *
188
-     * @return bool
189
-     */
190
-    protected function setGeometryEngine(): bool
191
-    {
192
-        try {
193
-            if (!GeometryEngineRegistry::has()) {
194
-                GeometryEngineRegistry::set(new PDOEngine(DB::connection()->getPdo()));
195
-            }
196
-            $point = Point::xy(1, 1);
197
-            return $point->equals($point);
198
-        } catch (Throwable $ex) {
199
-        }
200
-        return false;
201
-    }
202
-
203
-    /**
204
-     * Get the key to cache the indexed grid of features.
205
-     *
206
-     * @return string|NULL
207
-     */
208
-    protected function cacheKey(): ?string
209
-    {
210
-        if ($this->cache_key === null) {
211
-            $map_def = $this->data('map');
212
-            if ($map_def === null || !($map_def instanceof MapDefinitionInterface)) {
213
-                return null;
214
-            }
215
-            return spl_object_id($this) . '-map-' . $map_def->id();
216
-        }
217
-        return $this->cache_key;
218
-    }
39
+	use PlaceMapperTrait;
40
+
41
+	private ?string $cache_key = null;
42
+
43
+	/**
44
+	 * {@inheritDoc}
45
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::title()
46
+	 */
47
+	public function title(): string
48
+	{
49
+		return I18N::translate('Mapping on place coordinates');
50
+	}
51
+
52
+	/**
53
+	 * {@inheritDoc}
54
+	 *
55
+	 * {@internal The Place is associated to a Point only.
56
+	 * PlaceLocation can calculate a BoundingBox.
57
+	 * Using a BoundingBox could make the mapping more complex and potentially arbitary.
58
+	 * Furthermore, when no coordinate is found for the place or its children, then it bubbles up to the parents.
59
+	 * This could create the unwanted side effect of a very large area to consider}
60
+	 *
61
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperInterface::map()
62
+	 */
63
+	public function map(Place $place, string $feature_property): ?string
64
+	{
65
+		$location = new PlaceLocation($place->gedcomName());
66
+		$longitude = $location->longitude();
67
+		$latitude = $location->latitude();
68
+		if ($longitude === null || $latitude === null) {
69
+			return null;
70
+		}
71
+
72
+		$features_index = $this->featuresIndex();
73
+		if ($features_index === null) {
74
+			return null;
75
+		}
76
+
77
+		$place_point = Point::xy($longitude, $latitude, $features_index['SRID']);
78
+		$grid_box = $this->getGridCell(
79
+			$place_point,
80
+			$features_index['map_NE'],
81
+			$features_index['map_SW'],
82
+			$features_index['nb_columns']
83
+		);
84
+		if ($grid_box === null || !$this->setGeometryEngine()) {
85
+			return null;
86
+		}
87
+		$features = $features_index['grid'][$grid_box[0]][$grid_box[1]];
88
+		foreach ($features as $feature) {
89
+			$geometry = $feature->getGeometry();
90
+			if ($geometry !== null && $place_point->SRID() === $geometry->SRID() && $geometry->contains($place_point)) {
91
+				return $feature->getProperty($feature_property);
92
+			}
93
+		}
94
+		return null;
95
+	}
96
+
97
+	/**
98
+	 * Return the XY coordinates in a bounded grid of the cell containing a specific point.
99
+	 *
100
+	 * @param Point $point Point to find
101
+	 * @param Point $grid_NE North-East point of the bounded grid
102
+	 * @param Point $grid_SW South-West point fo the bounded grid
103
+	 * @param int $grid_columns Number of columns/rows in the grid
104
+	 * @return int[]|NULL
105
+	 */
106
+	protected function getGridCell(Point $point, Point $grid_NE, Point $grid_SW, int $grid_columns): ?array
107
+	{
108
+		list($x, $y) = $point->toArray();
109
+		list($x_max, $y_max) = $grid_NE->toArray();
110
+		list($x_min, $y_min) = $grid_SW->toArray();
111
+
112
+		$x_step = ($x_max - $x_min) / $grid_columns;
113
+		$y_step = ($y_max - $y_min) / $grid_columns;
114
+
115
+		if ($x_min <= $x && $x <= $x_max && $y_min <= $y && $y <= $y_max) {
116
+			return [
117
+				$x === $x_max ? $grid_columns - 1 : intval(($x - $x_min) / $x_step),
118
+				$y === $y_max ? $grid_columns - 1 : intval(($y - $y_min) / $y_step)
119
+			];
120
+		}
121
+		return null;
122
+	}
123
+
124
+	/**
125
+	 * Get an indexed array of the features of the map.
126
+	 *
127
+	 * {@internal The map is divided in a grid, eacg cell containing the features which bounding box overlaps that cell.
128
+	 * The grid is computed once for each map, and cached.}
129
+	 *
130
+	 * @phpcs:ignore Generic.Files.LineLength.TooLong
131
+	 * @return array{grid: array<int, array<int, \Brick\Geo\IO\GeoJSON\Feature[]>>, nb_columns: int, map_NE: \Brick\Geo\Point, map_SW: \Brick\Geo\Point, SRID: int}|NULL
132
+	 */
133
+	protected function featuresIndex(): ?array
134
+	{
135
+		$cacheKey = $this->cacheKey();
136
+		if ($cacheKey === null) {
137
+			return null;
138
+		}
139
+		return Registry::cache()->array()->remember($cacheKey, function (): ?array {
140
+			$map_def = $this->data('map');
141
+			if (
142
+				!$this->setGeometryEngine()
143
+				|| $map_def === null
144
+				|| !($map_def instanceof MapDefinitionInterface)
145
+			) {
146
+				return null;
147
+			}
148
+			$bounding_boxes = [];
149
+			$map_bounding_box = new BoundingBox();
150
+			$srid = 0;
151
+			foreach ($map_def->features() as $feature) {
152
+				$geometry = $feature->getGeometry();
153
+				if ($geometry === null) {
154
+					continue;
155
+				}
156
+				$srid = $geometry->SRID();
157
+				$bounding_box = $geometry->getBoundingBox();
158
+				$bounding_boxes[] = [$feature, $bounding_box];
159
+				$map_bounding_box = $map_bounding_box->extendedWithBoundingBox($bounding_box);
160
+			}
161
+			$grid_columns = count($bounding_boxes);
162
+			$grid = array_fill(0, $grid_columns, array_fill(0, $grid_columns, []));
163
+			$map_NE = $map_bounding_box->getNorthEast();
164
+			$map_SW = $map_bounding_box->getSouthWest();
165
+			foreach ($bounding_boxes as $item) {
166
+				$grid_box_SW = $this->getGridCell($item[1]->getSouthWest(), $map_NE, $map_SW, $grid_columns) ?? [1, 1];
167
+				$grid_box_NE = $this->getGridCell($item[1]->getNorthEast(), $map_NE, $map_SW, $grid_columns) ?? [0, 0];
168
+				for ($i = $grid_box_SW[0]; $i <= $grid_box_NE[0]; $i++) {
169
+					for ($j = $grid_box_SW[1]; $j <= $grid_box_NE[1]; $j++) {
170
+						$grid[$i][$j][] = $item[0];
171
+					}
172
+				}
173
+			}
174
+			return [
175
+				'grid'          =>  $grid,
176
+				'nb_columns'    =>  $grid_columns,
177
+				'map_NE'        =>  $map_NE,
178
+				'map_SW'        =>  $map_SW,
179
+				'SRID'          =>  $srid
180
+			];
181
+		});
182
+	}
183
+
184
+	/**
185
+	 * Set the Brick Geo Engine to use the database for geospatial computations.
186
+	 * The engine is set only if it has not been set beforehand.
187
+	 *
188
+	 * @return bool
189
+	 */
190
+	protected function setGeometryEngine(): bool
191
+	{
192
+		try {
193
+			if (!GeometryEngineRegistry::has()) {
194
+				GeometryEngineRegistry::set(new PDOEngine(DB::connection()->getPdo()));
195
+			}
196
+			$point = Point::xy(1, 1);
197
+			return $point->equals($point);
198
+		} catch (Throwable $ex) {
199
+		}
200
+		return false;
201
+	}
202
+
203
+	/**
204
+	 * Get the key to cache the indexed grid of features.
205
+	 *
206
+	 * @return string|NULL
207
+	 */
208
+	protected function cacheKey(): ?string
209
+	{
210
+		if ($this->cache_key === null) {
211
+			$map_def = $this->data('map');
212
+			if ($map_def === null || !($map_def instanceof MapDefinitionInterface)) {
213
+				return null;
214
+			}
215
+			return spl_object_id($this) . '-map-' . $map_def->id();
216
+		}
217
+		return $this->cache_key;
218
+	}
219 219
 }
Please login to merge, or discard this patch.
app/Module/Certificates/CertificatesModule.php 2 patches
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -102,11 +102,11 @@  discard block
 block discarded – undo
102 102
      */
103 103
     public function loadRoutes($router): void
104 104
     {
105
-        $router->attach('', '', static function (Map $router): void {
105
+        $router->attach('', '', static function(Map $router): void {
106 106
 
107
-            $router->attach('', '/module-maj/certificates', static function (Map $router): void {
107
+            $router->attach('', '/module-maj/certificates', static function(Map $router): void {
108 108
 
109
-                $router->attach('', '/admin', static function (Map $router): void {
109
+                $router->attach('', '/admin', static function(Map $router): void {
110 110
 
111 111
                     $router->get(AdminConfigPage::class, '/config{/tree}', AdminConfigPage::class);
112 112
                     $router->post(AdminConfigAction::class, '/config/{tree}', AdminConfigAction::class)
@@ -129,7 +129,7 @@  discard block
 block discarded – undo
129 129
                         'permission_preference' =>  'MAJ_CERTIF_SHOW_CERT'
130 130
                     ]);
131 131
 
132
-                $router->attach('', '/certificate/{tree}/{cid}', static function (Map $router): void {
132
+                $router->attach('', '/certificate/{tree}/{cid}', static function(Map $router): void {
133 133
 
134 134
                     $router->extras([
135 135
                         'middleware'            =>  [AuthTreePreference::class],
@@ -167,7 +167,7 @@  discard block
 block discarded – undo
167 167
      */
168 168
     public function headContent(): string
169 169
     {
170
-        return '<link rel="stylesheet" href="' . e($this->moduleCssUrl()) . '">';
170
+        return '<link rel="stylesheet" href="'.e($this->moduleCssUrl()).'">';
171 171
     }
172 172
 
173 173
     /**
@@ -176,7 +176,7 @@  discard block
 block discarded – undo
176 176
      */
177 177
     public function listUrl(Tree $tree, array $parameters = []): string
178 178
     {
179
-        return route(CertificatesList::class, ['tree' => $tree->name() ] + $parameters);
179
+        return route(CertificatesList::class, ['tree' => $tree->name()] + $parameters);
180 180
     }
181 181
 
182 182
     /**
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
      */
195 195
     public function listIsEmpty(Tree $tree): bool
196 196
     {
197
-        return Auth::accessLevel($tree) > (int) $tree->getPreference('MAJ_CERTIF_SHOW_CERT', (string) Auth::PRIV_HIDE);
197
+        return Auth::accessLevel($tree) > (int)$tree->getPreference('MAJ_CERTIF_SHOW_CERT', (string)Auth::PRIV_HIDE);
198 198
     }
199 199
 
200 200
     /**
Please login to merge, or discard this patch.
Indentation   +175 added lines, -175 removed lines patch added patch discarded remove patch
@@ -44,180 +44,180 @@
 block discarded – undo
44 44
  * Certificates Module.
45 45
  */
46 46
 class CertificatesModule extends AbstractModule implements
47
-    ModuleMyArtJaubInterface,
48
-    ModuleConfigInterface,
49
-    ModuleGlobalInterface,
50
-    ModuleListInterface,
51
-    ModuleHookSubscriberInterface
47
+	ModuleMyArtJaubInterface,
48
+	ModuleConfigInterface,
49
+	ModuleGlobalInterface,
50
+	ModuleListInterface,
51
+	ModuleHookSubscriberInterface
52 52
 {
53
-    use ModuleMyArtJaubTrait {
54
-        ModuleMyArtJaubTrait::boot as traitMajBoot;
55
-    }
56
-    use ModuleConfigTrait;
57
-    use ModuleGlobalTrait;
58
-    use ModuleListTrait;
59
-
60
-    /**
61
-     * {@inheritDoc}
62
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
63
-     */
64
-    public function title(): string
65
-    {
66
-        return /* I18N: Name of the “Certificates” module */ I18N::translate('Certificates');
67
-    }
68
-
69
-    /**
70
-     * {@inheritDoc}
71
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
72
-     */
73
-    public function description(): string
74
-    {
75
-        //phpcs:ignore Generic.Files.LineLength.TooLong
76
-        return /* I18N: Description of the “Certificates” module */ I18N::translate('Display and edition of certificates linked to sources.');
77
-    }
78
-
79
-    /**
80
-     * {@inheritDoc}
81
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::boot()
82
-     */
83
-    public function boot(): void
84
-    {
85
-        $this->traitMajBoot();
86
-
87
-        Registry::elementFactory()->registerTags([
88
-            'FAM:SOUR:_ACT'     =>  new SourceCertificate(I18N::translate('Certificate'), $this),
89
-            'FAM:*:SOUR:_ACT'   =>  new SourceCertificate(I18N::translate('Certificate'), $this),
90
-            'INDI:SOUR:_ACT'    =>  new SourceCertificate(I18N::translate('Certificate'), $this),
91
-            'INDI:*:SOUR:_ACT'  =>  new SourceCertificate(I18N::translate('Certificate'), $this),
92
-            'OBJE:SOUR:_ACT'    =>  new SourceCertificate(I18N::translate('Certificate'), $this),
93
-            'OBJE:*:SOUR:_ACT'  =>  new SourceCertificate(I18N::translate('Certificate'), $this),
94
-            'NOTE:SOUR:_ACT'    =>  new SourceCertificate(I18N::translate('Certificate'), $this),
95
-            'NOTE:*:SOUR:_ACT'  =>  new SourceCertificate(I18N::translate('Certificate'), $this)
96
-        ]);
97
-
98
-        Registry::elementFactory()->registerSubTags([
99
-            'FAM:SOUR'      =>  [['_ACT', '0:1']],
100
-            'FAM:*:SOUR'    =>  [['_ACT', '0:1']],
101
-            'INDI:SOUR'     =>  [['_ACT', '0:1']],
102
-            'INDI:*:SOUR'   =>  [['_ACT', '0:1']],
103
-            'OBJE:SOUR'     =>  [['_ACT', '0:1']],
104
-            'OBJE:*:SOUR'   =>  [['_ACT', '0:1']],
105
-            'NOTE:SOUR'     =>  [['_ACT', '0:1']],
106
-            'NOTE:*:SOUR'   =>  [['_ACT', '0:1']]
107
-        ]);
108
-    }
109
-
110
-    /**
111
-     * {@inheritDoc}
112
-     * @see \MyArtJaub\Webtrees\Module\ModuleMyArtJaubInterface::loadRoutes()
113
-     */
114
-    public function loadRoutes($router): void
115
-    {
116
-        $router->attach('', '', static function (Map $router): void {
117
-
118
-            $router->attach('', '/module-maj/certificates', static function (Map $router): void {
119
-
120
-                $router->attach('', '/admin', static function (Map $router): void {
121
-
122
-                    $router->get(AdminConfigPage::class, '/config{/tree}', AdminConfigPage::class);
123
-                    $router->post(AdminConfigAction::class, '/config/{tree}', AdminConfigAction::class)
124
-                        ->extras([
125
-                            'middleware' => [
126
-                                AuthManager::class,
127
-                            ],
128
-                        ]);
129
-                });
130
-
131
-                $router->get(AutoCompleteFile::class, '/autocomplete/file/{tree}/{query}', AutoCompleteFile::class)
132
-                    ->extras([
133
-                        'middleware'            =>  [AuthTreePreference::class],
134
-                        'permission_preference' =>  'MAJ_CERTIF_SHOW_CERT'
135
-                    ]);
136
-
137
-                $router->get(CertificatesList::class, '/list/{tree}{/cityobf}', CertificatesList::class)
138
-                    ->extras([
139
-                        'middleware'            =>  [AuthTreePreference::class],
140
-                        'permission_preference' =>  'MAJ_CERTIF_SHOW_CERT'
141
-                    ]);
142
-
143
-                $router->attach('', '/certificate/{tree}/{cid}', static function (Map $router): void {
144
-
145
-                    $router->extras([
146
-                        'middleware'            =>  [AuthTreePreference::class],
147
-                        'permission_preference' =>  'MAJ_CERTIF_SHOW_CERT'
148
-                    ]);
149
-
150
-                    $router->get(CertificatePage::class, '', CertificatePage::class);
151
-                    $router->get(CertificateImage::class, '/image', CertificateImage::class);
152
-                });
153
-            });
154
-        });
155
-    }
156
-
157
-    /**
158
-     * {@inheritDoc}
159
-     * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
160
-     */
161
-    public function customModuleVersion(): string
162
-    {
163
-        return '2.1.3-v.1';
164
-    }
165
-
166
-    /**
167
-     * {@inheritDoc}
168
-     * @see \Fisharebest\Webtrees\Module\ModuleConfigInterface::getConfigLink()
169
-     */
170
-    public function getConfigLink(): string
171
-    {
172
-        return route(AdminConfigPage::class);
173
-    }
174
-
175
-    /**
176
-     * {@inheritDoc}
177
-     * @see \Fisharebest\Webtrees\Module\ModuleGlobalInterface::headContent()
178
-     */
179
-    public function headContent(): string
180
-    {
181
-        return '<link rel="stylesheet" href="' . e($this->moduleCssUrl()) . '">';
182
-    }
183
-
184
-    /**
185
-     * {@inheritDoc}
186
-     * @see \Fisharebest\Webtrees\Module\ModuleListInterface::listUrl()
187
-     *
188
-     * @param array<bool|int|string|array<mixed>|null> $parameters
189
-     */
190
-    public function listUrl(Tree $tree, array $parameters = []): string
191
-    {
192
-        return route(CertificatesList::class, ['tree' => $tree->name() ] + $parameters);
193
-    }
194
-
195
-    /**
196
-     * {@inheritDoc}
197
-     * @see \Fisharebest\Webtrees\Module\ModuleListInterface::listMenuClass()
198
-     */
199
-    public function listMenuClass(): string
200
-    {
201
-        return 'menu-maj-certificates';
202
-    }
203
-
204
-    /**
205
-     * {@inheritDoc}
206
-     * @see \Fisharebest\Webtrees\Module\ModuleListInterface::listIsEmpty()
207
-     */
208
-    public function listIsEmpty(Tree $tree): bool
209
-    {
210
-        return Auth::accessLevel($tree) > (int) $tree->getPreference('MAJ_CERTIF_SHOW_CERT', (string) Auth::PRIV_HIDE);
211
-    }
212
-
213
-    /**
214
-     * {@inheritDoc}
215
-     * @see \MyArtJaub\Webtrees\Contracts\Hooks\ModuleHookSubscriberInterface::listSubscribedHooks()
216
-     */
217
-    public function listSubscribedHooks(): array
218
-    {
219
-        return [
220
-            app()->makeWith(SourceCertificateIconHook::class, ['module' => $this])
221
-        ];
222
-    }
53
+	use ModuleMyArtJaubTrait {
54
+		ModuleMyArtJaubTrait::boot as traitMajBoot;
55
+	}
56
+	use ModuleConfigTrait;
57
+	use ModuleGlobalTrait;
58
+	use ModuleListTrait;
59
+
60
+	/**
61
+	 * {@inheritDoc}
62
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
63
+	 */
64
+	public function title(): string
65
+	{
66
+		return /* I18N: Name of the “Certificates” module */ I18N::translate('Certificates');
67
+	}
68
+
69
+	/**
70
+	 * {@inheritDoc}
71
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
72
+	 */
73
+	public function description(): string
74
+	{
75
+		//phpcs:ignore Generic.Files.LineLength.TooLong
76
+		return /* I18N: Description of the “Certificates” module */ I18N::translate('Display and edition of certificates linked to sources.');
77
+	}
78
+
79
+	/**
80
+	 * {@inheritDoc}
81
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::boot()
82
+	 */
83
+	public function boot(): void
84
+	{
85
+		$this->traitMajBoot();
86
+
87
+		Registry::elementFactory()->registerTags([
88
+			'FAM:SOUR:_ACT'     =>  new SourceCertificate(I18N::translate('Certificate'), $this),
89
+			'FAM:*:SOUR:_ACT'   =>  new SourceCertificate(I18N::translate('Certificate'), $this),
90
+			'INDI:SOUR:_ACT'    =>  new SourceCertificate(I18N::translate('Certificate'), $this),
91
+			'INDI:*:SOUR:_ACT'  =>  new SourceCertificate(I18N::translate('Certificate'), $this),
92
+			'OBJE:SOUR:_ACT'    =>  new SourceCertificate(I18N::translate('Certificate'), $this),
93
+			'OBJE:*:SOUR:_ACT'  =>  new SourceCertificate(I18N::translate('Certificate'), $this),
94
+			'NOTE:SOUR:_ACT'    =>  new SourceCertificate(I18N::translate('Certificate'), $this),
95
+			'NOTE:*:SOUR:_ACT'  =>  new SourceCertificate(I18N::translate('Certificate'), $this)
96
+		]);
97
+
98
+		Registry::elementFactory()->registerSubTags([
99
+			'FAM:SOUR'      =>  [['_ACT', '0:1']],
100
+			'FAM:*:SOUR'    =>  [['_ACT', '0:1']],
101
+			'INDI:SOUR'     =>  [['_ACT', '0:1']],
102
+			'INDI:*:SOUR'   =>  [['_ACT', '0:1']],
103
+			'OBJE:SOUR'     =>  [['_ACT', '0:1']],
104
+			'OBJE:*:SOUR'   =>  [['_ACT', '0:1']],
105
+			'NOTE:SOUR'     =>  [['_ACT', '0:1']],
106
+			'NOTE:*:SOUR'   =>  [['_ACT', '0:1']]
107
+		]);
108
+	}
109
+
110
+	/**
111
+	 * {@inheritDoc}
112
+	 * @see \MyArtJaub\Webtrees\Module\ModuleMyArtJaubInterface::loadRoutes()
113
+	 */
114
+	public function loadRoutes($router): void
115
+	{
116
+		$router->attach('', '', static function (Map $router): void {
117
+
118
+			$router->attach('', '/module-maj/certificates', static function (Map $router): void {
119
+
120
+				$router->attach('', '/admin', static function (Map $router): void {
121
+
122
+					$router->get(AdminConfigPage::class, '/config{/tree}', AdminConfigPage::class);
123
+					$router->post(AdminConfigAction::class, '/config/{tree}', AdminConfigAction::class)
124
+						->extras([
125
+							'middleware' => [
126
+								AuthManager::class,
127
+							],
128
+						]);
129
+				});
130
+
131
+				$router->get(AutoCompleteFile::class, '/autocomplete/file/{tree}/{query}', AutoCompleteFile::class)
132
+					->extras([
133
+						'middleware'            =>  [AuthTreePreference::class],
134
+						'permission_preference' =>  'MAJ_CERTIF_SHOW_CERT'
135
+					]);
136
+
137
+				$router->get(CertificatesList::class, '/list/{tree}{/cityobf}', CertificatesList::class)
138
+					->extras([
139
+						'middleware'            =>  [AuthTreePreference::class],
140
+						'permission_preference' =>  'MAJ_CERTIF_SHOW_CERT'
141
+					]);
142
+
143
+				$router->attach('', '/certificate/{tree}/{cid}', static function (Map $router): void {
144
+
145
+					$router->extras([
146
+						'middleware'            =>  [AuthTreePreference::class],
147
+						'permission_preference' =>  'MAJ_CERTIF_SHOW_CERT'
148
+					]);
149
+
150
+					$router->get(CertificatePage::class, '', CertificatePage::class);
151
+					$router->get(CertificateImage::class, '/image', CertificateImage::class);
152
+				});
153
+			});
154
+		});
155
+	}
156
+
157
+	/**
158
+	 * {@inheritDoc}
159
+	 * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
160
+	 */
161
+	public function customModuleVersion(): string
162
+	{
163
+		return '2.1.3-v.1';
164
+	}
165
+
166
+	/**
167
+	 * {@inheritDoc}
168
+	 * @see \Fisharebest\Webtrees\Module\ModuleConfigInterface::getConfigLink()
169
+	 */
170
+	public function getConfigLink(): string
171
+	{
172
+		return route(AdminConfigPage::class);
173
+	}
174
+
175
+	/**
176
+	 * {@inheritDoc}
177
+	 * @see \Fisharebest\Webtrees\Module\ModuleGlobalInterface::headContent()
178
+	 */
179
+	public function headContent(): string
180
+	{
181
+		return '<link rel="stylesheet" href="' . e($this->moduleCssUrl()) . '">';
182
+	}
183
+
184
+	/**
185
+	 * {@inheritDoc}
186
+	 * @see \Fisharebest\Webtrees\Module\ModuleListInterface::listUrl()
187
+	 *
188
+	 * @param array<bool|int|string|array<mixed>|null> $parameters
189
+	 */
190
+	public function listUrl(Tree $tree, array $parameters = []): string
191
+	{
192
+		return route(CertificatesList::class, ['tree' => $tree->name() ] + $parameters);
193
+	}
194
+
195
+	/**
196
+	 * {@inheritDoc}
197
+	 * @see \Fisharebest\Webtrees\Module\ModuleListInterface::listMenuClass()
198
+	 */
199
+	public function listMenuClass(): string
200
+	{
201
+		return 'menu-maj-certificates';
202
+	}
203
+
204
+	/**
205
+	 * {@inheritDoc}
206
+	 * @see \Fisharebest\Webtrees\Module\ModuleListInterface::listIsEmpty()
207
+	 */
208
+	public function listIsEmpty(Tree $tree): bool
209
+	{
210
+		return Auth::accessLevel($tree) > (int) $tree->getPreference('MAJ_CERTIF_SHOW_CERT', (string) Auth::PRIV_HIDE);
211
+	}
212
+
213
+	/**
214
+	 * {@inheritDoc}
215
+	 * @see \MyArtJaub\Webtrees\Contracts\Hooks\ModuleHookSubscriberInterface::listSubscribedHooks()
216
+	 */
217
+	public function listSubscribedHooks(): array
218
+	{
219
+		return [
220
+			app()->makeWith(SourceCertificateIconHook::class, ['module' => $this])
221
+		];
222
+	}
223 223
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Http/RequestHandlers/CertificatesList.php 2 patches
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
 
80 80
         $title = I18N::translate('Certificates');
81 81
 
82
-        $cities = array_map(function (string $item): array {
82
+        $cities = array_map(function(string $item): array {
83 83
             return [$this->url_obfuscator_service->obfuscate($item), $item];
84 84
         }, $this->certif_filesystem->cities($tree));
85 85
 
@@ -90,7 +90,7 @@  discard block
 block discarded – undo
90 90
             $certificates = $this->certif_filesystem->certificatesForCity($tree, $city);
91 91
         }
92 92
 
93
-        return $this->viewResponse($this->module->name() . '::certificates-list', [
93
+        return $this->viewResponse($this->module->name().'::certificates-list', [
94 94
             'title'                     =>  $title,
95 95
             'tree'                      =>  $tree,
96 96
             'module_name'               =>  $this->module->name(),
Please login to merge, or discard this patch.
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -32,63 +32,63 @@
 block discarded – undo
32 32
  */
33 33
 class CertificatesList implements RequestHandlerInterface
34 34
 {
35
-    use ViewResponseTrait;
35
+	use ViewResponseTrait;
36 36
 
37
-    private ?CertificatesModule $module;
38
-    private CertificateFilesystemService $certif_filesystem;
39
-    private UrlObfuscatorService $url_obfuscator_service;
37
+	private ?CertificatesModule $module;
38
+	private CertificateFilesystemService $certif_filesystem;
39
+	private UrlObfuscatorService $url_obfuscator_service;
40 40
 
41
-    /**
42
-     * Constructor for CertificatesList Request Handler
43
-     *
44
-     * @param ModuleService $module_service
45
-     */
46
-    public function __construct(
47
-        ModuleService $module_service,
48
-        CertificateFilesystemService $certif_filesystem,
49
-        UrlObfuscatorService $url_obfuscator_service
50
-    ) {
51
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
52
-        $this->certif_filesystem = $certif_filesystem;
53
-        $this->url_obfuscator_service = $url_obfuscator_service;
54
-    }
41
+	/**
42
+	 * Constructor for CertificatesList Request Handler
43
+	 *
44
+	 * @param ModuleService $module_service
45
+	 */
46
+	public function __construct(
47
+		ModuleService $module_service,
48
+		CertificateFilesystemService $certif_filesystem,
49
+		UrlObfuscatorService $url_obfuscator_service
50
+	) {
51
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
52
+		$this->certif_filesystem = $certif_filesystem;
53
+		$this->url_obfuscator_service = $url_obfuscator_service;
54
+	}
55 55
 
56
-    /**
57
-     * {@inheritDoc}
58
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
59
-     */
60
-    public function handle(ServerRequestInterface $request): ResponseInterface
61
-    {
62
-        if ($this->module === null) {
63
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
-        }
56
+	/**
57
+	 * {@inheritDoc}
58
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
59
+	 */
60
+	public function handle(ServerRequestInterface $request): ResponseInterface
61
+	{
62
+		if ($this->module === null) {
63
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
+		}
65 65
 
66
-        $tree = Validator::attributes($request)->tree();
66
+		$tree = Validator::attributes($request)->tree();
67 67
 
68
-        $title = I18N::translate('Certificates');
68
+		$title = I18N::translate('Certificates');
69 69
 
70
-        $cities = array_map(function (string $item): array {
71
-            return [$this->url_obfuscator_service->obfuscate($item), $item];
72
-        }, $this->certif_filesystem->cities($tree));
70
+		$cities = array_map(function (string $item): array {
71
+			return [$this->url_obfuscator_service->obfuscate($item), $item];
72
+		}, $this->certif_filesystem->cities($tree));
73 73
 
74
-        $city = Validator::queryParams($request)->string(
75
-            'cityobf',
76
-            Validator::attributes($request)->string('cityobf', '')
77
-        );
74
+		$city = Validator::queryParams($request)->string(
75
+			'cityobf',
76
+			Validator::attributes($request)->string('cityobf', '')
77
+		);
78 78
 
79
-        if ($city !== '' && $this->url_obfuscator_service->tryDeobfuscate($city)) {
80
-            $title = I18N::translate('Certificates for %s', $city);
81
-            $certificates = $this->certif_filesystem->certificatesForCity($tree, $city);
82
-        }
79
+		if ($city !== '' && $this->url_obfuscator_service->tryDeobfuscate($city)) {
80
+			$title = I18N::translate('Certificates for %s', $city);
81
+			$certificates = $this->certif_filesystem->certificatesForCity($tree, $city);
82
+		}
83 83
 
84
-        return $this->viewResponse($this->module->name() . '::certificates-list', [
85
-            'title'                     =>  $title,
86
-            'tree'                      =>  $tree,
87
-            'module_name'               =>  $this->module->name(),
88
-            'cities'                    =>  $cities,
89
-            'selected_city'             =>  $city,
90
-            'certificates_list'         =>  $certificates ?? collect(),
91
-            'url_obfuscator_service'    =>  $this->url_obfuscator_service
92
-        ]);
93
-    }
84
+		return $this->viewResponse($this->module->name() . '::certificates-list', [
85
+			'title'                     =>  $title,
86
+			'tree'                      =>  $tree,
87
+			'module_name'               =>  $this->module->name(),
88
+			'cities'                    =>  $cities,
89
+			'selected_city'             =>  $city,
90
+			'certificates_list'         =>  $certificates ?? collect(),
91
+			'url_obfuscator_service'    =>  $this->url_obfuscator_service
92
+		]);
93
+	}
94 94
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Http/RequestHandlers/AdminConfigPage.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -87,7 +87,7 @@
 block discarded – undo
87 87
             throw new HttpAccessDeniedException();
88 88
         }
89 89
 
90
-        return $this->viewResponse($this->module->name() . '::admin/config', [
90
+        return $this->viewResponse($this->module->name().'::admin/config', [
91 91
             'module_name'       =>  $this->module->name(),
92 92
             'title'             =>  $this->module->title(),
93 93
             'tree'              =>  $tree,
Please login to merge, or discard this patch.
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -35,56 +35,56 @@
 block discarded – undo
35 35
  */
36 36
 class AdminConfigPage implements RequestHandlerInterface
37 37
 {
38
-    use ViewResponseTrait;
38
+	use ViewResponseTrait;
39 39
 
40
-    private ?CertificatesModule $module;
41
-    private TreeService $tree_service;
40
+	private ?CertificatesModule $module;
41
+	private TreeService $tree_service;
42 42
 
43
-    /**
44
-     * Constructor for Admin Config page request handler
45
-     *
46
-     * @param ModuleService $module_service
47
-     */
48
-    public function __construct(ModuleService $module_service, TreeService $tree_service)
49
-    {
50
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
51
-        $this->tree_service = $tree_service;
52
-    }
43
+	/**
44
+	 * Constructor for Admin Config page request handler
45
+	 *
46
+	 * @param ModuleService $module_service
47
+	 */
48
+	public function __construct(ModuleService $module_service, TreeService $tree_service)
49
+	{
50
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
51
+		$this->tree_service = $tree_service;
52
+	}
53 53
 
54
-    /**
55
-     * {@inheritDoc}
56
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
57
-     */
58
-    public function handle(ServerRequestInterface $request): ResponseInterface
59
-    {
60
-        $this->layout = 'layouts/administration';
54
+	/**
55
+	 * {@inheritDoc}
56
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
57
+	 */
58
+	public function handle(ServerRequestInterface $request): ResponseInterface
59
+	{
60
+		$this->layout = 'layouts/administration';
61 61
 
62
-        if ($this->module === null) {
63
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
-        }
62
+		if ($this->module === null) {
63
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
64
+		}
65 65
 
66
-        $user = Validator::attributes($request)->user();
66
+		$user = Validator::attributes($request)->user();
67 67
 
68
-        $all_trees = $this->tree_service->all()->filter(fn(Tree $tree) => Auth::isManager($tree, $user));
69
-        if ($all_trees->count() === 0) {
70
-            throw new HttpAccessDeniedException();
71
-        }
68
+		$all_trees = $this->tree_service->all()->filter(fn(Tree $tree) => Auth::isManager($tree, $user));
69
+		if ($all_trees->count() === 0) {
70
+			throw new HttpAccessDeniedException();
71
+		}
72 72
 
73
-        $tree = Validator::attributes($request)->treeOptional('tree') ?? $all_trees->first();
73
+		$tree = Validator::attributes($request)->treeOptional('tree') ?? $all_trees->first();
74 74
 
75
-        $data_folder = Registry::filesystem()->dataName();
75
+		$data_folder = Registry::filesystem()->dataName();
76 76
 
77
-        $same_tree = fn(Tree $tree_collection): bool => $tree->id() === $tree_collection->id();
78
-        if (!$all_trees->contains($same_tree)) {
79
-            throw new HttpAccessDeniedException();
80
-        }
77
+		$same_tree = fn(Tree $tree_collection): bool => $tree->id() === $tree_collection->id();
78
+		if (!$all_trees->contains($same_tree)) {
79
+			throw new HttpAccessDeniedException();
80
+		}
81 81
 
82
-        return $this->viewResponse($this->module->name() . '::admin/config', [
83
-            'module_name'       =>  $this->module->name(),
84
-            'title'             =>  $this->module->title(),
85
-            'tree'              =>  $tree,
86
-            'other_trees'       =>  $all_trees->reject($same_tree),
87
-            'data_folder'       =>  $data_folder
88
-        ]);
89
-    }
82
+		return $this->viewResponse($this->module->name() . '::admin/config', [
83
+			'module_name'       =>  $this->module->name(),
84
+			'title'             =>  $this->module->title(),
85
+			'tree'              =>  $tree,
86
+			'other_trees'       =>  $all_trees->reject($same_tree),
87
+			'data_folder'       =>  $data_folder
88
+		]);
89
+	}
90 90
 }
Please login to merge, or discard this patch.
app/Module/Certificates/Services/CertificateDataService.php 2 patches
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
         $tree = $certificate->tree();
44 44
         return DB::table('individuals')
45 45
             ->where('i_file', '=', $tree->id())
46
-            ->where('i_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
46
+            ->where('i_gedcom', 'like', '% _ACT '.$this->escapedSqlPath($certificate).'%')
47 47
             ->select(['individuals.*'])
48 48
             ->get()
49 49
             ->map(Registry::individualFactory()->mapper($tree))
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
         $tree = $certificate->tree();
65 65
         return DB::table('families')
66 66
             ->where('f_file', '=', $tree->id())
67
-            ->where('f_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
67
+            ->where('f_gedcom', 'like', '% _ACT '.$this->escapedSqlPath($certificate).'%')
68 68
             ->select(['families.*'])
69 69
             ->get()
70 70
             ->map(Registry::familyFactory()->mapper($tree))
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
         $tree = $certificate->tree();
86 86
         return DB::table('media')
87 87
             ->where('m_file', '=', $tree->id())
88
-            ->where('m_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
88
+            ->where('m_gedcom', 'like', '% _ACT '.$this->escapedSqlPath($certificate).'%')
89 89
             ->select(['media.*'])
90 90
             ->get()
91 91
             ->map(Registry::mediaFactory()->mapper($tree))
@@ -107,7 +107,7 @@  discard block
 block discarded – undo
107 107
         return DB::table('other')
108 108
             ->where('o_file', '=', $tree->id())
109 109
             ->where('o_type', '=', 'NOTE')
110
-            ->where('o_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
110
+            ->where('o_gedcom', 'like', '% _ACT '.$this->escapedSqlPath($certificate).'%')
111 111
             ->select(['other.*'])
112 112
             ->get()
113 113
             ->map(Registry::noteFactory()->mapper($tree))
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
     public function oneLinkedSource(Certificate $certificate): ?Source
136 136
     {
137 137
         $regex_query = preg_quote($certificate->gedcomPath(), '/');
138
-        $regex_pattern = '/[1-9] SOUR @(' . Gedcom::REGEX_XREF . ')@(?:\n[2-9]\s(?:(?!SOUR)\w+)\s.*)*\n[2-9] _ACT ' . $regex_query . '/i'; //phpcs:ignore Generic.Files.LineLength.TooLong
138
+        $regex_pattern = '/[1-9] SOUR @('.Gedcom::REGEX_XREF.')@(?:\n[2-9]\s(?:(?!SOUR)\w+)\s.*)*\n[2-9] _ACT '.$regex_query.'/i'; //phpcs:ignore Generic.Files.LineLength.TooLong
139 139
 
140 140
         foreach ($this->linkedRecordsLists($certificate) as $linked_records) {
141 141
             foreach ($linked_records as $gedcom_record) {
Please login to merge, or discard this patch.
Indentation   +132 added lines, -132 removed lines patch added patch discarded remove patch
@@ -28,144 +28,144 @@
 block discarded – undo
28 28
  */
29 29
 class CertificateDataService
30 30
 {
31
-    /**
32
-     * Find individuals linked to a certificate.
33
-     *
34
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
35
-     * but does not work with Sqlite if no default escape has been defined}
36
-     *
37
-     * @param Certificate $certificate
38
-     * @return Collection<\Fisharebest\Webtrees\Individual>
39
-     */
40
-    public function linkedIndividuals(Certificate $certificate): Collection
41
-    {
42
-        $tree = $certificate->tree();
43
-        return DB::table('individuals')
44
-            ->where('i_file', '=', $tree->id())
45
-            ->where('i_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
46
-            ->select(['individuals.*'])
47
-            ->get()
48
-            ->map(Registry::individualFactory()->mapper($tree))
49
-            ->filter(GedcomRecord::accessFilter());
50
-    }
31
+	/**
32
+	 * Find individuals linked to a certificate.
33
+	 *
34
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
35
+	 * but does not work with Sqlite if no default escape has been defined}
36
+	 *
37
+	 * @param Certificate $certificate
38
+	 * @return Collection<\Fisharebest\Webtrees\Individual>
39
+	 */
40
+	public function linkedIndividuals(Certificate $certificate): Collection
41
+	{
42
+		$tree = $certificate->tree();
43
+		return DB::table('individuals')
44
+			->where('i_file', '=', $tree->id())
45
+			->where('i_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
46
+			->select(['individuals.*'])
47
+			->get()
48
+			->map(Registry::individualFactory()->mapper($tree))
49
+			->filter(GedcomRecord::accessFilter());
50
+	}
51 51
 
52
-    /**
53
-     * Find families linked to a certificate.
54
-     *
55
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
56
-     * but does not work with Sqlite if no default escape has been defined}
57
-     *
58
-     * @param Certificate $certificate
59
-     * @return Collection<\Fisharebest\Webtrees\Family>
60
-     */
61
-    public function linkedFamilies(Certificate $certificate): Collection
62
-    {
63
-        $tree = $certificate->tree();
64
-        return DB::table('families')
65
-            ->where('f_file', '=', $tree->id())
66
-            ->where('f_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
67
-            ->select(['families.*'])
68
-            ->get()
69
-            ->map(Registry::familyFactory()->mapper($tree))
70
-            ->filter(GedcomRecord::accessFilter());
71
-    }
52
+	/**
53
+	 * Find families linked to a certificate.
54
+	 *
55
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
56
+	 * but does not work with Sqlite if no default escape has been defined}
57
+	 *
58
+	 * @param Certificate $certificate
59
+	 * @return Collection<\Fisharebest\Webtrees\Family>
60
+	 */
61
+	public function linkedFamilies(Certificate $certificate): Collection
62
+	{
63
+		$tree = $certificate->tree();
64
+		return DB::table('families')
65
+			->where('f_file', '=', $tree->id())
66
+			->where('f_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
67
+			->select(['families.*'])
68
+			->get()
69
+			->map(Registry::familyFactory()->mapper($tree))
70
+			->filter(GedcomRecord::accessFilter());
71
+	}
72 72
 
73
-    /**
74
-     * Find media objects linked to a certificate.
75
-     *
76
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
77
-     * but does not work with Sqlite if no default escape has been defined}
78
-     *
79
-     * @param Certificate $certificate
80
-     * @return Collection<\Fisharebest\Webtrees\Media>
81
-     */
82
-    public function linkedMedias(Certificate $certificate): Collection
83
-    {
84
-        $tree = $certificate->tree();
85
-        return DB::table('media')
86
-            ->where('m_file', '=', $tree->id())
87
-            ->where('m_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
88
-            ->select(['media.*'])
89
-            ->get()
90
-            ->map(Registry::mediaFactory()->mapper($tree))
91
-            ->filter(GedcomRecord::accessFilter());
92
-    }
73
+	/**
74
+	 * Find media objects linked to a certificate.
75
+	 *
76
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
77
+	 * but does not work with Sqlite if no default escape has been defined}
78
+	 *
79
+	 * @param Certificate $certificate
80
+	 * @return Collection<\Fisharebest\Webtrees\Media>
81
+	 */
82
+	public function linkedMedias(Certificate $certificate): Collection
83
+	{
84
+		$tree = $certificate->tree();
85
+		return DB::table('media')
86
+			->where('m_file', '=', $tree->id())
87
+			->where('m_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
88
+			->select(['media.*'])
89
+			->get()
90
+			->map(Registry::mediaFactory()->mapper($tree))
91
+			->filter(GedcomRecord::accessFilter());
92
+	}
93 93
 
94
-    /**
95
-     * Find notes linked to a certificate.
96
-     *
97
-     * {@internal Ideally, the underscore should be escaped in the WHERE clause,
98
-     * but does not work with Sqlite if no default escape has been defined}
99
-     *
100
-     * @param Certificate $certificate
101
-     * @return Collection<\Fisharebest\Webtrees\Note>
102
-     */
103
-    public function linkedNotes(Certificate $certificate): Collection
104
-    {
105
-        $tree = $certificate->tree();
106
-        return DB::table('other')
107
-            ->where('o_file', '=', $tree->id())
108
-            ->where('o_type', '=', 'NOTE')
109
-            ->where('o_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
110
-            ->select(['other.*'])
111
-            ->get()
112
-            ->map(Registry::noteFactory()->mapper($tree))
113
-            ->filter(GedcomRecord::accessFilter());
114
-    }
94
+	/**
95
+	 * Find notes linked to a certificate.
96
+	 *
97
+	 * {@internal Ideally, the underscore should be escaped in the WHERE clause,
98
+	 * but does not work with Sqlite if no default escape has been defined}
99
+	 *
100
+	 * @param Certificate $certificate
101
+	 * @return Collection<\Fisharebest\Webtrees\Note>
102
+	 */
103
+	public function linkedNotes(Certificate $certificate): Collection
104
+	{
105
+		$tree = $certificate->tree();
106
+		return DB::table('other')
107
+			->where('o_file', '=', $tree->id())
108
+			->where('o_type', '=', 'NOTE')
109
+			->where('o_gedcom', 'like', '% _ACT ' . $this->escapedSqlPath($certificate) . '%')
110
+			->select(['other.*'])
111
+			->get()
112
+			->map(Registry::noteFactory()->mapper($tree))
113
+			->filter(GedcomRecord::accessFilter());
114
+	}
115 115
 
116
-    /**
117
-     * Return an escaped string to be used in SQL LIKE comparisons.
118
-     * This would not work well for Sqlite, if the escape character is not defined.
119
-     *
120
-     * @param Certificate $certificate
121
-     * @return string
122
-     */
123
-    protected function escapedSqlPath(Certificate $certificate): string
124
-    {
125
-        return str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $certificate->gedcomPath());
126
-    }
116
+	/**
117
+	 * Return an escaped string to be used in SQL LIKE comparisons.
118
+	 * This would not work well for Sqlite, if the escape character is not defined.
119
+	 *
120
+	 * @param Certificate $certificate
121
+	 * @return string
122
+	 */
123
+	protected function escapedSqlPath(Certificate $certificate): string
124
+	{
125
+		return str_replace(array('\\', '%', '_'), array('\\\\', '\\%', '\\_'), $certificate->gedcomPath());
126
+	}
127 127
 
128
-    /**
129
-     * Find a source linked to a citation where a certificate file is referenced.
130
-     *
131
-     * @param Certificate $certificate
132
-     * @return Source|NULL
133
-     */
134
-    public function oneLinkedSource(Certificate $certificate): ?Source
135
-    {
136
-        $regex_query = preg_quote($certificate->gedcomPath(), '/');
137
-        $regex_pattern = '/[1-9] SOUR @(' . Gedcom::REGEX_XREF . ')@(?:\n[2-9]\s(?:(?!SOUR)\w+)\s.*)*\n[2-9] _ACT ' . $regex_query . '/i'; //phpcs:ignore Generic.Files.LineLength.TooLong
128
+	/**
129
+	 * Find a source linked to a citation where a certificate file is referenced.
130
+	 *
131
+	 * @param Certificate $certificate
132
+	 * @return Source|NULL
133
+	 */
134
+	public function oneLinkedSource(Certificate $certificate): ?Source
135
+	{
136
+		$regex_query = preg_quote($certificate->gedcomPath(), '/');
137
+		$regex_pattern = '/[1-9] SOUR @(' . Gedcom::REGEX_XREF . ')@(?:\n[2-9]\s(?:(?!SOUR)\w+)\s.*)*\n[2-9] _ACT ' . $regex_query . '/i'; //phpcs:ignore Generic.Files.LineLength.TooLong
138 138
 
139
-        foreach ($this->linkedRecordsLists($certificate) as $linked_records) {
140
-            foreach ($linked_records as $gedcom_record) {
141
-                foreach ($gedcom_record->facts() as $fact) {
142
-                    if (preg_match_all($regex_pattern, $fact->gedcom(), $matches, PREG_SET_ORDER) >= 1) {
143
-                        foreach ($matches as $match) {
144
-                            $source = Registry::sourceFactory()->make($match[1], $certificate->tree());
145
-                            if ($source !== null && $source->canShowName()) {
146
-                                return $source;
147
-                            }
148
-                        }
149
-                    }
150
-                }
151
-            }
152
-        }
139
+		foreach ($this->linkedRecordsLists($certificate) as $linked_records) {
140
+			foreach ($linked_records as $gedcom_record) {
141
+				foreach ($gedcom_record->facts() as $fact) {
142
+					if (preg_match_all($regex_pattern, $fact->gedcom(), $matches, PREG_SET_ORDER) >= 1) {
143
+						foreach ($matches as $match) {
144
+							$source = Registry::sourceFactory()->make($match[1], $certificate->tree());
145
+							if ($source !== null && $source->canShowName()) {
146
+								return $source;
147
+							}
148
+						}
149
+					}
150
+				}
151
+			}
152
+		}
153 153
 
154
-        return null;
155
-    }
154
+		return null;
155
+	}
156 156
 
157
-    /**
158
-     * Yield lists of gedcom records linked to a certificate.
159
-     *
160
-     * @param Certificate $certificate
161
-     * @return Generator<int, Collection<GedcomRecord>, mixed, void>
162
-     * @psalm-suppress InvalidReturnType
163
-     */
164
-    protected function linkedRecordsLists(Certificate $certificate): Generator
165
-    {
166
-        yield $this->linkedIndividuals($certificate);
167
-        yield $this->linkedFamilies($certificate);
168
-        yield $this->linkedMedias($certificate);
169
-        yield $this->linkedNotes($certificate);
170
-    }
157
+	/**
158
+	 * Yield lists of gedcom records linked to a certificate.
159
+	 *
160
+	 * @param Certificate $certificate
161
+	 * @return Generator<int, Collection<GedcomRecord>, mixed, void>
162
+	 * @psalm-suppress InvalidReturnType
163
+	 */
164
+	protected function linkedRecordsLists(Certificate $certificate): Generator
165
+	{
166
+		yield $this->linkedIndividuals($certificate);
167
+		yield $this->linkedFamilies($certificate);
168
+		yield $this->linkedMedias($certificate);
169
+		yield $this->linkedNotes($certificate);
170
+	}
171 171
 }
Please login to merge, or discard this patch.