Passed
Push — main ( c808ff...64cea5 )
by Jonathan
03:30
created
Module/GeoDispersion/PlaceMappers/Config/FilteredTopPlaceMapperConfig.php 2 patches
Indentation   +99 added lines, -99 removed lines patch added patch discarded remove patch
@@ -29,111 +29,111 @@
 block discarded – undo
29 29
  */
30 30
 class FilteredTopPlaceMapperConfig extends GenericPlaceMapperConfig
31 31
 {
32
-    private TreeService $tree_service;
32
+	private TreeService $tree_service;
33 33
 
34
-    /**
35
-     * FilteredTopPlaceMapperConfig
36
-     *
37
-     * @param TreeService $tree_service
38
-     */
39
-    public function __construct(TreeService $tree_service)
40
-    {
41
-        $this->tree_service = $tree_service;
42
-    }
34
+	/**
35
+	 * FilteredTopPlaceMapperConfig
36
+	 *
37
+	 * @param TreeService $tree_service
38
+	 */
39
+	public function __construct(TreeService $tree_service)
40
+	{
41
+		$this->tree_service = $tree_service;
42
+	}
43 43
 
44
-    /**
45
-     * Get the configured Top Places to filter on
46
-     *
47
-     * @return Collection<Place>
48
-     */
49
-    public function topPlaces(): Collection
50
-    {
51
-        return collect($this->get('topPlaces', []))
52
-            ->filter(
53
-                /** @psalm-suppress MissingClosureParamType */
54
-                fn($item): bool => $item instanceof Place
55
-            );
56
-    }
44
+	/**
45
+	 * Get the configured Top Places to filter on
46
+	 *
47
+	 * @return Collection<Place>
48
+	 */
49
+	public function topPlaces(): Collection
50
+	{
51
+		return collect($this->get('topPlaces', []))
52
+			->filter(
53
+				/** @psalm-suppress MissingClosureParamType */
54
+				fn($item): bool => $item instanceof Place
55
+			);
56
+	}
57 57
 
58
-    /**
59
-     * {@inheritDoc}
60
-     * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::jsonSerializeConfig()
61
-     */
62
-    public function jsonSerializeConfig()
63
-    {
64
-        return [
65
-            'topPlaces' => $this->topPlaces()
66
-                ->map(fn(Place $place): array => [ $place->tree()->id(), $place->gedcomName() ])
67
-                ->toArray()
68
-        ];
69
-    }
58
+	/**
59
+	 * {@inheritDoc}
60
+	 * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::jsonSerializeConfig()
61
+	 */
62
+	public function jsonSerializeConfig()
63
+	{
64
+		return [
65
+			'topPlaces' => $this->topPlaces()
66
+				->map(fn(Place $place): array => [ $place->tree()->id(), $place->gedcomName() ])
67
+				->toArray()
68
+		];
69
+	}
70 70
 
71
-    /**
72
-     * {@inheritDoc}
73
-     * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::jsonDeserialize()
74
-     *
75
-     * @param mixed $config
76
-     * @return $this
77
-     */
78
-    public function jsonDeserialize($config): self
79
-    {
80
-        if (is_string($config)) {
81
-            return $this->jsonDeserialize(json_decode($config));
82
-        }
83
-        if (is_array($config)) {
84
-            $this->setConfig([
85
-                'topPlaces' => collect($config['topPlaces'] ?? [])
86
-                    ->filter(
87
-                        /** @psalm-suppress MissingClosureParamType */
88
-                        fn($item): bool => is_array($item) && count($item) === 2
89
-                    )->map(function (array $item): ?Place {
90
-                        try {
91
-                            return new Place($item[1], $this->tree_service->find($item[0]));
92
-                        } catch (RuntimeException $ex) {
93
-                            return null;
94
-                        }
95
-                    })
96
-                    ->filter()
97
-                    ->toArray()
98
-                ]);
99
-        }
100
-        return $this;
101
-    }
71
+	/**
72
+	 * {@inheritDoc}
73
+	 * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::jsonDeserialize()
74
+	 *
75
+	 * @param mixed $config
76
+	 * @return $this
77
+	 */
78
+	public function jsonDeserialize($config): self
79
+	{
80
+		if (is_string($config)) {
81
+			return $this->jsonDeserialize(json_decode($config));
82
+		}
83
+		if (is_array($config)) {
84
+			$this->setConfig([
85
+				'topPlaces' => collect($config['topPlaces'] ?? [])
86
+					->filter(
87
+						/** @psalm-suppress MissingClosureParamType */
88
+						fn($item): bool => is_array($item) && count($item) === 2
89
+					)->map(function (array $item): ?Place {
90
+						try {
91
+							return new Place($item[1], $this->tree_service->find($item[0]));
92
+						} catch (RuntimeException $ex) {
93
+							return null;
94
+						}
95
+					})
96
+					->filter()
97
+					->toArray()
98
+				]);
99
+		}
100
+		return $this;
101
+	}
102 102
 
103
-    /**
104
-     * {@inheritDoc}
105
-     * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::configContent()
106
-     */
107
-    public function configContent(ModuleInterface $module, Tree $tree): string
108
-    {
109
-        return view($module->name() . '::mappers/filtered-top-config', [
110
-            'tree'          =>  $tree,
111
-            'top_places'    =>  $this->topPlaces()
112
-        ]);
113
-    }
103
+	/**
104
+	 * {@inheritDoc}
105
+	 * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::configContent()
106
+	 */
107
+	public function configContent(ModuleInterface $module, Tree $tree): string
108
+	{
109
+		return view($module->name() . '::mappers/filtered-top-config', [
110
+			'tree'          =>  $tree,
111
+			'top_places'    =>  $this->topPlaces()
112
+		]);
113
+	}
114 114
 
115
-    /**
116
-     * {@inheritDoc}
117
-     * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::withConfigUpdate()
118
-     * @return $this
119
-     */
120
-    public function withConfigUpdate(ServerRequestInterface $request): self
121
-    {
122
-        $tree = Validator::attributes($request)->treeOptional();
115
+	/**
116
+	 * {@inheritDoc}
117
+	 * @see \MyArtJaub\Webtrees\Common\GeoDispersion\Config\GenericPlaceMapperConfig::withConfigUpdate()
118
+	 * @return $this
119
+	 */
120
+	public function withConfigUpdate(ServerRequestInterface $request): self
121
+	{
122
+		$tree = Validator::attributes($request)->treeOptional();
123 123
 
124
-        if ($tree === null) {
125
-            return $this;
126
-        }
124
+		if ($tree === null) {
125
+			return $this;
126
+		}
127 127
 
128
-        $top_places = Validator::parsedBody($request)->array('mapper_filt_top_places');
129
-        $config = ['topPlaces' => []];
130
-        foreach ($top_places as $top_place_id) {
131
-            $place = Place::find((int) $top_place_id, $tree);
132
-            if (mb_strlen($place->gedcomName()) > 0) {
133
-                $config['topPlaces'][] = $place;
134
-            }
135
-        }
136
-        $this->setConfig($config);
137
-        return $this;
138
-    }
128
+		$top_places = Validator::parsedBody($request)->array('mapper_filt_top_places');
129
+		$config = ['topPlaces' => []];
130
+		foreach ($top_places as $top_place_id) {
131
+			$place = Place::find((int) $top_place_id, $tree);
132
+			if (mb_strlen($place->gedcomName()) > 0) {
133
+				$config['topPlaces'][] = $place;
134
+			}
135
+		}
136
+		$this->setConfig($config);
137
+		return $this;
138
+	}
139 139
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -63,7 +63,7 @@  discard block
 block discarded – undo
63 63
     {
64 64
         return [
65 65
             'topPlaces' => $this->topPlaces()
66
-                ->map(fn(Place $place): array => [ $place->tree()->id(), $place->gedcomName() ])
66
+                ->map(fn(Place $place): array => [$place->tree()->id(), $place->gedcomName()])
67 67
                 ->toArray()
68 68
         ];
69 69
     }
@@ -86,7 +86,7 @@  discard block
 block discarded – undo
86 86
                     ->filter(
87 87
                         /** @psalm-suppress MissingClosureParamType */
88 88
                         fn($item): bool => is_array($item) && count($item) === 2
89
-                    )->map(function (array $item): ?Place {
89
+                    )->map(function(array $item): ?Place {
90 90
                         try {
91 91
                             return new Place($item[1], $this->tree_service->find($item[0]));
92 92
                         } catch (RuntimeException $ex) {
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
      */
107 107
     public function configContent(ModuleInterface $module, Tree $tree): string
108 108
     {
109
-        return view($module->name() . '::mappers/filtered-top-config', [
109
+        return view($module->name().'::mappers/filtered-top-config', [
110 110
             'tree'          =>  $tree,
111 111
             'top_places'    =>  $this->topPlaces()
112 112
         ]);
@@ -128,7 +128,7 @@  discard block
 block discarded – undo
128 128
         $top_places = Validator::parsedBody($request)->array('mapper_filt_top_places');
129 129
         $config = ['topPlaces' => []];
130 130
         foreach ($top_places as $top_place_id) {
131
-            $place = Place::find((int) $top_place_id, $tree);
131
+            $place = Place::find((int)$top_place_id, $tree);
132 132
             if (mb_strlen($place->gedcomName()) > 0) {
133 133
                 $config['topPlaces'][] = $place;
134 134
             }
Please login to merge, or discard this patch.
app/Module/PatronymicLineage/Http/RequestHandlers/SurnamesList.php 2 patches
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -31,59 +31,59 @@
 block discarded – undo
31 31
  */
32 32
 class SurnamesList implements RequestHandlerInterface
33 33
 {
34
-    use ViewResponseTrait;
34
+	use ViewResponseTrait;
35 35
 
36
-    private ?PatronymicLineageModule $module;
36
+	private ?PatronymicLineageModule $module;
37 37
 
38
-    /**
39
-     * Constructor for SurnamesList Request Handler
40
-     *
41
-     * @param ModuleService $module_service
42
-     */
43
-    public function __construct(ModuleService $module_service)
44
-    {
45
-        $this->module = $module_service->findByInterface(PatronymicLineageModule::class)->first();
46
-    }
38
+	/**
39
+	 * Constructor for SurnamesList Request Handler
40
+	 *
41
+	 * @param ModuleService $module_service
42
+	 */
43
+	public function __construct(ModuleService $module_service)
44
+	{
45
+		$this->module = $module_service->findByInterface(PatronymicLineageModule::class)->first();
46
+	}
47 47
 
48
-    /**
49
-     * {@inheritDoc}
50
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
-     */
52
-    public function handle(ServerRequestInterface $request): ResponseInterface
53
-    {
54
-        if ($this->module === null) {
55
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
56
-        }
48
+	/**
49
+	 * {@inheritDoc}
50
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
+	 */
52
+	public function handle(ServerRequestInterface $request): ResponseInterface
53
+	{
54
+		if ($this->module === null) {
55
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
56
+		}
57 57
 
58
-        $tree = Validator::attributes($request)->tree();
59
-        $initial = Validator::attributes($request)->string('alpha', '');
58
+		$tree = Validator::attributes($request)->tree();
59
+		$initial = Validator::attributes($request)->string('alpha', '');
60 60
 
61
-        $initials_list = collect($this->module->surnameAlpha($tree, false, false, I18N::locale()))
62
-            ->reject(function (int $count, string $initial): bool {
63
-                return $initial === '@' || $initial === ',';
64
-            });
61
+		$initials_list = collect($this->module->surnameAlpha($tree, false, false, I18N::locale()))
62
+			->reject(function (int $count, string $initial): bool {
63
+				return $initial === '@' || $initial === ',';
64
+			});
65 65
 
66
-        $show_all = Validator::queryParams($request)->string('show_all', 'no');
66
+		$show_all = Validator::queryParams($request)->string('show_all', 'no');
67 67
 
68
-        if ($show_all === 'yes') {
69
-            $title = I18N::translate('Patronymic Lineages') . ' — ' . I18N::translate('All');
70
-            $surnames = $this->module->surnames($tree, '', '', false, false, I18N::locale());
71
-        } elseif (mb_strlen($initial) === 1) {
72
-            $title = I18N::translate('Patronymic Lineages') . ' — ' . $initial;
73
-            $surnames = $this->module->surnames($tree, '', $initial, false, false, I18N::locale());
74
-        } else {
75
-            $title =  I18N::translate('Patronymic Lineages');
76
-            $surnames = [];
77
-        }
68
+		if ($show_all === 'yes') {
69
+			$title = I18N::translate('Patronymic Lineages') . ' — ' . I18N::translate('All');
70
+			$surnames = $this->module->surnames($tree, '', '', false, false, I18N::locale());
71
+		} elseif (mb_strlen($initial) === 1) {
72
+			$title = I18N::translate('Patronymic Lineages') . ' — ' . $initial;
73
+			$surnames = $this->module->surnames($tree, '', $initial, false, false, I18N::locale());
74
+		} else {
75
+			$title =  I18N::translate('Patronymic Lineages');
76
+			$surnames = [];
77
+		}
78 78
 
79
-        return $this->viewResponse($this->module->name() . '::surnames-page', [
80
-            'title'         =>  $title,
81
-            'module'        =>  $this->module,
82
-            'tree'          =>  $tree,
83
-            'initials_list' =>  $initials_list,
84
-            'initial'       =>  $initial,
85
-            'show_all'      =>  $show_all,
86
-            'surnames'      =>  $surnames
87
-        ]);
88
-    }
79
+		return $this->viewResponse($this->module->name() . '::surnames-page', [
80
+			'title'         =>  $title,
81
+			'module'        =>  $this->module,
82
+			'tree'          =>  $tree,
83
+			'initials_list' =>  $initials_list,
84
+			'initial'       =>  $initial,
85
+			'show_all'      =>  $show_all,
86
+			'surnames'      =>  $surnames
87
+		]);
88
+	}
89 89
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -59,24 +59,24 @@
 block discarded – undo
59 59
         $initial = Validator::attributes($request)->string('alpha', '');
60 60
 
61 61
         $initials_list = collect($this->module->surnameAlpha($tree, false, false, I18N::locale()))
62
-            ->reject(function (int $count, string $initial): bool {
62
+            ->reject(function(int $count, string $initial): bool {
63 63
                 return $initial === '@' || $initial === ',';
64 64
             });
65 65
 
66 66
         $show_all = Validator::queryParams($request)->string('show_all', 'no');
67 67
 
68 68
         if ($show_all === 'yes') {
69
-            $title = I18N::translate('Patronymic Lineages') . ' — ' . I18N::translate('All');
69
+            $title = I18N::translate('Patronymic Lineages').' — '.I18N::translate('All');
70 70
             $surnames = $this->module->surnames($tree, '', '', false, false, I18N::locale());
71 71
         } elseif (mb_strlen($initial) === 1) {
72
-            $title = I18N::translate('Patronymic Lineages') . ' — ' . $initial;
72
+            $title = I18N::translate('Patronymic Lineages').' — '.$initial;
73 73
             $surnames = $this->module->surnames($tree, '', $initial, false, false, I18N::locale());
74 74
         } else {
75
-            $title =  I18N::translate('Patronymic Lineages');
75
+            $title = I18N::translate('Patronymic Lineages');
76 76
             $surnames = [];
77 77
         }
78 78
 
79
-        return $this->viewResponse($this->module->name() . '::surnames-page', [
79
+        return $this->viewResponse($this->module->name().'::surnames-page', [
80 80
             'title'         =>  $title,
81 81
             'module'        =>  $this->module,
82 82
             'tree'          =>  $tree,
Please login to merge, or discard this patch.
app/Module/PatronymicLineage/Model/LineageBuilder.php 2 patches
Indentation   +209 added lines, -209 removed lines patch added patch discarded remove patch
@@ -28,213 +28,213 @@
 block discarded – undo
28 28
  */
29 29
 class LineageBuilder
30 30
 {
31
-    private string $surname;
32
-    private Tree $tree;
33
-    private PatronymicLineageModule $patrolineage_module;
34
-
35
-    /**
36
-     * @var Collection<string, bool> $used_indis Individuals already processed
37
-     */
38
-    private Collection $used_indis;
39
-
40
-    /**
41
-     * Constructor for Lineage Builder
42
-     *
43
-     * @param string $surname Reference surname
44
-     * @param Tree $tree Gedcom tree
45
-     */
46
-    public function __construct(string $surname, Tree $tree, PatronymicLineageModule $patrolineage_module)
47
-    {
48
-        $this->surname = $surname;
49
-        $this->tree = $tree;
50
-        $this->patrolineage_module = $patrolineage_module;
51
-        $this->used_indis = new Collection();
52
-    }
53
-
54
-    /**
55
-     * Build all patronymic lineages for the reference surname.
56
-     *
57
-     * @return Collection<LineageRootNode>|NULL List of root patronymic lineages
58
-     */
59
-    public function buildLineages(): ?Collection
60
-    {
61
-        $indis = $this->patrolineage_module->individuals(
62
-            $this->tree,
63
-            $this->surname,
64
-            '',
65
-            '',
66
-            false,
67
-            false,
68
-            I18N::locale()
69
-        );
70
-        //Warning - the individuals method returns a clone of individuals objects. Cannot be used for object equality
71
-        if (count($indis) === 0) {
72
-            return null;
73
-        }
74
-
75
-        $root_lineages = new Collection();
76
-
77
-        foreach ($indis as $indi) {
78
-            /** @var Individual $indi */
79
-            if ($this->used_indis->get($indi->xref(), false) === false) {
80
-                $indi_first = $this->getLineageRootIndividual($indi);
81
-                if ($indi_first !== null) {
82
-                    // The root lineage needs to be recreated from the Factory, to retrieve the proper object
83
-                    $indi_first = Registry::individualFactory()->make($indi_first->xref(), $this->tree);
84
-                }
85
-                if ($indi_first === null) {
86
-                    continue;
87
-                }
88
-                $this->used_indis->put($indi_first->xref(), true);
89
-                if ($indi_first->canShow()) {
90
-                    //Check if the root individual has brothers and sisters, without parents
91
-                    $indi_first_child_family = $indi_first->childFamilies()->first();
92
-                    if ($indi_first_child_family !== null) {
93
-                        $root_node = new LineageRootNode(null);
94
-                        $root_node->addFamily($indi_first_child_family);
95
-                    } else {
96
-                        $root_node = new LineageRootNode($indi_first);
97
-                    }
98
-                    $root_node = $this->buildLineage($root_node);
99
-                    $root_lineages->add($root_node);
100
-                }
101
-            }
102
-        }
103
-
104
-        return $root_lineages->sort(function (LineageRootNode $a, LineageRootNode $b) {
105
-            if ($a->numberChildNodes() === $b->numberChildNodes()) {
106
-                return 0;
107
-            }
108
-            return ($a->numberChildNodes() > $b->numberChildNodes()) ? -1 : 1;
109
-        })->values();
110
-    }
111
-
112
-    /**
113
-     * Retrieve the root individual, from any individual, by recursion.
114
-     * The Root individual is the individual without a father, or without a mother holding the same name.
115
-     *
116
-     * @param Individual $indi
117
-     * @return Individual|NULL Root individual
118
-     */
119
-    private function getLineageRootIndividual(Individual $indi): ?Individual
120
-    {
121
-        $child_families = $indi->childFamilies();
122
-        if ($this->used_indis->get($indi->xref(), false) !== false) {
123
-            return null;
124
-        }
125
-
126
-        foreach ($child_families as $child_family) {
127
-            /** @var Family $child_family */
128
-            $child_family->husband();
129
-            if (($husb = $child_family->husband()) !== null) {
130
-                if ($husb->isPendingAddition() && $husb->privatizeGedcom(Auth::PRIV_HIDE) === '') {
131
-                    return $indi;
132
-                }
133
-                return $this->getLineageRootIndividual($husb);
134
-            } elseif (($wife = $child_family->wife()) !== null) {
135
-                if (!($wife->isPendingAddition() && $wife->privatizeGedcom(Auth::PRIV_HIDE) === '')) {
136
-                    $indi_surname = $indi->getAllNames()[$indi->getPrimaryName()]['surname'];
137
-                    $wife_surname = $wife->getAllNames()[$wife->getPrimaryName()]['surname'];
138
-                    if (
139
-                        $indi->canShowName()
140
-                        && $wife->canShowName()
141
-                        && I18N::comparator()($indi_surname, $wife_surname) === 0
142
-                    ) {
143
-                            return $this->getLineageRootIndividual($wife);
144
-                    }
145
-                }
146
-                return $indi;
147
-            }
148
-        }
149
-        return $indi;
150
-    }
151
-
152
-    /**
153
-     * Computes descendent Lineage from a node.
154
-     * Uses recursion to build the lineage tree
155
-     *
156
-     * @param LineageNode $node
157
-     * @return LineageNode Computed lineage
158
-     */
159
-    private function buildLineage(LineageNode $node): LineageNode
160
-    {
161
-        $indi_surname = '';
162
-
163
-        $indi_node = $node->individual();
164
-        if ($indi_node !== null) {
165
-            if ($node->families()->count() === 0) {
166
-                foreach ($indi_node->spouseFamilies() as $spouse_family) {
167
-                    $node->addFamily($spouse_family);
168
-                }
169
-            }
170
-
171
-            $indi_surname = $indi_node->getAllNames()[$indi_node->getPrimaryName()]['surname'] ?? '';
172
-            $node->rootNode()->addPlace($indi_node->getBirthPlace());
173
-
174
-            //Tag the individual as used
175
-            $this->used_indis->put($indi_node->xref(), true);
176
-        }
177
-
178
-        foreach ($node->families() as $family_node) {
179
-            /** @var Family $spouse_family */
180
-            $spouse_family = $family_node->family;
181
-            $spouse_surname = '';
182
-            $spouse = null;
183
-            if (
184
-                $indi_node !== null &&
185
-                ($spouse = $spouse_family->spouse($indi_node)) !== null && $spouse->canShowName()
186
-            ) {
187
-                $spouse_surname = $spouse->getAllNames()[$spouse->getPrimaryName()]['surname'] ?? '';
188
-            }
189
-
190
-            $nb_children = $nb_natural = 0;
191
-
192
-            foreach ($spouse_family->children() as $child) {
193
-                if (!($child->isPendingAddition() && $child->privatizeGedcom(Auth::PRIV_HIDE) === '')) {
194
-                    $child_surname = $child->getAllNames()[$child->getPrimaryName()]['surname'] ?? '';
195
-
196
-                    $nb_children++;
197
-                    if ($indi_node !== null && $indi_node->sex() === 'F') { //If the root individual is the mother
198
-                        //Print only lineages of children with the same surname as their mother
199
-                        //(supposing they are natural children)
200
-                        /** @psalm-suppress RedundantCondition */
201
-                        if (
202
-                            $spouse === null ||
203
-                            ($spouse_surname !== '' && I18N::comparator()($child_surname, $spouse_surname) != 0)
204
-                        ) {
205
-                            if (I18N::comparator()($child_surname, $indi_surname) === 0) {
206
-                                $nb_natural++;
207
-                                $node_child = new LineageNode($child, $node->rootNode());
208
-                                $node_child = $this->buildLineage($node_child);
209
-                                $node->addChild($spouse_family, $node_child);
210
-                            }
211
-                        }
212
-                    } else { //If the root individual is the father
213
-                        $nb_natural++;
214
-                        //Print if the children does not bear the same name as his mother
215
-                        //(and different from his father)
216
-                        if (
217
-                            mb_strlen($child_surname) === 0 ||
218
-                            mb_strlen($indi_surname) === 0 || mb_strlen($spouse_surname) === 0 ||
219
-                            I18N::comparator()($child_surname, $indi_surname) === 0 ||
220
-                            I18N::comparator()($child_surname, $spouse_surname) != 0
221
-                        ) {
222
-                            $node_child = new LineageNode($child, $node->rootNode());
223
-                            $node_child = $this->buildLineage($node_child);
224
-                        } else {
225
-                            $node_child = new LineageNode($child, $node->rootNode(), $child_surname);
226
-                        }
227
-                        $node->addChild($spouse_family, $node_child);
228
-                    }
229
-                }
230
-            }
231
-
232
-            //Do not print other children
233
-            if (($nb_children - $nb_natural) > 0) {
234
-                $node->addChild($spouse_family, null);
235
-            }
236
-        }
237
-
238
-        return $node;
239
-    }
31
+	private string $surname;
32
+	private Tree $tree;
33
+	private PatronymicLineageModule $patrolineage_module;
34
+
35
+	/**
36
+	 * @var Collection<string, bool> $used_indis Individuals already processed
37
+	 */
38
+	private Collection $used_indis;
39
+
40
+	/**
41
+	 * Constructor for Lineage Builder
42
+	 *
43
+	 * @param string $surname Reference surname
44
+	 * @param Tree $tree Gedcom tree
45
+	 */
46
+	public function __construct(string $surname, Tree $tree, PatronymicLineageModule $patrolineage_module)
47
+	{
48
+		$this->surname = $surname;
49
+		$this->tree = $tree;
50
+		$this->patrolineage_module = $patrolineage_module;
51
+		$this->used_indis = new Collection();
52
+	}
53
+
54
+	/**
55
+	 * Build all patronymic lineages for the reference surname.
56
+	 *
57
+	 * @return Collection<LineageRootNode>|NULL List of root patronymic lineages
58
+	 */
59
+	public function buildLineages(): ?Collection
60
+	{
61
+		$indis = $this->patrolineage_module->individuals(
62
+			$this->tree,
63
+			$this->surname,
64
+			'',
65
+			'',
66
+			false,
67
+			false,
68
+			I18N::locale()
69
+		);
70
+		//Warning - the individuals method returns a clone of individuals objects. Cannot be used for object equality
71
+		if (count($indis) === 0) {
72
+			return null;
73
+		}
74
+
75
+		$root_lineages = new Collection();
76
+
77
+		foreach ($indis as $indi) {
78
+			/** @var Individual $indi */
79
+			if ($this->used_indis->get($indi->xref(), false) === false) {
80
+				$indi_first = $this->getLineageRootIndividual($indi);
81
+				if ($indi_first !== null) {
82
+					// The root lineage needs to be recreated from the Factory, to retrieve the proper object
83
+					$indi_first = Registry::individualFactory()->make($indi_first->xref(), $this->tree);
84
+				}
85
+				if ($indi_first === null) {
86
+					continue;
87
+				}
88
+				$this->used_indis->put($indi_first->xref(), true);
89
+				if ($indi_first->canShow()) {
90
+					//Check if the root individual has brothers and sisters, without parents
91
+					$indi_first_child_family = $indi_first->childFamilies()->first();
92
+					if ($indi_first_child_family !== null) {
93
+						$root_node = new LineageRootNode(null);
94
+						$root_node->addFamily($indi_first_child_family);
95
+					} else {
96
+						$root_node = new LineageRootNode($indi_first);
97
+					}
98
+					$root_node = $this->buildLineage($root_node);
99
+					$root_lineages->add($root_node);
100
+				}
101
+			}
102
+		}
103
+
104
+		return $root_lineages->sort(function (LineageRootNode $a, LineageRootNode $b) {
105
+			if ($a->numberChildNodes() === $b->numberChildNodes()) {
106
+				return 0;
107
+			}
108
+			return ($a->numberChildNodes() > $b->numberChildNodes()) ? -1 : 1;
109
+		})->values();
110
+	}
111
+
112
+	/**
113
+	 * Retrieve the root individual, from any individual, by recursion.
114
+	 * The Root individual is the individual without a father, or without a mother holding the same name.
115
+	 *
116
+	 * @param Individual $indi
117
+	 * @return Individual|NULL Root individual
118
+	 */
119
+	private function getLineageRootIndividual(Individual $indi): ?Individual
120
+	{
121
+		$child_families = $indi->childFamilies();
122
+		if ($this->used_indis->get($indi->xref(), false) !== false) {
123
+			return null;
124
+		}
125
+
126
+		foreach ($child_families as $child_family) {
127
+			/** @var Family $child_family */
128
+			$child_family->husband();
129
+			if (($husb = $child_family->husband()) !== null) {
130
+				if ($husb->isPendingAddition() && $husb->privatizeGedcom(Auth::PRIV_HIDE) === '') {
131
+					return $indi;
132
+				}
133
+				return $this->getLineageRootIndividual($husb);
134
+			} elseif (($wife = $child_family->wife()) !== null) {
135
+				if (!($wife->isPendingAddition() && $wife->privatizeGedcom(Auth::PRIV_HIDE) === '')) {
136
+					$indi_surname = $indi->getAllNames()[$indi->getPrimaryName()]['surname'];
137
+					$wife_surname = $wife->getAllNames()[$wife->getPrimaryName()]['surname'];
138
+					if (
139
+						$indi->canShowName()
140
+						&& $wife->canShowName()
141
+						&& I18N::comparator()($indi_surname, $wife_surname) === 0
142
+					) {
143
+							return $this->getLineageRootIndividual($wife);
144
+					}
145
+				}
146
+				return $indi;
147
+			}
148
+		}
149
+		return $indi;
150
+	}
151
+
152
+	/**
153
+	 * Computes descendent Lineage from a node.
154
+	 * Uses recursion to build the lineage tree
155
+	 *
156
+	 * @param LineageNode $node
157
+	 * @return LineageNode Computed lineage
158
+	 */
159
+	private function buildLineage(LineageNode $node): LineageNode
160
+	{
161
+		$indi_surname = '';
162
+
163
+		$indi_node = $node->individual();
164
+		if ($indi_node !== null) {
165
+			if ($node->families()->count() === 0) {
166
+				foreach ($indi_node->spouseFamilies() as $spouse_family) {
167
+					$node->addFamily($spouse_family);
168
+				}
169
+			}
170
+
171
+			$indi_surname = $indi_node->getAllNames()[$indi_node->getPrimaryName()]['surname'] ?? '';
172
+			$node->rootNode()->addPlace($indi_node->getBirthPlace());
173
+
174
+			//Tag the individual as used
175
+			$this->used_indis->put($indi_node->xref(), true);
176
+		}
177
+
178
+		foreach ($node->families() as $family_node) {
179
+			/** @var Family $spouse_family */
180
+			$spouse_family = $family_node->family;
181
+			$spouse_surname = '';
182
+			$spouse = null;
183
+			if (
184
+				$indi_node !== null &&
185
+				($spouse = $spouse_family->spouse($indi_node)) !== null && $spouse->canShowName()
186
+			) {
187
+				$spouse_surname = $spouse->getAllNames()[$spouse->getPrimaryName()]['surname'] ?? '';
188
+			}
189
+
190
+			$nb_children = $nb_natural = 0;
191
+
192
+			foreach ($spouse_family->children() as $child) {
193
+				if (!($child->isPendingAddition() && $child->privatizeGedcom(Auth::PRIV_HIDE) === '')) {
194
+					$child_surname = $child->getAllNames()[$child->getPrimaryName()]['surname'] ?? '';
195
+
196
+					$nb_children++;
197
+					if ($indi_node !== null && $indi_node->sex() === 'F') { //If the root individual is the mother
198
+						//Print only lineages of children with the same surname as their mother
199
+						//(supposing they are natural children)
200
+						/** @psalm-suppress RedundantCondition */
201
+						if (
202
+							$spouse === null ||
203
+							($spouse_surname !== '' && I18N::comparator()($child_surname, $spouse_surname) != 0)
204
+						) {
205
+							if (I18N::comparator()($child_surname, $indi_surname) === 0) {
206
+								$nb_natural++;
207
+								$node_child = new LineageNode($child, $node->rootNode());
208
+								$node_child = $this->buildLineage($node_child);
209
+								$node->addChild($spouse_family, $node_child);
210
+							}
211
+						}
212
+					} else { //If the root individual is the father
213
+						$nb_natural++;
214
+						//Print if the children does not bear the same name as his mother
215
+						//(and different from his father)
216
+						if (
217
+							mb_strlen($child_surname) === 0 ||
218
+							mb_strlen($indi_surname) === 0 || mb_strlen($spouse_surname) === 0 ||
219
+							I18N::comparator()($child_surname, $indi_surname) === 0 ||
220
+							I18N::comparator()($child_surname, $spouse_surname) != 0
221
+						) {
222
+							$node_child = new LineageNode($child, $node->rootNode());
223
+							$node_child = $this->buildLineage($node_child);
224
+						} else {
225
+							$node_child = new LineageNode($child, $node->rootNode(), $child_surname);
226
+						}
227
+						$node->addChild($spouse_family, $node_child);
228
+					}
229
+				}
230
+			}
231
+
232
+			//Do not print other children
233
+			if (($nb_children - $nb_natural) > 0) {
234
+				$node->addChild($spouse_family, null);
235
+			}
236
+		}
237
+
238
+		return $node;
239
+	}
240 240
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@
 block discarded – undo
101 101
             }
102 102
         }
103 103
 
104
-        return $root_lineages->sort(function (LineageRootNode $a, LineageRootNode $b) {
104
+        return $root_lineages->sort(function(LineageRootNode $a, LineageRootNode $b) {
105 105
             if ($a->numberChildNodes() === $b->numberChildNodes()) {
106 106
                 return 0;
107 107
             }
Please login to merge, or discard this patch.
app/Module/Certificates/Http/RequestHandlers/CertificatePage.php 2 patches
Indentation   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -35,79 +35,79 @@
 block discarded – undo
35 35
  */
36 36
 class CertificatePage implements RequestHandlerInterface
37 37
 {
38
-    use ViewResponseTrait;
39
-
40
-    /**
41
-     * @var CertificatesModule|null $module
42
-     */
43
-    private $module;
44
-
45
-    /**
46
-     * @var CertificateFilesystemService $certif_filesystem
47
-     */
48
-    private $certif_filesystem;
49
-
50
-    /**
51
-     * @var CertificateDataService $certif_data_service
52
-     */
53
-    private $certif_data_service;
54
-
55
-    /**
56
-     * @var UrlObfuscatorService $url_obfuscator_service
57
-     */
58
-    private $url_obfuscator_service;
59
-
60
-
61
-    /**
62
-     * Constructor for CertificatePage Request Handler
63
-     *
64
-     * @param ModuleService $module_service
65
-     * @param CertificateFilesystemService $certif_filesystem
66
-     * @param CertificateDataService $certif_data_service
67
-     * @param UrlObfuscatorService $url_obfuscator_service
68
-     */
69
-    public function __construct(
70
-        ModuleService $module_service,
71
-        CertificateFilesystemService $certif_filesystem,
72
-        CertificateDataService $certif_data_service,
73
-        UrlObfuscatorService $url_obfuscator_service
74
-    ) {
75
-        $this->module = $module_service->findByInterface(CertificatesModule::class)->first();
76
-        $this->certif_filesystem = $certif_filesystem;
77
-        $this->certif_data_service = $certif_data_service;
78
-        $this->url_obfuscator_service = $url_obfuscator_service;
79
-    }
80
-
81
-    /**
82
-     * {@inheritDoc}
83
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
84
-     */
85
-    public function handle(ServerRequestInterface $request): ResponseInterface
86
-    {
87
-        if ($this->module === null) {
88
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
89
-        }
90
-
91
-        $tree = Validator::attributes($request)->tree();
92
-
93
-        $certif_path = Validator::attributes($request)->string('cid', '');
94
-        if ($certif_path !== '' && $this->url_obfuscator_service->tryDeobfuscate($certif_path)) {
95
-            $certificate = $this->certif_filesystem->certificate($tree, $certif_path);
96
-        }
97
-
98
-        if (!isset($certificate)) {
99
-            FlashMessages::addMessage('The requested certificate is not valid.');
100
-            return Registry::responseFactory()->redirect(TreePage::class, ['tree' => $tree->name()]);
101
-        }
102
-
103
-        return $this->viewResponse($this->module->name() . '::certificate-page', [
104
-            'title'                     =>  I18N::translate('Certificate - %s', $certificate->name()),
105
-            'tree'                      =>  $tree,
106
-            'module_name'               =>  $this->module->name(),
107
-            'certificate'               =>  $certificate,
108
-            'url_obfuscator_service'    =>  $this->url_obfuscator_service,
109
-            'linked_individuals'        =>  $this->certif_data_service->linkedIndividuals($certificate),
110
-            'linked_families'           =>  $this->certif_data_service->linkedFamilies($certificate)
111
-        ]);
112
-    }
38
+	use ViewResponseTrait;
39
+
40
+	/**
41
+	 * @var CertificatesModule|null $module
42
+	 */
43
+	private $module;
44
+
45
+	/**
46
+	 * @var CertificateFilesystemService $certif_filesystem
47
+	 */
48
+	private $certif_filesystem;
49
+
50
+	/**
51
+	 * @var CertificateDataService $certif_data_service
52
+	 */
53
+	private $certif_data_service;
54
+
55
+	/**
56
+	 * @var UrlObfuscatorService $url_obfuscator_service
57
+	 */
58
+	private $url_obfuscator_service;
59
+
60
+
61
+	/**
62
+	 * Constructor for CertificatePage Request Handler
63
+	 *
64
+	 * @param ModuleService $module_service
65
+	 * @param CertificateFilesystemService $certif_filesystem
66
+	 * @param CertificateDataService $certif_data_service
67
+	 * @param UrlObfuscatorService $url_obfuscator_service
68
+	 */
69
+	public function __construct(
70
+		ModuleService $module_service,
71
+		CertificateFilesystemService $certif_filesystem,
72
+		CertificateDataService $certif_data_service,
73
+		UrlObfuscatorService $url_obfuscator_service
74
+	) {
75
+		$this->module = $module_service->findByInterface(CertificatesModule::class)->first();
76
+		$this->certif_filesystem = $certif_filesystem;
77
+		$this->certif_data_service = $certif_data_service;
78
+		$this->url_obfuscator_service = $url_obfuscator_service;
79
+	}
80
+
81
+	/**
82
+	 * {@inheritDoc}
83
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
84
+	 */
85
+	public function handle(ServerRequestInterface $request): ResponseInterface
86
+	{
87
+		if ($this->module === null) {
88
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
89
+		}
90
+
91
+		$tree = Validator::attributes($request)->tree();
92
+
93
+		$certif_path = Validator::attributes($request)->string('cid', '');
94
+		if ($certif_path !== '' && $this->url_obfuscator_service->tryDeobfuscate($certif_path)) {
95
+			$certificate = $this->certif_filesystem->certificate($tree, $certif_path);
96
+		}
97
+
98
+		if (!isset($certificate)) {
99
+			FlashMessages::addMessage('The requested certificate is not valid.');
100
+			return Registry::responseFactory()->redirect(TreePage::class, ['tree' => $tree->name()]);
101
+		}
102
+
103
+		return $this->viewResponse($this->module->name() . '::certificate-page', [
104
+			'title'                     =>  I18N::translate('Certificate - %s', $certificate->name()),
105
+			'tree'                      =>  $tree,
106
+			'module_name'               =>  $this->module->name(),
107
+			'certificate'               =>  $certificate,
108
+			'url_obfuscator_service'    =>  $this->url_obfuscator_service,
109
+			'linked_individuals'        =>  $this->certif_data_service->linkedIndividuals($certificate),
110
+			'linked_families'           =>  $this->certif_data_service->linkedFamilies($certificate)
111
+		]);
112
+	}
113 113
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@
 block discarded – undo
100 100
             return Registry::responseFactory()->redirect(TreePage::class, ['tree' => $tree->name()]);
101 101
         }
102 102
 
103
-        return $this->viewResponse($this->module->name() . '::certificate-page', [
103
+        return $this->viewResponse($this->module->name().'::certificate-page', [
104 104
             'title'                     =>  I18N::translate('Certificate - %s', $certificate->name()),
105 105
             'tree'                      =>  $tree,
106 106
             'module_name'               =>  $this->module->name(),
Please login to merge, or discard this patch.
app/Module/Hooks/Http/RequestHandlers/ModulesHooksAction.php 1 patch
Indentation   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -31,58 +31,58 @@
 block discarded – undo
31 31
  */
32 32
 class ModulesHooksAction extends AbstractModuleComponentAction
33 33
 {
34
-    protected HookService $hook_service;
34
+	protected HookService $hook_service;
35 35
 
36
-    /**
37
-     * Constructor for ModulesHooksAction Request Handler
38
-     *
39
-     * @param ModuleService $module_service
40
-     * @param TreeService $tree_service
41
-     * @param HookService $hook_service
42
-     */
43
-    public function __construct(ModuleService $module_service, TreeService $tree_service, HookService $hook_service)
44
-    {
45
-        parent::__construct($module_service, $tree_service);
46
-        $this->hook_service = $hook_service;
47
-    }
36
+	/**
37
+	 * Constructor for ModulesHooksAction Request Handler
38
+	 *
39
+	 * @param ModuleService $module_service
40
+	 * @param TreeService $tree_service
41
+	 * @param HookService $hook_service
42
+	 */
43
+	public function __construct(ModuleService $module_service, TreeService $tree_service, HookService $hook_service)
44
+	{
45
+		parent::__construct($module_service, $tree_service);
46
+		$this->hook_service = $hook_service;
47
+	}
48 48
 
49
-    /**
50
-     * {@inheritDoc}
51
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
52
-     */
53
-    public function handle(ServerRequestInterface $request): ResponseInterface
54
-    {
55
-        $hook_name = Validator::attributes($request)->string('hook_name', '');
56
-        $hook_collector = $this->hook_service->find($hook_name, true);
57
-        if ($hook_collector === null) {
58
-            FlashMessages::addMessage(I18N::translate('The hook with name “%s” does not exist.', $hook_name), 'danger');
59
-            return Registry::responseFactory()->redirect(AdminConfigPage::class);
60
-        }
49
+	/**
50
+	 * {@inheritDoc}
51
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
52
+	 */
53
+	public function handle(ServerRequestInterface $request): ResponseInterface
54
+	{
55
+		$hook_name = Validator::attributes($request)->string('hook_name', '');
56
+		$hook_collector = $this->hook_service->find($hook_name, true);
57
+		if ($hook_collector === null) {
58
+			FlashMessages::addMessage(I18N::translate('The hook with name “%s” does not exist.', $hook_name), 'danger');
59
+			return Registry::responseFactory()->redirect(AdminConfigPage::class);
60
+		}
61 61
 
62
-        foreach ($hook_collector->hooks() as $hook) {
63
-            $this->updateStatus(get_class($hook->module()), $request);
64
-        }
62
+		foreach ($hook_collector->hooks() as $hook) {
63
+			$this->updateStatus(get_class($hook->module()), $request);
64
+		}
65 65
 
66
-        $this->updateHookOrder($hook_collector, $request);
66
+		$this->updateHookOrder($hook_collector, $request);
67 67
 
68
-        FlashMessages::addMessage(I18N::translate('The hook preferences have been updated.'), 'success');
68
+		FlashMessages::addMessage(I18N::translate('The hook preferences have been updated.'), 'success');
69 69
 
70
-        return Registry::responseFactory()->redirect(ModulesHooksPage::class, ['hook_name' => $hook_name]);
71
-    }
70
+		return Registry::responseFactory()->redirect(ModulesHooksPage::class, ['hook_name' => $hook_name]);
71
+	}
72 72
 
73
-    /**
74
-     * Update the order of modules for a hook interface.
75
-     *
76
-     * @param HookCollectorInterface $hook_collector
77
-     * @param ServerRequestInterface $request
78
-     */
79
-    protected function updateHookOrder(HookCollectorInterface $hook_collector, ServerRequestInterface $request): void
80
-    {
81
-        $order = Validator::parsedBody($request)->array('order');
82
-        $order = array_flip($order);
73
+	/**
74
+	 * Update the order of modules for a hook interface.
75
+	 *
76
+	 * @param HookCollectorInterface $hook_collector
77
+	 * @param ServerRequestInterface $request
78
+	 */
79
+	protected function updateHookOrder(HookCollectorInterface $hook_collector, ServerRequestInterface $request): void
80
+	{
81
+		$order = Validator::parsedBody($request)->array('order');
82
+		$order = array_flip($order);
83 83
 
84
-        foreach ($hook_collector->hooks() as $hook) {
85
-            $this->hook_service->updateOrder($hook_collector, $hook->module(), $order[$hook->module()->name()] ?? 0);
86
-        }
87
-    }
84
+		foreach ($hook_collector->hooks() as $hook) {
85
+			$this->hook_service->updateOrder($hook_collector, $hook->module(), $order[$hook->module()->name()] ?? 0);
86
+		}
87
+	}
88 88
 }
Please login to merge, or discard this patch.
app/Module/Sosa/Http/RequestHandlers/SosaComputeAction.php 2 patches
Indentation   +43 added lines, -43 removed lines patch added patch discarded remove patch
@@ -31,54 +31,54 @@
 block discarded – undo
31 31
  */
32 32
 class SosaComputeAction implements RequestHandlerInterface
33 33
 {
34
-    private UserService $user_service;
34
+	private UserService $user_service;
35 35
 
36
-    /**
37
-     * Constructor for SosaConfigAction Request Handler
38
-     *
39
-     * @param UserService $user_service
40
-     */
41
-    public function __construct(UserService $user_service)
42
-    {
43
-        $this->user_service = $user_service;
44
-    }
36
+	/**
37
+	 * Constructor for SosaConfigAction Request Handler
38
+	 *
39
+	 * @param UserService $user_service
40
+	 */
41
+	public function __construct(UserService $user_service)
42
+	{
43
+		$this->user_service = $user_service;
44
+	}
45 45
 
46
-    /**
47
-     * {@inheritDoc}
48
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
49
-     */
50
-    public function handle(ServerRequestInterface $request): ResponseInterface
51
-    {
52
-        $tree = Validator::attributes($request)->tree();
46
+	/**
47
+	 * {@inheritDoc}
48
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
49
+	 */
50
+	public function handle(ServerRequestInterface $request): ResponseInterface
51
+	{
52
+		$tree = Validator::attributes($request)->tree();
53 53
 
54
-        $user_id = Validator::parsedBody($request)->integer('user_id', Auth::id() ?? 0);
55
-        $partial_from = Validator::parsedBody($request)->isXref()->string('partial_from', '');
54
+		$user_id = Validator::parsedBody($request)->integer('user_id', Auth::id() ?? 0);
55
+		$partial_from = Validator::parsedBody($request)->isXref()->string('partial_from', '');
56 56
 
57
-        if (($user_id === -1 && Auth::isManager($tree)) || Auth::id() === $user_id) {
58
-            $user = $user_id === -1 ? new DefaultUser() : $this->user_service->find($user_id);
57
+		if (($user_id === -1 && Auth::isManager($tree)) || Auth::id() === $user_id) {
58
+			$user = $user_id === -1 ? new DefaultUser() : $this->user_service->find($user_id);
59 59
 
60
-            /** @var SosaCalculatorService $sosa_calc_service */
61
-            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
60
+			/** @var SosaCalculatorService $sosa_calc_service */
61
+			$sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
62 62
 
63
-            if (
64
-                $partial_from !== '' &&
65
-                ($sosa_from = Registry::individualFactory()->make($partial_from, $tree)) !== null
66
-            ) {
67
-                $res = $sosa_calc_service->computeFromIndividual($sosa_from);
68
-            } else {
69
-                $res = $sosa_calc_service->computeAll();
70
-            }
63
+			if (
64
+				$partial_from !== '' &&
65
+				($sosa_from = Registry::individualFactory()->make($partial_from, $tree)) !== null
66
+			) {
67
+				$res = $sosa_calc_service->computeFromIndividual($sosa_from);
68
+			} else {
69
+				$res = $sosa_calc_service->computeAll();
70
+			}
71 71
 
72
-            return $res ?
73
-                Registry::responseFactory()->response() :
74
-                Registry::responseFactory()->response(
75
-                    I18N::translate('An error occurred while computing Sosa ancestors.'),
76
-                    StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR
77
-                );
78
-        }
79
-        return Registry::responseFactory()->response(
80
-            I18N::translate('You do not have permission to modify the user.'),
81
-            StatusCodeInterface::STATUS_FORBIDDEN
82
-        );
83
-    }
72
+			return $res ?
73
+				Registry::responseFactory()->response() :
74
+				Registry::responseFactory()->response(
75
+					I18N::translate('An error occurred while computing Sosa ancestors.'),
76
+					StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR
77
+				);
78
+		}
79
+		return Registry::responseFactory()->response(
80
+			I18N::translate('You do not have permission to modify the user.'),
81
+			StatusCodeInterface::STATUS_FORBIDDEN
82
+		);
83
+	}
84 84
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -3 removed lines patch added patch discarded remove patch
@@ -58,7 +58,7 @@  discard block
 block discarded – undo
58 58
             $user = $user_id === -1 ? new DefaultUser() : $this->user_service->find($user_id);
59 59
 
60 60
             /** @var SosaCalculatorService $sosa_calc_service */
61
-            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
61
+            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, ['tree' => $tree, 'user' => $user]);
62 62
 
63 63
             if (
64 64
                 $partial_from !== '' &&
@@ -70,8 +70,7 @@  discard block
 block discarded – undo
70 70
             }
71 71
 
72 72
             return $res ?
73
-                Registry::responseFactory()->response() :
74
-                Registry::responseFactory()->response(
73
+                Registry::responseFactory()->response() : Registry::responseFactory()->response(
75 74
                     I18N::translate('An error occurred while computing Sosa ancestors.'),
76 75
                     StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR
77 76
                 );
Please login to merge, or discard this patch.
app/Module/Sosa/Http/RequestHandlers/SosaConfigAction.php 2 patches
Indentation   +42 added lines, -42 removed lines patch added patch discarded remove patch
@@ -31,51 +31,51 @@
 block discarded – undo
31 31
  */
32 32
 class SosaConfigAction implements RequestHandlerInterface
33 33
 {
34
-    private UserService $user_service;
35
-    private SosaRecordsService $sosa_record_service;
34
+	private UserService $user_service;
35
+	private SosaRecordsService $sosa_record_service;
36 36
 
37
-    /**
38
-     * Constructor for SosaConfigAction Request Handler
39
-     *
40
-     * @param UserService $user_service
41
-     * @param SosaRecordsService $sosa_records_service
42
-     */
43
-    public function __construct(UserService $user_service, SosaRecordsService $sosa_records_service)
44
-    {
45
-        $this->user_service = $user_service;
46
-        $this->sosa_record_service = $sosa_records_service;
47
-    }
37
+	/**
38
+	 * Constructor for SosaConfigAction Request Handler
39
+	 *
40
+	 * @param UserService $user_service
41
+	 * @param SosaRecordsService $sosa_records_service
42
+	 */
43
+	public function __construct(UserService $user_service, SosaRecordsService $sosa_records_service)
44
+	{
45
+		$this->user_service = $user_service;
46
+		$this->sosa_record_service = $sosa_records_service;
47
+	}
48 48
 
49
-    /**
50
-     * {@inheritDoc}
51
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
52
-     */
53
-    public function handle(ServerRequestInterface $request): ResponseInterface
54
-    {
55
-        $tree = Validator::attributes($request)->tree();
49
+	/**
50
+	 * {@inheritDoc}
51
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
52
+	 */
53
+	public function handle(ServerRequestInterface $request): ResponseInterface
54
+	{
55
+		$tree = Validator::attributes($request)->tree();
56 56
 
57
-        $user_id = Validator::parsedBody($request)->integer('sosa-userid', -1);
58
-        $root_id = Validator::parsedBody($request)->isXref()->string('sosa-rootid', '');
59
-        $max_gen = Validator::parsedBody($request)->integer(
60
-            'sosa-maxgen',
61
-            $this->sosa_record_service->maxSystemGenerations()
62
-        );
57
+		$user_id = Validator::parsedBody($request)->integer('sosa-userid', -1);
58
+		$root_id = Validator::parsedBody($request)->isXref()->string('sosa-rootid', '');
59
+		$max_gen = Validator::parsedBody($request)->integer(
60
+			'sosa-maxgen',
61
+			$this->sosa_record_service->maxSystemGenerations()
62
+		);
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', (string) $max_gen);
69
-                FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
70
-                return Registry::responseFactory()->redirect(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', (string) $max_gen);
69
+				FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
70
+				return Registry::responseFactory()->redirect(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 Registry::responseFactory()->redirect(SosaConfig::class, ['tree' => $tree->name()]);
80
-    }
78
+		FlashMessages::addMessage(I18N::translate('The root individual could not be updated.'), 'danger');
79
+		return Registry::responseFactory()->redirect(SosaConfig::class, ['tree' => $tree->name()]);
80
+	}
81 81
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@
 block discarded – undo
65 65
             $user = $user_id === -1 ? new DefaultUser() : $this->user_service->find($user_id);
66 66
             if ($user !== null && ($root_indi = Registry::individualFactory()->make($root_id, $tree)) !== null) {
67 67
                 $tree->setUserPreference($user, 'MAJ_SOSA_ROOT_ID', $root_indi->xref());
68
-                $tree->setUserPreference($user, 'MAJ_SOSA_MAX_GEN', (string) $max_gen);
68
+                $tree->setUserPreference($user, 'MAJ_SOSA_MAX_GEN', (string)$max_gen);
69 69
                 FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
70 70
                 return Registry::responseFactory()->redirect(SosaConfig::class, [
71 71
                     'tree' => $tree->name(),
Please login to merge, or discard this patch.
app/Common/GeoDispersion/Config/GenericPlaceMapperConfig.php 2 patches
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -100,7 +100,7 @@
 block discarded – undo
100 100
     public function jsonDeserialize($config): self
101 101
     {
102 102
         if (is_string($config)) {
103
-            return $this->jsonDeserialize((array) json_decode($config));
103
+            return $this->jsonDeserialize((array)json_decode($config));
104 104
         }
105 105
         if (is_array($config)) {
106 106
             return $this->setConfig($config);
Please login to merge, or discard this patch.
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -25,106 +25,106 @@
 block discarded – undo
25 25
  */
26 26
 class GenericPlaceMapperConfig implements PlaceMapperConfigInterface
27 27
 {
28
-    /** @var array<string, mixed> $config */
29
-    private array $config = [];
28
+	/** @var array<string, mixed> $config */
29
+	private array $config = [];
30 30
 
31
-    /**
32
-     * Get the generic mapper's config
33
-     *
34
-     * @return array<string, mixed>
35
-     */
36
-    public function config(): array
37
-    {
38
-        return $this->config;
39
-    }
31
+	/**
32
+	 * Get the generic mapper's config
33
+	 *
34
+	 * @return array<string, mixed>
35
+	 */
36
+	public function config(): array
37
+	{
38
+		return $this->config;
39
+	}
40 40
 
41
-    /**
42
-     * Set the generic mapper's config
43
-     *
44
-     * @param array<string, mixed> $config
45
-     * @return $this
46
-     */
47
-    public function setConfig(array $config): self
48
-    {
49
-        $this->config = $config;
50
-        return $this;
51
-    }
41
+	/**
42
+	 * Set the generic mapper's config
43
+	 *
44
+	 * @param array<string, mixed> $config
45
+	 * @return $this
46
+	 */
47
+	public function setConfig(array $config): self
48
+	{
49
+		$this->config = $config;
50
+		return $this;
51
+	}
52 52
 
53
-    /**
54
-     * {@inheritDoc}
55
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::get()
56
-     */
57
-    public function get(string $key, $default = null)
58
-    {
59
-        return $this->config[$key] ?? $default;
60
-    }
53
+	/**
54
+	 * {@inheritDoc}
55
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::get()
56
+	 */
57
+	public function get(string $key, $default = null)
58
+	{
59
+		return $this->config[$key] ?? $default;
60
+	}
61 61
 
62
-    /**
63
-     * {@inheritDoc}
64
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::has()
65
-     */
66
-    public function has(string $key): bool
67
-    {
68
-        return key_exists($key, $this->config);
69
-    }
62
+	/**
63
+	 * {@inheritDoc}
64
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::has()
65
+	 */
66
+	public function has(string $key): bool
67
+	{
68
+		return key_exists($key, $this->config);
69
+	}
70 70
 
71
-    /**
72
-     * {@inheritDoc}
73
-     * @see \JsonSerializable::jsonSerialize()
74
-     */
75
-    #[\ReturnTypeWillChange]
76
-    public function jsonSerialize()
77
-    {
78
-        return [
79
-            'class'     =>  get_class($this),
80
-            'config'    =>  $this->jsonSerializeConfig()
81
-        ];
82
-    }
71
+	/**
72
+	 * {@inheritDoc}
73
+	 * @see \JsonSerializable::jsonSerialize()
74
+	 */
75
+	#[\ReturnTypeWillChange]
76
+	public function jsonSerialize()
77
+	{
78
+		return [
79
+			'class'     =>  get_class($this),
80
+			'config'    =>  $this->jsonSerializeConfig()
81
+		];
82
+	}
83 83
 
84
-    /**
85
-     * Returns a representation of the mapper config compatible with Json serialisation
86
-     *
87
-     * @return mixed
88
-     */
89
-    public function jsonSerializeConfig()
90
-    {
91
-        return $this->config;
92
-    }
84
+	/**
85
+	 * Returns a representation of the mapper config compatible with Json serialisation
86
+	 *
87
+	 * @return mixed
88
+	 */
89
+	public function jsonSerializeConfig()
90
+	{
91
+		return $this->config;
92
+	}
93 93
 
94
-    /**
95
-     * {@inheritDoc}
96
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::jsonDeserialize()
97
-     *
98
-     * @param mixed $config
99
-     * @return $this
100
-     */
101
-    public function jsonDeserialize($config): self
102
-    {
103
-        if (is_string($config)) {
104
-            return $this->jsonDeserialize((array) json_decode($config));
105
-        }
106
-        if (is_array($config)) {
107
-            return $this->setConfig($config);
108
-        }
109
-        return $this;
110
-    }
94
+	/**
95
+	 * {@inheritDoc}
96
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::jsonDeserialize()
97
+	 *
98
+	 * @param mixed $config
99
+	 * @return $this
100
+	 */
101
+	public function jsonDeserialize($config): self
102
+	{
103
+		if (is_string($config)) {
104
+			return $this->jsonDeserialize((array) json_decode($config));
105
+		}
106
+		if (is_array($config)) {
107
+			return $this->setConfig($config);
108
+		}
109
+		return $this;
110
+	}
111 111
 
112
-    /**
113
-     * {@inheritDoc}
114
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::configContent()
115
-     */
116
-    public function configContent(ModuleInterface $module, Tree $tree): string
117
-    {
118
-        return '';
119
-    }
112
+	/**
113
+	 * {@inheritDoc}
114
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::configContent()
115
+	 */
116
+	public function configContent(ModuleInterface $module, Tree $tree): string
117
+	{
118
+		return '';
119
+	}
120 120
 
121
-    /**
122
-     * {@inheritDoc}
123
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::withConfigUpdate()
124
-     * @return $this
125
-     */
126
-    public function withConfigUpdate(ServerRequestInterface $request): self
127
-    {
128
-        return $this;
129
-    }
121
+	/**
122
+	 * {@inheritDoc}
123
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\PlaceMapperConfigInterface::withConfigUpdate()
124
+	 * @return $this
125
+	 */
126
+	public function withConfigUpdate(ServerRequestInterface $request): self
127
+	{
128
+		return $this;
129
+	}
130 130
 }
Please login to merge, or discard this patch.
app/Module/Sosa/Services/SosaStatisticsService.php 2 patches
Indentation   +528 added lines, -528 removed lines patch added patch discarded remove patch
@@ -29,539 +29,539 @@
 block discarded – undo
29 29
  */
30 30
 class SosaStatisticsService
31 31
 {
32
-    private UserInterface $user;
33
-    private Tree $tree;
34
-
35
-    /**
36
-     * Constructor for Sosa Statistics Service
37
-     *
38
-     * @param Tree $tree
39
-     * @param UserInterface $user
40
-     */
41
-    public function __construct(Tree $tree, UserInterface $user)
42
-    {
43
-        $this->tree = $tree;
44
-        $this->user = $user;
45
-    }
46
-
47
-    /**
48
-     * Check if PDO support the queries used in Sosa statistics.
49
-     *
50
-     * SQLite does not support RIGHT and FULL JOIN, and POWER/SQRT require a specific compilation flag.
51
-     *
52
-     * @return bool
53
-     */
54
-    public function isPdoSupported(): bool
55
-    {
56
-        return DB::connection()->getDriverName() !== 'sqlite';
57
-    }
58
-
59
-    /**
60
-     * Return the root individual for the reference tree and user.
61
-     *
62
-     * @return Individual|NULL
63
-     */
64
-    public function rootIndividual(): ?Individual
65
-    {
66
-        $root_indi_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
67
-        return Registry::individualFactory()->make($root_indi_id, $this->tree);
68
-    }
69
-
70
-    /**
71
-     * Get the highest generation for the reference tree and user.
72
-     *
73
-     * @return int
74
-     */
75
-    public function maxGeneration(): int
76
-    {
77
-        return (int) DB::table('maj_sosa')
78
-            ->where('majs_gedcom_id', '=', $this->tree->id())
79
-            ->where('majs_user_id', '=', $this->user->id())
80
-            ->max('majs_gen');
81
-    }
82
-
83
-    /**
84
-     * Get the total count of individuals in the tree.
85
-     *
86
-     * @return int
87
-     */
88
-    public function totalIndividuals(): int
89
-    {
90
-        return DB::table('individuals')
91
-            ->where('i_file', '=', $this->tree->id())
92
-            ->count();
93
-    }
94
-
95
-    /**
96
-     * Get the total count of Sosa ancestors for all generations
97
-     *
98
-     * @return int
99
-     */
100
-    public function totalAncestors(): int
101
-    {
102
-        return DB::table('maj_sosa')
103
-            ->where('majs_gedcom_id', '=', $this->tree->id())
104
-            ->where('majs_user_id', '=', $this->user->id())
105
-            ->count();
106
-    }
107
-
108
-    /**
109
-     * Get the total count of Sosa ancestors for a generation
110
-     *
111
-     * @return int
112
-     */
113
-    public function totalAncestorsAtGeneration(int $gen): int
114
-    {
115
-        return DB::table('maj_sosa')
116
-            ->where('majs_gedcom_id', '=', $this->tree->id())
117
-            ->where('majs_user_id', '=', $this->user->id())
118
-            ->where('majs_gen', '=', $gen)
119
-            ->count();
120
-    }
121
-
122
-    /**
123
-     * Get the total count of distinct Sosa ancestors for all generations
124
-     *
125
-     * @return int
126
-     */
127
-    public function totalDistinctAncestors(): int
128
-    {
129
-        return DB::table('maj_sosa')
130
-            ->where('majs_gedcom_id', '=', $this->tree->id())
131
-            ->where('majs_user_id', '=', $this->user->id())
132
-            ->distinct()
133
-            ->count('majs_i_id');
134
-    }
135
-
136
-    /**
137
-     * Get the mean generation time, as the slope of the linear regression of birth years vs generations
138
-     *
139
-     * @return float
140
-     */
141
-    public function meanGenerationTime(): float
142
-    {
143
-        $row = DB::table('maj_sosa')
144
-            ->where('majs_gedcom_id', '=', $this->tree->id())
145
-            ->where('majs_user_id', '=', $this->user->id())
146
-            ->whereNotNull('majs_birth_year')
147
-            ->selectRaw('COUNT(majs_sosa) AS n')
148
-            ->selectRaw('SUM(majs_gen * majs_birth_year) AS sum_xy')
149
-            ->selectRaw('SUM(majs_gen) AS sum_x')
150
-            ->selectRaw('SUM(majs_birth_year) AS sum_y')
151
-            ->selectRaw('SUM(majs_gen * majs_gen) AS sum_x2')
152
-            ->get()->first();
153
-
154
-        $denom = $row->n * $row->sum_x2 - pow($row->sum_x, 2);
155
-        return ((int) $row->n === 0 || $denom === 0) ? 0 :
156
-            -($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / $denom;
157
-    }
158
-
159
-    /**
160
-     * Get the statistic array detailed by generation.
161
-     * Statistics for each generation are:
162
-     *  - The number of Sosa in generation
163
-     *  - The number of Sosa up to generation
164
-     *  - The number of distinct Sosa up to generation
165
-     *  - The year of the first birth in generation
166
-     *  - The year of the first estimated birth in generation
167
-     *  - The year of the last birth in generation
168
-     *  - The year of the last estimated birth in generation
169
-     *  - The average year of birth in generation
170
-     *
171
-     * @return array<int, array<string, int|null>> Statistics array
172
-     */
173
-    public function statisticsByGenerations(): array
174
-    {
175
-        $stats_by_gen = $this->statisticsByGenerationBasicData();
176
-        $cumul_stats_by_gen = $this->statisticsByGenerationCumulativeData();
177
-
178
-        $statistics_by_gen = [];
179
-        foreach ($stats_by_gen as $gen => $stats_gen) {
180
-            $statistics_by_gen[(int) $stats_gen->gen] = array(
181
-                'sosaCount'             =>  (int) $stats_gen->total_sosa,
182
-                'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
183
-                'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
184
-                'firstBirth'            =>  $stats_gen->first_year,
185
-                'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
186
-                'lastBirth'             =>  $stats_gen->last_year,
187
-                'lastEstimatedBirth'    =>  $stats_gen->last_est_year
188
-            );
189
-        }
190
-
191
-        return $statistics_by_gen;
192
-    }
193
-
194
-    /**
195
-     * Returns the basic statistics data by generation.
196
-     *
197
-     * @return Collection<int, \stdClass>
198
-     */
199
-    private function statisticsByGenerationBasicData(): Collection
200
-    {
201
-        return DB::table('maj_sosa')
202
-            ->where('majs_gedcom_id', '=', $this->tree->id())
203
-            ->where('majs_user_id', '=', $this->user->id())
204
-            ->groupBy('majs_gen')
205
-            ->orderBy('majs_gen', 'asc')
206
-            ->select('majs_gen AS gen')
207
-            ->selectRaw('COUNT(majs_sosa) AS total_sosa')
208
-            ->selectRaw('MIN(majs_birth_year) AS first_year')
209
-            ->selectRaw('MIN(majs_birth_year_est) AS first_est_year')
210
-            ->selectRaw('MAX(majs_birth_year) AS last_year')
211
-            ->selectRaw('MAX(majs_birth_year_est) AS last_est_year')
212
-            ->get()->keyBy('gen');
213
-    }
214
-
215
-    /**
216
-     * Returns the cumulative statistics data by generation
217
-     *
218
-     * @return Collection<int, \stdClass>
219
-     */
220
-    private function statisticsByGenerationCumulativeData(): Collection
221
-    {
222
-        $list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
223
-            ->where('majs_gedcom_id', '=', $this->tree->id())
224
-            ->where('majs_user_id', '=', $this->user->id());
225
-
226
-        return DB::table('maj_sosa')
227
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
228
-                $join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
229
-                ->where('majs_gedcom_id', '=', $this->tree->id())
230
-                ->where('majs_user_id', '=', $this->user->id());
231
-            })
232
-            ->groupBy('list_gen.majs_gen')
233
-            ->select('list_gen.majs_gen AS gen')
234
-            ->selectRaw('COUNT(majs_i_id) AS total_cumul')
235
-            ->selectRaw('COUNT(DISTINCT majs_i_id) AS total_distinct_cumul')
236
-            ->selectRaw('1 - COUNT(DISTINCT majs_i_id) / COUNT(majs_i_id) AS pedi_collapse_simple')
237
-            ->get()->keyBy('gen');
238
-    }
239
-
240
-    /**
241
-     * Returns the pedigree collapse improved calculation by generation.
242
-     *
243
-     * Format:
244
-     *  - key : generation
245
-     *  - values:
246
-     *      - pedi_collapse_roots : pedigree collapse of ancestor roots for the generation
247
-     *      - pedi_collapse_xgen : pedigree cross-generation shrinkage for the generation
248
-     *
249
-     * @return array<int, array<string, float>>
250
-     */
251
-    public function pedigreeCollapseByGenerationData(): array
252
-    {
253
-        if (!$this->isPdoSupported()) {
254
-            return [];
255
-        }
256
-
257
-        $table_prefix = DB::connection()->getTablePrefix();
258
-
259
-        $list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
260
-            ->where('majs_gedcom_id', '=', $this->tree->id())
261
-            ->where('majs_user_id', '=', $this->user->id());
262
-
263
-        /* Compute the contributions of nodes of previous generations to the current generation */
264
-        $root_ancestors_contributions = DB::table('maj_sosa AS sosa')
265
-            ->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
266
-            ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
267
-            ->selectRaw(
268
-                '(CASE ' .
269
-                    ' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
270
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
271
-                    ' ELSE 0 ' .
272
-                ' END)' .
273
-                ' + (CASE ' .
274
-                    ' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
275
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
276
-                    ' ELSE 0 ' .
277
-                ' END) contrib'
278
-            )
279
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
280
-                $join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
281
-                    ->where('majs_gedcom_id', '=', $this->tree->id())
282
-                    ->where('majs_user_id', '=', $this->user->id());
283
-            })
284
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
285
-                // Link to sosa's father
286
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
287
-                    ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
288
-                    ->where('sosa_fat.majs_user_id', '=', $this->user->id());
289
-            })
290
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
291
-                // Link to sosa's mother
292
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
293
-                    ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
294
-                    ->where('sosa_mot.majs_user_id', '=', $this->user->id());
295
-            })
296
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
297
-            ->where('sosa.majs_user_id', '=', $this->user->id())
298
-            ->where(function (Builder $query): void {
299
-                $query->whereNull('sosa_fat.majs_i_id')
300
-                ->orWhereNull('sosa_mot.majs_i_id');
301
-            });
302
-
303
-        /* Identify nodes in the generations with ancestors who are also in the same generation.
32
+	private UserInterface $user;
33
+	private Tree $tree;
34
+
35
+	/**
36
+	 * Constructor for Sosa Statistics Service
37
+	 *
38
+	 * @param Tree $tree
39
+	 * @param UserInterface $user
40
+	 */
41
+	public function __construct(Tree $tree, UserInterface $user)
42
+	{
43
+		$this->tree = $tree;
44
+		$this->user = $user;
45
+	}
46
+
47
+	/**
48
+	 * Check if PDO support the queries used in Sosa statistics.
49
+	 *
50
+	 * SQLite does not support RIGHT and FULL JOIN, and POWER/SQRT require a specific compilation flag.
51
+	 *
52
+	 * @return bool
53
+	 */
54
+	public function isPdoSupported(): bool
55
+	{
56
+		return DB::connection()->getDriverName() !== 'sqlite';
57
+	}
58
+
59
+	/**
60
+	 * Return the root individual for the reference tree and user.
61
+	 *
62
+	 * @return Individual|NULL
63
+	 */
64
+	public function rootIndividual(): ?Individual
65
+	{
66
+		$root_indi_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
67
+		return Registry::individualFactory()->make($root_indi_id, $this->tree);
68
+	}
69
+
70
+	/**
71
+	 * Get the highest generation for the reference tree and user.
72
+	 *
73
+	 * @return int
74
+	 */
75
+	public function maxGeneration(): int
76
+	{
77
+		return (int) DB::table('maj_sosa')
78
+			->where('majs_gedcom_id', '=', $this->tree->id())
79
+			->where('majs_user_id', '=', $this->user->id())
80
+			->max('majs_gen');
81
+	}
82
+
83
+	/**
84
+	 * Get the total count of individuals in the tree.
85
+	 *
86
+	 * @return int
87
+	 */
88
+	public function totalIndividuals(): int
89
+	{
90
+		return DB::table('individuals')
91
+			->where('i_file', '=', $this->tree->id())
92
+			->count();
93
+	}
94
+
95
+	/**
96
+	 * Get the total count of Sosa ancestors for all generations
97
+	 *
98
+	 * @return int
99
+	 */
100
+	public function totalAncestors(): int
101
+	{
102
+		return DB::table('maj_sosa')
103
+			->where('majs_gedcom_id', '=', $this->tree->id())
104
+			->where('majs_user_id', '=', $this->user->id())
105
+			->count();
106
+	}
107
+
108
+	/**
109
+	 * Get the total count of Sosa ancestors for a generation
110
+	 *
111
+	 * @return int
112
+	 */
113
+	public function totalAncestorsAtGeneration(int $gen): int
114
+	{
115
+		return DB::table('maj_sosa')
116
+			->where('majs_gedcom_id', '=', $this->tree->id())
117
+			->where('majs_user_id', '=', $this->user->id())
118
+			->where('majs_gen', '=', $gen)
119
+			->count();
120
+	}
121
+
122
+	/**
123
+	 * Get the total count of distinct Sosa ancestors for all generations
124
+	 *
125
+	 * @return int
126
+	 */
127
+	public function totalDistinctAncestors(): int
128
+	{
129
+		return DB::table('maj_sosa')
130
+			->where('majs_gedcom_id', '=', $this->tree->id())
131
+			->where('majs_user_id', '=', $this->user->id())
132
+			->distinct()
133
+			->count('majs_i_id');
134
+	}
135
+
136
+	/**
137
+	 * Get the mean generation time, as the slope of the linear regression of birth years vs generations
138
+	 *
139
+	 * @return float
140
+	 */
141
+	public function meanGenerationTime(): float
142
+	{
143
+		$row = DB::table('maj_sosa')
144
+			->where('majs_gedcom_id', '=', $this->tree->id())
145
+			->where('majs_user_id', '=', $this->user->id())
146
+			->whereNotNull('majs_birth_year')
147
+			->selectRaw('COUNT(majs_sosa) AS n')
148
+			->selectRaw('SUM(majs_gen * majs_birth_year) AS sum_xy')
149
+			->selectRaw('SUM(majs_gen) AS sum_x')
150
+			->selectRaw('SUM(majs_birth_year) AS sum_y')
151
+			->selectRaw('SUM(majs_gen * majs_gen) AS sum_x2')
152
+			->get()->first();
153
+
154
+		$denom = $row->n * $row->sum_x2 - pow($row->sum_x, 2);
155
+		return ((int) $row->n === 0 || $denom === 0) ? 0 :
156
+			-($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / $denom;
157
+	}
158
+
159
+	/**
160
+	 * Get the statistic array detailed by generation.
161
+	 * Statistics for each generation are:
162
+	 *  - The number of Sosa in generation
163
+	 *  - The number of Sosa up to generation
164
+	 *  - The number of distinct Sosa up to generation
165
+	 *  - The year of the first birth in generation
166
+	 *  - The year of the first estimated birth in generation
167
+	 *  - The year of the last birth in generation
168
+	 *  - The year of the last estimated birth in generation
169
+	 *  - The average year of birth in generation
170
+	 *
171
+	 * @return array<int, array<string, int|null>> Statistics array
172
+	 */
173
+	public function statisticsByGenerations(): array
174
+	{
175
+		$stats_by_gen = $this->statisticsByGenerationBasicData();
176
+		$cumul_stats_by_gen = $this->statisticsByGenerationCumulativeData();
177
+
178
+		$statistics_by_gen = [];
179
+		foreach ($stats_by_gen as $gen => $stats_gen) {
180
+			$statistics_by_gen[(int) $stats_gen->gen] = array(
181
+				'sosaCount'             =>  (int) $stats_gen->total_sosa,
182
+				'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
183
+				'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
184
+				'firstBirth'            =>  $stats_gen->first_year,
185
+				'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
186
+				'lastBirth'             =>  $stats_gen->last_year,
187
+				'lastEstimatedBirth'    =>  $stats_gen->last_est_year
188
+			);
189
+		}
190
+
191
+		return $statistics_by_gen;
192
+	}
193
+
194
+	/**
195
+	 * Returns the basic statistics data by generation.
196
+	 *
197
+	 * @return Collection<int, \stdClass>
198
+	 */
199
+	private function statisticsByGenerationBasicData(): Collection
200
+	{
201
+		return DB::table('maj_sosa')
202
+			->where('majs_gedcom_id', '=', $this->tree->id())
203
+			->where('majs_user_id', '=', $this->user->id())
204
+			->groupBy('majs_gen')
205
+			->orderBy('majs_gen', 'asc')
206
+			->select('majs_gen AS gen')
207
+			->selectRaw('COUNT(majs_sosa) AS total_sosa')
208
+			->selectRaw('MIN(majs_birth_year) AS first_year')
209
+			->selectRaw('MIN(majs_birth_year_est) AS first_est_year')
210
+			->selectRaw('MAX(majs_birth_year) AS last_year')
211
+			->selectRaw('MAX(majs_birth_year_est) AS last_est_year')
212
+			->get()->keyBy('gen');
213
+	}
214
+
215
+	/**
216
+	 * Returns the cumulative statistics data by generation
217
+	 *
218
+	 * @return Collection<int, \stdClass>
219
+	 */
220
+	private function statisticsByGenerationCumulativeData(): Collection
221
+	{
222
+		$list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
223
+			->where('majs_gedcom_id', '=', $this->tree->id())
224
+			->where('majs_user_id', '=', $this->user->id());
225
+
226
+		return DB::table('maj_sosa')
227
+			->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
228
+				$join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
229
+				->where('majs_gedcom_id', '=', $this->tree->id())
230
+				->where('majs_user_id', '=', $this->user->id());
231
+			})
232
+			->groupBy('list_gen.majs_gen')
233
+			->select('list_gen.majs_gen AS gen')
234
+			->selectRaw('COUNT(majs_i_id) AS total_cumul')
235
+			->selectRaw('COUNT(DISTINCT majs_i_id) AS total_distinct_cumul')
236
+			->selectRaw('1 - COUNT(DISTINCT majs_i_id) / COUNT(majs_i_id) AS pedi_collapse_simple')
237
+			->get()->keyBy('gen');
238
+	}
239
+
240
+	/**
241
+	 * Returns the pedigree collapse improved calculation by generation.
242
+	 *
243
+	 * Format:
244
+	 *  - key : generation
245
+	 *  - values:
246
+	 *      - pedi_collapse_roots : pedigree collapse of ancestor roots for the generation
247
+	 *      - pedi_collapse_xgen : pedigree cross-generation shrinkage for the generation
248
+	 *
249
+	 * @return array<int, array<string, float>>
250
+	 */
251
+	public function pedigreeCollapseByGenerationData(): array
252
+	{
253
+		if (!$this->isPdoSupported()) {
254
+			return [];
255
+		}
256
+
257
+		$table_prefix = DB::connection()->getTablePrefix();
258
+
259
+		$list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
260
+			->where('majs_gedcom_id', '=', $this->tree->id())
261
+			->where('majs_user_id', '=', $this->user->id());
262
+
263
+		/* Compute the contributions of nodes of previous generations to the current generation */
264
+		$root_ancestors_contributions = DB::table('maj_sosa AS sosa')
265
+			->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
266
+			->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
267
+			->selectRaw(
268
+				'(CASE ' .
269
+					' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
270
+					' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
271
+					' ELSE 0 ' .
272
+				' END)' .
273
+				' + (CASE ' .
274
+					' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
275
+					' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
276
+					' ELSE 0 ' .
277
+				' END) contrib'
278
+			)
279
+			->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
280
+				$join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
281
+					->where('majs_gedcom_id', '=', $this->tree->id())
282
+					->where('majs_user_id', '=', $this->user->id());
283
+			})
284
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
285
+				// Link to sosa's father
286
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
287
+					->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
288
+					->where('sosa_fat.majs_user_id', '=', $this->user->id());
289
+			})
290
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
291
+				// Link to sosa's mother
292
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
293
+					->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
294
+					->where('sosa_mot.majs_user_id', '=', $this->user->id());
295
+			})
296
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
297
+			->where('sosa.majs_user_id', '=', $this->user->id())
298
+			->where(function (Builder $query): void {
299
+				$query->whereNull('sosa_fat.majs_i_id')
300
+				->orWhereNull('sosa_mot.majs_i_id');
301
+			});
302
+
303
+		/* Identify nodes in the generations with ancestors who are also in the same generation.
304 304
          * This is the vertical/generational collapse that will reduce the number or roots.
305 305
          */
306
-        $non_roots_ancestors = DB::table('maj_sosa AS sosa')
307
-            ->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
308
-            ->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
309
-                ' AS full_ancestors')
310
-            ->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
311
-                $join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
312
-                    ->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
313
-                        $table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
314
-                        $table_prefix . 'sosa.majs_sosa')
315
-                    ->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
316
-                    ->where('sosa_anc.majs_user_id', '=', $this->user->id());
317
-            })
318
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
319
-            ->where('sosa.majs_user_id', '=', $this->user->id())
320
-            ->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
321
-                $query->from('maj_sosa AS sosa_gen')
322
-                ->select('sosa_gen.majs_i_id')->distinct()
323
-                ->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
324
-                ->where('sosa_gen.majs_user_id', '=', $this->user->id())
325
-                ->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
326
-            })
327
-            ->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
328
-                'sosa.majs_sosa', 'sosa.majs_i_id']);
329
-
330
-        /* Compute the contribution of the nodes in the generation,
306
+		$non_roots_ancestors = DB::table('maj_sosa AS sosa')
307
+			->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
308
+			->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
309
+				' AS full_ancestors')
310
+			->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
311
+				$join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
312
+					->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
313
+						$table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
314
+						$table_prefix . 'sosa.majs_sosa')
315
+					->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
316
+					->where('sosa_anc.majs_user_id', '=', $this->user->id());
317
+			})
318
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
319
+			->where('sosa.majs_user_id', '=', $this->user->id())
320
+			->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
321
+				$query->from('maj_sosa AS sosa_gen')
322
+				->select('sosa_gen.majs_i_id')->distinct()
323
+				->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
324
+				->where('sosa_gen.majs_user_id', '=', $this->user->id())
325
+				->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
326
+			})
327
+			->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
328
+				'sosa.majs_sosa', 'sosa.majs_i_id']);
329
+
330
+		/* Compute the contribution of the nodes in the generation,
331 331
          * excluding the nodes with ancestors in the same generation.
332 332
          * Nodes with a parent missing are not excluded to cater for the missing one.
333 333
          */
334
-        $known_ancestors_contributions = DB::table('maj_sosa AS sosa')
335
-            ->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
336
-            ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
337
-            ->selectRaw('1 AS contrib')
338
-            ->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
339
-                $join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
340
-                    ->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
341
-                    ->where('nonroot.full_ancestors', '>', 0)
342
-                    ->where('nonroot.majs_gedcom_id', '=', $this->tree->id())
343
-                    ->where('nonroot.majs_user_id', '=', $this->user->id());
344
-            })
345
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
346
-            ->where('sosa.majs_user_id', '=', $this->user->id())
347
-            ->whereNull('nonroot.majs_sosa');
348
-
349
-        /* Aggregate both queries, and calculate the sum of contributions by generation roots.
334
+		$known_ancestors_contributions = DB::table('maj_sosa AS sosa')
335
+			->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
336
+			->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
337
+			->selectRaw('1 AS contrib')
338
+			->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
339
+				$join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
340
+					->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
341
+					->where('nonroot.full_ancestors', '>', 0)
342
+					->where('nonroot.majs_gedcom_id', '=', $this->tree->id())
343
+					->where('nonroot.majs_user_id', '=', $this->user->id());
344
+			})
345
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
346
+			->where('sosa.majs_user_id', '=', $this->user->id())
347
+			->whereNull('nonroot.majs_sosa');
348
+
349
+		/* Aggregate both queries, and calculate the sum of contributions by generation roots.
350 350
          * Exclude as well nodes that already appear in lower generations, as their branche has already been reduced.
351 351
          */
352
-        $ancestors_contributions_sum = DB::connection()->query()
353
-            ->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
354
-            ->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
355
-            ->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
356
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
357
-                $table_prefix . 'sosa_contribs.contrib AS totalContrib')
358
-            ->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
359
-                $join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
360
-                    ->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
361
-                    ->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
362
-                    ->where('sosa_low.majs_user_id', '=', $this->user->id());
363
-            })
364
-            ->whereNull('sosa_low.majs_sosa')
365
-            ->groupBy(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id',
366
-                'sosa_contribs.majs_i_id', 'sosa_contribs.contrib']);
367
-
368
-        // Aggregate all generation roots to compute root and generation pedigree collapse
369
-        $pedi_collapse_coll = DB::connection()->query()->fromSub($ancestors_contributions_sum, 'sosa_contribs_sum')
370
-            ->select(['gen'])->selectRaw('SUM(contrib), SUM(totalContrib)')
371
-            ->selectRaw('1 - SUM(contrib) / SUM(totalContrib) AS pedi_collapse_roots')  // Roots/horizontal collapse
372
-            ->selectRaw('1 - SUM(totalContrib) / POWER ( 2, gen - 1) AS pedi_collapse_xgen') // Crossgeneration collapse
373
-            ->groupBy(['gen', 'majs_gedcom_id', 'majs_user_id'])
374
-            ->orderBy('gen')
375
-            ->get();
376
-
377
-        $pedi_collapse_by_gen = [];
378
-        foreach ($pedi_collapse_coll as $collapse_gen) {
379
-            $pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
380
-                'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
381
-                'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
382
-            );
383
-        }
384
-        return $pedi_collapse_by_gen;
385
-    }
386
-
387
-    /**
388
-     * Return a Collection of the mean generation depth and deviation for all Sosa ancestors at a given generation.
389
-     * Sosa 1 is of generation 1.
390
-     *
391
-     * Mean generation depth and deviation are calculated based on the works of Marie-Héléne Cazes and Pierre Cazes,
392
-     * published in Population (French Edition), Vol. 51, No. 1 (Jan. - Feb., 1996), pp. 117-140
393
-     * http://kintip.net/index.php?option=com_jdownloads&task=download.send&id=9&catid=4&m=0
394
-     *
395
-     * Format:
396
-     *  - key : sosa number of the ancestor
397
-     *  - values:
398
-     *      - root_ancestor_id : ID of the ancestor
399
-     *      - mean_gen_depth : Mean generation depth
400
-     *      - stddev_gen_depth : Standard deviation of generation depth
401
-     *
402
-     * @param int $gen Sosa generation
403
-     * @return Collection<int, \stdClass>
404
-     */
405
-    public function generationDepthStatsAtGeneration(int $gen): Collection
406
-    {
407
-        if (!$this->isPdoSupported()) {
408
-            return collect();
409
-        }
410
-
411
-        $table_prefix = DB::connection()->getTablePrefix();
412
-        $missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
413
-            ->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
414
-            ->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
415
-            ->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
416
-            ->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
417
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
418
-                // Link to sosa's father
419
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
420
-                ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
421
-                ->where('sosa_fat.majs_user_id', '=', $this->user->id());
422
-            })
423
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
424
-                // Link to sosa's mother
425
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
426
-                ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
427
-                ->where('sosa_mot.majs_user_id', '=', $this->user->id());
428
-            })
429
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
430
-            ->where('sosa.majs_user_id', '=', $this->user->id())
431
-            ->where('sosa.majs_gen', '>=', $gen)
432
-            ->where(function (Builder $query): void {
433
-                $query->whereNull('sosa_fat.majs_i_id')
434
-                    ->orWhereNull('sosa_mot.majs_i_id');
435
-            })
436
-            ->groupBy(['sosa.majs_gen', 'root_ancestor']);
437
-
438
-        return DB::table('maj_sosa AS sosa_list')
439
-            ->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
440
-            ->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
441
-            ->selectRaw(' SQRT(' .
442
-                '   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
443
-                '   - 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
444
-                ' ) AS stddev_gen_depth')
445
-            ->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
446
-                $join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
447
-                    ->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
448
-                    ->where('sosa_list.majs_user_id', '=', $this->user->id());
449
-            })
450
-            ->groupBy(['stats_by_gen.root_ancestor', 'sosa_list.majs_i_id'])
451
-            ->orderBy('stats_by_gen.root_ancestor')
452
-            ->get()->keyBy('root_ancestor_sosa');
453
-    }
454
-
455
-    /**
456
-     * Return a collection of the most duplicated root Sosa ancestors.
457
-     * The number of ancestors to return is limited by the parameter $limit.
458
-     * If several individuals are tied when reaching the limit, none of them are returned,
459
-     * which means that there can be less individuals returned than requested.
460
-     *
461
-     * Format:
462
-     *  - value:
463
-     *      - sosa_i_id : sosa individual
464
-     *      - sosa_count: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
465
-     *
466
-     * @param int $limit
467
-     * @return Collection<\stdClass>
468
-     */
469
-    public function topMultipleAncestorsWithNoTies(int $limit): Collection
470
-    {
471
-        $table_prefix = DB::connection()->getTablePrefix();
472
-        $multiple_ancestors = DB::table('maj_sosa AS sosa')
473
-            ->select('sosa.majs_i_id AS sosa_i_id')
474
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
475
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
476
-                // Link to sosa's father
477
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
478
-                    ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
479
-                    ->where('sosa_fat.majs_user_id', '=', $this->user->id());
480
-            })
481
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
482
-                // Link to sosa's mother
483
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
484
-                ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
485
-                ->where('sosa_mot.majs_user_id', '=', $this->user->id());
486
-            })
487
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
488
-            ->where('sosa.majs_user_id', '=', $this->user->id())
489
-            ->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
490
-            ->whereNull('sosa_mot.majs_sosa')
491
-            ->groupBy('sosa.majs_i_id')
492
-            ->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
493
-            ->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
494
-            ->limit($limit + 1)     // We want to select one more than required, for ties
495
-            ->get();
496
-
497
-        if ($multiple_ancestors->count() > $limit) {
498
-            $last_count = $multiple_ancestors->last()->sosa_count;
499
-            $multiple_ancestors = $multiple_ancestors->reject(
500
-                fn (stdClass $element): bool => $element->sosa_count ===  $last_count
501
-            );
502
-        }
503
-        return $multiple_ancestors;
504
-    }
505
-
506
-    /**
507
-     * Return a computed array of statistics about the dispersion of ancestors across the ancestors
508
-     * at a specified generation.
509
-     *
510
-     * Format:
511
-     *  - key : rank of the ancestor in generation G for which exclusive ancestors have been found
512
-     *          For instance 3 represent the maternal grand father
513
-     *          0 is used for shared ancestors
514
-     *  - values:
515
-     *      - branches: same as key
516
-     *      - majs_i_id: xref of the ancestor at rank key in generation G, or null for shared ancestors
517
-     *      - count_indi: number of ancestors exclusively in the ancestors of the ancestor at rank key
518
-     *
519
-     * For instance a result at generation 3 could be :
520
-     * [
521
-     *  0 => { branches: 0, majs_i_id: X1, count_indi: 12 } -> 12 ancestors are shared by the grand-parents
522
-     *  1 => { branches: 1, majs_i_id: X2, count_indi: 32 } -> 32 ancestors are exclusive to the paternal grand-father
523
-     *  2 => { branches: 2, majs_i_id: X3, count_indi: 25 } -> 25 ancestors are exclusive to the paternal grand-mother
524
-     *  3 => { branches: 3, majs_i_id: X4, count_indi: 12 } -> 12 ancestors are exclusive to the maternal grand-father
525
-     *  4 => { branches: 4, majs_i_id: X5, count_indi: 30 } -> 30 ancestors are exclusive to the maternal grand-mother
526
-     * ]
527
-     *
528
-     * @param int $gen
529
-     * @return Collection<int, \stdClass>
530
-     */
531
-    public function ancestorsDispersionForGeneration(int $gen): Collection
532
-    {
533
-        if (!$this->isPdoSupported()) {
534
-            return collect();
535
-        }
536
-
537
-        $ancestors_branches = DB::table('maj_sosa')
538
-            ->select('majs_i_id AS i_id')
539
-            ->selectRaw('FLOOR(majs_sosa / POW(2, (majs_gen - ?))) - POW(2, ? -1) + 1 AS branch', [$gen, $gen])
540
-            ->where('majs_gedcom_id', '=', $this->tree->id())
541
-            ->where('majs_user_id', '=', $this->user->id())
542
-            ->where('majs_gen', '>=', $gen)
543
-            ->groupBy('majs_i_id', 'branch');
544
-
545
-        $consolidated_ancestors_branches = DB::table('maj_sosa')
546
-            ->fromSub($ancestors_branches, 'indi_branch')
547
-            ->select('i_id')
548
-            ->selectRaw('CASE WHEN COUNT(branch) > 1 THEN 0 ELSE MIN(branch) END AS branches')
549
-            ->groupBy('i_id');
550
-
551
-        return DB::table('maj_sosa')
552
-            ->rightJoinSub(
553
-                $consolidated_ancestors_branches,
554
-                'indi_branch_consolidated',
555
-                function (JoinClause $join) use ($gen): void {
556
-                    $join->where('maj_sosa.majs_gedcom_id', '=', $this->tree->id())
557
-                        ->where('maj_sosa.majs_user_id', '=', $this->user->id())
558
-                        ->where('branches', '>', 0)
559
-                        ->whereRaw('majs_sosa = POW(2, ? - 1) + branches - 1', [$gen]);
560
-                }
561
-            )
562
-            ->select(['branches', 'majs_i_id'])
563
-            ->selectRaw('COUNT(i_id) AS count_indi')
564
-            ->groupBy(['branches', 'majs_i_id'])
565
-            ->get()->keyBy('branches');
566
-    }
352
+		$ancestors_contributions_sum = DB::connection()->query()
353
+			->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
354
+			->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
355
+			->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
356
+			->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
357
+				$table_prefix . 'sosa_contribs.contrib AS totalContrib')
358
+			->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
359
+				$join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
360
+					->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
361
+					->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
362
+					->where('sosa_low.majs_user_id', '=', $this->user->id());
363
+			})
364
+			->whereNull('sosa_low.majs_sosa')
365
+			->groupBy(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id',
366
+				'sosa_contribs.majs_i_id', 'sosa_contribs.contrib']);
367
+
368
+		// Aggregate all generation roots to compute root and generation pedigree collapse
369
+		$pedi_collapse_coll = DB::connection()->query()->fromSub($ancestors_contributions_sum, 'sosa_contribs_sum')
370
+			->select(['gen'])->selectRaw('SUM(contrib), SUM(totalContrib)')
371
+			->selectRaw('1 - SUM(contrib) / SUM(totalContrib) AS pedi_collapse_roots')  // Roots/horizontal collapse
372
+			->selectRaw('1 - SUM(totalContrib) / POWER ( 2, gen - 1) AS pedi_collapse_xgen') // Crossgeneration collapse
373
+			->groupBy(['gen', 'majs_gedcom_id', 'majs_user_id'])
374
+			->orderBy('gen')
375
+			->get();
376
+
377
+		$pedi_collapse_by_gen = [];
378
+		foreach ($pedi_collapse_coll as $collapse_gen) {
379
+			$pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
380
+				'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
381
+				'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
382
+			);
383
+		}
384
+		return $pedi_collapse_by_gen;
385
+	}
386
+
387
+	/**
388
+	 * Return a Collection of the mean generation depth and deviation for all Sosa ancestors at a given generation.
389
+	 * Sosa 1 is of generation 1.
390
+	 *
391
+	 * Mean generation depth and deviation are calculated based on the works of Marie-Héléne Cazes and Pierre Cazes,
392
+	 * published in Population (French Edition), Vol. 51, No. 1 (Jan. - Feb., 1996), pp. 117-140
393
+	 * http://kintip.net/index.php?option=com_jdownloads&task=download.send&id=9&catid=4&m=0
394
+	 *
395
+	 * Format:
396
+	 *  - key : sosa number of the ancestor
397
+	 *  - values:
398
+	 *      - root_ancestor_id : ID of the ancestor
399
+	 *      - mean_gen_depth : Mean generation depth
400
+	 *      - stddev_gen_depth : Standard deviation of generation depth
401
+	 *
402
+	 * @param int $gen Sosa generation
403
+	 * @return Collection<int, \stdClass>
404
+	 */
405
+	public function generationDepthStatsAtGeneration(int $gen): Collection
406
+	{
407
+		if (!$this->isPdoSupported()) {
408
+			return collect();
409
+		}
410
+
411
+		$table_prefix = DB::connection()->getTablePrefix();
412
+		$missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
413
+			->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
414
+			->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
415
+			->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
416
+			->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
417
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
418
+				// Link to sosa's father
419
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
420
+				->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
421
+				->where('sosa_fat.majs_user_id', '=', $this->user->id());
422
+			})
423
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
424
+				// Link to sosa's mother
425
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
426
+				->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
427
+				->where('sosa_mot.majs_user_id', '=', $this->user->id());
428
+			})
429
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
430
+			->where('sosa.majs_user_id', '=', $this->user->id())
431
+			->where('sosa.majs_gen', '>=', $gen)
432
+			->where(function (Builder $query): void {
433
+				$query->whereNull('sosa_fat.majs_i_id')
434
+					->orWhereNull('sosa_mot.majs_i_id');
435
+			})
436
+			->groupBy(['sosa.majs_gen', 'root_ancestor']);
437
+
438
+		return DB::table('maj_sosa AS sosa_list')
439
+			->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
440
+			->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
441
+			->selectRaw(' SQRT(' .
442
+				'   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
443
+				'   - 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
444
+				' ) AS stddev_gen_depth')
445
+			->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
446
+				$join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
447
+					->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
448
+					->where('sosa_list.majs_user_id', '=', $this->user->id());
449
+			})
450
+			->groupBy(['stats_by_gen.root_ancestor', 'sosa_list.majs_i_id'])
451
+			->orderBy('stats_by_gen.root_ancestor')
452
+			->get()->keyBy('root_ancestor_sosa');
453
+	}
454
+
455
+	/**
456
+	 * Return a collection of the most duplicated root Sosa ancestors.
457
+	 * The number of ancestors to return is limited by the parameter $limit.
458
+	 * If several individuals are tied when reaching the limit, none of them are returned,
459
+	 * which means that there can be less individuals returned than requested.
460
+	 *
461
+	 * Format:
462
+	 *  - value:
463
+	 *      - sosa_i_id : sosa individual
464
+	 *      - sosa_count: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
465
+	 *
466
+	 * @param int $limit
467
+	 * @return Collection<\stdClass>
468
+	 */
469
+	public function topMultipleAncestorsWithNoTies(int $limit): Collection
470
+	{
471
+		$table_prefix = DB::connection()->getTablePrefix();
472
+		$multiple_ancestors = DB::table('maj_sosa AS sosa')
473
+			->select('sosa.majs_i_id AS sosa_i_id')
474
+			->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
475
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
476
+				// Link to sosa's father
477
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
478
+					->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
479
+					->where('sosa_fat.majs_user_id', '=', $this->user->id());
480
+			})
481
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
482
+				// Link to sosa's mother
483
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
484
+				->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
485
+				->where('sosa_mot.majs_user_id', '=', $this->user->id());
486
+			})
487
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
488
+			->where('sosa.majs_user_id', '=', $this->user->id())
489
+			->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
490
+			->whereNull('sosa_mot.majs_sosa')
491
+			->groupBy('sosa.majs_i_id')
492
+			->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
493
+			->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
494
+			->limit($limit + 1)     // We want to select one more than required, for ties
495
+			->get();
496
+
497
+		if ($multiple_ancestors->count() > $limit) {
498
+			$last_count = $multiple_ancestors->last()->sosa_count;
499
+			$multiple_ancestors = $multiple_ancestors->reject(
500
+				fn (stdClass $element): bool => $element->sosa_count ===  $last_count
501
+			);
502
+		}
503
+		return $multiple_ancestors;
504
+	}
505
+
506
+	/**
507
+	 * Return a computed array of statistics about the dispersion of ancestors across the ancestors
508
+	 * at a specified generation.
509
+	 *
510
+	 * Format:
511
+	 *  - key : rank of the ancestor in generation G for which exclusive ancestors have been found
512
+	 *          For instance 3 represent the maternal grand father
513
+	 *          0 is used for shared ancestors
514
+	 *  - values:
515
+	 *      - branches: same as key
516
+	 *      - majs_i_id: xref of the ancestor at rank key in generation G, or null for shared ancestors
517
+	 *      - count_indi: number of ancestors exclusively in the ancestors of the ancestor at rank key
518
+	 *
519
+	 * For instance a result at generation 3 could be :
520
+	 * [
521
+	 *  0 => { branches: 0, majs_i_id: X1, count_indi: 12 } -> 12 ancestors are shared by the grand-parents
522
+	 *  1 => { branches: 1, majs_i_id: X2, count_indi: 32 } -> 32 ancestors are exclusive to the paternal grand-father
523
+	 *  2 => { branches: 2, majs_i_id: X3, count_indi: 25 } -> 25 ancestors are exclusive to the paternal grand-mother
524
+	 *  3 => { branches: 3, majs_i_id: X4, count_indi: 12 } -> 12 ancestors are exclusive to the maternal grand-father
525
+	 *  4 => { branches: 4, majs_i_id: X5, count_indi: 30 } -> 30 ancestors are exclusive to the maternal grand-mother
526
+	 * ]
527
+	 *
528
+	 * @param int $gen
529
+	 * @return Collection<int, \stdClass>
530
+	 */
531
+	public function ancestorsDispersionForGeneration(int $gen): Collection
532
+	{
533
+		if (!$this->isPdoSupported()) {
534
+			return collect();
535
+		}
536
+
537
+		$ancestors_branches = DB::table('maj_sosa')
538
+			->select('majs_i_id AS i_id')
539
+			->selectRaw('FLOOR(majs_sosa / POW(2, (majs_gen - ?))) - POW(2, ? -1) + 1 AS branch', [$gen, $gen])
540
+			->where('majs_gedcom_id', '=', $this->tree->id())
541
+			->where('majs_user_id', '=', $this->user->id())
542
+			->where('majs_gen', '>=', $gen)
543
+			->groupBy('majs_i_id', 'branch');
544
+
545
+		$consolidated_ancestors_branches = DB::table('maj_sosa')
546
+			->fromSub($ancestors_branches, 'indi_branch')
547
+			->select('i_id')
548
+			->selectRaw('CASE WHEN COUNT(branch) > 1 THEN 0 ELSE MIN(branch) END AS branches')
549
+			->groupBy('i_id');
550
+
551
+		return DB::table('maj_sosa')
552
+			->rightJoinSub(
553
+				$consolidated_ancestors_branches,
554
+				'indi_branch_consolidated',
555
+				function (JoinClause $join) use ($gen): void {
556
+					$join->where('maj_sosa.majs_gedcom_id', '=', $this->tree->id())
557
+						->where('maj_sosa.majs_user_id', '=', $this->user->id())
558
+						->where('branches', '>', 0)
559
+						->whereRaw('majs_sosa = POW(2, ? - 1) + branches - 1', [$gen]);
560
+				}
561
+			)
562
+			->select(['branches', 'majs_i_id'])
563
+			->selectRaw('COUNT(i_id) AS count_indi')
564
+			->groupBy(['branches', 'majs_i_id'])
565
+			->get()->keyBy('branches');
566
+	}
567 567
 }
Please login to merge, or discard this patch.
Spacing   +58 added lines, -59 removed lines patch added patch discarded remove patch
@@ -74,7 +74,7 @@  discard block
 block discarded – undo
74 74
      */
75 75
     public function maxGeneration(): int
76 76
     {
77
-        return (int) DB::table('maj_sosa')
77
+        return (int)DB::table('maj_sosa')
78 78
             ->where('majs_gedcom_id', '=', $this->tree->id())
79 79
             ->where('majs_user_id', '=', $this->user->id())
80 80
             ->max('majs_gen');
@@ -152,8 +152,7 @@  discard block
 block discarded – undo
152 152
             ->get()->first();
153 153
 
154 154
         $denom = $row->n * $row->sum_x2 - pow($row->sum_x, 2);
155
-        return ((int) $row->n === 0 || $denom === 0) ? 0 :
156
-            -($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / $denom;
155
+        return ((int)$row->n === 0 || $denom === 0) ? 0 : -($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / $denom;
157 156
     }
158 157
 
159 158
     /**
@@ -177,10 +176,10 @@  discard block
 block discarded – undo
177 176
 
178 177
         $statistics_by_gen = [];
179 178
         foreach ($stats_by_gen as $gen => $stats_gen) {
180
-            $statistics_by_gen[(int) $stats_gen->gen] = array(
181
-                'sosaCount'             =>  (int) $stats_gen->total_sosa,
182
-                'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
183
-                'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
179
+            $statistics_by_gen[(int)$stats_gen->gen] = array(
180
+                'sosaCount'             =>  (int)$stats_gen->total_sosa,
181
+                'sosaTotalCount'        =>  (int)$cumul_stats_by_gen[$gen]->total_cumul,
182
+                'diffSosaTotalCount'    =>  (int)$cumul_stats_by_gen[$gen]->total_distinct_cumul,
184 183
                 'firstBirth'            =>  $stats_gen->first_year,
185 184
                 'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
186 185
                 'lastBirth'             =>  $stats_gen->last_year,
@@ -224,7 +223,7 @@  discard block
 block discarded – undo
224 223
             ->where('majs_user_id', '=', $this->user->id());
225 224
 
226 225
         return DB::table('maj_sosa')
227
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
226
+            ->joinSub($list_gen, 'list_gen', function(JoinClause $join): void {
228 227
                 $join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
229 228
                 ->where('majs_gedcom_id', '=', $this->tree->id())
230 229
                 ->where('majs_user_id', '=', $this->user->id());
@@ -265,37 +264,37 @@  discard block
 block discarded – undo
265 264
             ->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
266 265
             ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
267 266
             ->selectRaw(
268
-                '(CASE ' .
269
-                    ' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
270
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
271
-                    ' ELSE 0 ' .
272
-                ' END)' .
273
-                ' + (CASE ' .
274
-                    ' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
275
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
276
-                    ' ELSE 0 ' .
267
+                '(CASE '.
268
+                    ' WHEN '.$table_prefix.'sosa_fat.majs_i_id IS NULL'.
269
+                    ' THEN POWER(2, '.$table_prefix.'list_gen.majs_gen - '.$table_prefix.'sosa.majs_gen - 1)'.
270
+                    ' ELSE 0 '.
271
+                ' END)'.
272
+                ' + (CASE '.
273
+                    ' WHEN '.$table_prefix.'sosa_mot.majs_i_id IS NULL'.
274
+                    ' THEN POWER(2, '.$table_prefix.'list_gen.majs_gen - '.$table_prefix.'sosa.majs_gen - 1)'.
275
+                    ' ELSE 0 '.
277 276
                 ' END) contrib'
278 277
             )
279
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
278
+            ->joinSub($list_gen, 'list_gen', function(JoinClause $join): void {
280 279
                 $join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
281 280
                     ->where('majs_gedcom_id', '=', $this->tree->id())
282 281
                     ->where('majs_user_id', '=', $this->user->id());
283 282
             })
284
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
283
+            ->leftJoin('maj_sosa AS sosa_fat', function(JoinClause $join) use ($table_prefix): void {
285 284
                 // Link to sosa's father
286
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
285
+                $join->whereRaw($table_prefix.'sosa_fat.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa')
287 286
                     ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
288 287
                     ->where('sosa_fat.majs_user_id', '=', $this->user->id());
289 288
             })
290
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
289
+            ->leftJoin('maj_sosa AS sosa_mot', function(JoinClause $join) use ($table_prefix): void {
291 290
                 // Link to sosa's mother
292
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
291
+                $join->whereRaw($table_prefix.'sosa_mot.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa + 1')
293 292
                     ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
294 293
                     ->where('sosa_mot.majs_user_id', '=', $this->user->id());
295 294
             })
296 295
             ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
297 296
             ->where('sosa.majs_user_id', '=', $this->user->id())
298
-            ->where(function (Builder $query): void {
297
+            ->where(function(Builder $query): void {
299 298
                 $query->whereNull('sosa_fat.majs_i_id')
300 299
                 ->orWhereNull('sosa_mot.majs_i_id');
301 300
             });
@@ -305,24 +304,24 @@  discard block
 block discarded – undo
305 304
          */
306 305
         $non_roots_ancestors = DB::table('maj_sosa AS sosa')
307 306
             ->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
308
-            ->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
307
+            ->selectRaw('MAX('.$table_prefix.'sosa_anc.majs_sosa) - MIN('.$table_prefix.'sosa_anc.majs_sosa)'.
309 308
                 ' AS full_ancestors')
310
-            ->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
309
+            ->join('maj_sosa AS sosa_anc', function(JoinClause $join) use ($table_prefix): void {
311 310
                 $join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
312
-                    ->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
313
-                        $table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
314
-                        $table_prefix . 'sosa.majs_sosa')
311
+                    ->whereRaw('FLOOR('.$table_prefix.'sosa_anc.majs_sosa / POWER(2, '.
312
+                        $table_prefix.'sosa_anc.majs_gen - '.$table_prefix.'sosa.majs_gen)) = '.
313
+                        $table_prefix.'sosa.majs_sosa')
315 314
                     ->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
316 315
                     ->where('sosa_anc.majs_user_id', '=', $this->user->id());
317 316
             })
318 317
             ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
319 318
             ->where('sosa.majs_user_id', '=', $this->user->id())
320
-            ->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
319
+            ->whereIn('sosa_anc.majs_i_id', function(Builder $query) use ($table_prefix): void {
321 320
                 $query->from('maj_sosa AS sosa_gen')
322 321
                 ->select('sosa_gen.majs_i_id')->distinct()
323 322
                 ->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
324 323
                 ->where('sosa_gen.majs_user_id', '=', $this->user->id())
325
-                ->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
324
+                ->whereRaw($table_prefix.'sosa_gen.majs_gen = '.$table_prefix.'sosa.majs_gen');
326 325
             })
327 326
             ->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
328 327
                 'sosa.majs_sosa', 'sosa.majs_i_id']);
@@ -335,7 +334,7 @@  discard block
 block discarded – undo
335 334
             ->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
336 335
             ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
337 336
             ->selectRaw('1 AS contrib')
338
-            ->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
337
+            ->leftJoinSub($non_roots_ancestors, 'nonroot', function(JoinClause $join): void {
339 338
                 $join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
340 339
                     ->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
341 340
                     ->where('nonroot.full_ancestors', '>', 0)
@@ -353,9 +352,9 @@  discard block
 block discarded – undo
353 352
             ->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
354 353
             ->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
355 354
             ->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
356
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
357
-                $table_prefix . 'sosa_contribs.contrib AS totalContrib')
358
-            ->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
355
+            ->selectRaw('COUNT('.$table_prefix.'sosa_contribs.majs_i_id) * '.
356
+                $table_prefix.'sosa_contribs.contrib AS totalContrib')
357
+            ->leftJoin('maj_sosa AS sosa_low', function(JoinClause $join): void {
359 358
                 $join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
360 359
                     ->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
361 360
                     ->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
@@ -376,9 +375,9 @@  discard block
 block discarded – undo
376 375
 
377 376
         $pedi_collapse_by_gen = [];
378 377
         foreach ($pedi_collapse_coll as $collapse_gen) {
379
-            $pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
380
-                'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
381
-                'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
378
+            $pedi_collapse_by_gen[(int)$collapse_gen->gen] = array(
379
+                'pedi_collapse_roots'   =>  (float)$collapse_gen->pedi_collapse_roots,
380
+                'pedi_collapse_xgen'   =>  (float)$collapse_gen->pedi_collapse_xgen
382 381
             );
383 382
         }
384 383
         return $pedi_collapse_by_gen;
@@ -410,26 +409,26 @@  discard block
 block discarded – undo
410 409
 
411 410
         $table_prefix = DB::connection()->getTablePrefix();
412 411
         $missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
413
-            ->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
414
-            ->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
415
-            ->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
416
-            ->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
417
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
412
+            ->selectRaw($table_prefix.'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
413
+            ->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
414
+            ->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
415
+            ->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
416
+            ->leftJoin('maj_sosa AS sosa_fat', function(JoinClause $join) use ($table_prefix): void {
418 417
                 // Link to sosa's father
419
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
418
+                $join->whereRaw($table_prefix.'sosa_fat.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa')
420 419
                 ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
421 420
                 ->where('sosa_fat.majs_user_id', '=', $this->user->id());
422 421
             })
423
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
422
+            ->leftJoin('maj_sosa AS sosa_mot', function(JoinClause $join) use ($table_prefix): void {
424 423
                 // Link to sosa's mother
425
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
424
+                $join->whereRaw($table_prefix.'sosa_mot.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa + 1')
426 425
                 ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
427 426
                 ->where('sosa_mot.majs_user_id', '=', $this->user->id());
428 427
             })
429 428
             ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
430 429
             ->where('sosa.majs_user_id', '=', $this->user->id())
431 430
             ->where('sosa.majs_gen', '>=', $gen)
432
-            ->where(function (Builder $query): void {
431
+            ->where(function(Builder $query): void {
433 432
                 $query->whereNull('sosa_fat.majs_i_id')
434 433
                     ->orWhereNull('sosa_mot.majs_i_id');
435 434
             })
@@ -438,11 +437,11 @@  discard block
 block discarded – undo
438 437
         return DB::table('maj_sosa AS sosa_list')
439 438
             ->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
440 439
             ->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
441
-            ->selectRaw(' SQRT(' .
442
-                '   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
443
-                '   - 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
440
+            ->selectRaw(' SQRT('.
441
+                '   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
442
+                '   - 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
444 443
                 ' ) AS stddev_gen_depth')
445
-            ->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
444
+            ->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function(JoinClause $join): void {
446 445
                 $join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
447 446
                     ->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
448 447
                     ->where('sosa_list.majs_user_id', '=', $this->user->id());
@@ -471,16 +470,16 @@  discard block
 block discarded – undo
471 470
         $table_prefix = DB::connection()->getTablePrefix();
472 471
         $multiple_ancestors = DB::table('maj_sosa AS sosa')
473 472
             ->select('sosa.majs_i_id AS sosa_i_id')
474
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
475
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
473
+            ->selectRaw('COUNT('.$table_prefix.'sosa.majs_sosa) AS sosa_count')
474
+            ->leftJoin('maj_sosa AS sosa_fat', function(JoinClause $join) use ($table_prefix): void {
476 475
                 // Link to sosa's father
477
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
476
+                $join->whereRaw($table_prefix.'sosa_fat.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa')
478 477
                     ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
479 478
                     ->where('sosa_fat.majs_user_id', '=', $this->user->id());
480 479
             })
481
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
480
+            ->leftJoin('maj_sosa AS sosa_mot', function(JoinClause $join) use ($table_prefix): void {
482 481
                 // Link to sosa's mother
483
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
482
+                $join->whereRaw($table_prefix.'sosa_mot.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa + 1')
484 483
                 ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
485 484
                 ->where('sosa_mot.majs_user_id', '=', $this->user->id());
486 485
             })
@@ -489,15 +488,15 @@  discard block
 block discarded – undo
489 488
             ->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
490 489
             ->whereNull('sosa_mot.majs_sosa')
491 490
             ->groupBy('sosa.majs_i_id')
492
-            ->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
493
-            ->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
491
+            ->havingRaw('COUNT('.$table_prefix.'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
492
+            ->orderByRaw('COUNT('.$table_prefix.'sosa.majs_sosa) DESC, MIN('.$table_prefix.'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
494 493
             ->limit($limit + 1)     // We want to select one more than required, for ties
495 494
             ->get();
496 495
 
497 496
         if ($multiple_ancestors->count() > $limit) {
498 497
             $last_count = $multiple_ancestors->last()->sosa_count;
499 498
             $multiple_ancestors = $multiple_ancestors->reject(
500
-                fn (stdClass $element): bool => $element->sosa_count ===  $last_count
499
+                fn (stdClass $element): bool => $element->sosa_count === $last_count
501 500
             );
502 501
         }
503 502
         return $multiple_ancestors;
@@ -552,7 +551,7 @@  discard block
 block discarded – undo
552 551
             ->rightJoinSub(
553 552
                 $consolidated_ancestors_branches,
554 553
                 'indi_branch_consolidated',
555
-                function (JoinClause $join) use ($gen): void {
554
+                function(JoinClause $join) use ($gen): void {
556 555
                     $join->where('maj_sosa.majs_gedcom_id', '=', $this->tree->id())
557 556
                         ->where('maj_sosa.majs_user_id', '=', $this->user->id())
558 557
                         ->where('branches', '>', 0)
Please login to merge, or discard this patch.