Passed
Branch feature/2.0 (9789a8)
by Jonathan
14:17
created
src/Webtrees/Module/Sosa/Services/SosaRecordsService.php 1 patch
Indentation   +228 added lines, -228 removed lines patch added patch discarded remove patch
@@ -28,244 +28,244 @@
 block discarded – undo
28 28
  */
29 29
 class SosaRecordsService
30 30
 {
31
-    /**
32
-     * @var int $max_system_generations
33
-     */
34
-    private $max_system_generations;
31
+	/**
32
+	 * @var int $max_system_generations
33
+	 */
34
+	private $max_system_generations;
35 35
 
36
-    /**
37
-     * Maximum number of generation the system is able to hold.
38
-     * This is based on the size of the bigint SQL type (2^63) and the maximum PHP integer type
39
-     *
40
-     * @return int
41
-     */
42
-    public function maxSystemGenerations(): int
43
-    {
44
-        if ($this->max_system_generations === null) {
45
-            $this->max_system_generations = min(63, $this->generation(PHP_INT_MAX));
46
-        }
47
-        return $this->max_system_generations;
48
-    }
36
+	/**
37
+	 * Maximum number of generation the system is able to hold.
38
+	 * This is based on the size of the bigint SQL type (2^63) and the maximum PHP integer type
39
+	 *
40
+	 * @return int
41
+	 */
42
+	public function maxSystemGenerations(): int
43
+	{
44
+		if ($this->max_system_generations === null) {
45
+			$this->max_system_generations = min(63, $this->generation(PHP_INT_MAX));
46
+		}
47
+		return $this->max_system_generations;
48
+	}
49 49
 
50
-    /**
51
-     * Calculate the generation of a sosa
52
-     * Sosa 1 is of generation 1.
53
-     *
54
-     * @param int $sosa
55
-     * @return int
56
-     */
57
-    public function generation(int $sosa): int
58
-    {
59
-        return BigInteger::of($sosa)->getBitLength();
60
-    }
50
+	/**
51
+	 * Calculate the generation of a sosa
52
+	 * Sosa 1 is of generation 1.
53
+	 *
54
+	 * @param int $sosa
55
+	 * @return int
56
+	 */
57
+	public function generation(int $sosa): int
58
+	{
59
+		return BigInteger::of($sosa)->getBitLength();
60
+	}
61 61
 
62
-    /**
63
-     * Returns all Sosa numbers associated to an Individual
64
-     *
65
-     * @param Tree $tree
66
-     * @param User $user
67
-     * @param Individual $indi
68
-     * @return Collection
69
-     */
70
-    public function getSosaNumbers(Tree $tree, User $user, Individual $indi): Collection
71
-    {
72
-        return DB::table('maj_sosa')
73
-            ->select(['majs_sosa', 'majs_gen'])
74
-            ->where('majs_gedcom_id', '=', $tree->id())
75
-            ->where('majs_user_id', '=', $user->id())
76
-            ->where('majs_i_id', '=', $indi->xref())
77
-            ->orderBy('majs_sosa')
78
-            ->get()->pluck('majs_gen', 'majs_sosa');
79
-    }
62
+	/**
63
+	 * Returns all Sosa numbers associated to an Individual
64
+	 *
65
+	 * @param Tree $tree
66
+	 * @param User $user
67
+	 * @param Individual $indi
68
+	 * @return Collection
69
+	 */
70
+	public function getSosaNumbers(Tree $tree, User $user, Individual $indi): Collection
71
+	{
72
+		return DB::table('maj_sosa')
73
+			->select(['majs_sosa', 'majs_gen'])
74
+			->where('majs_gedcom_id', '=', $tree->id())
75
+			->where('majs_user_id', '=', $user->id())
76
+			->where('majs_i_id', '=', $indi->xref())
77
+			->orderBy('majs_sosa')
78
+			->get()->pluck('majs_gen', 'majs_sosa');
79
+	}
80 80
 
81
-    /**
82
-     * Return a list of the Sosa ancestors at a given generation
83
-     *
84
-     * @param Tree $tree
85
-     * @param User $user
86
-     * @param int $gen
87
-     * @return Collection
88
-     */
89
-    public function listAncestorsAtGeneration(Tree $tree, User $user, int $gen): Collection
90
-    {
91
-        return DB::table('maj_sosa')
92
-            ->select(['majs_sosa', 'majs_i_id'])
93
-            ->where('majs_gedcom_id', '=', $tree->id())
94
-            ->where('majs_user_id', '=', $user->id())
95
-            ->where('majs_gen', '=', $gen)
96
-            ->orderBy('majs_sosa')
97
-            ->get();
98
-    }
81
+	/**
82
+	 * Return a list of the Sosa ancestors at a given generation
83
+	 *
84
+	 * @param Tree $tree
85
+	 * @param User $user
86
+	 * @param int $gen
87
+	 * @return Collection
88
+	 */
89
+	public function listAncestorsAtGeneration(Tree $tree, User $user, int $gen): Collection
90
+	{
91
+		return DB::table('maj_sosa')
92
+			->select(['majs_sosa', 'majs_i_id'])
93
+			->where('majs_gedcom_id', '=', $tree->id())
94
+			->where('majs_user_id', '=', $user->id())
95
+			->where('majs_gen', '=', $gen)
96
+			->orderBy('majs_sosa')
97
+			->get();
98
+	}
99 99
 
100
-    /**
101
-     * Return a list of the Sosa families at a given generation
102
-     *
103
-     * @param Tree $tree
104
-     * @param User $user
105
-     * @param int $gen
106
-     * @return Collection
107
-     */
108
-    public function listAncestorFamiliesAtGeneration(Tree $tree, User $user, int $gen): Collection
109
-    {
110
-        $table_prefix = DB::connection()->getTablePrefix();
111
-        return DB::table('families')
112
-            ->join('maj_sosa AS sosa_husb', function (JoinClause $join) use ($tree, $user): void {
113
-                // Link to family husband
114
-                $join->on('families.f_file', '=', 'sosa_husb.majs_gedcom_id')
115
-                    ->on('families.f_husb', '=', 'sosa_husb.majs_i_id')
116
-                    ->where('sosa_husb.majs_gedcom_id', '=', $tree->id())
117
-                    ->where('sosa_husb.majs_user_id', '=', $user->id());
118
-            })
119
-            ->join('maj_sosa AS sosa_wife', function (JoinClause $join) use ($tree, $user): void {
120
-                // Link to family husband
121
-                $join->on('families.f_file', '=', 'sosa_wife.majs_gedcom_id')
122
-                ->on('families.f_wife', '=', 'sosa_wife.majs_i_id')
123
-                ->where('sosa_wife.majs_gedcom_id', '=', $tree->id())
124
-                ->where('sosa_wife.majs_user_id', '=', $user->id());
125
-            })
126
-            ->select(['sosa_husb.majs_sosa', 'families.f_id'])
127
-            ->where('sosa_husb.majs_gen', '=', $gen)
128
-            ->whereRaw($table_prefix . 'sosa_husb.majs_sosa + 1 = ' . $table_prefix . 'sosa_wife.majs_sosa')
129
-            ->orderBy('sosa_husb.majs_sosa')
130
-            ->get();
131
-    }
100
+	/**
101
+	 * Return a list of the Sosa families at a given generation
102
+	 *
103
+	 * @param Tree $tree
104
+	 * @param User $user
105
+	 * @param int $gen
106
+	 * @return Collection
107
+	 */
108
+	public function listAncestorFamiliesAtGeneration(Tree $tree, User $user, int $gen): Collection
109
+	{
110
+		$table_prefix = DB::connection()->getTablePrefix();
111
+		return DB::table('families')
112
+			->join('maj_sosa AS sosa_husb', function (JoinClause $join) use ($tree, $user): void {
113
+				// Link to family husband
114
+				$join->on('families.f_file', '=', 'sosa_husb.majs_gedcom_id')
115
+					->on('families.f_husb', '=', 'sosa_husb.majs_i_id')
116
+					->where('sosa_husb.majs_gedcom_id', '=', $tree->id())
117
+					->where('sosa_husb.majs_user_id', '=', $user->id());
118
+			})
119
+			->join('maj_sosa AS sosa_wife', function (JoinClause $join) use ($tree, $user): void {
120
+				// Link to family husband
121
+				$join->on('families.f_file', '=', 'sosa_wife.majs_gedcom_id')
122
+				->on('families.f_wife', '=', 'sosa_wife.majs_i_id')
123
+				->where('sosa_wife.majs_gedcom_id', '=', $tree->id())
124
+				->where('sosa_wife.majs_user_id', '=', $user->id());
125
+			})
126
+			->select(['sosa_husb.majs_sosa', 'families.f_id'])
127
+			->where('sosa_husb.majs_gen', '=', $gen)
128
+			->whereRaw($table_prefix . 'sosa_husb.majs_sosa + 1 = ' . $table_prefix . 'sosa_wife.majs_sosa')
129
+			->orderBy('sosa_husb.majs_sosa')
130
+			->get();
131
+	}
132 132
 
133
-    /**
134
-     * Return a list of Sosa ancestors missing at a given generation.
135
-     * It includes the reference of either parent if it is known.
136
-     *
137
-     * @param Tree $tree
138
-     * @param User $user
139
-     * @param int $gen
140
-     * @return Collection
141
-     */
142
-    public function listMissingAncestorsAtGeneration(Tree $tree, User $user, int $gen): Collection
143
-    {
144
-        if ($gen == 1) {
145
-            return collect();
146
-        }
133
+	/**
134
+	 * Return a list of Sosa ancestors missing at a given generation.
135
+	 * It includes the reference of either parent if it is known.
136
+	 *
137
+	 * @param Tree $tree
138
+	 * @param User $user
139
+	 * @param int $gen
140
+	 * @return Collection
141
+	 */
142
+	public function listMissingAncestorsAtGeneration(Tree $tree, User $user, int $gen): Collection
143
+	{
144
+		if ($gen == 1) {
145
+			return collect();
146
+		}
147 147
 
148
-        $table_prefix = DB::connection()->getTablePrefix();
149
-        return DB::table('maj_sosa AS sosa')
150
-            ->select(['sosa.majs_i_id', 'sosa_fat.majs_i_id AS majs_fat_id', 'sosa_mot.majs_i_id AS majs_mot_id'])
151
-            ->selectRaw('MIN(' . $table_prefix . 'sosa.majs_sosa) AS majs_sosa')
152
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
153
-                // Link to sosa's father
154
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
155
-                    ->where('sosa_fat.majs_gedcom_id', '=', $tree->id())
156
-                    ->where('sosa_fat.majs_user_id', '=', $user->id());
157
-            })
158
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
159
-                // Link to sosa's mother
160
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
161
-                    ->where('sosa_mot.majs_gedcom_id', '=', $tree->id())
162
-                    ->where('sosa_mot.majs_user_id', '=', $user->id());
163
-            })
164
-            ->where('sosa.majs_gedcom_id', '=', $tree->id())
165
-            ->where('sosa.majs_user_id', '=', $user->id())
166
-            ->where('sosa.majs_gen', '=', $gen - 1)
167
-            ->where(function (Builder $query): void {
168
-                $query->whereNull('sosa_fat.majs_i_id')
169
-                    ->orWhereNull('sosa_mot.majs_i_id');
170
-            })
171
-            ->groupBy('sosa.majs_i_id', 'sosa_fat.majs_i_id', 'sosa_mot.majs_i_id')
172
-            ->orderByRaw('MIN(' . $table_prefix . 'sosa.majs_sosa)')
173
-            ->get();
174
-    }
148
+		$table_prefix = DB::connection()->getTablePrefix();
149
+		return DB::table('maj_sosa AS sosa')
150
+			->select(['sosa.majs_i_id', 'sosa_fat.majs_i_id AS majs_fat_id', 'sosa_mot.majs_i_id AS majs_mot_id'])
151
+			->selectRaw('MIN(' . $table_prefix . 'sosa.majs_sosa) AS majs_sosa')
152
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
153
+				// Link to sosa's father
154
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
155
+					->where('sosa_fat.majs_gedcom_id', '=', $tree->id())
156
+					->where('sosa_fat.majs_user_id', '=', $user->id());
157
+			})
158
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
159
+				// Link to sosa's mother
160
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
161
+					->where('sosa_mot.majs_gedcom_id', '=', $tree->id())
162
+					->where('sosa_mot.majs_user_id', '=', $user->id());
163
+			})
164
+			->where('sosa.majs_gedcom_id', '=', $tree->id())
165
+			->where('sosa.majs_user_id', '=', $user->id())
166
+			->where('sosa.majs_gen', '=', $gen - 1)
167
+			->where(function (Builder $query): void {
168
+				$query->whereNull('sosa_fat.majs_i_id')
169
+					->orWhereNull('sosa_mot.majs_i_id');
170
+			})
171
+			->groupBy('sosa.majs_i_id', 'sosa_fat.majs_i_id', 'sosa_mot.majs_i_id')
172
+			->orderByRaw('MIN(' . $table_prefix . 'sosa.majs_sosa)')
173
+			->get();
174
+	}
175 175
 
176
-    /**
177
-     * Remove all Sosa entries related to the gedcom file and user
178
-     *
179
-     * @param Tree $tree
180
-     * @param User $user
181
-     */
182
-    public function deleteAll(Tree $tree, User $user): void
183
-    {
184
-        DB::table('maj_sosa')
185
-            ->where('majs_gedcom_id', '=', $tree->id())
186
-            ->where('majs_user_id', '=', $user->id())
187
-            ->delete();
188
-    }
176
+	/**
177
+	 * Remove all Sosa entries related to the gedcom file and user
178
+	 *
179
+	 * @param Tree $tree
180
+	 * @param User $user
181
+	 */
182
+	public function deleteAll(Tree $tree, User $user): void
183
+	{
184
+		DB::table('maj_sosa')
185
+			->where('majs_gedcom_id', '=', $tree->id())
186
+			->where('majs_user_id', '=', $user->id())
187
+			->delete();
188
+	}
189 189
 
190
-    /**
191
-     *
192
-     * @param Tree $tree
193
-     * @param User $user
194
-     * @param int $sosa
195
-     */
196
-    public function deleteAncestorsFrom(Tree $tree, User $user, int $sosa): void
197
-    {
198
-        DB::table('maj_sosa')
199
-            ->where('majs_gedcom_id', '=', $tree->id())
200
-            ->where('majs_user_id', '=', $user->id())
201
-            ->where('majs_sosa', '>=', $sosa)
202
-            ->whereRaw(
203
-                'FLOOR(majs_sosa / (POW(2, (majs_gen - ?)))) = ?',
204
-                [$this->generation($sosa), $sosa]
205
-            )
206
-            ->delete();
207
-    }
190
+	/**
191
+	 *
192
+	 * @param Tree $tree
193
+	 * @param User $user
194
+	 * @param int $sosa
195
+	 */
196
+	public function deleteAncestorsFrom(Tree $tree, User $user, int $sosa): void
197
+	{
198
+		DB::table('maj_sosa')
199
+			->where('majs_gedcom_id', '=', $tree->id())
200
+			->where('majs_user_id', '=', $user->id())
201
+			->where('majs_sosa', '>=', $sosa)
202
+			->whereRaw(
203
+				'FLOOR(majs_sosa / (POW(2, (majs_gen - ?)))) = ?',
204
+				[$this->generation($sosa), $sosa]
205
+			)
206
+			->delete();
207
+	}
208 208
 
209
-    /**
210
-     * Insert (or update if already existing) a list of Sosa individuals
211
-     *
212
-     * @param Tree $tree
213
-     * @param User $user
214
-     * @param array $sosa_records
215
-     */
216
-    public function insertOrUpdate(Tree $tree, User $user, array $sosa_records): void
217
-    {
218
-        $mass_update = DB::connection()->getDriverName() === 'mysql';
209
+	/**
210
+	 * Insert (or update if already existing) a list of Sosa individuals
211
+	 *
212
+	 * @param Tree $tree
213
+	 * @param User $user
214
+	 * @param array $sosa_records
215
+	 */
216
+	public function insertOrUpdate(Tree $tree, User $user, array $sosa_records): void
217
+	{
218
+		$mass_update = DB::connection()->getDriverName() === 'mysql';
219 219
 
220
-        $bindings_placeholders = $bindings_values = [];
221
-        foreach ($sosa_records as $i => $row) {
222
-            $gen = $this->generation($row['sosa']);
223
-            if ($gen <=  $this->maxSystemGenerations()) {
224
-                if ($mass_update) {
225
-                    $bindings_placeholders[] = '(:tree_id' . $i . ', :user_id' . $i . ', :sosa' . $i . ',' .
226
-                        ' :indi_id' . $i . ', :gen' . $i . ',' .
227
-                        ' :byear' . $i . ', :byearest' . $i . ', :dyear' . $i . ', :dyearest' . $i . ')';
228
-                    $bindings_values = array_merge(
229
-                        $bindings_values,
230
-                        [
231
-                            'tree_id' . $i => $tree->id(),
232
-                            'user_id' . $i => $user->id(),
233
-                            'sosa' . $i => $row['sosa'],
234
-                            'indi_id' . $i => $row['indi'],
235
-                            'gen' . $i => $gen,
236
-                            'byear' . $i => $row['birth_year'],
237
-                            'byearest' . $i => $row['birth_year_est'],
238
-                            'dyear' . $i => $row['death_year'],
239
-                            'dyearest' . $i => $row['death_year_est']
240
-                        ]
241
-                    );
242
-                } else {
243
-                    DB::table('maj_sosa')->updateOrInsert(
244
-                        [ 'majs_gedcom_id' => $tree->id(), 'majs_user_id' => $user->id(), 'majs_sosa' => $row['sosa']],
245
-                        [
246
-                            'majs_i_id' => $row['indi'],
247
-                            'majs_gen' => $gen,
248
-                            'majs_birth_year' => $row['birth_year'],
249
-                            'majs_birth_year_est' => $row['birth_year_est'],
250
-                            'majs_death_year' => $row['death_year'],
251
-                            'majs_death_year_est' => $row['death_year_est']
252
-                        ]
253
-                    );
254
-                }
255
-            }
256
-        }
220
+		$bindings_placeholders = $bindings_values = [];
221
+		foreach ($sosa_records as $i => $row) {
222
+			$gen = $this->generation($row['sosa']);
223
+			if ($gen <=  $this->maxSystemGenerations()) {
224
+				if ($mass_update) {
225
+					$bindings_placeholders[] = '(:tree_id' . $i . ', :user_id' . $i . ', :sosa' . $i . ',' .
226
+						' :indi_id' . $i . ', :gen' . $i . ',' .
227
+						' :byear' . $i . ', :byearest' . $i . ', :dyear' . $i . ', :dyearest' . $i . ')';
228
+					$bindings_values = array_merge(
229
+						$bindings_values,
230
+						[
231
+							'tree_id' . $i => $tree->id(),
232
+							'user_id' . $i => $user->id(),
233
+							'sosa' . $i => $row['sosa'],
234
+							'indi_id' . $i => $row['indi'],
235
+							'gen' . $i => $gen,
236
+							'byear' . $i => $row['birth_year'],
237
+							'byearest' . $i => $row['birth_year_est'],
238
+							'dyear' . $i => $row['death_year'],
239
+							'dyearest' . $i => $row['death_year_est']
240
+						]
241
+					);
242
+				} else {
243
+					DB::table('maj_sosa')->updateOrInsert(
244
+						[ 'majs_gedcom_id' => $tree->id(), 'majs_user_id' => $user->id(), 'majs_sosa' => $row['sosa']],
245
+						[
246
+							'majs_i_id' => $row['indi'],
247
+							'majs_gen' => $gen,
248
+							'majs_birth_year' => $row['birth_year'],
249
+							'majs_birth_year_est' => $row['birth_year_est'],
250
+							'majs_death_year' => $row['death_year'],
251
+							'majs_death_year_est' => $row['death_year_est']
252
+						]
253
+					);
254
+				}
255
+			}
256
+		}
257 257
 
258
-        if ($mass_update) {
259
-            DB::connection()->statement(
260
-                'INSERT INTO `' . DB::connection()->getTablePrefix() . 'maj_sosa`' .
261
-                ' (majs_gedcom_id, majs_user_id, majs_sosa,' .
262
-                '   majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
263
-                ' VALUES ' . implode(',', $bindings_placeholders) .
264
-                ' ON DUPLICATE KEY UPDATE majs_i_id = VALUES(majs_i_id), majs_gen = VALUES(majs_gen),' .
265
-                '   majs_birth_year = VALUES(majs_birth_year), majs_birth_year_est = VALUES(majs_birth_year_est),' .
266
-                '   majs_death_year = VALUES(majs_death_year), majs_death_year_est = VALUES(majs_death_year_est)',
267
-                $bindings_values
268
-            );
269
-        }
270
-    }
258
+		if ($mass_update) {
259
+			DB::connection()->statement(
260
+				'INSERT INTO `' . DB::connection()->getTablePrefix() . 'maj_sosa`' .
261
+				' (majs_gedcom_id, majs_user_id, majs_sosa,' .
262
+				'   majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
263
+				' VALUES ' . implode(',', $bindings_placeholders) .
264
+				' ON DUPLICATE KEY UPDATE majs_i_id = VALUES(majs_i_id), majs_gen = VALUES(majs_gen),' .
265
+				'   majs_birth_year = VALUES(majs_birth_year), majs_birth_year_est = VALUES(majs_birth_year_est),' .
266
+				'   majs_death_year = VALUES(majs_death_year), majs_death_year_est = VALUES(majs_death_year_est)',
267
+				$bindings_values
268
+			);
269
+		}
270
+	}
271 271
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Services/SosaStatisticsService.php 1 patch
Indentation   +500 added lines, -500 removed lines patch added patch discarded remove patch
@@ -29,511 +29,511 @@
 block discarded – undo
29 29
 class SosaStatisticsService
30 30
 {
31 31
 
32
-    /**
33
-     * Reference user
34
-     * @var User $user
35
-     */
36
-    private $user;
37
-
38
-    /**
39
-     * Reference tree
40
-     * @var Tree $tree
41
-     */
42
-    private $tree;
43
-
44
-    /**
45
-     * Constructor for Sosa Statistics Service
46
-     *
47
-     * @param Tree $tree
48
-     * @param User $user
49
-     */
50
-    public function __construct(Tree $tree, User $user)
51
-    {
52
-        $this->tree = $tree;
53
-        $this->user = $user;
54
-    }
55
-
56
-    /**
57
-     * Return the root individual for the reference tree and user.
58
-     *
59
-     * @return Individual|NULL
60
-     */
61
-    public function rootIndividual(): ?Individual
62
-    {
63
-        $root_indi_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
64
-        return Registry::individualFactory()->make($root_indi_id, $this->tree);
65
-    }
66
-
67
-    /**
68
-     * Get the highest generation for the reference tree and user.
69
-     *
70
-     * @return int
71
-     */
72
-    public function maxGeneration(): int
73
-    {
74
-        return (int) DB::table('maj_sosa')
75
-            ->where('majs_gedcom_id', '=', $this->tree->id())
76
-            ->where('majs_user_id', '=', $this->user->id())
77
-            ->max('majs_gen');
78
-    }
79
-
80
-    /**
81
-     * Get the total count of individuals in the tree.
82
-     *
83
-     * @return int
84
-     */
85
-    public function totalIndividuals(): int
86
-    {
87
-        return DB::table('individuals')
88
-            ->where('i_file', '=', $this->tree->id())
89
-            ->count();
90
-    }
91
-
92
-    /**
93
-     * Get the total count of Sosa ancestors for all generations
94
-     *
95
-     * @return int
96
-     */
97
-    public function totalAncestors(): int
98
-    {
99
-        return DB::table('maj_sosa')
100
-            ->where('majs_gedcom_id', '=', $this->tree->id())
101
-            ->where('majs_user_id', '=', $this->user->id())
102
-            ->count();
103
-    }
104
-
105
-    /**
106
-     * Get the total count of Sosa ancestors for a generation
107
-     *
108
-     * @return int
109
-     */
110
-    public function totalAncestorsAtGeneration(int $gen): int
111
-    {
112
-        return DB::table('maj_sosa')
113
-            ->where('majs_gedcom_id', '=', $this->tree->id())
114
-            ->where('majs_user_id', '=', $this->user->id())
115
-            ->where('majs_gen', '=', $gen)
116
-            ->count();
117
-    }
118
-
119
-    /**
120
-     * Get the total count of distinct Sosa ancestors for all generations
121
-     *
122
-     * @return int
123
-     */
124
-    public function totalDistinctAncestors(): int
125
-    {
126
-        return DB::table('maj_sosa')
127
-            ->where('majs_gedcom_id', '=', $this->tree->id())
128
-            ->where('majs_user_id', '=', $this->user->id())
129
-            ->distinct()
130
-            ->count('majs_i_id');
131
-    }
132
-
133
-    /**
134
-     * Get the mean generation time, as the slope of the linear regression of birth years vs generations
135
-     *
136
-     * @return float
137
-     */
138
-    public function meanGenerationTime(): float
139
-    {
140
-        $row = DB::table('maj_sosa')
141
-            ->where('majs_gedcom_id', '=', $this->tree->id())
142
-            ->where('majs_user_id', '=', $this->user->id())
143
-            ->whereNotNull('majs_birth_year')
144
-            ->selectRaw('COUNT(majs_sosa) AS n')
145
-            ->selectRaw('SUM(majs_gen * majs_birth_year) AS sum_xy')
146
-            ->selectRaw('SUM(majs_gen) AS sum_x')
147
-            ->selectRaw('SUM(majs_birth_year) AS sum_y')
148
-            ->selectRaw('SUM(majs_gen * majs_gen) AS sum_x2')
149
-            ->get()->first();
150
-
151
-        return $row->n == 0 ? 0 :
152
-            -($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / ($row->n * $row->sum_x2 - pow($row->sum_x, 2));
153
-    }
154
-
155
-    /**
156
-     * Get the statistic array detailed by generation.
157
-     * Statistics for each generation are:
158
-     *  - The number of Sosa in generation
159
-     *  - The number of Sosa up to generation
160
-     *  - The number of distinct Sosa up to generation
161
-     *  - The year of the first birth in generation
162
-     *  - The year of the first estimated birth in generation
163
-     *  - The year of the last birth in generation
164
-     *  - The year of the last estimated birth in generation
165
-     *  - The average year of birth in generation
166
-     *
167
-     * @return array<int, array<string, int|null>> Statistics array
168
-     */
169
-    public function statisticsByGenerations(): array
170
-    {
171
-        $stats_by_gen = $this->statisticsByGenerationBasicData();
172
-        $cumul_stats_by_gen = $this->statisticsByGenerationCumulativeData();
173
-
174
-        $statistics_by_gen = [];
175
-        foreach ($stats_by_gen as $gen => $stats_gen) {
176
-            $statistics_by_gen[(int) $stats_gen->gen] = array(
177
-                'sosaCount'             =>  (int) $stats_gen->total_sosa,
178
-                'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
179
-                'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
180
-                'firstBirth'            =>  $stats_gen->first_year,
181
-                'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
182
-                'lastBirth'             =>  $stats_gen->last_year,
183
-                'lastEstimatedBirth'    =>  $stats_gen->last_est_year
184
-            );
185
-        }
186
-
187
-        return $statistics_by_gen;
188
-    }
189
-
190
-    /**
191
-     * Returns the basic statistics data by generation.
192
-     *
193
-     * @return Collection
194
-     */
195
-    private function statisticsByGenerationBasicData(): Collection
196
-    {
197
-        return DB::table('maj_sosa')
198
-            ->where('majs_gedcom_id', '=', $this->tree->id())
199
-            ->where('majs_user_id', '=', $this->user->id())
200
-            ->groupBy('majs_gen')
201
-            ->orderBy('majs_gen', 'asc')
202
-            ->select('majs_gen AS gen')
203
-            ->selectRaw('COUNT(majs_sosa) AS total_sosa')
204
-            ->selectRaw('MIN(majs_birth_year) AS first_year')
205
-            ->selectRaw('MIN(majs_birth_year_est) AS first_est_year')
206
-            ->selectRaw('MAX(majs_birth_year) AS last_year')
207
-            ->selectRaw('MAX(majs_birth_year_est) AS last_est_year')
208
-            ->get()->keyBy('gen');
209
-    }
210
-
211
-    /**
212
-     * Returns the cumulative statistics data by generation
213
-     *
214
-     * @return Collection
215
-     */
216
-    private function statisticsByGenerationCumulativeData(): Collection
217
-    {
218
-        $list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
219
-            ->where('majs_gedcom_id', '=', $this->tree->id())
220
-            ->where('majs_user_id', '=', $this->user->id());
221
-
222
-        return DB::table('maj_sosa')
223
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
224
-                $join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
225
-                ->where('majs_gedcom_id', '=', $this->tree->id())
226
-                ->where('majs_user_id', '=', $this->user->id());
227
-            })
228
-            ->groupBy('list_gen.majs_gen')
229
-            ->select('list_gen.majs_gen AS gen')
230
-            ->selectRaw('COUNT(majs_i_id) AS total_cumul')
231
-            ->selectRaw('COUNT(DISTINCT majs_i_id) AS total_distinct_cumul')
232
-            ->selectRaw('1 - COUNT(DISTINCT majs_i_id) / COUNT(majs_i_id) AS pedi_collapse_simple')
233
-            ->get()->keyBy('gen');
234
-    }
235
-
236
-    /**
237
-     * Returns the pedigree collapse improved calculation by generation.
238
-     *
239
-     * Format:
240
-     *  - key : generation
241
-     *  - values:
242
-     *      - pedi_collapse_roots : pedigree collapse of ancestor roots for the generation
243
-     *      - pedi_collapse_xgen : pedigree cross-generation shrinkage for the generation
244
-     *
245
-     * @return array<int, array<string, float>>
246
-     */
247
-    public function pedigreeCollapseByGenerationData(): array
248
-    {
249
-        $table_prefix = DB::connection()->getTablePrefix();
250
-
251
-        $list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
252
-            ->where('majs_gedcom_id', '=', $this->tree->id())
253
-            ->where('majs_user_id', '=', $this->user->id());
254
-
255
-        /* Compute the contributions of nodes of previous generations to the current generation */
256
-        $root_ancestors_contributions = DB::table('maj_sosa AS sosa')
257
-            ->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
258
-            ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
259
-            ->selectRaw(
260
-                '(CASE ' .
261
-                    ' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
262
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
263
-                    ' ELSE 0 ' .
264
-                ' END)' .
265
-                ' + (CASE ' .
266
-                    ' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
267
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
268
-                    ' ELSE 0 ' .
269
-                ' END) contrib'
270
-            )
271
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
272
-                $join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
273
-                    ->where('majs_gedcom_id', '=', $this->tree->id())
274
-                    ->where('majs_user_id', '=', $this->user->id());
275
-            })
276
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
277
-                // Link to sosa's father
278
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
279
-                    ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
280
-                    ->where('sosa_fat.majs_user_id', '=', $this->user->id());
281
-            })
282
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
283
-                // Link to sosa's mother
284
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
285
-                    ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
286
-                    ->where('sosa_mot.majs_user_id', '=', $this->user->id());
287
-            })
288
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
289
-            ->where('sosa.majs_user_id', '=', $this->user->id())
290
-            ->where(function (Builder $query): void {
291
-                $query->whereNull('sosa_fat.majs_i_id')
292
-                ->orWhereNull('sosa_mot.majs_i_id');
293
-            });
294
-
295
-        /* Identify nodes in the generations with ancestors who are also in the same generation.
32
+	/**
33
+	 * Reference user
34
+	 * @var User $user
35
+	 */
36
+	private $user;
37
+
38
+	/**
39
+	 * Reference tree
40
+	 * @var Tree $tree
41
+	 */
42
+	private $tree;
43
+
44
+	/**
45
+	 * Constructor for Sosa Statistics Service
46
+	 *
47
+	 * @param Tree $tree
48
+	 * @param User $user
49
+	 */
50
+	public function __construct(Tree $tree, User $user)
51
+	{
52
+		$this->tree = $tree;
53
+		$this->user = $user;
54
+	}
55
+
56
+	/**
57
+	 * Return the root individual for the reference tree and user.
58
+	 *
59
+	 * @return Individual|NULL
60
+	 */
61
+	public function rootIndividual(): ?Individual
62
+	{
63
+		$root_indi_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
64
+		return Registry::individualFactory()->make($root_indi_id, $this->tree);
65
+	}
66
+
67
+	/**
68
+	 * Get the highest generation for the reference tree and user.
69
+	 *
70
+	 * @return int
71
+	 */
72
+	public function maxGeneration(): int
73
+	{
74
+		return (int) DB::table('maj_sosa')
75
+			->where('majs_gedcom_id', '=', $this->tree->id())
76
+			->where('majs_user_id', '=', $this->user->id())
77
+			->max('majs_gen');
78
+	}
79
+
80
+	/**
81
+	 * Get the total count of individuals in the tree.
82
+	 *
83
+	 * @return int
84
+	 */
85
+	public function totalIndividuals(): int
86
+	{
87
+		return DB::table('individuals')
88
+			->where('i_file', '=', $this->tree->id())
89
+			->count();
90
+	}
91
+
92
+	/**
93
+	 * Get the total count of Sosa ancestors for all generations
94
+	 *
95
+	 * @return int
96
+	 */
97
+	public function totalAncestors(): int
98
+	{
99
+		return DB::table('maj_sosa')
100
+			->where('majs_gedcom_id', '=', $this->tree->id())
101
+			->where('majs_user_id', '=', $this->user->id())
102
+			->count();
103
+	}
104
+
105
+	/**
106
+	 * Get the total count of Sosa ancestors for a generation
107
+	 *
108
+	 * @return int
109
+	 */
110
+	public function totalAncestorsAtGeneration(int $gen): int
111
+	{
112
+		return DB::table('maj_sosa')
113
+			->where('majs_gedcom_id', '=', $this->tree->id())
114
+			->where('majs_user_id', '=', $this->user->id())
115
+			->where('majs_gen', '=', $gen)
116
+			->count();
117
+	}
118
+
119
+	/**
120
+	 * Get the total count of distinct Sosa ancestors for all generations
121
+	 *
122
+	 * @return int
123
+	 */
124
+	public function totalDistinctAncestors(): int
125
+	{
126
+		return DB::table('maj_sosa')
127
+			->where('majs_gedcom_id', '=', $this->tree->id())
128
+			->where('majs_user_id', '=', $this->user->id())
129
+			->distinct()
130
+			->count('majs_i_id');
131
+	}
132
+
133
+	/**
134
+	 * Get the mean generation time, as the slope of the linear regression of birth years vs generations
135
+	 *
136
+	 * @return float
137
+	 */
138
+	public function meanGenerationTime(): float
139
+	{
140
+		$row = DB::table('maj_sosa')
141
+			->where('majs_gedcom_id', '=', $this->tree->id())
142
+			->where('majs_user_id', '=', $this->user->id())
143
+			->whereNotNull('majs_birth_year')
144
+			->selectRaw('COUNT(majs_sosa) AS n')
145
+			->selectRaw('SUM(majs_gen * majs_birth_year) AS sum_xy')
146
+			->selectRaw('SUM(majs_gen) AS sum_x')
147
+			->selectRaw('SUM(majs_birth_year) AS sum_y')
148
+			->selectRaw('SUM(majs_gen * majs_gen) AS sum_x2')
149
+			->get()->first();
150
+
151
+		return $row->n == 0 ? 0 :
152
+			-($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / ($row->n * $row->sum_x2 - pow($row->sum_x, 2));
153
+	}
154
+
155
+	/**
156
+	 * Get the statistic array detailed by generation.
157
+	 * Statistics for each generation are:
158
+	 *  - The number of Sosa in generation
159
+	 *  - The number of Sosa up to generation
160
+	 *  - The number of distinct Sosa up to generation
161
+	 *  - The year of the first birth in generation
162
+	 *  - The year of the first estimated birth in generation
163
+	 *  - The year of the last birth in generation
164
+	 *  - The year of the last estimated birth in generation
165
+	 *  - The average year of birth in generation
166
+	 *
167
+	 * @return array<int, array<string, int|null>> Statistics array
168
+	 */
169
+	public function statisticsByGenerations(): array
170
+	{
171
+		$stats_by_gen = $this->statisticsByGenerationBasicData();
172
+		$cumul_stats_by_gen = $this->statisticsByGenerationCumulativeData();
173
+
174
+		$statistics_by_gen = [];
175
+		foreach ($stats_by_gen as $gen => $stats_gen) {
176
+			$statistics_by_gen[(int) $stats_gen->gen] = array(
177
+				'sosaCount'             =>  (int) $stats_gen->total_sosa,
178
+				'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
179
+				'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
180
+				'firstBirth'            =>  $stats_gen->first_year,
181
+				'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
182
+				'lastBirth'             =>  $stats_gen->last_year,
183
+				'lastEstimatedBirth'    =>  $stats_gen->last_est_year
184
+			);
185
+		}
186
+
187
+		return $statistics_by_gen;
188
+	}
189
+
190
+	/**
191
+	 * Returns the basic statistics data by generation.
192
+	 *
193
+	 * @return Collection
194
+	 */
195
+	private function statisticsByGenerationBasicData(): Collection
196
+	{
197
+		return DB::table('maj_sosa')
198
+			->where('majs_gedcom_id', '=', $this->tree->id())
199
+			->where('majs_user_id', '=', $this->user->id())
200
+			->groupBy('majs_gen')
201
+			->orderBy('majs_gen', 'asc')
202
+			->select('majs_gen AS gen')
203
+			->selectRaw('COUNT(majs_sosa) AS total_sosa')
204
+			->selectRaw('MIN(majs_birth_year) AS first_year')
205
+			->selectRaw('MIN(majs_birth_year_est) AS first_est_year')
206
+			->selectRaw('MAX(majs_birth_year) AS last_year')
207
+			->selectRaw('MAX(majs_birth_year_est) AS last_est_year')
208
+			->get()->keyBy('gen');
209
+	}
210
+
211
+	/**
212
+	 * Returns the cumulative statistics data by generation
213
+	 *
214
+	 * @return Collection
215
+	 */
216
+	private function statisticsByGenerationCumulativeData(): Collection
217
+	{
218
+		$list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
219
+			->where('majs_gedcom_id', '=', $this->tree->id())
220
+			->where('majs_user_id', '=', $this->user->id());
221
+
222
+		return DB::table('maj_sosa')
223
+			->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
224
+				$join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
225
+				->where('majs_gedcom_id', '=', $this->tree->id())
226
+				->where('majs_user_id', '=', $this->user->id());
227
+			})
228
+			->groupBy('list_gen.majs_gen')
229
+			->select('list_gen.majs_gen AS gen')
230
+			->selectRaw('COUNT(majs_i_id) AS total_cumul')
231
+			->selectRaw('COUNT(DISTINCT majs_i_id) AS total_distinct_cumul')
232
+			->selectRaw('1 - COUNT(DISTINCT majs_i_id) / COUNT(majs_i_id) AS pedi_collapse_simple')
233
+			->get()->keyBy('gen');
234
+	}
235
+
236
+	/**
237
+	 * Returns the pedigree collapse improved calculation by generation.
238
+	 *
239
+	 * Format:
240
+	 *  - key : generation
241
+	 *  - values:
242
+	 *      - pedi_collapse_roots : pedigree collapse of ancestor roots for the generation
243
+	 *      - pedi_collapse_xgen : pedigree cross-generation shrinkage for the generation
244
+	 *
245
+	 * @return array<int, array<string, float>>
246
+	 */
247
+	public function pedigreeCollapseByGenerationData(): array
248
+	{
249
+		$table_prefix = DB::connection()->getTablePrefix();
250
+
251
+		$list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
252
+			->where('majs_gedcom_id', '=', $this->tree->id())
253
+			->where('majs_user_id', '=', $this->user->id());
254
+
255
+		/* Compute the contributions of nodes of previous generations to the current generation */
256
+		$root_ancestors_contributions = DB::table('maj_sosa AS sosa')
257
+			->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
258
+			->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
259
+			->selectRaw(
260
+				'(CASE ' .
261
+					' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
262
+					' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
263
+					' ELSE 0 ' .
264
+				' END)' .
265
+				' + (CASE ' .
266
+					' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
267
+					' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
268
+					' ELSE 0 ' .
269
+				' END) contrib'
270
+			)
271
+			->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
272
+				$join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
273
+					->where('majs_gedcom_id', '=', $this->tree->id())
274
+					->where('majs_user_id', '=', $this->user->id());
275
+			})
276
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
277
+				// Link to sosa's father
278
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
279
+					->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
280
+					->where('sosa_fat.majs_user_id', '=', $this->user->id());
281
+			})
282
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
283
+				// Link to sosa's mother
284
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
285
+					->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
286
+					->where('sosa_mot.majs_user_id', '=', $this->user->id());
287
+			})
288
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
289
+			->where('sosa.majs_user_id', '=', $this->user->id())
290
+			->where(function (Builder $query): void {
291
+				$query->whereNull('sosa_fat.majs_i_id')
292
+				->orWhereNull('sosa_mot.majs_i_id');
293
+			});
294
+
295
+		/* Identify nodes in the generations with ancestors who are also in the same generation.
296 296
          * This is the vertical/generational collapse that will reduce the number or roots.
297 297
          */
298
-        $non_roots_ancestors = DB::table('maj_sosa AS sosa')
299
-            ->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
300
-            ->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
301
-                ' AS full_ancestors')
302
-            ->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
303
-                $join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
304
-                    ->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
305
-                        $table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
306
-                        $table_prefix . 'sosa.majs_sosa')
307
-                    ->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
308
-                    ->where('sosa_anc.majs_user_id', '=', $this->user->id());
309
-            })
310
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
311
-            ->where('sosa.majs_user_id', '=', $this->user->id())
312
-            ->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
313
-                $query->from('maj_sosa AS sosa_gen')
314
-                ->select('sosa_gen.majs_i_id')->distinct()
315
-                ->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
316
-                ->where('sosa_gen.majs_user_id', '=', $this->user->id())
317
-                ->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
318
-            })
319
-            ->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
320
-                'sosa.majs_sosa', 'sosa.majs_i_id']);
321
-
322
-        /* Compute the contribution of the nodes in the generation,
298
+		$non_roots_ancestors = DB::table('maj_sosa AS sosa')
299
+			->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
300
+			->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
301
+				' AS full_ancestors')
302
+			->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
303
+				$join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
304
+					->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
305
+						$table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
306
+						$table_prefix . 'sosa.majs_sosa')
307
+					->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
308
+					->where('sosa_anc.majs_user_id', '=', $this->user->id());
309
+			})
310
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
311
+			->where('sosa.majs_user_id', '=', $this->user->id())
312
+			->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
313
+				$query->from('maj_sosa AS sosa_gen')
314
+				->select('sosa_gen.majs_i_id')->distinct()
315
+				->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
316
+				->where('sosa_gen.majs_user_id', '=', $this->user->id())
317
+				->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
318
+			})
319
+			->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
320
+				'sosa.majs_sosa', 'sosa.majs_i_id']);
321
+
322
+		/* Compute the contribution of the nodes in the generation,
323 323
          * excluding the nodes with ancestors in the same generation.
324 324
          * Nodes with a parent missing are not excluded to cater for the missing one.
325 325
          */
326
-        $known_ancestors_contributions = DB::table('maj_sosa AS sosa')
327
-            ->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
328
-            ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
329
-            ->selectRaw('1 AS contrib')
330
-            ->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
331
-                $join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
332
-                    ->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
333
-                    ->where('nonroot.full_ancestors', '>', 0)
334
-                    ->where('nonroot.majs_gedcom_id', '=', $this->tree->id())
335
-                    ->where('nonroot.majs_user_id', '=', $this->user->id());
336
-            })
337
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
338
-            ->where('sosa.majs_user_id', '=', $this->user->id())
339
-            ->whereNull('nonroot.majs_sosa');
340
-
341
-        /* Aggregate both queries, and calculate the sum of contributions by generation roots.
326
+		$known_ancestors_contributions = DB::table('maj_sosa AS sosa')
327
+			->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
328
+			->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
329
+			->selectRaw('1 AS contrib')
330
+			->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
331
+				$join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
332
+					->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
333
+					->where('nonroot.full_ancestors', '>', 0)
334
+					->where('nonroot.majs_gedcom_id', '=', $this->tree->id())
335
+					->where('nonroot.majs_user_id', '=', $this->user->id());
336
+			})
337
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
338
+			->where('sosa.majs_user_id', '=', $this->user->id())
339
+			->whereNull('nonroot.majs_sosa');
340
+
341
+		/* Aggregate both queries, and calculate the sum of contributions by generation roots.
342 342
          * Exclude as well nodes that already appear in lower generations, as their branche has already been reduced.
343 343
          */
344
-        $ancestors_contributions_sum = DB::connection()->query()
345
-            ->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
346
-            ->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
347
-            ->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
348
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
349
-                $table_prefix . 'sosa_contribs.contrib AS totalContrib')
350
-            ->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
351
-                $join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
352
-                    ->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
353
-                    ->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
354
-                    ->where('sosa_low.majs_user_id', '=', $this->user->id());
355
-            })
356
-            ->whereNull('sosa_low.majs_sosa')
357
-            ->groupBy(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id',
358
-                'sosa_contribs.majs_i_id', 'sosa_contribs.contrib']);
359
-
360
-        // Aggregate all generation roots to compute root and generation pedigree collapse
361
-        $pedi_collapse_coll = DB::connection()->query()->fromSub($ancestors_contributions_sum, 'sosa_contribs_sum')
362
-            ->select(['gen'])->selectRaw('SUM(contrib), SUM(totalContrib)')
363
-            ->selectRaw('1 - SUM(contrib) / SUM(totalContrib) AS pedi_collapse_roots')  // Roots/horizontal collapse
364
-            ->selectRaw('1 - SUM(totalContrib) / POWER ( 2, gen - 1) AS pedi_collapse_xgen') // Crossgeneration collapse
365
-            ->groupBy(['gen', 'majs_gedcom_id', 'majs_user_id'])
366
-            ->orderBy('gen')
367
-            ->get();
368
-
369
-        $pedi_collapse_by_gen = [];
370
-        foreach ($pedi_collapse_coll as $collapse_gen) {
371
-            $pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
372
-                'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
373
-                'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
374
-            );
375
-        }
376
-        return $pedi_collapse_by_gen;
377
-    }
378
-
379
-    /**
380
-     * Return a Collection of the mean generation depth and deviation for all Sosa ancestors at a given generation.
381
-     * Sosa 1 is of generation 1.
382
-     *
383
-     * Mean generation depth and deviation are calculated based on the works of Marie-Héléne Cazes and Pierre Cazes,
384
-     * published in Population (French Edition), Vol. 51, No. 1 (Jan. - Feb., 1996), pp. 117-140
385
-     * http://kintip.net/index.php?option=com_jdownloads&task=download.send&id=9&catid=4&m=0
386
-     *
387
-     * Format:
388
-     *  - key : sosa number of the ancestor
389
-     *  - values:
390
-     *      - root_ancestor_id : ID of the ancestor
391
-     *      - mean_gen_depth : Mean generation depth
392
-     *      - stddev_gen_depth : Standard deviation of generation depth
393
-     *
394
-     * @param int $gen Sosa generation
395
-     * @return Collection
396
-     */
397
-    public function generationDepthStatsAtGeneration(int $gen): Collection
398
-    {
399
-        $table_prefix = DB::connection()->getTablePrefix();
400
-        $missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
401
-            ->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
402
-            ->selectRaw('FLOOR(((' . $table_prefix . 'sosa.majs_sosa / POW(2, ' . $table_prefix . 'sosa.majs_gen -1 )) - 1) * POWER(2, ? - 1)) + POWER(2, ? - 1) AS root_ancestor', [$gen, $gen])   //@phpcs:ignore Generic.Files.LineLength.TooLong
403
-            ->selectRaw('SUM(CASE WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL AND ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL THEN 1 ELSE 0 END) AS full_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
404
-            ->selectRaw('SUM(CASE WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL AND ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL THEN 0 ELSE 1 END) As semi_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
405
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
406
-                // Link to sosa's father
407
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
408
-                ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
409
-                ->where('sosa_fat.majs_user_id', '=', $this->user->id());
410
-            })
411
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
412
-                // Link to sosa's mother
413
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
414
-                ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
415
-                ->where('sosa_mot.majs_user_id', '=', $this->user->id());
416
-            })
417
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
418
-            ->where('sosa.majs_user_id', '=', $this->user->id())
419
-            ->where('sosa.majs_gen', '>=', $gen)
420
-            ->where(function (Builder $query): void {
421
-                $query->whereNull('sosa_fat.majs_i_id')
422
-                    ->orWhereNull('sosa_mot.majs_i_id');
423
-            })
424
-            ->groupBy(['sosa.majs_gen', 'root_ancestor']);
425
-
426
-        return DB::table('maj_sosa AS sosa_list')
427
-            ->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
428
-            ->selectRaw('1 + SUM( (majs_gen_norm) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm))) AS mean_gen_depth')  //@phpcs:ignore Generic.Files.LineLength.TooLong
429
-            ->selectRaw(' SQRT(' .
430
-                '   SUM(POWER(majs_gen_norm, 2) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm)))' .     //@phpcs:ignore Generic.Files.LineLength.TooLong
431
-                '   - POWER( SUM( (majs_gen_norm) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm))), 2)' .       //@phpcs:ignore Generic.Files.LineLength.TooLong
432
-                ' ) AS stddev_gen_depth')
433
-            ->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
434
-                $join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
435
-                    ->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
436
-                    ->where('sosa_list.majs_user_id', '=', $this->user->id());
437
-            })
438
-            ->groupBy(['stats_by_gen.root_ancestor', 'sosa_list.majs_i_id'])
439
-            ->orderBy('stats_by_gen.root_ancestor')
440
-            ->get()->keyBy('root_ancestor_sosa');
441
-    }
442
-
443
-    /**
444
-     * Return a collection of the most duplicated root Sosa ancestors.
445
-     * The number of ancestors to return is limited by the parameter $limit.
446
-     * If several individuals are tied when reaching the limit, none of them are returned,
447
-     * which means that there can be less individuals returned than requested.
448
-     *
449
-     * Format:
450
-     *  - value:
451
-     *      - sosa_i_id : sosa individual
452
-     *      - sosa_count: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
453
-     *
454
-     * @param int $limit
455
-     * @return Collection
456
-     */
457
-    public function topMultipleAncestorsWithNoTies(int $limit): Collection
458
-    {
459
-        $table_prefix = DB::connection()->getTablePrefix();
460
-        $multiple_ancestors = DB::table('maj_sosa AS sosa')
461
-            ->select('sosa.majs_i_id AS sosa_i_id')
462
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
463
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
464
-                // Link to sosa's father
465
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
466
-                    ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
467
-                    ->where('sosa_fat.majs_user_id', '=', $this->user->id());
468
-            })
469
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
470
-                // Link to sosa's mother
471
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
472
-                ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
473
-                ->where('sosa_mot.majs_user_id', '=', $this->user->id());
474
-            })
475
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
476
-            ->where('sosa.majs_user_id', '=', $this->user->id())
477
-            ->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
478
-            ->whereNull('sosa_mot.majs_sosa')
479
-            ->groupBy('sosa.majs_i_id')
480
-            ->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
481
-            ->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
482
-            ->limit($limit + 1)     // We want to select one more than required, for ties
483
-            ->get();
484
-
485
-        if ($multiple_ancestors->count() > $limit) {
486
-            $last_count = $multiple_ancestors->last()->sosa_count;
487
-            $multiple_ancestors = $multiple_ancestors->reject(function ($element) use ($last_count): bool {
488
-                return $element->sosa_count ==  $last_count;
489
-            });
490
-        }
491
-        return $multiple_ancestors;
492
-    }
493
-
494
-    /**
495
-     * Return a computed array of statistics about the dispersion of ancestors across the ancestors
496
-     * at a specified generation.
497
-     *
498
-     * Format:
499
-     *  - key : rank of the ancestor in generation G for which exclusive ancestors have been found
500
-     *          For instance 3 represent the maternal grand father
501
-     *          0 is used for shared ancestors
502
-     *  - values: number of ancestors exclusively in the ancestors of the ancestor in key
503
-     *
504
-     *  For instance a result at generation 3 could be :
505
-     *      array (   0     =>  12      -> 12 ancestors are shared by the grand-parents
506
-     *                1     =>  32      -> 32 ancestors are exclusive to the paternal grand-father
507
-     *                2     =>  25      -> 25 ancestors are exclusive to the paternal grand-mother
508
-     *                3     =>  12      -> 12 ancestors are exclusive to the maternal grand-father
509
-     *                4     =>  30      -> 30 ancestors are exclusive to the maternal grand-mother
510
-     *            )
511
-     *
512
-     * @param int $gen
513
-     * @return Collection
514
-     */
515
-    public function ancestorsDispersionForGeneration(int $gen): Collection
516
-    {
517
-        $ancestors_branches = DB::table('maj_sosa')
518
-            ->select('majs_i_id AS i_id')
519
-            ->selectRaw('FLOOR(majs_sosa / POW(2, (majs_gen - ?))) - POW(2, ? -1) + 1 AS branch', [$gen, $gen])
520
-            ->where('majs_gedcom_id', '=', $this->tree->id())
521
-            ->where('majs_user_id', '=', $this->user->id())
522
-            ->where('majs_gen', '>=', $gen)
523
-            ->groupBy('majs_i_id', 'branch');
524
-
525
-
526
-        $consolidated_ancestors_branches = DB::table('maj_sosa')
527
-            ->fromSub($ancestors_branches, 'indi_branch')
528
-            ->select('i_id')
529
-            ->selectRaw('CASE WHEN COUNT(branch) > 1 THEN 0 ELSE MIN(branch) END AS branches')
530
-            ->groupBy('i_id');
531
-
532
-        return DB::table('maj_sosa')
533
-            ->fromSub($consolidated_ancestors_branches, 'indi_branch_consolidated')
534
-            ->select('branches')
535
-            ->selectRaw('COUNT(i_id) AS count_indi')
536
-            ->groupBy('branches')
537
-            ->get()->pluck('count_indi', 'branches');
538
-    }
344
+		$ancestors_contributions_sum = DB::connection()->query()
345
+			->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
346
+			->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
347
+			->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
348
+			->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
349
+				$table_prefix . 'sosa_contribs.contrib AS totalContrib')
350
+			->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
351
+				$join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
352
+					->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
353
+					->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
354
+					->where('sosa_low.majs_user_id', '=', $this->user->id());
355
+			})
356
+			->whereNull('sosa_low.majs_sosa')
357
+			->groupBy(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id',
358
+				'sosa_contribs.majs_i_id', 'sosa_contribs.contrib']);
359
+
360
+		// Aggregate all generation roots to compute root and generation pedigree collapse
361
+		$pedi_collapse_coll = DB::connection()->query()->fromSub($ancestors_contributions_sum, 'sosa_contribs_sum')
362
+			->select(['gen'])->selectRaw('SUM(contrib), SUM(totalContrib)')
363
+			->selectRaw('1 - SUM(contrib) / SUM(totalContrib) AS pedi_collapse_roots')  // Roots/horizontal collapse
364
+			->selectRaw('1 - SUM(totalContrib) / POWER ( 2, gen - 1) AS pedi_collapse_xgen') // Crossgeneration collapse
365
+			->groupBy(['gen', 'majs_gedcom_id', 'majs_user_id'])
366
+			->orderBy('gen')
367
+			->get();
368
+
369
+		$pedi_collapse_by_gen = [];
370
+		foreach ($pedi_collapse_coll as $collapse_gen) {
371
+			$pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
372
+				'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
373
+				'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
374
+			);
375
+		}
376
+		return $pedi_collapse_by_gen;
377
+	}
378
+
379
+	/**
380
+	 * Return a Collection of the mean generation depth and deviation for all Sosa ancestors at a given generation.
381
+	 * Sosa 1 is of generation 1.
382
+	 *
383
+	 * Mean generation depth and deviation are calculated based on the works of Marie-Héléne Cazes and Pierre Cazes,
384
+	 * published in Population (French Edition), Vol. 51, No. 1 (Jan. - Feb., 1996), pp. 117-140
385
+	 * http://kintip.net/index.php?option=com_jdownloads&task=download.send&id=9&catid=4&m=0
386
+	 *
387
+	 * Format:
388
+	 *  - key : sosa number of the ancestor
389
+	 *  - values:
390
+	 *      - root_ancestor_id : ID of the ancestor
391
+	 *      - mean_gen_depth : Mean generation depth
392
+	 *      - stddev_gen_depth : Standard deviation of generation depth
393
+	 *
394
+	 * @param int $gen Sosa generation
395
+	 * @return Collection
396
+	 */
397
+	public function generationDepthStatsAtGeneration(int $gen): Collection
398
+	{
399
+		$table_prefix = DB::connection()->getTablePrefix();
400
+		$missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
401
+			->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
402
+			->selectRaw('FLOOR(((' . $table_prefix . 'sosa.majs_sosa / POW(2, ' . $table_prefix . 'sosa.majs_gen -1 )) - 1) * POWER(2, ? - 1)) + POWER(2, ? - 1) AS root_ancestor', [$gen, $gen])   //@phpcs:ignore Generic.Files.LineLength.TooLong
403
+			->selectRaw('SUM(CASE WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL AND ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL THEN 1 ELSE 0 END) AS full_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
404
+			->selectRaw('SUM(CASE WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL AND ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL THEN 0 ELSE 1 END) As semi_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
405
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
406
+				// Link to sosa's father
407
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
408
+				->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
409
+				->where('sosa_fat.majs_user_id', '=', $this->user->id());
410
+			})
411
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
412
+				// Link to sosa's mother
413
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
414
+				->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
415
+				->where('sosa_mot.majs_user_id', '=', $this->user->id());
416
+			})
417
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
418
+			->where('sosa.majs_user_id', '=', $this->user->id())
419
+			->where('sosa.majs_gen', '>=', $gen)
420
+			->where(function (Builder $query): void {
421
+				$query->whereNull('sosa_fat.majs_i_id')
422
+					->orWhereNull('sosa_mot.majs_i_id');
423
+			})
424
+			->groupBy(['sosa.majs_gen', 'root_ancestor']);
425
+
426
+		return DB::table('maj_sosa AS sosa_list')
427
+			->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
428
+			->selectRaw('1 + SUM( (majs_gen_norm) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm))) AS mean_gen_depth')  //@phpcs:ignore Generic.Files.LineLength.TooLong
429
+			->selectRaw(' SQRT(' .
430
+				'   SUM(POWER(majs_gen_norm, 2) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm)))' .     //@phpcs:ignore Generic.Files.LineLength.TooLong
431
+				'   - POWER( SUM( (majs_gen_norm) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm))), 2)' .       //@phpcs:ignore Generic.Files.LineLength.TooLong
432
+				' ) AS stddev_gen_depth')
433
+			->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
434
+				$join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
435
+					->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
436
+					->where('sosa_list.majs_user_id', '=', $this->user->id());
437
+			})
438
+			->groupBy(['stats_by_gen.root_ancestor', 'sosa_list.majs_i_id'])
439
+			->orderBy('stats_by_gen.root_ancestor')
440
+			->get()->keyBy('root_ancestor_sosa');
441
+	}
442
+
443
+	/**
444
+	 * Return a collection of the most duplicated root Sosa ancestors.
445
+	 * The number of ancestors to return is limited by the parameter $limit.
446
+	 * If several individuals are tied when reaching the limit, none of them are returned,
447
+	 * which means that there can be less individuals returned than requested.
448
+	 *
449
+	 * Format:
450
+	 *  - value:
451
+	 *      - sosa_i_id : sosa individual
452
+	 *      - sosa_count: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
453
+	 *
454
+	 * @param int $limit
455
+	 * @return Collection
456
+	 */
457
+	public function topMultipleAncestorsWithNoTies(int $limit): Collection
458
+	{
459
+		$table_prefix = DB::connection()->getTablePrefix();
460
+		$multiple_ancestors = DB::table('maj_sosa AS sosa')
461
+			->select('sosa.majs_i_id AS sosa_i_id')
462
+			->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
463
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
464
+				// Link to sosa's father
465
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
466
+					->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
467
+					->where('sosa_fat.majs_user_id', '=', $this->user->id());
468
+			})
469
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
470
+				// Link to sosa's mother
471
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
472
+				->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
473
+				->where('sosa_mot.majs_user_id', '=', $this->user->id());
474
+			})
475
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
476
+			->where('sosa.majs_user_id', '=', $this->user->id())
477
+			->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
478
+			->whereNull('sosa_mot.majs_sosa')
479
+			->groupBy('sosa.majs_i_id')
480
+			->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
481
+			->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
482
+			->limit($limit + 1)     // We want to select one more than required, for ties
483
+			->get();
484
+
485
+		if ($multiple_ancestors->count() > $limit) {
486
+			$last_count = $multiple_ancestors->last()->sosa_count;
487
+			$multiple_ancestors = $multiple_ancestors->reject(function ($element) use ($last_count): bool {
488
+				return $element->sosa_count ==  $last_count;
489
+			});
490
+		}
491
+		return $multiple_ancestors;
492
+	}
493
+
494
+	/**
495
+	 * Return a computed array of statistics about the dispersion of ancestors across the ancestors
496
+	 * at a specified generation.
497
+	 *
498
+	 * Format:
499
+	 *  - key : rank of the ancestor in generation G for which exclusive ancestors have been found
500
+	 *          For instance 3 represent the maternal grand father
501
+	 *          0 is used for shared ancestors
502
+	 *  - values: number of ancestors exclusively in the ancestors of the ancestor in key
503
+	 *
504
+	 *  For instance a result at generation 3 could be :
505
+	 *      array (   0     =>  12      -> 12 ancestors are shared by the grand-parents
506
+	 *                1     =>  32      -> 32 ancestors are exclusive to the paternal grand-father
507
+	 *                2     =>  25      -> 25 ancestors are exclusive to the paternal grand-mother
508
+	 *                3     =>  12      -> 12 ancestors are exclusive to the maternal grand-father
509
+	 *                4     =>  30      -> 30 ancestors are exclusive to the maternal grand-mother
510
+	 *            )
511
+	 *
512
+	 * @param int $gen
513
+	 * @return Collection
514
+	 */
515
+	public function ancestorsDispersionForGeneration(int $gen): Collection
516
+	{
517
+		$ancestors_branches = DB::table('maj_sosa')
518
+			->select('majs_i_id AS i_id')
519
+			->selectRaw('FLOOR(majs_sosa / POW(2, (majs_gen - ?))) - POW(2, ? -1) + 1 AS branch', [$gen, $gen])
520
+			->where('majs_gedcom_id', '=', $this->tree->id())
521
+			->where('majs_user_id', '=', $this->user->id())
522
+			->where('majs_gen', '>=', $gen)
523
+			->groupBy('majs_i_id', 'branch');
524
+
525
+
526
+		$consolidated_ancestors_branches = DB::table('maj_sosa')
527
+			->fromSub($ancestors_branches, 'indi_branch')
528
+			->select('i_id')
529
+			->selectRaw('CASE WHEN COUNT(branch) > 1 THEN 0 ELSE MIN(branch) END AS branches')
530
+			->groupBy('i_id');
531
+
532
+		return DB::table('maj_sosa')
533
+			->fromSub($consolidated_ancestors_branches, 'indi_branch_consolidated')
534
+			->select('branches')
535
+			->selectRaw('COUNT(i_id) AS count_indi')
536
+			->groupBy('branches')
537
+			->get()->pluck('count_indi', 'branches');
538
+	}
539 539
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Services/SosaCalculatorService.php 1 patch
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -24,143 +24,143 @@
 block discarded – undo
24 24
  */
25 25
 class SosaCalculatorService
26 26
 {
27
-    /**
28
-     * Maximium size for the temporary Sosa table
29
-     * @var int TMP_SOSA_TABLE_LIMIT
30
-     */
31
-    private const TMP_SOSA_TABLE_LIMIT = 1000;
32
-
33
-    /**
34
-     * @var SosaRecordsService $sosa_records_service
35
-     */
36
-    private $sosa_records_service;
37
-
38
-    /**
39
-     * Reference user
40
-     * @var User $user
41
-     */
42
-    private $user;
43
-
44
-    /**
45
-     * Reference tree
46
-     * @var Tree $tree
47
-     */
48
-    private $tree;
49
-
50
-    /**
51
-     * Temporary Sosa table, used during construction
52
-     * @var array<array<string,mixed>> $tmp_sosa_table
53
-     */
54
-    private $tmp_sosa_table;
55
-
56
-    /**
57
-     * Maximum number of generations to calculate
58
-     * @var int $max_generations
59
-     */
60
-    private $max_generations;
61
-
62
-    /**
63
-     * Constructor for the Sosa Calculator
64
-     *
65
-     * @param SosaRecordsService $sosa_records_service
66
-     * @param Tree $tree
67
-     * @param User $user
68
-     */
69
-    public function __construct(SosaRecordsService $sosa_records_service, Tree $tree, User $user)
70
-    {
71
-        $this->sosa_records_service = $sosa_records_service;
72
-        $this->tree = $tree;
73
-        $this->user = $user;
74
-        $this->tmp_sosa_table = array();
75
-        $max_gen_setting = $tree->getUserPreference($user, 'MAJ_SOSA_MAX_GEN');
76
-        $this->max_generations = is_numeric($max_gen_setting) ?
77
-            (int) $max_gen_setting :
78
-            $this->sosa_records_service->maxSystemGenerations();
79
-    }
80
-
81
-    /**
82
-     * Compute all Sosa ancestors from the user's root individual.
83
-     *
84
-     * @return bool Result of the computation
85
-     */
86
-    public function computeAll(): bool
87
-    {
88
-        $root_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
89
-        if (($indi = Registry::individualFactory()->make($root_id, $this->tree)) !== null) {
90
-            $this->sosa_records_service->deleteAll($this->tree, $this->user);
91
-            $this->addNode($indi, 1);
92
-            $this->flushTmpSosaTable(true);
93
-            return true;
94
-        }
95
-        return false;
96
-    }
97
-
98
-    /**
99
-     * Compute all Sosa Ancestors from a specified Individual
100
-     *
101
-     * @param Individual $indi
102
-     * @return bool
103
-     */
104
-    public function computeFromIndividual(Individual $indi): bool
105
-    {
106
-        $current_sosas = $this->sosa_records_service->getSosaNumbers($this->tree, $this->user, $indi);
107
-        foreach ($current_sosas->keys() as $sosa) {
108
-            $this->sosa_records_service->deleteAncestorsFrom($this->tree, $this->user, $sosa);
109
-            $this->addNode($indi, $sosa);
110
-        }
111
-        $this->flushTmpSosaTable(true);
112
-        return true;
113
-    }
114
-
115
-    /**
116
-     * Recursive method to add individual to the Sosa table, and flush it regularly
117
-     *
118
-     * @param Individual $indi Individual to add
119
-     * @param int $sosa Individual's sosa
120
-     */
121
-    private function addNode(Individual $indi, int $sosa): void
122
-    {
123
-        $birth_year = $indi->getBirthDate()->gregorianYear();
124
-        $birth_year_est = $birth_year === 0 ? $indi->getEstimatedBirthDate()->gregorianYear() : $birth_year;
125
-
126
-        $death_year = $indi->getDeathDate()->gregorianYear();
127
-        $death_year_est = $death_year === 0 ? $indi->getEstimatedDeathDate()->gregorianYear() : $death_year;
128
-
129
-        $this->tmp_sosa_table[] = [
130
-            'indi' => $indi->xref(),
131
-            'sosa' => $sosa,
132
-            'birth_year' => $birth_year === 0 ? null : $birth_year,
133
-            'birth_year_est' => $birth_year_est === 0 ? null : $birth_year_est,
134
-            'death_year' => $death_year === 0 ? null : $death_year,
135
-            'death_year_est' => $death_year_est === 0 ? null : $death_year_est
136
-        ];
137
-
138
-        $this->flushTmpSosaTable();
139
-
140
-        if (
141
-            ($fam = $indi->childFamilies()->first()) !== null
142
-            && $this->sosa_records_service->generation($sosa) < $this->max_generations
143
-        ) {
144
-            /** @var \Fisharebest\Webtrees\Family $fam */
145
-            if (($husb = $fam->husband()) !== null) {
146
-                $this->addNode($husb, 2 * $sosa);
147
-            }
148
-            if (($wife = $fam->wife()) !== null) {
149
-                $this->addNode($wife, 2 * $sosa + 1);
150
-            }
151
-        }
152
-    }
153
-
154
-    /**
155
-     * Write sosas in the table, if the number of items is superior to the limit, or if forced.
156
-     *
157
-     * @param bool $force Should the flush be forced
158
-     */
159
-    private function flushTmpSosaTable($force = false): void
160
-    {
161
-        if ($force || count($this->tmp_sosa_table) >= self::TMP_SOSA_TABLE_LIMIT) {
162
-            $this->sosa_records_service->insertOrUpdate($this->tree, $this->user, $this->tmp_sosa_table);
163
-            $this->tmp_sosa_table = array();
164
-        }
165
-    }
27
+	/**
28
+	 * Maximium size for the temporary Sosa table
29
+	 * @var int TMP_SOSA_TABLE_LIMIT
30
+	 */
31
+	private const TMP_SOSA_TABLE_LIMIT = 1000;
32
+
33
+	/**
34
+	 * @var SosaRecordsService $sosa_records_service
35
+	 */
36
+	private $sosa_records_service;
37
+
38
+	/**
39
+	 * Reference user
40
+	 * @var User $user
41
+	 */
42
+	private $user;
43
+
44
+	/**
45
+	 * Reference tree
46
+	 * @var Tree $tree
47
+	 */
48
+	private $tree;
49
+
50
+	/**
51
+	 * Temporary Sosa table, used during construction
52
+	 * @var array<array<string,mixed>> $tmp_sosa_table
53
+	 */
54
+	private $tmp_sosa_table;
55
+
56
+	/**
57
+	 * Maximum number of generations to calculate
58
+	 * @var int $max_generations
59
+	 */
60
+	private $max_generations;
61
+
62
+	/**
63
+	 * Constructor for the Sosa Calculator
64
+	 *
65
+	 * @param SosaRecordsService $sosa_records_service
66
+	 * @param Tree $tree
67
+	 * @param User $user
68
+	 */
69
+	public function __construct(SosaRecordsService $sosa_records_service, Tree $tree, User $user)
70
+	{
71
+		$this->sosa_records_service = $sosa_records_service;
72
+		$this->tree = $tree;
73
+		$this->user = $user;
74
+		$this->tmp_sosa_table = array();
75
+		$max_gen_setting = $tree->getUserPreference($user, 'MAJ_SOSA_MAX_GEN');
76
+		$this->max_generations = is_numeric($max_gen_setting) ?
77
+			(int) $max_gen_setting :
78
+			$this->sosa_records_service->maxSystemGenerations();
79
+	}
80
+
81
+	/**
82
+	 * Compute all Sosa ancestors from the user's root individual.
83
+	 *
84
+	 * @return bool Result of the computation
85
+	 */
86
+	public function computeAll(): bool
87
+	{
88
+		$root_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
89
+		if (($indi = Registry::individualFactory()->make($root_id, $this->tree)) !== null) {
90
+			$this->sosa_records_service->deleteAll($this->tree, $this->user);
91
+			$this->addNode($indi, 1);
92
+			$this->flushTmpSosaTable(true);
93
+			return true;
94
+		}
95
+		return false;
96
+	}
97
+
98
+	/**
99
+	 * Compute all Sosa Ancestors from a specified Individual
100
+	 *
101
+	 * @param Individual $indi
102
+	 * @return bool
103
+	 */
104
+	public function computeFromIndividual(Individual $indi): bool
105
+	{
106
+		$current_sosas = $this->sosa_records_service->getSosaNumbers($this->tree, $this->user, $indi);
107
+		foreach ($current_sosas->keys() as $sosa) {
108
+			$this->sosa_records_service->deleteAncestorsFrom($this->tree, $this->user, $sosa);
109
+			$this->addNode($indi, $sosa);
110
+		}
111
+		$this->flushTmpSosaTable(true);
112
+		return true;
113
+	}
114
+
115
+	/**
116
+	 * Recursive method to add individual to the Sosa table, and flush it regularly
117
+	 *
118
+	 * @param Individual $indi Individual to add
119
+	 * @param int $sosa Individual's sosa
120
+	 */
121
+	private function addNode(Individual $indi, int $sosa): void
122
+	{
123
+		$birth_year = $indi->getBirthDate()->gregorianYear();
124
+		$birth_year_est = $birth_year === 0 ? $indi->getEstimatedBirthDate()->gregorianYear() : $birth_year;
125
+
126
+		$death_year = $indi->getDeathDate()->gregorianYear();
127
+		$death_year_est = $death_year === 0 ? $indi->getEstimatedDeathDate()->gregorianYear() : $death_year;
128
+
129
+		$this->tmp_sosa_table[] = [
130
+			'indi' => $indi->xref(),
131
+			'sosa' => $sosa,
132
+			'birth_year' => $birth_year === 0 ? null : $birth_year,
133
+			'birth_year_est' => $birth_year_est === 0 ? null : $birth_year_est,
134
+			'death_year' => $death_year === 0 ? null : $death_year,
135
+			'death_year_est' => $death_year_est === 0 ? null : $death_year_est
136
+		];
137
+
138
+		$this->flushTmpSosaTable();
139
+
140
+		if (
141
+			($fam = $indi->childFamilies()->first()) !== null
142
+			&& $this->sosa_records_service->generation($sosa) < $this->max_generations
143
+		) {
144
+			/** @var \Fisharebest\Webtrees\Family $fam */
145
+			if (($husb = $fam->husband()) !== null) {
146
+				$this->addNode($husb, 2 * $sosa);
147
+			}
148
+			if (($wife = $fam->wife()) !== null) {
149
+				$this->addNode($wife, 2 * $sosa + 1);
150
+			}
151
+		}
152
+	}
153
+
154
+	/**
155
+	 * Write sosas in the table, if the number of items is superior to the limit, or if forced.
156
+	 *
157
+	 * @param bool $force Should the flush be forced
158
+	 */
159
+	private function flushTmpSosaTable($force = false): void
160
+	{
161
+		if ($force || count($this->tmp_sosa_table) >= self::TMP_SOSA_TABLE_LIMIT) {
162
+			$this->sosa_records_service->insertOrUpdate($this->tree, $this->user, $this->tmp_sosa_table);
163
+			$this->tmp_sosa_table = array();
164
+		}
165
+	}
166 166
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/SosaStatistics.php 1 patch
Indentation   +140 added lines, -140 removed lines patch added patch discarded remove patch
@@ -36,144 +36,144 @@
 block discarded – undo
36 36
  */
37 37
 class SosaStatistics implements RequestHandlerInterface
38 38
 {
39
-    use ViewResponseTrait;
40
-
41
-    /**
42
-     * @var SosaModule $module
43
-     */
44
-    private $module;
45
-
46
-    /**
47
-     * Constructor for AncestorsList Request Handler
48
-     *
49
-     * @param ModuleService $module_service
50
-     */
51
-    public function __construct(ModuleService $module_service)
52
-    {
53
-        $this->module = $module_service->findByInterface(SosaModule::class)->first();
54
-    }
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
-        }
65
-
66
-        $tree = $request->getAttribute('tree');
67
-        assert($tree instanceof Tree);
68
-
69
-        $user = Auth::check() ? $request->getAttribute('user') : new DefaultUser();
70
-
71
-        /** @var SosaStatisticsService $sosa_stats_service */
72
-        $sosa_stats_service = app()->makeWith(SosaStatisticsService::class, ['tree' => $tree, 'user' => $user]);
73
-
74
-        return $this->viewResponse($this->module->name() . '::statistics-page', [
75
-            'module_name'       =>  $this->module->name(),
76
-            'title'             =>  I18N::translate('Sosa Statistics'),
77
-            'tree'              =>  $tree,
78
-            'theme'             =>  app(ModuleThemeInterface::class),
79
-            'root_indi'         =>  $sosa_stats_service->rootIndividual(),
80
-            'general_stats'     =>  $this->statisticsGeneral($sosa_stats_service),
81
-            'generation_stats'  =>  $this->statisticsByGenerations($sosa_stats_service),
82
-            'generation_depth'  =>  $sosa_stats_service->generationDepthStatsAtGeneration(1)->first(),
83
-            'multiple_sosas'    =>  $sosa_stats_service->topMultipleAncestorsWithNoTies(10)->groupBy('sosa_count'),
84
-            'sosa_dispersion_g2' =>  $sosa_stats_service->ancestorsDispersionForGeneration(2),
85
-            'sosa_dispersion_g3' =>  $sosa_stats_service->ancestorsDispersionForGeneration(3),
86
-            'gen_depth_g3'      =>  $sosa_stats_service->generationDepthStatsAtGeneration(3)
87
-        ]);
88
-    }
89
-
90
-    /**
91
-     * Retrieve and compute the global statistics of ancestors for the tree.
92
-     * Statistics include the number of ancestors, the number of different ancestors, pedigree collapse...
93
-     *
94
-     * @param SosaStatisticsService $sosa_stats_service
95
-     * @return array<string, int|float>
96
-     */
97
-    private function statisticsGeneral(SosaStatisticsService $sosa_stats_service): array
98
-    {
99
-        $ancestors_count = $sosa_stats_service->totalAncestors();
100
-        $ancestors_distinct_count = $sosa_stats_service->totalDistinctAncestors();
101
-        $individual_count = $sosa_stats_service->totalIndividuals();
102
-
103
-        return [
104
-            'sosa_count'    =>  $ancestors_count,
105
-            'distinct_count'    =>  $ancestors_distinct_count,
106
-            'sosa_rate' =>  $this->safeDivision(
107
-                BigInteger::of($ancestors_distinct_count),
108
-                BigInteger::of($individual_count)
109
-            ),
110
-            'mean_gen_time'         =>  $sosa_stats_service->meanGenerationTime()
111
-        ];
112
-    }
113
-
114
-    /**
115
-     * Retrieve and compute the statistics of ancestors by generations.
116
-     * Statistics include the number of ancestors, the number of different ancestors, cumulative statistics...
117
-     *
118
-     * @param SosaStatisticsService $sosa_stats_service
119
-     * @return array<int, array<string, int|float>>
120
-     */
121
-    private function statisticsByGenerations(SosaStatisticsService $sosa_stats_service): array
122
-    {
123
-        $stats_by_gen = $sosa_stats_service->statisticsByGenerations();
124
-
125
-        $generation_stats = array();
126
-
127
-        foreach ($stats_by_gen as $gen => $stats_gen) {
128
-            $gen_diff = $gen > 1 ?
129
-                (int) $stats_gen['diffSosaTotalCount'] - (int) $stats_by_gen[$gen - 1]['diffSosaTotalCount'] :
130
-                1;
131
-            $generation_stats[$gen] = array(
132
-                'gen_min_birth' => $stats_gen['firstBirth'] ?? (int) $stats_gen['firstEstimatedBirth'],
133
-                'gen_max_birth' => $stats_gen['lastBirth'] ?? (int) $stats_gen['lastEstimatedBirth'],
134
-                'theoretical' => BigInteger::of(2)->power($gen - 1)->toInt(),
135
-                'known' => (int) $stats_gen['sosaCount'],
136
-                'perc_known' => $this->safeDivision(
137
-                    BigInteger::of((int) $stats_gen['sosaCount']),
138
-                    BigInteger::of(2)->power($gen - 1)
139
-                ),
140
-                'missing' => $gen > 1 ?
141
-                    2 * (int) $stats_by_gen[$gen - 1]['sosaCount'] - (int) $stats_gen['sosaCount'] :
142
-                    0,
143
-                'perc_missing' => $gen > 1 ?
144
-                    1 - $this->safeDivision(
145
-                        BigInteger::of((int) $stats_gen['sosaCount']),
146
-                        BigInteger::of(2 * (int) $stats_by_gen[$gen - 1]['sosaCount'])
147
-                    ) :
148
-                    0,
149
-                'total_known' => (int) $stats_gen['sosaTotalCount'],
150
-                'perc_total_known' => $this->safeDivision(
151
-                    BigInteger::of((int) $stats_gen['sosaTotalCount']),
152
-                    BigInteger::of(2)->power($gen)->minus(1)
153
-                ),
154
-                'different' => $gen_diff,
155
-                'perc_different' => $this->safeDivision(
156
-                    BigInteger::of($gen_diff),
157
-                    BigInteger::of((int) $stats_gen['sosaCount'])
158
-                ),
159
-                'total_different' => (int) $stats_gen['diffSosaTotalCount']
160
-            );
161
-        }
162
-
163
-        return $generation_stats;
164
-    }
165
-
166
-    /**
167
-     * Return the result of a division, and a default value if denominator is 0
168
-     *
169
-     * @param BigInteger $p Numerator
170
-     * @param BigInteger $q Denominator
171
-     * @param int $scale Rounding scale
172
-     * @param float $default Value if denominator is 0
173
-     * @return float
174
-     */
175
-    private function safeDivision(BigInteger $p, BigInteger $q, int $scale = 10, float $default = 0): float
176
-    {
177
-        return $q->isZero() ? $default : $p->toBigDecimal()->dividedBy($q, $scale, RoundingMode::HALF_DOWN)->toFloat();
178
-    }
39
+	use ViewResponseTrait;
40
+
41
+	/**
42
+	 * @var SosaModule $module
43
+	 */
44
+	private $module;
45
+
46
+	/**
47
+	 * Constructor for AncestorsList Request Handler
48
+	 *
49
+	 * @param ModuleService $module_service
50
+	 */
51
+	public function __construct(ModuleService $module_service)
52
+	{
53
+		$this->module = $module_service->findByInterface(SosaModule::class)->first();
54
+	}
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
+		}
65
+
66
+		$tree = $request->getAttribute('tree');
67
+		assert($tree instanceof Tree);
68
+
69
+		$user = Auth::check() ? $request->getAttribute('user') : new DefaultUser();
70
+
71
+		/** @var SosaStatisticsService $sosa_stats_service */
72
+		$sosa_stats_service = app()->makeWith(SosaStatisticsService::class, ['tree' => $tree, 'user' => $user]);
73
+
74
+		return $this->viewResponse($this->module->name() . '::statistics-page', [
75
+			'module_name'       =>  $this->module->name(),
76
+			'title'             =>  I18N::translate('Sosa Statistics'),
77
+			'tree'              =>  $tree,
78
+			'theme'             =>  app(ModuleThemeInterface::class),
79
+			'root_indi'         =>  $sosa_stats_service->rootIndividual(),
80
+			'general_stats'     =>  $this->statisticsGeneral($sosa_stats_service),
81
+			'generation_stats'  =>  $this->statisticsByGenerations($sosa_stats_service),
82
+			'generation_depth'  =>  $sosa_stats_service->generationDepthStatsAtGeneration(1)->first(),
83
+			'multiple_sosas'    =>  $sosa_stats_service->topMultipleAncestorsWithNoTies(10)->groupBy('sosa_count'),
84
+			'sosa_dispersion_g2' =>  $sosa_stats_service->ancestorsDispersionForGeneration(2),
85
+			'sosa_dispersion_g3' =>  $sosa_stats_service->ancestorsDispersionForGeneration(3),
86
+			'gen_depth_g3'      =>  $sosa_stats_service->generationDepthStatsAtGeneration(3)
87
+		]);
88
+	}
89
+
90
+	/**
91
+	 * Retrieve and compute the global statistics of ancestors for the tree.
92
+	 * Statistics include the number of ancestors, the number of different ancestors, pedigree collapse...
93
+	 *
94
+	 * @param SosaStatisticsService $sosa_stats_service
95
+	 * @return array<string, int|float>
96
+	 */
97
+	private function statisticsGeneral(SosaStatisticsService $sosa_stats_service): array
98
+	{
99
+		$ancestors_count = $sosa_stats_service->totalAncestors();
100
+		$ancestors_distinct_count = $sosa_stats_service->totalDistinctAncestors();
101
+		$individual_count = $sosa_stats_service->totalIndividuals();
102
+
103
+		return [
104
+			'sosa_count'    =>  $ancestors_count,
105
+			'distinct_count'    =>  $ancestors_distinct_count,
106
+			'sosa_rate' =>  $this->safeDivision(
107
+				BigInteger::of($ancestors_distinct_count),
108
+				BigInteger::of($individual_count)
109
+			),
110
+			'mean_gen_time'         =>  $sosa_stats_service->meanGenerationTime()
111
+		];
112
+	}
113
+
114
+	/**
115
+	 * Retrieve and compute the statistics of ancestors by generations.
116
+	 * Statistics include the number of ancestors, the number of different ancestors, cumulative statistics...
117
+	 *
118
+	 * @param SosaStatisticsService $sosa_stats_service
119
+	 * @return array<int, array<string, int|float>>
120
+	 */
121
+	private function statisticsByGenerations(SosaStatisticsService $sosa_stats_service): array
122
+	{
123
+		$stats_by_gen = $sosa_stats_service->statisticsByGenerations();
124
+
125
+		$generation_stats = array();
126
+
127
+		foreach ($stats_by_gen as $gen => $stats_gen) {
128
+			$gen_diff = $gen > 1 ?
129
+				(int) $stats_gen['diffSosaTotalCount'] - (int) $stats_by_gen[$gen - 1]['diffSosaTotalCount'] :
130
+				1;
131
+			$generation_stats[$gen] = array(
132
+				'gen_min_birth' => $stats_gen['firstBirth'] ?? (int) $stats_gen['firstEstimatedBirth'],
133
+				'gen_max_birth' => $stats_gen['lastBirth'] ?? (int) $stats_gen['lastEstimatedBirth'],
134
+				'theoretical' => BigInteger::of(2)->power($gen - 1)->toInt(),
135
+				'known' => (int) $stats_gen['sosaCount'],
136
+				'perc_known' => $this->safeDivision(
137
+					BigInteger::of((int) $stats_gen['sosaCount']),
138
+					BigInteger::of(2)->power($gen - 1)
139
+				),
140
+				'missing' => $gen > 1 ?
141
+					2 * (int) $stats_by_gen[$gen - 1]['sosaCount'] - (int) $stats_gen['sosaCount'] :
142
+					0,
143
+				'perc_missing' => $gen > 1 ?
144
+					1 - $this->safeDivision(
145
+						BigInteger::of((int) $stats_gen['sosaCount']),
146
+						BigInteger::of(2 * (int) $stats_by_gen[$gen - 1]['sosaCount'])
147
+					) :
148
+					0,
149
+				'total_known' => (int) $stats_gen['sosaTotalCount'],
150
+				'perc_total_known' => $this->safeDivision(
151
+					BigInteger::of((int) $stats_gen['sosaTotalCount']),
152
+					BigInteger::of(2)->power($gen)->minus(1)
153
+				),
154
+				'different' => $gen_diff,
155
+				'perc_different' => $this->safeDivision(
156
+					BigInteger::of($gen_diff),
157
+					BigInteger::of((int) $stats_gen['sosaCount'])
158
+				),
159
+				'total_different' => (int) $stats_gen['diffSosaTotalCount']
160
+			);
161
+		}
162
+
163
+		return $generation_stats;
164
+	}
165
+
166
+	/**
167
+	 * Return the result of a division, and a default value if denominator is 0
168
+	 *
169
+	 * @param BigInteger $p Numerator
170
+	 * @param BigInteger $q Denominator
171
+	 * @param int $scale Rounding scale
172
+	 * @param float $default Value if denominator is 0
173
+	 * @return float
174
+	 */
175
+	private function safeDivision(BigInteger $p, BigInteger $q, int $scale = 10, float $default = 0): float
176
+	{
177
+		return $q->isZero() ? $default : $p->toBigDecimal()->dividedBy($q, $scale, RoundingMode::HALF_DOWN)->toFloat();
178
+	}
179 179
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/PedigreeCollapseData.php 1 patch
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -33,51 +33,51 @@
 block discarded – undo
33 33
  */
34 34
 class PedigreeCollapseData implements RequestHandlerInterface
35 35
 {
36
-    /**
37
-     * @var SosaModule $module
38
-     */
39
-    private $module;
36
+	/**
37
+	 * @var SosaModule $module
38
+	 */
39
+	private $module;
40 40
 
41
-    /**
42
-     * Constructor for PedigreeCollapseData Request Handler
43
-     *
44
-     * @param ModuleService $module_service
45
-     */
46
-    public function __construct(ModuleService $module_service)
47
-    {
48
-        $this->module = $module_service->findByInterface(SosaModule::class)->first();
49
-    }
41
+	/**
42
+	 * Constructor for PedigreeCollapseData Request Handler
43
+	 *
44
+	 * @param ModuleService $module_service
45
+	 */
46
+	public function __construct(ModuleService $module_service)
47
+	{
48
+		$this->module = $module_service->findByInterface(SosaModule::class)->first();
49
+	}
50 50
 
51
-    /**
52
-     * {@inheritDoc}
53
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
-     */
55
-    public function handle(ServerRequestInterface $request): ResponseInterface
56
-    {
57
-        if ($this->module === null) {
58
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
59
-        }
51
+	/**
52
+	 * {@inheritDoc}
53
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
+	 */
55
+	public function handle(ServerRequestInterface $request): ResponseInterface
56
+	{
57
+		if ($this->module === null) {
58
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
59
+		}
60 60
 
61
-        $tree = $request->getAttribute('tree');
62
-        assert($tree instanceof Tree);
61
+		$tree = $request->getAttribute('tree');
62
+		assert($tree instanceof Tree);
63 63
 
64
-        $user = Auth::check() ? $request->getAttribute('user') : new DefaultUser();
64
+		$user = Auth::check() ? $request->getAttribute('user') : new DefaultUser();
65 65
 
66
-        /** @var SosaStatisticsService $sosa_stats_service */
67
-        $sosa_stats_service = app()->makeWith(SosaStatisticsService::class, ['tree' => $tree, 'user' => $user]);
68
-        $pedi_collapse_data = $sosa_stats_service->pedigreeCollapseByGenerationData();
66
+		/** @var SosaStatisticsService $sosa_stats_service */
67
+		$sosa_stats_service = app()->makeWith(SosaStatisticsService::class, ['tree' => $tree, 'user' => $user]);
68
+		$pedi_collapse_data = $sosa_stats_service->pedigreeCollapseByGenerationData();
69 69
 
70
-        $response = [ 'cells' => [] ];
71
-        $last_pedi_collapse = 0;
72
-        foreach ($pedi_collapse_data as $gen => $rec) {
73
-            $response['cells'][$gen] = view($this->module->name() . '::components/pedigree-collapse-cell', [
74
-                'pedi_collapse_roots'   =>  $rec['pedi_collapse_roots'],
75
-                'pedi_collapse_xgen'    =>  $rec['pedi_collapse_xgen']
76
-            ]);
77
-            $last_pedi_collapse = $rec['pedi_collapse_roots'];
78
-        }
79
-        $response['pedi_collapse'] = I18N::percentage($last_pedi_collapse, 2);
70
+		$response = [ 'cells' => [] ];
71
+		$last_pedi_collapse = 0;
72
+		foreach ($pedi_collapse_data as $gen => $rec) {
73
+			$response['cells'][$gen] = view($this->module->name() . '::components/pedigree-collapse-cell', [
74
+				'pedi_collapse_roots'   =>  $rec['pedi_collapse_roots'],
75
+				'pedi_collapse_xgen'    =>  $rec['pedi_collapse_xgen']
76
+			]);
77
+			$last_pedi_collapse = $rec['pedi_collapse_roots'];
78
+		}
79
+		$response['pedi_collapse'] = I18N::percentage($last_pedi_collapse, 2);
80 80
 
81
-        return response($response, StatusCodeInterface::STATUS_OK);
82
-    }
81
+		return response($response, StatusCodeInterface::STATUS_OK);
82
+	}
83 83
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/SosaConfigAction.php 1 patch
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -30,52 +30,52 @@
 block discarded – undo
30 30
  */
31 31
 class SosaConfigAction implements RequestHandlerInterface
32 32
 {
33
-    /**
34
-     * @var UserService $user_service
35
-     */
36
-    private $user_service;
33
+	/**
34
+	 * @var UserService $user_service
35
+	 */
36
+	private $user_service;
37 37
 
38
-    /**
39
-     * Constructor for SosaConfigAction Request Handler
40
-     *
41
-     * @param UserService $user_service
42
-     */
43
-    public function __construct(UserService $user_service)
44
-    {
45
-        $this->user_service = $user_service;
46
-    }
38
+	/**
39
+	 * Constructor for SosaConfigAction Request Handler
40
+	 *
41
+	 * @param UserService $user_service
42
+	 */
43
+	public function __construct(UserService $user_service)
44
+	{
45
+		$this->user_service = $user_service;
46
+	}
47 47
 
48
-    /**
49
-     * {@inheritDoc}
50
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
-     */
52
-    public function handle(ServerRequestInterface $request): ResponseInterface
53
-    {
54
-        $tree = $request->getAttribute('tree');
55
-        assert($tree instanceof Tree);
48
+	/**
49
+	 * {@inheritDoc}
50
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
+	 */
52
+	public function handle(ServerRequestInterface $request): ResponseInterface
53
+	{
54
+		$tree = $request->getAttribute('tree');
55
+		assert($tree instanceof Tree);
56 56
 
57
-        $params = $request->getParsedBody();
58
-        assert(is_array($params));
57
+		$params = $request->getParsedBody();
58
+		assert(is_array($params));
59 59
 
60
-        $user_id = (int) $params['sosa-userid'];
61
-        $root_id = $params['sosa-rootid'] ?? '';
62
-        $max_gen = $params['sosa-maxgen'] ?? '';
60
+		$user_id = (int) $params['sosa-userid'];
61
+		$root_id = $params['sosa-rootid'] ?? '';
62
+		$max_gen = $params['sosa-maxgen'] ?? '';
63 63
 
64
-        if (Auth::id() == $user_id || ($user_id == -1 && Auth::isManager($tree))) {
65
-            $user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
66
-            if ($user !== null && ($root_indi = Registry::individualFactory()->make($root_id, $tree)) !== null) {
67
-                $tree->setUserPreference($user, 'MAJ_SOSA_ROOT_ID', $root_indi->xref());
68
-                $tree->setUserPreference($user, 'MAJ_SOSA_MAX_GEN', $max_gen);
69
-                FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
70
-                return redirect(route(SosaConfig::class, [
71
-                    'tree' => $tree->name(),
72
-                    'compute' => 'yes',
73
-                    'user_id' => $user_id
74
-                ]));
75
-            }
76
-        }
64
+		if (Auth::id() == $user_id || ($user_id == -1 && Auth::isManager($tree))) {
65
+			$user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
66
+			if ($user !== null && ($root_indi = Registry::individualFactory()->make($root_id, $tree)) !== null) {
67
+				$tree->setUserPreference($user, 'MAJ_SOSA_ROOT_ID', $root_indi->xref());
68
+				$tree->setUserPreference($user, 'MAJ_SOSA_MAX_GEN', $max_gen);
69
+				FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
70
+				return redirect(route(SosaConfig::class, [
71
+					'tree' => $tree->name(),
72
+					'compute' => 'yes',
73
+					'user_id' => $user_id
74
+				]));
75
+			}
76
+		}
77 77
 
78
-        FlashMessages::addMessage(I18N::translate('The root individual could not be updated.'), 'danger');
79
-        return redirect(route(SosaConfig::class, ['tree' => $tree->name()]));
80
-    }
78
+		FlashMessages::addMessage(I18N::translate('The root individual could not be updated.'), 'danger');
79
+		return redirect(route(SosaConfig::class, ['tree' => $tree->name()]));
80
+	}
81 81
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/SosaConfig.php 1 patch
Indentation   +60 added lines, -60 removed lines patch added patch discarded remove patch
@@ -32,72 +32,72 @@
 block discarded – undo
32 32
  */
33 33
 class SosaConfig implements RequestHandlerInterface
34 34
 {
35
-    use ViewResponseTrait;
35
+	use ViewResponseTrait;
36 36
 
37
-    /**
38
-     * @var SosaModule $module
39
-     */
40
-    private $module;
37
+	/**
38
+	 * @var SosaModule $module
39
+	 */
40
+	private $module;
41 41
 
42
-    /**
43
-     * Constructor for SosaConfig Request Handler
44
-     *
45
-     * @param ModuleService $module_service
46
-     */
47
-    public function __construct(ModuleService $module_service)
48
-    {
49
-        $this->module = $module_service->findByInterface(SosaModule::class)->first();
50
-    }
42
+	/**
43
+	 * Constructor for SosaConfig Request Handler
44
+	 *
45
+	 * @param ModuleService $module_service
46
+	 */
47
+	public function __construct(ModuleService $module_service)
48
+	{
49
+		$this->module = $module_service->findByInterface(SosaModule::class)->first();
50
+	}
51 51
 
52
-    /**
53
-     * {@inheritDoc}
54
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
55
-     */
56
-    public function handle(ServerRequestInterface $request): ResponseInterface
57
-    {
58
-        if ($this->module === null) {
59
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
60
-        }
52
+	/**
53
+	 * {@inheritDoc}
54
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
55
+	 */
56
+	public function handle(ServerRequestInterface $request): ResponseInterface
57
+	{
58
+		if ($this->module === null) {
59
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
60
+		}
61 61
 
62
-        $tree = $request->getAttribute('tree');
63
-        assert($tree instanceof Tree);
62
+		$tree = $request->getAttribute('tree');
63
+		assert($tree instanceof Tree);
64 64
 
65
-        $users_root = array();
66
-        if (Auth::check()) {
67
-            /** @var \Fisharebest\Webtrees\User $user */
68
-            $user = Auth::user();
69
-            $users_root[] = [
70
-                'user'      => $user,
71
-                'root_id'   => $tree->getUserPreference($user, 'MAJ_SOSA_ROOT_ID'),
72
-                'max_gen'   => $tree->getUserPreference($user, 'MAJ_SOSA_MAX_GEN')
73
-            ];
65
+		$users_root = array();
66
+		if (Auth::check()) {
67
+			/** @var \Fisharebest\Webtrees\User $user */
68
+			$user = Auth::user();
69
+			$users_root[] = [
70
+				'user'      => $user,
71
+				'root_id'   => $tree->getUserPreference($user, 'MAJ_SOSA_ROOT_ID'),
72
+				'max_gen'   => $tree->getUserPreference($user, 'MAJ_SOSA_MAX_GEN')
73
+			];
74 74
 
75
-            if (Auth::isManager($tree)) {
76
-                $default_user = new DefaultUser();
77
-                $users_root[] = [
78
-                    'user' => $default_user,
79
-                    'root_id' => $tree->getUserPreference($default_user, 'MAJ_SOSA_ROOT_ID'),
80
-                    'max_gen'   => $tree->getUserPreference($default_user, 'MAJ_SOSA_MAX_GEN')
81
-                ];
82
-            }
83
-        }
75
+			if (Auth::isManager($tree)) {
76
+				$default_user = new DefaultUser();
77
+				$users_root[] = [
78
+					'user' => $default_user,
79
+					'root_id' => $tree->getUserPreference($default_user, 'MAJ_SOSA_ROOT_ID'),
80
+					'max_gen'   => $tree->getUserPreference($default_user, 'MAJ_SOSA_MAX_GEN')
81
+				];
82
+			}
83
+		}
84 84
 
85
-        // Use the system max generations if not set
86
-        $max_gen_system = app(SosaRecordsService::class)->maxSystemGenerations();
87
-        foreach ($users_root as $key => $user_root) {
88
-            $users_root[$key]['max_gen'] = is_numeric($user_root['max_gen']) ?
89
-                (int) $user_root['max_gen'] :
90
-                $max_gen_system;
91
-        };
85
+		// Use the system max generations if not set
86
+		$max_gen_system = app(SosaRecordsService::class)->maxSystemGenerations();
87
+		foreach ($users_root as $key => $user_root) {
88
+			$users_root[$key]['max_gen'] = is_numeric($user_root['max_gen']) ?
89
+				(int) $user_root['max_gen'] :
90
+				$max_gen_system;
91
+		};
92 92
 
93
-        return $this->viewResponse($this->module->name() . '::config-page', [
94
-            'module_name'       =>  $this->module->name(),
95
-            'title'             =>  I18N::translate('Sosa Configuration'),
96
-            'tree'              =>  $tree,
97
-            'user_id'           =>  $request->getAttribute('user'),
98
-            'selected_user_id'  =>  (int) ($request->getQueryParams()['user_id'] ?? 0),
99
-            'immediate_compute' =>  ($request->getQueryParams()['compute'] ?? '') == 'yes',
100
-            'users_root'        =>  $users_root
101
-        ]);
102
-    }
93
+		return $this->viewResponse($this->module->name() . '::config-page', [
94
+			'module_name'       =>  $this->module->name(),
95
+			'title'             =>  I18N::translate('Sosa Configuration'),
96
+			'tree'              =>  $tree,
97
+			'user_id'           =>  $request->getAttribute('user'),
98
+			'selected_user_id'  =>  (int) ($request->getQueryParams()['user_id'] ?? 0),
99
+			'immediate_compute' =>  ($request->getQueryParams()['compute'] ?? '') == 'yes',
100
+			'users_root'        =>  $users_root
101
+		]);
102
+	}
103 103
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/SosaModule.php 1 patch
Indentation   +165 added lines, -165 removed lines patch added patch discarded remove patch
@@ -47,174 +47,174 @@
 block discarded – undo
47 47
  */
48 48
 class SosaModule extends AbstractModule implements ModuleMyArtJaubInterface, ModuleGlobalInterface, ModuleMenuInterface
49 49
 {
50
-    use ModuleMyArtJaubTrait {
51
-        boot as traitBoot;
52
-    }
53
-    use ModuleGlobalTrait;
54
-    use ModuleMenuTrait;
50
+	use ModuleMyArtJaubTrait {
51
+		boot as traitBoot;
52
+	}
53
+	use ModuleGlobalTrait;
54
+	use ModuleMenuTrait;
55 55
 
56 56
 // How to update the database schema for this module
57 57
 
58 58
 
59
-    private const SCHEMA_TARGET_VERSION   = 3;
60
-    private const SCHEMA_SETTING_NAME     = 'MAJ_SOSA_SCHEMA_VERSION';
61
-    private const SCHEMA_MIGRATION_PREFIX = __NAMESPACE__ . '\Schema';
59
+	private const SCHEMA_TARGET_VERSION   = 3;
60
+	private const SCHEMA_SETTING_NAME     = 'MAJ_SOSA_SCHEMA_VERSION';
61
+	private const SCHEMA_MIGRATION_PREFIX = __NAMESPACE__ . '\Schema';
62 62
 /**
63
-     * {@inheritDoc}
64
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
65
-     */
66
-    public function title(): string
67
-    {
68
-        return /* I18N: Name of the “Sosa” module */ I18N::translate('Sosa');
69
-    }
70
-
71
-    /**
72
-     * {@inheritDoc}
73
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
74
-     */
75
-    public function description(): string
76
-    {
77
-        //phpcs:ignore Generic.Files.LineLength.TooLong
78
-        return /* I18N: Description of the “Sosa” module */ I18N::translate('Calculate and display Sosa ancestors of the root person.');
79
-    }
80
-
81
-    /**
82
-     * {@inheritDoc}
83
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::boot()
84
-     */
85
-    public function boot(): void
86
-    {
87
-        $this->traitBoot();
88
-        app(MigrationService::class)->updateSchema(
89
-            self::SCHEMA_MIGRATION_PREFIX,
90
-            self::SCHEMA_SETTING_NAME,
91
-            self::SCHEMA_TARGET_VERSION
92
-        );
93
-    }
94
-
95
-    /**
96
-     * {@inheritDoc}
97
-     * @see \MyArtJaub\Webtrees\Module\ModuleMyArtJaubInterface::loadRoutes()
98
-     */
99
-    public function loadRoutes(Map $router): void
100
-    {
101
-        $router->attach('', '', static function (Map $router): void {
102
-
103
-            $router->attach('', '/module-maj/sosa', static function (Map $router): void {
104
-
105
-                $router->attach('', '/list', static function (Map $router): void {
106
-
107
-                    $router->get(AncestorsList::class, '/ancestors/{tree}{/gen}', AncestorsList::class);
108
-                    $router->get(AncestorsListIndividual::class, '/ancestors/{tree}/{gen}/tab/individuals', AncestorsListIndividual::class);    //phpcs:ignore Generic.Files.LineLength.TooLong
109
-                    $router->get(AncestorsListFamily::class, '/ancestors/{tree}/{gen}/tab/families', AncestorsListFamily::class);   //phpcs:ignore Generic.Files.LineLength.TooLong
110
-                    $router->get(MissingAncestorsList::class, '/missing/{tree}{/gen}', MissingAncestorsList::class);
111
-                });
112
-
113
-                $router->attach('', '/statistics/{tree}', static function (Map $router): void {
114
-
115
-                    $router->get(SosaStatistics::class, '', SosaStatistics::class);
116
-                    $router->get(PedigreeCollapseData::class, '/pedigreecollapse', PedigreeCollapseData::class);
117
-                });
118
-
119
-                $router->attach('', '/config/{tree}', static function (Map $router): void {
120
-
121
-                    $router->get(SosaConfig::class, '', SosaConfig::class);
122
-                    $router->post(SosaConfigAction::class, '', SosaConfigAction::class);
123
-                    $router->get(SosaComputeModal::class, '/compute/{xref}', SosaComputeModal::class);
124
-                    $router->post(SosaComputeAction::class, '/compute', SosaComputeAction::class);
125
-                });
126
-            });
127
-        });
128
-    }
129
-
130
-    /**
131
-     * {@inheritDoc}
132
-     * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
133
-     */
134
-    public function customModuleVersion(): string
135
-    {
136
-        return '2.0.11-v.1';
137
-    }
138
-
139
-    /**
140
-     * {@inheritDoc}
141
-     * @see \Fisharebest\Webtrees\Module\ModuleMenuInterface::defaultMenuOrder()
142
-     */
143
-    public function defaultMenuOrder(): int
144
-    {
145
-        return 7;
146
-    }
147
-
148
-    /**
149
-     * {@inhericDoc}
150
-     * @see \Fisharebest\Webtrees\Module\ModuleMenuInterface::getMenu()
151
-     */
152
-    public function getMenu(Tree $tree): ?Menu
153
-    {
154
-        $menu = new Menu(I18N::translate('Sosa Statistics'));
155
-        $menu->setClass('menu-maj-sosa');
156
-        $menu->setSubmenus([
157
-            new Menu(
158
-                I18N::translate('Sosa Ancestors'),
159
-                route(AncestorsList::class, ['tree' => $tree->name()]),
160
-                'menu-maj-sosa-list',
161
-                ['rel' => 'nofollow']
162
-            ),
163
-            new Menu(
164
-                I18N::translate('Missing Ancestors'),
165
-                route(MissingAncestorsList::class, ['tree' => $tree->name()]),
166
-                'menu-maj-sosa-missing',
167
-                ['rel' => 'nofollow']
168
-            ),
169
-            new Menu(
170
-                I18N::translate('Sosa Statistics'),
171
-                route(SosaStatistics::class, ['tree' => $tree->name()]),
172
-                'menu-maj-sosa-stats'
173
-            )
174
-        ]);
175
-
176
-        if (Auth::check()) {
177
-            $menu->addSubmenu(new Menu(
178
-                I18N::translate('Sosa Configuration'),
179
-                route(SosaConfig::class, ['tree' => $tree->name()]),
180
-                'menu-maj-sosa-config'
181
-            ));
182
-
183
-            /** @var ServerRequestInterface $request */
184
-            $request = app(ServerRequestInterface::class);
185
-            $route = $request->getAttribute('route');
186
-            assert($route instanceof Route);
187
-
188
-            $root_indi_id = $tree->getUserPreference(Auth::user(), 'MAJ_SOSA_ROOT_ID');
189
-
190
-            if ($route->name === IndividualPage::class && mb_strlen($root_indi_id) > 0) {
191
-                $xref = $request->getAttribute('xref');
192
-                assert(is_string($xref));
193
-
194
-                $menu->addSubmenu(new Menu(
195
-                    I18N::translate('Complete Sosas'),
196
-                    '#',
197
-                    'menu-maj-sosa-compute',
198
-                    [
199
-                        'rel'           => 'nofollow',
200
-                        'data-href'     => route(SosaComputeModal::class, ['tree' => $tree->name(), 'xref' => $xref]),
201
-                        'data-target'   => '#wt-ajax-modal',
202
-                        'data-toggle'   => 'modal',
203
-                        'data-backdrop' => 'static'
204
-                    ]
205
-                ));
206
-            }
207
-        }
208
-
209
-        return $menu;
210
-    }
211
-
212
-    /**
213
-     * {@inheritDoc}
214
-     * @see \Fisharebest\Webtrees\Module\ModuleGlobalInterface::headContent()
215
-     */
216
-    public function headContent(): string
217
-    {
218
-        return '<link rel="stylesheet" href="' . e($this->moduleCssUrl()) . '">';
219
-    }
63
+	 * {@inheritDoc}
64
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
65
+	 */
66
+	public function title(): string
67
+	{
68
+		return /* I18N: Name of the “Sosa” module */ I18N::translate('Sosa');
69
+	}
70
+
71
+	/**
72
+	 * {@inheritDoc}
73
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
74
+	 */
75
+	public function description(): string
76
+	{
77
+		//phpcs:ignore Generic.Files.LineLength.TooLong
78
+		return /* I18N: Description of the “Sosa” module */ I18N::translate('Calculate and display Sosa ancestors of the root person.');
79
+	}
80
+
81
+	/**
82
+	 * {@inheritDoc}
83
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::boot()
84
+	 */
85
+	public function boot(): void
86
+	{
87
+		$this->traitBoot();
88
+		app(MigrationService::class)->updateSchema(
89
+			self::SCHEMA_MIGRATION_PREFIX,
90
+			self::SCHEMA_SETTING_NAME,
91
+			self::SCHEMA_TARGET_VERSION
92
+		);
93
+	}
94
+
95
+	/**
96
+	 * {@inheritDoc}
97
+	 * @see \MyArtJaub\Webtrees\Module\ModuleMyArtJaubInterface::loadRoutes()
98
+	 */
99
+	public function loadRoutes(Map $router): void
100
+	{
101
+		$router->attach('', '', static function (Map $router): void {
102
+
103
+			$router->attach('', '/module-maj/sosa', static function (Map $router): void {
104
+
105
+				$router->attach('', '/list', static function (Map $router): void {
106
+
107
+					$router->get(AncestorsList::class, '/ancestors/{tree}{/gen}', AncestorsList::class);
108
+					$router->get(AncestorsListIndividual::class, '/ancestors/{tree}/{gen}/tab/individuals', AncestorsListIndividual::class);    //phpcs:ignore Generic.Files.LineLength.TooLong
109
+					$router->get(AncestorsListFamily::class, '/ancestors/{tree}/{gen}/tab/families', AncestorsListFamily::class);   //phpcs:ignore Generic.Files.LineLength.TooLong
110
+					$router->get(MissingAncestorsList::class, '/missing/{tree}{/gen}', MissingAncestorsList::class);
111
+				});
112
+
113
+				$router->attach('', '/statistics/{tree}', static function (Map $router): void {
114
+
115
+					$router->get(SosaStatistics::class, '', SosaStatistics::class);
116
+					$router->get(PedigreeCollapseData::class, '/pedigreecollapse', PedigreeCollapseData::class);
117
+				});
118
+
119
+				$router->attach('', '/config/{tree}', static function (Map $router): void {
120
+
121
+					$router->get(SosaConfig::class, '', SosaConfig::class);
122
+					$router->post(SosaConfigAction::class, '', SosaConfigAction::class);
123
+					$router->get(SosaComputeModal::class, '/compute/{xref}', SosaComputeModal::class);
124
+					$router->post(SosaComputeAction::class, '/compute', SosaComputeAction::class);
125
+				});
126
+			});
127
+		});
128
+	}
129
+
130
+	/**
131
+	 * {@inheritDoc}
132
+	 * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
133
+	 */
134
+	public function customModuleVersion(): string
135
+	{
136
+		return '2.0.11-v.1';
137
+	}
138
+
139
+	/**
140
+	 * {@inheritDoc}
141
+	 * @see \Fisharebest\Webtrees\Module\ModuleMenuInterface::defaultMenuOrder()
142
+	 */
143
+	public function defaultMenuOrder(): int
144
+	{
145
+		return 7;
146
+	}
147
+
148
+	/**
149
+	 * {@inhericDoc}
150
+	 * @see \Fisharebest\Webtrees\Module\ModuleMenuInterface::getMenu()
151
+	 */
152
+	public function getMenu(Tree $tree): ?Menu
153
+	{
154
+		$menu = new Menu(I18N::translate('Sosa Statistics'));
155
+		$menu->setClass('menu-maj-sosa');
156
+		$menu->setSubmenus([
157
+			new Menu(
158
+				I18N::translate('Sosa Ancestors'),
159
+				route(AncestorsList::class, ['tree' => $tree->name()]),
160
+				'menu-maj-sosa-list',
161
+				['rel' => 'nofollow']
162
+			),
163
+			new Menu(
164
+				I18N::translate('Missing Ancestors'),
165
+				route(MissingAncestorsList::class, ['tree' => $tree->name()]),
166
+				'menu-maj-sosa-missing',
167
+				['rel' => 'nofollow']
168
+			),
169
+			new Menu(
170
+				I18N::translate('Sosa Statistics'),
171
+				route(SosaStatistics::class, ['tree' => $tree->name()]),
172
+				'menu-maj-sosa-stats'
173
+			)
174
+		]);
175
+
176
+		if (Auth::check()) {
177
+			$menu->addSubmenu(new Menu(
178
+				I18N::translate('Sosa Configuration'),
179
+				route(SosaConfig::class, ['tree' => $tree->name()]),
180
+				'menu-maj-sosa-config'
181
+			));
182
+
183
+			/** @var ServerRequestInterface $request */
184
+			$request = app(ServerRequestInterface::class);
185
+			$route = $request->getAttribute('route');
186
+			assert($route instanceof Route);
187
+
188
+			$root_indi_id = $tree->getUserPreference(Auth::user(), 'MAJ_SOSA_ROOT_ID');
189
+
190
+			if ($route->name === IndividualPage::class && mb_strlen($root_indi_id) > 0) {
191
+				$xref = $request->getAttribute('xref');
192
+				assert(is_string($xref));
193
+
194
+				$menu->addSubmenu(new Menu(
195
+					I18N::translate('Complete Sosas'),
196
+					'#',
197
+					'menu-maj-sosa-compute',
198
+					[
199
+						'rel'           => 'nofollow',
200
+						'data-href'     => route(SosaComputeModal::class, ['tree' => $tree->name(), 'xref' => $xref]),
201
+						'data-target'   => '#wt-ajax-modal',
202
+						'data-toggle'   => 'modal',
203
+						'data-backdrop' => 'static'
204
+					]
205
+				));
206
+			}
207
+		}
208
+
209
+		return $menu;
210
+	}
211
+
212
+	/**
213
+	 * {@inheritDoc}
214
+	 * @see \Fisharebest\Webtrees\Module\ModuleGlobalInterface::headContent()
215
+	 */
216
+	public function headContent(): string
217
+	{
218
+		return '<link rel="stylesheet" href="' . e($this->moduleCssUrl()) . '">';
219
+	}
220 220
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/WelcomeBlock/WelcomeBlockModule.php 1 patch
Indentation   +154 added lines, -154 removed lines patch added patch discarded remove patch
@@ -32,158 +32,158 @@
 block discarded – undo
32 32
  */
33 33
 class WelcomeBlockModule extends AbstractModule implements ModuleMyArtJaubInterface, ModuleBlockInterface
34 34
 {
35
-    use ModuleMyArtJaubTrait;
36
-    use ModuleBlockTrait;
37
-
38
-    /**
39
-     * {@inheritDoc}
40
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
41
-     */
42
-    public function title(): string
43
-    {
44
-        return /* I18N: Name of the “WelcomeBlock” module */ I18N::translate('MyArtJaub Welcome Block');
45
-    }
46
-
47
-    /**
48
-     * {@inheritDoc}
49
-     * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
50
-     */
51
-    public function description(): string
52
-    {
53
-        //phpcs:ignore Generic.Files.LineLength.TooLong
54
-        return /* I18N: Description of the “WelcomeBlock” module */ I18N::translate('The MyArtJaub Welcome block welcomes the visitor to the site, allows a quick login to the site, and displays statistics on visits.');
55
-    }
56
-
57
-    /**
58
-     * {@inheritDoc}
59
-     * @see \MyArtJaub\Webtrees\Module\ModuleMyArtJaubInterface::loadRoutes()
60
-     */
61
-    public function loadRoutes(Map $router): void
62
-    {
63
-        $router->attach('', '', static function (Map $router): void {
64
-
65
-            $router->attach('', '/module-maj/welcomeblock/{block_id}', static function (Map $router): void {
66
-
67
-                $router->get(MatomoStats::class, '/matomostats', MatomoStats::class);
68
-            });
69
-        });
70
-    }
71
-
72
-    /**
73
-     * {@inheritDoc}
74
-     * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
75
-     */
76
-    public function customModuleVersion(): string
77
-    {
78
-        return '2.0.11-v.1';
79
-    }
80
-
81
-    /**
82
-     * {@inheritDoc}
83
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::getBlock()
84
-     */
85
-    public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
86
-    {
87
-        $fab_welcome_block_view = app(\Fisharebest\Webtrees\Module\WelcomeBlockModule::class)
88
-            ->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
89
-
90
-        $fab_login_block_view = app(\Fisharebest\Webtrees\Module\LoginBlockModule::class)
91
-            ->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
92
-
93
-        $content = view($this->name() . '::block-embed', [
94
-            'block_id'                  =>  $block_id,
95
-            'fab_welcome_block_view'    =>  $fab_welcome_block_view,
96
-            'fab_login_block_view'      =>  $fab_login_block_view,
97
-            'matomo_enabled'            =>  $this->isMatomoEnabled($block_id)
98
-        ]);
99
-
100
-        if ($context !== self::CONTEXT_EMBED) {
101
-            return view('modules/block-template', [
102
-                'block'      => Str::kebab($this->name()),
103
-                'id'         => $block_id,
104
-                'config_url' => $this->configUrl($tree, $context, $block_id),
105
-                'title'      => $tree->title(),
106
-                'content'    => $content,
107
-            ]);
108
-        }
109
-
110
-        return $content;
111
-    }
112
-
113
-    /**
114
-     * {@inheritDoc}
115
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::isTreeBlock()
116
-     */
117
-    public function isTreeBlock(): bool
118
-    {
119
-        return true;
120
-    }
121
-
122
-    /**
123
-     * {@inheritDoc}
124
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::editBlockConfiguration()
125
-     */
126
-    public function editBlockConfiguration(Tree $tree, int $block_id): string
127
-    {
128
-        return view($this->name() . '::config', $this->matomoSettings($block_id));
129
-    }
130
-
131
-    /**
132
-     * {@inheritDoc}
133
-     * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::saveBlockConfiguration()
134
-     */
135
-    public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
136
-    {
137
-        $params = (array) $request->getParsedBody();
138
-
139
-        $matomo_enabled = $params['matomo_enabled'] == 'yes';
140
-        $this->setBlockSetting($block_id, 'matomo_enabled', $matomo_enabled ? 'yes' : 'no');
141
-        if (!$matomo_enabled) {
142
-            return;
143
-        }
144
-
145
-        if (filter_var($params['matomo_url'], FILTER_VALIDATE_URL) === false) {
146
-            FlashMessages::addMessage(I18N::translate('The Matomo URL provided is not valid.'), 'danger');
147
-            return;
148
-        }
149
-
150
-        if (filter_var($params['matomo_siteid'], FILTER_VALIDATE_INT) === false) {
151
-            FlashMessages::addMessage(I18N::translate('The Matomo Site ID provided is not valid.'), 'danger');
152
-            return;
153
-        }
154
-
155
-        $this
156
-            ->setBlockSetting($block_id, 'matomo_url', trim($params['matomo_url']))
157
-            ->setBlockSetting($block_id, 'matomo_token', trim($params['matomo_token']))
158
-            ->setBlockSetting($block_id, 'matomo_siteid', $params['matomo_siteid']);
159
-
160
-        app('cache.files')->forget($this->name() . '-matomovisits-yearly-' . $block_id);
161
-    }
162
-
163
-    /**
164
-     * Returns whether Matomo statistics is enabled for a specific MyArtJaub WelcomeBlock block
165
-     *
166
-     * @param int $block_id
167
-     * @return bool
168
-     */
169
-    public function isMatomoEnabled(int $block_id): bool
170
-    {
171
-        return $this->getBlockSetting($block_id, 'matomo_enabled', 'no') === 'yes';
172
-    }
173
-
174
-    /**
175
-     * Returns settings for retrieving Matomo statistics for a specific MyArtJaub WelcomeBlock block
176
-     *
177
-     * @param int $block_id
178
-     * @return array<string, mixed>
179
-     */
180
-    public function matomoSettings(int $block_id): array
181
-    {
182
-        return [
183
-            'matomo_enabled' => $this->isMatomoEnabled($block_id),
184
-            'matomo_url' => $this->getBlockSetting($block_id, 'matomo_url'),
185
-            'matomo_token' => $this->getBlockSetting($block_id, 'matomo_token'),
186
-            'matomo_siteid'  => (int) $this->getBlockSetting($block_id, 'matomo_siteid', '0')
187
-        ];
188
-    }
35
+	use ModuleMyArtJaubTrait;
36
+	use ModuleBlockTrait;
37
+
38
+	/**
39
+	 * {@inheritDoc}
40
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::title()
41
+	 */
42
+	public function title(): string
43
+	{
44
+		return /* I18N: Name of the “WelcomeBlock” module */ I18N::translate('MyArtJaub Welcome Block');
45
+	}
46
+
47
+	/**
48
+	 * {@inheritDoc}
49
+	 * @see \Fisharebest\Webtrees\Module\AbstractModule::description()
50
+	 */
51
+	public function description(): string
52
+	{
53
+		//phpcs:ignore Generic.Files.LineLength.TooLong
54
+		return /* I18N: Description of the “WelcomeBlock” module */ I18N::translate('The MyArtJaub Welcome block welcomes the visitor to the site, allows a quick login to the site, and displays statistics on visits.');
55
+	}
56
+
57
+	/**
58
+	 * {@inheritDoc}
59
+	 * @see \MyArtJaub\Webtrees\Module\ModuleMyArtJaubInterface::loadRoutes()
60
+	 */
61
+	public function loadRoutes(Map $router): void
62
+	{
63
+		$router->attach('', '', static function (Map $router): void {
64
+
65
+			$router->attach('', '/module-maj/welcomeblock/{block_id}', static function (Map $router): void {
66
+
67
+				$router->get(MatomoStats::class, '/matomostats', MatomoStats::class);
68
+			});
69
+		});
70
+	}
71
+
72
+	/**
73
+	 * {@inheritDoc}
74
+	 * @see \Fisharebest\Webtrees\Module\ModuleCustomInterface::customModuleVersion()
75
+	 */
76
+	public function customModuleVersion(): string
77
+	{
78
+		return '2.0.11-v.1';
79
+	}
80
+
81
+	/**
82
+	 * {@inheritDoc}
83
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::getBlock()
84
+	 */
85
+	public function getBlock(Tree $tree, int $block_id, string $context, array $config = []): string
86
+	{
87
+		$fab_welcome_block_view = app(\Fisharebest\Webtrees\Module\WelcomeBlockModule::class)
88
+			->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
89
+
90
+		$fab_login_block_view = app(\Fisharebest\Webtrees\Module\LoginBlockModule::class)
91
+			->getBlock($tree, $block_id, ModuleBlockInterface::CONTEXT_EMBED);
92
+
93
+		$content = view($this->name() . '::block-embed', [
94
+			'block_id'                  =>  $block_id,
95
+			'fab_welcome_block_view'    =>  $fab_welcome_block_view,
96
+			'fab_login_block_view'      =>  $fab_login_block_view,
97
+			'matomo_enabled'            =>  $this->isMatomoEnabled($block_id)
98
+		]);
99
+
100
+		if ($context !== self::CONTEXT_EMBED) {
101
+			return view('modules/block-template', [
102
+				'block'      => Str::kebab($this->name()),
103
+				'id'         => $block_id,
104
+				'config_url' => $this->configUrl($tree, $context, $block_id),
105
+				'title'      => $tree->title(),
106
+				'content'    => $content,
107
+			]);
108
+		}
109
+
110
+		return $content;
111
+	}
112
+
113
+	/**
114
+	 * {@inheritDoc}
115
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::isTreeBlock()
116
+	 */
117
+	public function isTreeBlock(): bool
118
+	{
119
+		return true;
120
+	}
121
+
122
+	/**
123
+	 * {@inheritDoc}
124
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::editBlockConfiguration()
125
+	 */
126
+	public function editBlockConfiguration(Tree $tree, int $block_id): string
127
+	{
128
+		return view($this->name() . '::config', $this->matomoSettings($block_id));
129
+	}
130
+
131
+	/**
132
+	 * {@inheritDoc}
133
+	 * @see \Fisharebest\Webtrees\Module\ModuleBlockInterface::saveBlockConfiguration()
134
+	 */
135
+	public function saveBlockConfiguration(ServerRequestInterface $request, int $block_id): void
136
+	{
137
+		$params = (array) $request->getParsedBody();
138
+
139
+		$matomo_enabled = $params['matomo_enabled'] == 'yes';
140
+		$this->setBlockSetting($block_id, 'matomo_enabled', $matomo_enabled ? 'yes' : 'no');
141
+		if (!$matomo_enabled) {
142
+			return;
143
+		}
144
+
145
+		if (filter_var($params['matomo_url'], FILTER_VALIDATE_URL) === false) {
146
+			FlashMessages::addMessage(I18N::translate('The Matomo URL provided is not valid.'), 'danger');
147
+			return;
148
+		}
149
+
150
+		if (filter_var($params['matomo_siteid'], FILTER_VALIDATE_INT) === false) {
151
+			FlashMessages::addMessage(I18N::translate('The Matomo Site ID provided is not valid.'), 'danger');
152
+			return;
153
+		}
154
+
155
+		$this
156
+			->setBlockSetting($block_id, 'matomo_url', trim($params['matomo_url']))
157
+			->setBlockSetting($block_id, 'matomo_token', trim($params['matomo_token']))
158
+			->setBlockSetting($block_id, 'matomo_siteid', $params['matomo_siteid']);
159
+
160
+		app('cache.files')->forget($this->name() . '-matomovisits-yearly-' . $block_id);
161
+	}
162
+
163
+	/**
164
+	 * Returns whether Matomo statistics is enabled for a specific MyArtJaub WelcomeBlock block
165
+	 *
166
+	 * @param int $block_id
167
+	 * @return bool
168
+	 */
169
+	public function isMatomoEnabled(int $block_id): bool
170
+	{
171
+		return $this->getBlockSetting($block_id, 'matomo_enabled', 'no') === 'yes';
172
+	}
173
+
174
+	/**
175
+	 * Returns settings for retrieving Matomo statistics for a specific MyArtJaub WelcomeBlock block
176
+	 *
177
+	 * @param int $block_id
178
+	 * @return array<string, mixed>
179
+	 */
180
+	public function matomoSettings(int $block_id): array
181
+	{
182
+		return [
183
+			'matomo_enabled' => $this->isMatomoEnabled($block_id),
184
+			'matomo_url' => $this->getBlockSetting($block_id, 'matomo_url'),
185
+			'matomo_token' => $this->getBlockSetting($block_id, 'matomo_token'),
186
+			'matomo_siteid'  => (int) $this->getBlockSetting($block_id, 'matomo_siteid', '0')
187
+		];
188
+	}
189 189
 }
Please login to merge, or discard this patch.