Passed
Push — main ( f9aaf7...4197a4 )
by Jonathan
14:34
created
app/Module/Sosa/Http/RequestHandlers/SosaComputeModal.php 2 patches
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -28,40 +28,40 @@
 block discarded – undo
28 28
  */
29 29
 class SosaComputeModal implements RequestHandlerInterface
30 30
 {
31
-    /**
32
-     * @var SosaModule|null $module
33
-     */
34
-    private $module;
31
+	/**
32
+	 * @var SosaModule|null $module
33
+	 */
34
+	private $module;
35 35
 
36
-    /**
37
-     * Constructor for SosaComputeModal Request Handler
38
-     *
39
-     * @param ModuleService $module_service
40
-     */
41
-    public function __construct(ModuleService $module_service)
42
-    {
43
-        $this->module = $module_service->findByInterface(SosaModule::class)->first();
44
-    }
36
+	/**
37
+	 * Constructor for SosaComputeModal Request Handler
38
+	 *
39
+	 * @param ModuleService $module_service
40
+	 */
41
+	public function __construct(ModuleService $module_service)
42
+	{
43
+		$this->module = $module_service->findByInterface(SosaModule::class)->first();
44
+	}
45 45
 
46
-    /**
47
-     * {@inheritDoc}
48
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
49
-     */
50
-    public function handle(ServerRequestInterface $request): ResponseInterface
51
-    {
52
-        if ($this->module === null) {
53
-            return response(view('modals/error', [
54
-                'title' => I18N::translate('Error'),
55
-                'error' => I18N::translate('The attached module could not be found.')
56
-            ]));
57
-        }
46
+	/**
47
+	 * {@inheritDoc}
48
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
49
+	 */
50
+	public function handle(ServerRequestInterface $request): ResponseInterface
51
+	{
52
+		if ($this->module === null) {
53
+			return response(view('modals/error', [
54
+				'title' => I18N::translate('Error'),
55
+				'error' => I18N::translate('The attached module could not be found.')
56
+			]));
57
+		}
58 58
 
59
-        $tree = $request->getAttribute('tree');
60
-        assert($tree instanceof Tree);
59
+		$tree = $request->getAttribute('tree');
60
+		assert($tree instanceof Tree);
61 61
 
62
-        return response(view($this->module->name() . '::modals/sosa-compute', [
63
-            'tree'          => $tree,
64
-            'xref'          =>  $request->getAttribute('xref')
65
-        ]));
66
-    }
62
+		return response(view($this->module->name() . '::modals/sosa-compute', [
63
+			'tree'          => $tree,
64
+			'xref'          =>  $request->getAttribute('xref')
65
+		]));
66
+	}
67 67
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@
 block discarded – undo
60 60
         $tree = $request->getAttribute('tree');
61 61
         assert($tree instanceof Tree);
62 62
 
63
-        return response(view($this->module->name() . '::modals/sosa-compute', [
63
+        return response(view($this->module->name().'::modals/sosa-compute', [
64 64
             'tree'          => $tree,
65 65
             'xref'          =>  $request->getAttribute('xref')
66 66
         ]));
Please login to merge, or discard this patch.
app/Module/Sosa/Http/RequestHandlers/SosaComputeAction.php 2 patches
Indentation   +49 added lines, -49 removed lines patch added patch discarded remove patch
@@ -31,61 +31,61 @@
 block discarded – undo
31 31
  */
32 32
 class SosaComputeAction implements RequestHandlerInterface
33 33
 {
34
-    /**
35
-     * @var UserService $user_service
36
-     */
37
-    private $user_service;
34
+	/**
35
+	 * @var UserService $user_service
36
+	 */
37
+	private $user_service;
38 38
 
39
-    /**
40
-     * Constructor for SosaConfigAction Request Handler
41
-     *
42
-     * @param UserService $user_service
43
-     */
44
-    public function __construct(UserService $user_service)
45
-    {
46
-        $this->user_service = $user_service;
47
-    }
39
+	/**
40
+	 * Constructor for SosaConfigAction Request Handler
41
+	 *
42
+	 * @param UserService $user_service
43
+	 */
44
+	public function __construct(UserService $user_service)
45
+	{
46
+		$this->user_service = $user_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 = $request->getAttribute('tree');
56
-        assert($tree instanceof Tree);
49
+	/**
50
+	 * {@inheritDoc}
51
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
52
+	 */
53
+	public function handle(ServerRequestInterface $request): ResponseInterface
54
+	{
55
+		$tree = $request->getAttribute('tree');
56
+		assert($tree instanceof Tree);
57 57
 
58
-        $params = $request->getParsedBody();
59
-        assert(is_array($params));
58
+		$params = $request->getParsedBody();
59
+		assert(is_array($params));
60 60
 
61
-        $user_id = (int) ($params['user_id'] ?? Auth::id() ?? 0);
62
-        $partial_from = $params['partial_from'] ?? null;
61
+		$user_id = (int) ($params['user_id'] ?? Auth::id() ?? 0);
62
+		$partial_from = $params['partial_from'] ?? null;
63 63
 
64
-        if (($user_id == -1 && Auth::isManager($tree)) || Auth::id() == $user_id) {
65
-            $user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
64
+		if (($user_id == -1 && Auth::isManager($tree)) || Auth::id() == $user_id) {
65
+			$user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
66 66
 
67
-            /** @var SosaCalculatorService $sosa_calc_service */
68
-            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
67
+			/** @var SosaCalculatorService $sosa_calc_service */
68
+			$sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
69 69
 
70
-            if (
71
-                $partial_from !== null &&
72
-                ($sosa_from = Registry::individualFactory()->make($partial_from, $tree)) !== null
73
-            ) {
74
-                $res = $sosa_calc_service->computeFromIndividual($sosa_from);
75
-            } else {
76
-                $res = $sosa_calc_service->computeAll();
77
-            }
70
+			if (
71
+				$partial_from !== null &&
72
+				($sosa_from = Registry::individualFactory()->make($partial_from, $tree)) !== null
73
+			) {
74
+				$res = $sosa_calc_service->computeFromIndividual($sosa_from);
75
+			} else {
76
+				$res = $sosa_calc_service->computeAll();
77
+			}
78 78
 
79
-            return $res ?
80
-                response('', 200) :
81
-                response(
82
-                    I18N::translate('An error occurred while computing Sosa ancestors.'),
83
-                    StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR
84
-                );
85
-        }
86
-        return response(
87
-            I18N::translate('You do not have permission to modify the user.'),
88
-            StatusCodeInterface::STATUS_FORBIDDEN
89
-        );
90
-    }
79
+			return $res ?
80
+				response('', 200) :
81
+				response(
82
+					I18N::translate('An error occurred while computing Sosa ancestors.'),
83
+					StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR
84
+				);
85
+		}
86
+		return response(
87
+			I18N::translate('You do not have permission to modify the user.'),
88
+			StatusCodeInterface::STATUS_FORBIDDEN
89
+		);
90
+	}
91 91
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -4 removed lines patch added patch discarded remove patch
@@ -58,14 +58,14 @@  discard block
 block discarded – undo
58 58
         $params = $request->getParsedBody();
59 59
         assert(is_array($params));
60 60
 
61
-        $user_id = (int) ($params['user_id'] ?? Auth::id() ?? 0);
61
+        $user_id = (int)($params['user_id'] ?? Auth::id() ?? 0);
62 62
         $partial_from = $params['partial_from'] ?? null;
63 63
 
64 64
         if (($user_id == -1 && Auth::isManager($tree)) || Auth::id() == $user_id) {
65 65
             $user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
66 66
 
67 67
             /** @var SosaCalculatorService $sosa_calc_service */
68
-            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
68
+            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, ['tree' => $tree, 'user' => $user]);
69 69
 
70 70
             if (
71 71
                 $partial_from !== null &&
@@ -77,8 +77,7 @@  discard block
 block discarded – undo
77 77
             }
78 78
 
79 79
             return $res ?
80
-                response('', 200) :
81
-                response(
80
+                response('', 200) : response(
82 81
                     I18N::translate('An error occurred while computing Sosa ancestors.'),
83 82
                     StatusCodeInterface::STATUS_INTERNAL_SERVER_ERROR
84 83
                 );
Please login to merge, or discard this patch.
app/Module/Sosa/Schema/Migration1.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -22,12 +22,12 @@
 block discarded – undo
22 22
 class Migration1 implements MigrationInterface
23 23
 {
24 24
     
25
-    /**
26
-     * {@inheritDoc}
27
-     * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
28
-     */
29
-    public function upgrade(): void
30
-    {
31
-        // These migrations have been merged into migration 2.
32
-    }
25
+	/**
26
+	 * {@inheritDoc}
27
+	 * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
28
+	 */
29
+	public function upgrade(): void
30
+	{
31
+		// These migrations have been merged into migration 2.
32
+	}
33 33
 }
Please login to merge, or discard this patch.
app/Module/Sosa/Schema/Migration2.php 2 patches
Indentation   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -24,36 +24,36 @@
 block discarded – undo
24 24
 class Migration2 implements MigrationInterface
25 25
 {
26 26
 
27
-    /**
28
-     * {@inheritDoc}
29
-     * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
30
-     */
31
-    public function upgrade(): void
32
-    {
33
-
34
-        // Clean up previous sosa table if it exists
35
-        DB::schema()->dropIfExists('maj_sosa');
36
-
37
-        DB::schema()->create('maj_sosa', static function (Blueprint $table): void {
38
-
39
-            $table->integer('majs_gedcom_id');
40
-            $table->integer('majs_user_id')->default(-1);
41
-            $table->bigInteger('majs_sosa')->unsigned(); // Allow to calculate sosa on 64 generations
42
-            $table->string('majs_i_id', 20);
43
-            $table->tinyInteger('majs_gen')->nullable();
44
-            $table->smallInteger('majs_birth_year')->nullable();
45
-            $table->smallInteger('majs_birth_year_est')->nullable();
46
-            $table->smallInteger('majs_death_year')->nullable();
47
-            $table->smallInteger('majs_death_year_est')->nullable();
48
-
49
-            $table->primary(['majs_gedcom_id', 'majs_user_id', 'majs_sosa']);
50
-
51
-            $table->index(['majs_gedcom_id', 'majs_user_id']);
52
-            $table->index(['majs_gedcom_id', 'majs_user_id', 'majs_i_id']);
53
-            $table->index(['majs_gedcom_id', 'majs_user_id', 'majs_gen']);
54
-
55
-            $table->foreign('majs_gedcom_id')->references('gedcom_id')->on('gedcom')->onDelete('cascade');
56
-            $table->foreign('majs_user_id')->references('user_id')->on('user')->onDelete('cascade');
57
-        });
58
-    }
27
+	/**
28
+	 * {@inheritDoc}
29
+	 * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
30
+	 */
31
+	public function upgrade(): void
32
+	{
33
+
34
+		// Clean up previous sosa table if it exists
35
+		DB::schema()->dropIfExists('maj_sosa');
36
+
37
+		DB::schema()->create('maj_sosa', static function (Blueprint $table): void {
38
+
39
+			$table->integer('majs_gedcom_id');
40
+			$table->integer('majs_user_id')->default(-1);
41
+			$table->bigInteger('majs_sosa')->unsigned(); // Allow to calculate sosa on 64 generations
42
+			$table->string('majs_i_id', 20);
43
+			$table->tinyInteger('majs_gen')->nullable();
44
+			$table->smallInteger('majs_birth_year')->nullable();
45
+			$table->smallInteger('majs_birth_year_est')->nullable();
46
+			$table->smallInteger('majs_death_year')->nullable();
47
+			$table->smallInteger('majs_death_year_est')->nullable();
48
+
49
+			$table->primary(['majs_gedcom_id', 'majs_user_id', 'majs_sosa']);
50
+
51
+			$table->index(['majs_gedcom_id', 'majs_user_id']);
52
+			$table->index(['majs_gedcom_id', 'majs_user_id', 'majs_i_id']);
53
+			$table->index(['majs_gedcom_id', 'majs_user_id', 'majs_gen']);
54
+
55
+			$table->foreign('majs_gedcom_id')->references('gedcom_id')->on('gedcom')->onDelete('cascade');
56
+			$table->foreign('majs_user_id')->references('user_id')->on('user')->onDelete('cascade');
57
+		});
58
+	}
59 59
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -34,7 +34,7 @@
 block discarded – undo
34 34
         // Clean up previous sosa table if it exists
35 35
         DB::schema()->dropIfExists('maj_sosa');
36 36
 
37
-        DB::schema()->create('maj_sosa', static function (Blueprint $table): void {
37
+        DB::schema()->create('maj_sosa', static function(Blueprint $table): void {
38 38
 
39 39
             $table->integer('majs_gedcom_id');
40 40
             $table->integer('majs_user_id')->default(-1);
Please login to merge, or discard this patch.
app/Module/Sosa/Schema/Migration0.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -22,12 +22,12 @@
 block discarded – undo
22 22
 class Migration0 implements MigrationInterface
23 23
 {
24 24
 
25
-    /**
26
-     * {@inheritDoc}
27
-     * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
28
-     */
29
-    public function upgrade(): void
30
-    {
31
-        // These migrations have been merged into migration 2.
32
-    }
25
+	/**
26
+	 * {@inheritDoc}
27
+	 * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
28
+	 */
29
+	public function upgrade(): void
30
+	{
31
+		// These migrations have been merged into migration 2.
32
+	}
33 33
 }
Please login to merge, or discard this patch.
app/Module/Sosa/Services/SosaCalculatorService.php 2 patches
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -24,143 +24,143 @@
 block discarded – undo
24 24
  */
25 25
 class SosaCalculatorService
26 26
 {
27
-    /**
28
-     * Maximium size for the temporary Sosa table
29
-     * @var int TMP_SOSA_TABLE_LIMIT
30
-     */
31
-    private const TMP_SOSA_TABLE_LIMIT = 1000;
32
-
33
-    /**
34
-     * @var SosaRecordsService $sosa_records_service
35
-     */
36
-    private $sosa_records_service;
37
-
38
-    /**
39
-     * Reference user
40
-     * @var UserInterface $user
41
-     */
42
-    private $user;
43
-
44
-    /**
45
-     * Reference tree
46
-     * @var Tree $tree
47
-     */
48
-    private $tree;
49
-
50
-    /**
51
-     * Temporary Sosa table, used during construction
52
-     * @var array<array<string,mixed>> $tmp_sosa_table
53
-     */
54
-    private $tmp_sosa_table;
55
-
56
-    /**
57
-     * Maximum number of generations to calculate
58
-     * @var int $max_generations
59
-     */
60
-    private $max_generations;
61
-
62
-    /**
63
-     * Constructor for the Sosa Calculator
64
-     *
65
-     * @param SosaRecordsService $sosa_records_service
66
-     * @param Tree $tree
67
-     * @param UserInterface $user
68
-     */
69
-    public function __construct(SosaRecordsService $sosa_records_service, Tree $tree, UserInterface $user)
70
-    {
71
-        $this->sosa_records_service = $sosa_records_service;
72
-        $this->tree = $tree;
73
-        $this->user = $user;
74
-        $this->tmp_sosa_table = array();
75
-        $max_gen_setting = $tree->getUserPreference($user, 'MAJ_SOSA_MAX_GEN');
76
-        $this->max_generations = is_numeric($max_gen_setting) ?
77
-            (int) $max_gen_setting :
78
-            $this->sosa_records_service->maxSystemGenerations();
79
-    }
80
-
81
-    /**
82
-     * Compute all Sosa ancestors from the user's root individual.
83
-     *
84
-     * @return bool Result of the computation
85
-     */
86
-    public function computeAll(): bool
87
-    {
88
-        $root_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
89
-        if (($indi = Registry::individualFactory()->make($root_id, $this->tree)) !== null) {
90
-            $this->sosa_records_service->deleteAll($this->tree, $this->user);
91
-            $this->addNode($indi, 1);
92
-            $this->flushTmpSosaTable(true);
93
-            return true;
94
-        }
95
-        return false;
96
-    }
97
-
98
-    /**
99
-     * Compute all Sosa Ancestors from a specified Individual
100
-     *
101
-     * @param Individual $indi
102
-     * @return bool
103
-     */
104
-    public function computeFromIndividual(Individual $indi): bool
105
-    {
106
-        $current_sosas = $this->sosa_records_service->sosaNumbers($this->tree, $this->user, $indi);
107
-        foreach ($current_sosas->keys() as $sosa) {
108
-            $this->sosa_records_service->deleteAncestorsFrom($this->tree, $this->user, $sosa);
109
-            $this->addNode($indi, $sosa);
110
-        }
111
-        $this->flushTmpSosaTable(true);
112
-        return true;
113
-    }
114
-
115
-    /**
116
-     * Recursive method to add individual to the Sosa table, and flush it regularly
117
-     *
118
-     * @param Individual $indi Individual to add
119
-     * @param int $sosa Individual's sosa
120
-     */
121
-    private function addNode(Individual $indi, int $sosa): void
122
-    {
123
-        $birth_year = $indi->getBirthDate()->gregorianYear();
124
-        $birth_year_est = $birth_year === 0 ? $indi->getEstimatedBirthDate()->gregorianYear() : $birth_year;
125
-
126
-        $death_year = $indi->getDeathDate()->gregorianYear();
127
-        $death_year_est = $death_year === 0 ? $indi->getEstimatedDeathDate()->gregorianYear() : $death_year;
128
-
129
-        $this->tmp_sosa_table[] = [
130
-            'indi' => $indi->xref(),
131
-            'sosa' => $sosa,
132
-            'birth_year' => $birth_year === 0 ? null : $birth_year,
133
-            'birth_year_est' => $birth_year_est === 0 ? null : $birth_year_est,
134
-            'death_year' => $death_year === 0 ? null : $death_year,
135
-            'death_year_est' => $death_year_est === 0 ? null : $death_year_est
136
-        ];
137
-
138
-        $this->flushTmpSosaTable();
139
-
140
-        if (
141
-            ($fam = $indi->childFamilies()->first()) !== null
142
-            && $this->sosa_records_service->generation($sosa) < $this->max_generations
143
-        ) {
144
-            /** @var \Fisharebest\Webtrees\Family $fam */
145
-            if (($husb = $fam->husband()) !== null) {
146
-                $this->addNode($husb, 2 * $sosa);
147
-            }
148
-            if (($wife = $fam->wife()) !== null) {
149
-                $this->addNode($wife, 2 * $sosa + 1);
150
-            }
151
-        }
152
-    }
153
-
154
-    /**
155
-     * Write sosas in the table, if the number of items is superior to the limit, or if forced.
156
-     *
157
-     * @param bool $force Should the flush be forced
158
-     */
159
-    private function flushTmpSosaTable($force = false): void
160
-    {
161
-        if ($force || count($this->tmp_sosa_table) >= self::TMP_SOSA_TABLE_LIMIT) {
162
-            $this->sosa_records_service->insertOrUpdate($this->tree, $this->user, $this->tmp_sosa_table);
163
-            $this->tmp_sosa_table = array();
164
-        }
165
-    }
27
+	/**
28
+	 * Maximium size for the temporary Sosa table
29
+	 * @var int TMP_SOSA_TABLE_LIMIT
30
+	 */
31
+	private const TMP_SOSA_TABLE_LIMIT = 1000;
32
+
33
+	/**
34
+	 * @var SosaRecordsService $sosa_records_service
35
+	 */
36
+	private $sosa_records_service;
37
+
38
+	/**
39
+	 * Reference user
40
+	 * @var UserInterface $user
41
+	 */
42
+	private $user;
43
+
44
+	/**
45
+	 * Reference tree
46
+	 * @var Tree $tree
47
+	 */
48
+	private $tree;
49
+
50
+	/**
51
+	 * Temporary Sosa table, used during construction
52
+	 * @var array<array<string,mixed>> $tmp_sosa_table
53
+	 */
54
+	private $tmp_sosa_table;
55
+
56
+	/**
57
+	 * Maximum number of generations to calculate
58
+	 * @var int $max_generations
59
+	 */
60
+	private $max_generations;
61
+
62
+	/**
63
+	 * Constructor for the Sosa Calculator
64
+	 *
65
+	 * @param SosaRecordsService $sosa_records_service
66
+	 * @param Tree $tree
67
+	 * @param UserInterface $user
68
+	 */
69
+	public function __construct(SosaRecordsService $sosa_records_service, Tree $tree, UserInterface $user)
70
+	{
71
+		$this->sosa_records_service = $sosa_records_service;
72
+		$this->tree = $tree;
73
+		$this->user = $user;
74
+		$this->tmp_sosa_table = array();
75
+		$max_gen_setting = $tree->getUserPreference($user, 'MAJ_SOSA_MAX_GEN');
76
+		$this->max_generations = is_numeric($max_gen_setting) ?
77
+			(int) $max_gen_setting :
78
+			$this->sosa_records_service->maxSystemGenerations();
79
+	}
80
+
81
+	/**
82
+	 * Compute all Sosa ancestors from the user's root individual.
83
+	 *
84
+	 * @return bool Result of the computation
85
+	 */
86
+	public function computeAll(): bool
87
+	{
88
+		$root_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
89
+		if (($indi = Registry::individualFactory()->make($root_id, $this->tree)) !== null) {
90
+			$this->sosa_records_service->deleteAll($this->tree, $this->user);
91
+			$this->addNode($indi, 1);
92
+			$this->flushTmpSosaTable(true);
93
+			return true;
94
+		}
95
+		return false;
96
+	}
97
+
98
+	/**
99
+	 * Compute all Sosa Ancestors from a specified Individual
100
+	 *
101
+	 * @param Individual $indi
102
+	 * @return bool
103
+	 */
104
+	public function computeFromIndividual(Individual $indi): bool
105
+	{
106
+		$current_sosas = $this->sosa_records_service->sosaNumbers($this->tree, $this->user, $indi);
107
+		foreach ($current_sosas->keys() as $sosa) {
108
+			$this->sosa_records_service->deleteAncestorsFrom($this->tree, $this->user, $sosa);
109
+			$this->addNode($indi, $sosa);
110
+		}
111
+		$this->flushTmpSosaTable(true);
112
+		return true;
113
+	}
114
+
115
+	/**
116
+	 * Recursive method to add individual to the Sosa table, and flush it regularly
117
+	 *
118
+	 * @param Individual $indi Individual to add
119
+	 * @param int $sosa Individual's sosa
120
+	 */
121
+	private function addNode(Individual $indi, int $sosa): void
122
+	{
123
+		$birth_year = $indi->getBirthDate()->gregorianYear();
124
+		$birth_year_est = $birth_year === 0 ? $indi->getEstimatedBirthDate()->gregorianYear() : $birth_year;
125
+
126
+		$death_year = $indi->getDeathDate()->gregorianYear();
127
+		$death_year_est = $death_year === 0 ? $indi->getEstimatedDeathDate()->gregorianYear() : $death_year;
128
+
129
+		$this->tmp_sosa_table[] = [
130
+			'indi' => $indi->xref(),
131
+			'sosa' => $sosa,
132
+			'birth_year' => $birth_year === 0 ? null : $birth_year,
133
+			'birth_year_est' => $birth_year_est === 0 ? null : $birth_year_est,
134
+			'death_year' => $death_year === 0 ? null : $death_year,
135
+			'death_year_est' => $death_year_est === 0 ? null : $death_year_est
136
+		];
137
+
138
+		$this->flushTmpSosaTable();
139
+
140
+		if (
141
+			($fam = $indi->childFamilies()->first()) !== null
142
+			&& $this->sosa_records_service->generation($sosa) < $this->max_generations
143
+		) {
144
+			/** @var \Fisharebest\Webtrees\Family $fam */
145
+			if (($husb = $fam->husband()) !== null) {
146
+				$this->addNode($husb, 2 * $sosa);
147
+			}
148
+			if (($wife = $fam->wife()) !== null) {
149
+				$this->addNode($wife, 2 * $sosa + 1);
150
+			}
151
+		}
152
+	}
153
+
154
+	/**
155
+	 * Write sosas in the table, if the number of items is superior to the limit, or if forced.
156
+	 *
157
+	 * @param bool $force Should the flush be forced
158
+	 */
159
+	private function flushTmpSosaTable($force = false): void
160
+	{
161
+		if ($force || count($this->tmp_sosa_table) >= self::TMP_SOSA_TABLE_LIMIT) {
162
+			$this->sosa_records_service->insertOrUpdate($this->tree, $this->user, $this->tmp_sosa_table);
163
+			$this->tmp_sosa_table = array();
164
+		}
165
+	}
166 166
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -2 removed lines patch added patch discarded remove patch
@@ -74,8 +74,7 @@
 block discarded – undo
74 74
         $this->tmp_sosa_table = array();
75 75
         $max_gen_setting = $tree->getUserPreference($user, 'MAJ_SOSA_MAX_GEN');
76 76
         $this->max_generations = is_numeric($max_gen_setting) ?
77
-            (int) $max_gen_setting :
78
-            $this->sosa_records_service->maxSystemGenerations();
77
+            (int)$max_gen_setting : $this->sosa_records_service->maxSystemGenerations();
79 78
     }
80 79
 
81 80
     /**
Please login to merge, or discard this patch.
app/Module/Sosa/Services/SosaRecordsService.php 2 patches
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -88,8 +88,8 @@  discard block
 block discarded – undo
88 88
     public function sosaNumbers(Tree $tree, UserInterface $user, Individual $indi): Collection
89 89
     {
90 90
         return Registry::cache()->array()->remember(
91
-            'sosanumbers-' . $indi->xref() . '@' . $tree->id() . '-' . $user->id(),
92
-            function () use ($tree, $user, $indi): Collection {
91
+            'sosanumbers-'.$indi->xref().'@'.$tree->id().'-'.$user->id(),
92
+            function() use ($tree, $user, $indi): Collection {
93 93
                 return DB::table('maj_sosa')
94 94
                     ->select(['majs_sosa', 'majs_gen'])
95 95
                     ->where('majs_gedcom_id', '=', $tree->id())
@@ -149,14 +149,14 @@  discard block
 block discarded – undo
149 149
     {
150 150
         $table_prefix = DB::connection()->getTablePrefix();
151 151
         return DB::table('families')
152
-            ->join('maj_sosa AS sosa_husb', function (JoinClause $join) use ($tree, $user): void {
152
+            ->join('maj_sosa AS sosa_husb', function(JoinClause $join) use ($tree, $user): void {
153 153
                 // Link to family husband
154 154
                 $join->on('families.f_file', '=', 'sosa_husb.majs_gedcom_id')
155 155
                     ->on('families.f_husb', '=', 'sosa_husb.majs_i_id')
156 156
                     ->where('sosa_husb.majs_gedcom_id', '=', $tree->id())
157 157
                     ->where('sosa_husb.majs_user_id', '=', $user->id());
158 158
             })
159
-            ->join('maj_sosa AS sosa_wife', function (JoinClause $join) use ($tree, $user): void {
159
+            ->join('maj_sosa AS sosa_wife', function(JoinClause $join) use ($tree, $user): void {
160 160
                 // Link to family husband
161 161
                 $join->on('families.f_file', '=', 'sosa_wife.majs_gedcom_id')
162 162
                 ->on('families.f_wife', '=', 'sosa_wife.majs_i_id')
@@ -165,7 +165,7 @@  discard block
 block discarded – undo
165 165
             })
166 166
             ->select(['sosa_husb.majs_sosa', 'families.f_id'])
167 167
             ->where('sosa_husb.majs_gen', '=', $gen)
168
-            ->whereRaw($table_prefix . 'sosa_husb.majs_sosa + 1 = ' . $table_prefix . 'sosa_wife.majs_sosa')
168
+            ->whereRaw($table_prefix.'sosa_husb.majs_sosa + 1 = '.$table_prefix.'sosa_wife.majs_sosa')
169 169
             ->orderBy('sosa_husb.majs_sosa')
170 170
             ->get();
171 171
     }
@@ -188,28 +188,28 @@  discard block
 block discarded – undo
188 188
         $table_prefix = DB::connection()->getTablePrefix();
189 189
         return DB::table('maj_sosa AS sosa')
190 190
             ->select(['sosa.majs_i_id', 'sosa_fat.majs_i_id AS majs_fat_id', 'sosa_mot.majs_i_id AS majs_mot_id'])
191
-            ->selectRaw('MIN(' . $table_prefix . 'sosa.majs_sosa) AS majs_sosa')
192
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
191
+            ->selectRaw('MIN('.$table_prefix.'sosa.majs_sosa) AS majs_sosa')
192
+            ->leftJoin('maj_sosa AS sosa_fat', function(JoinClause $join) use ($tree, $user, $table_prefix): void {
193 193
                 // Link to sosa's father
194
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
194
+                $join->whereRaw($table_prefix.'sosa_fat.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa')
195 195
                     ->where('sosa_fat.majs_gedcom_id', '=', $tree->id())
196 196
                     ->where('sosa_fat.majs_user_id', '=', $user->id());
197 197
             })
198
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
198
+            ->leftJoin('maj_sosa AS sosa_mot', function(JoinClause $join) use ($tree, $user, $table_prefix): void {
199 199
                 // Link to sosa's mother
200
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
200
+                $join->whereRaw($table_prefix.'sosa_mot.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa + 1')
201 201
                     ->where('sosa_mot.majs_gedcom_id', '=', $tree->id())
202 202
                     ->where('sosa_mot.majs_user_id', '=', $user->id());
203 203
             })
204 204
             ->where('sosa.majs_gedcom_id', '=', $tree->id())
205 205
             ->where('sosa.majs_user_id', '=', $user->id())
206 206
             ->where('sosa.majs_gen', '=', $gen - 1)
207
-            ->where(function (Builder $query): void {
207
+            ->where(function(Builder $query): void {
208 208
                 $query->whereNull('sosa_fat.majs_i_id')
209 209
                     ->orWhereNull('sosa_mot.majs_i_id');
210 210
             })
211 211
             ->groupBy('sosa.majs_i_id', 'sosa_fat.majs_i_id', 'sosa_mot.majs_i_id')
212
-            ->orderByRaw('MIN(' . $table_prefix . 'sosa.majs_sosa)')
212
+            ->orderByRaw('MIN('.$table_prefix.'sosa.majs_sosa)')
213 213
             ->get();
214 214
     }
215 215
 
@@ -261,29 +261,29 @@  discard block
 block discarded – undo
261 261
         $has_records = false;
262 262
         foreach ($sosa_records as $i => $row) {
263 263
             $gen = $this->generation($row['sosa']);
264
-            if ($gen <=  $this->maxSystemGenerations()) {
264
+            if ($gen <= $this->maxSystemGenerations()) {
265 265
                 $has_records = true;
266 266
                 if ($mass_update) {
267
-                    $bindings_placeholders[] = '(:tree_id' . $i . ', :user_id' . $i . ', :sosa' . $i . ',' .
268
-                        ' :indi_id' . $i . ', :gen' . $i . ',' .
269
-                        ' :byear' . $i . ', :byearest' . $i . ', :dyear' . $i . ', :dyearest' . $i . ')';
267
+                    $bindings_placeholders[] = '(:tree_id'.$i.', :user_id'.$i.', :sosa'.$i.','.
268
+                        ' :indi_id'.$i.', :gen'.$i.','.
269
+                        ' :byear'.$i.', :byearest'.$i.', :dyear'.$i.', :dyearest'.$i.')';
270 270
                     $bindings_values = array_merge(
271 271
                         $bindings_values,
272 272
                         [
273
-                            'tree_id' . $i => $tree->id(),
274
-                            'user_id' . $i => $user->id(),
275
-                            'sosa' . $i => $row['sosa'],
276
-                            'indi_id' . $i => $row['indi'],
277
-                            'gen' . $i => $gen,
278
-                            'byear' . $i => $row['birth_year'],
279
-                            'byearest' . $i => $row['birth_year_est'],
280
-                            'dyear' . $i => $row['death_year'],
281
-                            'dyearest' . $i => $row['death_year_est']
273
+                            'tree_id'.$i => $tree->id(),
274
+                            'user_id'.$i => $user->id(),
275
+                            'sosa'.$i => $row['sosa'],
276
+                            'indi_id'.$i => $row['indi'],
277
+                            'gen'.$i => $gen,
278
+                            'byear'.$i => $row['birth_year'],
279
+                            'byearest'.$i => $row['birth_year_est'],
280
+                            'dyear'.$i => $row['death_year'],
281
+                            'dyearest'.$i => $row['death_year_est']
282 282
                         ]
283 283
                     );
284 284
                 } else {
285 285
                     DB::table('maj_sosa')->updateOrInsert(
286
-                        [ 'majs_gedcom_id' => $tree->id(), 'majs_user_id' => $user->id(), 'majs_sosa' => $row['sosa']],
286
+                        ['majs_gedcom_id' => $tree->id(), 'majs_user_id' => $user->id(), 'majs_sosa' => $row['sosa']],
287 287
                         [
288 288
                             'majs_i_id' => $row['indi'],
289 289
                             'majs_gen' => $gen,
@@ -299,12 +299,12 @@  discard block
 block discarded – undo
299 299
 
300 300
         if ($has_records && $mass_update) {
301 301
             DB::connection()->statement(
302
-                'INSERT INTO `' . DB::connection()->getTablePrefix() . 'maj_sosa`' .
303
-                ' (majs_gedcom_id, majs_user_id, majs_sosa,' .
304
-                '   majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
305
-                ' VALUES ' . implode(',', $bindings_placeholders) .
306
-                ' ON DUPLICATE KEY UPDATE majs_i_id = VALUES(majs_i_id), majs_gen = VALUES(majs_gen),' .
307
-                '   majs_birth_year = VALUES(majs_birth_year), majs_birth_year_est = VALUES(majs_birth_year_est),' .
302
+                'INSERT INTO `'.DB::connection()->getTablePrefix().'maj_sosa`'.
303
+                ' (majs_gedcom_id, majs_user_id, majs_sosa,'.
304
+                '   majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)'.
305
+                ' VALUES '.implode(',', $bindings_placeholders).
306
+                ' ON DUPLICATE KEY UPDATE majs_i_id = VALUES(majs_i_id), majs_gen = VALUES(majs_gen),'.
307
+                '   majs_birth_year = VALUES(majs_birth_year), majs_birth_year_est = VALUES(majs_birth_year_est),'.
308 308
                 '   majs_death_year = VALUES(majs_death_year), majs_death_year_est = VALUES(majs_death_year_est)',
309 309
                 $bindings_values
310 310
             );
Please login to merge, or discard this patch.
Indentation   +275 added lines, -275 removed lines patch added patch discarded remove patch
@@ -30,294 +30,294 @@
 block discarded – undo
30 30
  */
31 31
 class SosaRecordsService
32 32
 {
33
-    private ?int $max_system_generations = null;
33
+	private ?int $max_system_generations = null;
34 34
 
35
-    /**
36
-     * Maximum number of generation the system is able to hold.
37
-     * This is based on the size of the bigint SQL type (2^63) and the maximum PHP integer type
38
-     *
39
-     * @return int
40
-     */
41
-    public function maxSystemGenerations(): int
42
-    {
43
-        if ($this->max_system_generations === null) {
44
-            $this->max_system_generations = min(63, $this->generation(PHP_INT_MAX));
45
-        }
46
-        return $this->max_system_generations;
47
-    }
35
+	/**
36
+	 * Maximum number of generation the system is able to hold.
37
+	 * This is based on the size of the bigint SQL type (2^63) and the maximum PHP integer type
38
+	 *
39
+	 * @return int
40
+	 */
41
+	public function maxSystemGenerations(): int
42
+	{
43
+		if ($this->max_system_generations === null) {
44
+			$this->max_system_generations = min(63, $this->generation(PHP_INT_MAX));
45
+		}
46
+		return $this->max_system_generations;
47
+	}
48 48
 
49
-    /**
50
-     * Calculate the generation of a sosa
51
-     * Sosa 1 is of generation 1.
52
-     *
53
-     * @param int $sosa
54
-     * @return int
55
-     */
56
-    public function generation(int $sosa): int
57
-    {
58
-        return BigInteger::of($sosa)->getBitLength();
59
-    }
49
+	/**
50
+	 * Calculate the generation of a sosa
51
+	 * Sosa 1 is of generation 1.
52
+	 *
53
+	 * @param int $sosa
54
+	 * @return int
55
+	 */
56
+	public function generation(int $sosa): int
57
+	{
58
+		return BigInteger::of($sosa)->getBitLength();
59
+	}
60 60
 
61
-    /**
62
-     * Calculate the descendant sosa of the given sosa, at the given generation.
63
-     * For instance, the descendant of the Sosa 14 at generation 2 is Sosa 3 (mother).
64
-     *
65
-     * @param int $sosa
66
-     * @param int $gen
67
-     * @return int
68
-     */
69
-    public function sosaDescendantOf(int $sosa, int $gen): int
70
-    {
71
-        $gen_sosa = $this->generation($sosa);
72
-        return $gen_sosa <= $gen ? $sosa : BigInteger::of($sosa)
73
-            ->dividedBy(BigInteger::of(2)->power($this->generation($sosa) - $gen), RoundingMode::DOWN)
74
-            ->toInt();
75
-    }
61
+	/**
62
+	 * Calculate the descendant sosa of the given sosa, at the given generation.
63
+	 * For instance, the descendant of the Sosa 14 at generation 2 is Sosa 3 (mother).
64
+	 *
65
+	 * @param int $sosa
66
+	 * @param int $gen
67
+	 * @return int
68
+	 */
69
+	public function sosaDescendantOf(int $sosa, int $gen): int
70
+	{
71
+		$gen_sosa = $this->generation($sosa);
72
+		return $gen_sosa <= $gen ? $sosa : BigInteger::of($sosa)
73
+			->dividedBy(BigInteger::of(2)->power($this->generation($sosa) - $gen), RoundingMode::DOWN)
74
+			->toInt();
75
+	}
76 76
 
77
-    /**
78
-     * Check whether an individual is a Sosa ancestor.
79
-     *
80
-     * @param Tree $tree
81
-     * @param UserInterface $user
82
-     * @param Individual $indi
83
-     * @return bool
84
-     */
85
-    public function isSosa(Tree $tree, UserInterface $user, Individual $indi): bool
86
-    {
87
-        return $this->sosaNumbers($tree, $user, $indi)->count() > 0;
88
-    }
77
+	/**
78
+	 * Check whether an individual is a Sosa ancestor.
79
+	 *
80
+	 * @param Tree $tree
81
+	 * @param UserInterface $user
82
+	 * @param Individual $indi
83
+	 * @return bool
84
+	 */
85
+	public function isSosa(Tree $tree, UserInterface $user, Individual $indi): bool
86
+	{
87
+		return $this->sosaNumbers($tree, $user, $indi)->count() > 0;
88
+	}
89 89
 
90
-    /**
91
-     * Returns all Sosa numbers associated to an Individual
92
-     *
93
-     * @param Tree $tree
94
-     * @param UserInterface $user
95
-     * @param Individual $indi
96
-     * @return Collection<int, int>
97
-     */
98
-    public function sosaNumbers(Tree $tree, UserInterface $user, Individual $indi): Collection
99
-    {
100
-        return Registry::cache()->array()->remember(
101
-            'sosanumbers-' . $indi->xref() . '@' . $tree->id() . '-' . $user->id(),
102
-            function () use ($tree, $user, $indi): Collection {
103
-                return DB::table('maj_sosa')
104
-                    ->select(['majs_sosa', 'majs_gen'])
105
-                    ->where('majs_gedcom_id', '=', $tree->id())
106
-                    ->where('majs_user_id', '=', $user->id())
107
-                    ->where('majs_i_id', '=', $indi->xref())
108
-                    ->orderBy('majs_sosa')
109
-                    ->get()->pluck('majs_gen', 'majs_sosa');
110
-            }
111
-        );
112
-    }
90
+	/**
91
+	 * Returns all Sosa numbers associated to an Individual
92
+	 *
93
+	 * @param Tree $tree
94
+	 * @param UserInterface $user
95
+	 * @param Individual $indi
96
+	 * @return Collection<int, int>
97
+	 */
98
+	public function sosaNumbers(Tree $tree, UserInterface $user, Individual $indi): Collection
99
+	{
100
+		return Registry::cache()->array()->remember(
101
+			'sosanumbers-' . $indi->xref() . '@' . $tree->id() . '-' . $user->id(),
102
+			function () use ($tree, $user, $indi): Collection {
103
+				return DB::table('maj_sosa')
104
+					->select(['majs_sosa', 'majs_gen'])
105
+					->where('majs_gedcom_id', '=', $tree->id())
106
+					->where('majs_user_id', '=', $user->id())
107
+					->where('majs_i_id', '=', $indi->xref())
108
+					->orderBy('majs_sosa')
109
+					->get()->pluck('majs_gen', 'majs_sosa');
110
+			}
111
+		);
112
+	}
113 113
 
114
-    /**
115
-     * Return a list of the Sosa ancestors across all generation
116
-     *
117
-     * @param Tree $tree
118
-     * @param UserInterface $user
119
-     * @return Collection<\stdClass>
120
-     */
121
-    public function listAncestors(Tree $tree, UserInterface $user): Collection
122
-    {
123
-        return DB::table('maj_sosa')
124
-            ->select(['majs_sosa', 'majs_i_id'])
125
-            ->where('majs_gedcom_id', '=', $tree->id())
126
-            ->where('majs_user_id', '=', $user->id())
127
-            ->orderBy('majs_sosa')
128
-            ->get();
129
-    }
114
+	/**
115
+	 * Return a list of the Sosa ancestors across all generation
116
+	 *
117
+	 * @param Tree $tree
118
+	 * @param UserInterface $user
119
+	 * @return Collection<\stdClass>
120
+	 */
121
+	public function listAncestors(Tree $tree, UserInterface $user): Collection
122
+	{
123
+		return DB::table('maj_sosa')
124
+			->select(['majs_sosa', 'majs_i_id'])
125
+			->where('majs_gedcom_id', '=', $tree->id())
126
+			->where('majs_user_id', '=', $user->id())
127
+			->orderBy('majs_sosa')
128
+			->get();
129
+	}
130 130
 
131
-    /**
132
-     * Return a list of the Sosa ancestors at a given generation
133
-     *
134
-     * @param Tree $tree
135
-     * @param UserInterface $user
136
-     * @param int $gen
137
-     * @return Collection<\stdClass>
138
-     */
139
-    public function listAncestorsAtGeneration(Tree $tree, UserInterface $user, int $gen): Collection
140
-    {
141
-        return DB::table('maj_sosa')
142
-            ->select(['majs_sosa', 'majs_i_id'])
143
-            ->where('majs_gedcom_id', '=', $tree->id())
144
-            ->where('majs_user_id', '=', $user->id())
145
-            ->where('majs_gen', '=', $gen)
146
-            ->orderBy('majs_sosa')
147
-            ->get();
148
-    }
131
+	/**
132
+	 * Return a list of the Sosa ancestors at a given generation
133
+	 *
134
+	 * @param Tree $tree
135
+	 * @param UserInterface $user
136
+	 * @param int $gen
137
+	 * @return Collection<\stdClass>
138
+	 */
139
+	public function listAncestorsAtGeneration(Tree $tree, UserInterface $user, int $gen): Collection
140
+	{
141
+		return DB::table('maj_sosa')
142
+			->select(['majs_sosa', 'majs_i_id'])
143
+			->where('majs_gedcom_id', '=', $tree->id())
144
+			->where('majs_user_id', '=', $user->id())
145
+			->where('majs_gen', '=', $gen)
146
+			->orderBy('majs_sosa')
147
+			->get();
148
+	}
149 149
 
150
-    /**
151
-     * Return a list of the Sosa families at a given generation
152
-     *
153
-     * @param Tree $tree
154
-     * @param UserInterface $user
155
-     * @param int $gen
156
-     * @return Collection<\stdClass>
157
-     */
158
-    public function listAncestorFamiliesAtGeneration(Tree $tree, UserInterface $user, int $gen): Collection
159
-    {
160
-        $table_prefix = DB::connection()->getTablePrefix();
161
-        return DB::table('families')
162
-            ->join('maj_sosa AS sosa_husb', function (JoinClause $join) use ($tree, $user): void {
163
-                // Link to family husband
164
-                $join->on('families.f_file', '=', 'sosa_husb.majs_gedcom_id')
165
-                    ->on('families.f_husb', '=', 'sosa_husb.majs_i_id')
166
-                    ->where('sosa_husb.majs_gedcom_id', '=', $tree->id())
167
-                    ->where('sosa_husb.majs_user_id', '=', $user->id());
168
-            })
169
-            ->join('maj_sosa AS sosa_wife', function (JoinClause $join) use ($tree, $user): void {
170
-                // Link to family husband
171
-                $join->on('families.f_file', '=', 'sosa_wife.majs_gedcom_id')
172
-                ->on('families.f_wife', '=', 'sosa_wife.majs_i_id')
173
-                ->where('sosa_wife.majs_gedcom_id', '=', $tree->id())
174
-                ->where('sosa_wife.majs_user_id', '=', $user->id());
175
-            })
176
-            ->select(['sosa_husb.majs_sosa', 'families.f_id'])
177
-            ->where('sosa_husb.majs_gen', '=', $gen)
178
-            ->whereRaw($table_prefix . 'sosa_husb.majs_sosa + 1 = ' . $table_prefix . 'sosa_wife.majs_sosa')
179
-            ->orderBy('sosa_husb.majs_sosa')
180
-            ->get();
181
-    }
150
+	/**
151
+	 * Return a list of the Sosa families at a given generation
152
+	 *
153
+	 * @param Tree $tree
154
+	 * @param UserInterface $user
155
+	 * @param int $gen
156
+	 * @return Collection<\stdClass>
157
+	 */
158
+	public function listAncestorFamiliesAtGeneration(Tree $tree, UserInterface $user, int $gen): Collection
159
+	{
160
+		$table_prefix = DB::connection()->getTablePrefix();
161
+		return DB::table('families')
162
+			->join('maj_sosa AS sosa_husb', function (JoinClause $join) use ($tree, $user): void {
163
+				// Link to family husband
164
+				$join->on('families.f_file', '=', 'sosa_husb.majs_gedcom_id')
165
+					->on('families.f_husb', '=', 'sosa_husb.majs_i_id')
166
+					->where('sosa_husb.majs_gedcom_id', '=', $tree->id())
167
+					->where('sosa_husb.majs_user_id', '=', $user->id());
168
+			})
169
+			->join('maj_sosa AS sosa_wife', function (JoinClause $join) use ($tree, $user): void {
170
+				// Link to family husband
171
+				$join->on('families.f_file', '=', 'sosa_wife.majs_gedcom_id')
172
+				->on('families.f_wife', '=', 'sosa_wife.majs_i_id')
173
+				->where('sosa_wife.majs_gedcom_id', '=', $tree->id())
174
+				->where('sosa_wife.majs_user_id', '=', $user->id());
175
+			})
176
+			->select(['sosa_husb.majs_sosa', 'families.f_id'])
177
+			->where('sosa_husb.majs_gen', '=', $gen)
178
+			->whereRaw($table_prefix . 'sosa_husb.majs_sosa + 1 = ' . $table_prefix . 'sosa_wife.majs_sosa')
179
+			->orderBy('sosa_husb.majs_sosa')
180
+			->get();
181
+	}
182 182
 
183
-    /**
184
-     * Return a list of Sosa ancestors missing at a given generation.
185
-     * It includes the reference of either parent if it is known.
186
-     *
187
-     * @param Tree $tree
188
-     * @param UserInterface $user
189
-     * @param int $gen
190
-     * @return Collection<\stdClass>
191
-     */
192
-    public function listMissingAncestorsAtGeneration(Tree $tree, UserInterface $user, int $gen): Collection
193
-    {
194
-        if ($gen == 1) {
195
-            return collect();
196
-        }
183
+	/**
184
+	 * Return a list of Sosa ancestors missing at a given generation.
185
+	 * It includes the reference of either parent if it is known.
186
+	 *
187
+	 * @param Tree $tree
188
+	 * @param UserInterface $user
189
+	 * @param int $gen
190
+	 * @return Collection<\stdClass>
191
+	 */
192
+	public function listMissingAncestorsAtGeneration(Tree $tree, UserInterface $user, int $gen): Collection
193
+	{
194
+		if ($gen == 1) {
195
+			return collect();
196
+		}
197 197
 
198
-        $table_prefix = DB::connection()->getTablePrefix();
199
-        return DB::table('maj_sosa AS sosa')
200
-            ->select(['sosa.majs_i_id', 'sosa_fat.majs_i_id AS majs_fat_id', 'sosa_mot.majs_i_id AS majs_mot_id'])
201
-            ->selectRaw('MIN(' . $table_prefix . 'sosa.majs_sosa) AS majs_sosa')
202
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
203
-                // Link to sosa's father
204
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
205
-                    ->where('sosa_fat.majs_gedcom_id', '=', $tree->id())
206
-                    ->where('sosa_fat.majs_user_id', '=', $user->id());
207
-            })
208
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
209
-                // Link to sosa's mother
210
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
211
-                    ->where('sosa_mot.majs_gedcom_id', '=', $tree->id())
212
-                    ->where('sosa_mot.majs_user_id', '=', $user->id());
213
-            })
214
-            ->where('sosa.majs_gedcom_id', '=', $tree->id())
215
-            ->where('sosa.majs_user_id', '=', $user->id())
216
-            ->where('sosa.majs_gen', '=', $gen - 1)
217
-            ->where(function (Builder $query): void {
218
-                $query->whereNull('sosa_fat.majs_i_id')
219
-                    ->orWhereNull('sosa_mot.majs_i_id');
220
-            })
221
-            ->groupBy('sosa.majs_i_id', 'sosa_fat.majs_i_id', 'sosa_mot.majs_i_id')
222
-            ->orderByRaw('MIN(' . $table_prefix . 'sosa.majs_sosa)')
223
-            ->get();
224
-    }
198
+		$table_prefix = DB::connection()->getTablePrefix();
199
+		return DB::table('maj_sosa AS sosa')
200
+			->select(['sosa.majs_i_id', 'sosa_fat.majs_i_id AS majs_fat_id', 'sosa_mot.majs_i_id AS majs_mot_id'])
201
+			->selectRaw('MIN(' . $table_prefix . 'sosa.majs_sosa) AS majs_sosa')
202
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
203
+				// Link to sosa's father
204
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
205
+					->where('sosa_fat.majs_gedcom_id', '=', $tree->id())
206
+					->where('sosa_fat.majs_user_id', '=', $user->id());
207
+			})
208
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($tree, $user, $table_prefix): void {
209
+				// Link to sosa's mother
210
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
211
+					->where('sosa_mot.majs_gedcom_id', '=', $tree->id())
212
+					->where('sosa_mot.majs_user_id', '=', $user->id());
213
+			})
214
+			->where('sosa.majs_gedcom_id', '=', $tree->id())
215
+			->where('sosa.majs_user_id', '=', $user->id())
216
+			->where('sosa.majs_gen', '=', $gen - 1)
217
+			->where(function (Builder $query): void {
218
+				$query->whereNull('sosa_fat.majs_i_id')
219
+					->orWhereNull('sosa_mot.majs_i_id');
220
+			})
221
+			->groupBy('sosa.majs_i_id', 'sosa_fat.majs_i_id', 'sosa_mot.majs_i_id')
222
+			->orderByRaw('MIN(' . $table_prefix . 'sosa.majs_sosa)')
223
+			->get();
224
+	}
225 225
 
226
-    /**
227
-     * Remove all Sosa entries related to the gedcom file and user
228
-     *
229
-     * @param Tree $tree
230
-     * @param UserInterface $user
231
-     */
232
-    public function deleteAll(Tree $tree, UserInterface $user): void
233
-    {
234
-        DB::table('maj_sosa')
235
-            ->where('majs_gedcom_id', '=', $tree->id())
236
-            ->where('majs_user_id', '=', $user->id())
237
-            ->delete();
238
-    }
226
+	/**
227
+	 * Remove all Sosa entries related to the gedcom file and user
228
+	 *
229
+	 * @param Tree $tree
230
+	 * @param UserInterface $user
231
+	 */
232
+	public function deleteAll(Tree $tree, UserInterface $user): void
233
+	{
234
+		DB::table('maj_sosa')
235
+			->where('majs_gedcom_id', '=', $tree->id())
236
+			->where('majs_user_id', '=', $user->id())
237
+			->delete();
238
+	}
239 239
 
240
-    /**
241
-     *
242
-     * @param Tree $tree
243
-     * @param UserInterface $user
244
-     * @param int $sosa
245
-     */
246
-    public function deleteAncestorsFrom(Tree $tree, UserInterface $user, int $sosa): void
247
-    {
248
-        DB::table('maj_sosa')
249
-            ->where('majs_gedcom_id', '=', $tree->id())
250
-            ->where('majs_user_id', '=', $user->id())
251
-            ->where('majs_sosa', '>=', $sosa)
252
-            ->whereRaw(
253
-                'FLOOR(majs_sosa / (POW(2, (majs_gen - ?)))) = ?',
254
-                [$this->generation($sosa), $sosa]
255
-            )
256
-            ->delete();
257
-    }
240
+	/**
241
+	 *
242
+	 * @param Tree $tree
243
+	 * @param UserInterface $user
244
+	 * @param int $sosa
245
+	 */
246
+	public function deleteAncestorsFrom(Tree $tree, UserInterface $user, int $sosa): void
247
+	{
248
+		DB::table('maj_sosa')
249
+			->where('majs_gedcom_id', '=', $tree->id())
250
+			->where('majs_user_id', '=', $user->id())
251
+			->where('majs_sosa', '>=', $sosa)
252
+			->whereRaw(
253
+				'FLOOR(majs_sosa / (POW(2, (majs_gen - ?)))) = ?',
254
+				[$this->generation($sosa), $sosa]
255
+			)
256
+			->delete();
257
+	}
258 258
 
259
-    /**
260
-     * Insert (or update if already existing) a list of Sosa individuals
261
-     *
262
-     * @param Tree $tree
263
-     * @param UserInterface $user
264
-     * @param array<array<string,mixed>> $sosa_records
265
-     */
266
-    public function insertOrUpdate(Tree $tree, UserInterface $user, array $sosa_records): void
267
-    {
268
-        $mass_update = DB::connection()->getDriverName() === 'mysql';
259
+	/**
260
+	 * Insert (or update if already existing) a list of Sosa individuals
261
+	 *
262
+	 * @param Tree $tree
263
+	 * @param UserInterface $user
264
+	 * @param array<array<string,mixed>> $sosa_records
265
+	 */
266
+	public function insertOrUpdate(Tree $tree, UserInterface $user, array $sosa_records): void
267
+	{
268
+		$mass_update = DB::connection()->getDriverName() === 'mysql';
269 269
 
270
-        $bindings_placeholders = $bindings_values = [];
271
-        $has_records = false;
272
-        foreach ($sosa_records as $i => $row) {
273
-            $gen = $this->generation($row['sosa']);
274
-            if ($gen <=  $this->maxSystemGenerations()) {
275
-                $has_records = true;
276
-                if ($mass_update) {
277
-                    $bindings_placeholders[] = '(:tree_id' . $i . ', :user_id' . $i . ', :sosa' . $i . ',' .
278
-                        ' :indi_id' . $i . ', :gen' . $i . ',' .
279
-                        ' :byear' . $i . ', :byearest' . $i . ', :dyear' . $i . ', :dyearest' . $i . ')';
280
-                    $bindings_values = array_merge(
281
-                        $bindings_values,
282
-                        [
283
-                            'tree_id' . $i => $tree->id(),
284
-                            'user_id' . $i => $user->id(),
285
-                            'sosa' . $i => $row['sosa'],
286
-                            'indi_id' . $i => $row['indi'],
287
-                            'gen' . $i => $gen,
288
-                            'byear' . $i => $row['birth_year'],
289
-                            'byearest' . $i => $row['birth_year_est'],
290
-                            'dyear' . $i => $row['death_year'],
291
-                            'dyearest' . $i => $row['death_year_est']
292
-                        ]
293
-                    );
294
-                } else {
295
-                    DB::table('maj_sosa')->updateOrInsert(
296
-                        [ 'majs_gedcom_id' => $tree->id(), 'majs_user_id' => $user->id(), 'majs_sosa' => $row['sosa']],
297
-                        [
298
-                            'majs_i_id' => $row['indi'],
299
-                            'majs_gen' => $gen,
300
-                            'majs_birth_year' => $row['birth_year'],
301
-                            'majs_birth_year_est' => $row['birth_year_est'],
302
-                            'majs_death_year' => $row['death_year'],
303
-                            'majs_death_year_est' => $row['death_year_est']
304
-                        ]
305
-                    );
306
-                }
307
-            }
308
-        }
270
+		$bindings_placeholders = $bindings_values = [];
271
+		$has_records = false;
272
+		foreach ($sosa_records as $i => $row) {
273
+			$gen = $this->generation($row['sosa']);
274
+			if ($gen <=  $this->maxSystemGenerations()) {
275
+				$has_records = true;
276
+				if ($mass_update) {
277
+					$bindings_placeholders[] = '(:tree_id' . $i . ', :user_id' . $i . ', :sosa' . $i . ',' .
278
+						' :indi_id' . $i . ', :gen' . $i . ',' .
279
+						' :byear' . $i . ', :byearest' . $i . ', :dyear' . $i . ', :dyearest' . $i . ')';
280
+					$bindings_values = array_merge(
281
+						$bindings_values,
282
+						[
283
+							'tree_id' . $i => $tree->id(),
284
+							'user_id' . $i => $user->id(),
285
+							'sosa' . $i => $row['sosa'],
286
+							'indi_id' . $i => $row['indi'],
287
+							'gen' . $i => $gen,
288
+							'byear' . $i => $row['birth_year'],
289
+							'byearest' . $i => $row['birth_year_est'],
290
+							'dyear' . $i => $row['death_year'],
291
+							'dyearest' . $i => $row['death_year_est']
292
+						]
293
+					);
294
+				} else {
295
+					DB::table('maj_sosa')->updateOrInsert(
296
+						[ 'majs_gedcom_id' => $tree->id(), 'majs_user_id' => $user->id(), 'majs_sosa' => $row['sosa']],
297
+						[
298
+							'majs_i_id' => $row['indi'],
299
+							'majs_gen' => $gen,
300
+							'majs_birth_year' => $row['birth_year'],
301
+							'majs_birth_year_est' => $row['birth_year_est'],
302
+							'majs_death_year' => $row['death_year'],
303
+							'majs_death_year_est' => $row['death_year_est']
304
+						]
305
+					);
306
+				}
307
+			}
308
+		}
309 309
 
310
-        if ($has_records && $mass_update) {
311
-            DB::connection()->statement(
312
-                'INSERT INTO `' . DB::connection()->getTablePrefix() . 'maj_sosa`' .
313
-                ' (majs_gedcom_id, majs_user_id, majs_sosa,' .
314
-                '   majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
315
-                ' VALUES ' . implode(',', $bindings_placeholders) .
316
-                ' ON DUPLICATE KEY UPDATE majs_i_id = VALUES(majs_i_id), majs_gen = VALUES(majs_gen),' .
317
-                '   majs_birth_year = VALUES(majs_birth_year), majs_birth_year_est = VALUES(majs_birth_year_est),' .
318
-                '   majs_death_year = VALUES(majs_death_year), majs_death_year_est = VALUES(majs_death_year_est)',
319
-                $bindings_values
320
-            );
321
-        }
322
-    }
310
+		if ($has_records && $mass_update) {
311
+			DB::connection()->statement(
312
+				'INSERT INTO `' . DB::connection()->getTablePrefix() . 'maj_sosa`' .
313
+				' (majs_gedcom_id, majs_user_id, majs_sosa,' .
314
+				'   majs_i_id, majs_gen, majs_birth_year, majs_birth_year_est, majs_death_year, majs_death_year_est)' .
315
+				' VALUES ' . implode(',', $bindings_placeholders) .
316
+				' ON DUPLICATE KEY UPDATE majs_i_id = VALUES(majs_i_id), majs_gen = VALUES(majs_gen),' .
317
+				'   majs_birth_year = VALUES(majs_birth_year), majs_birth_year_est = VALUES(majs_birth_year_est),' .
318
+				'   majs_death_year = VALUES(majs_death_year), majs_death_year_est = VALUES(majs_death_year_est)',
319
+				$bindings_values
320
+			);
321
+		}
322
+	}
323 323
 }
Please login to merge, or discard this patch.
app/Module/Sosa/Services/SosaStatisticsService.php 2 patches
Indentation   +500 added lines, -500 removed lines patch added patch discarded remove patch
@@ -30,511 +30,511 @@
 block discarded – undo
30 30
 class SosaStatisticsService
31 31
 {
32 32
 
33
-    /**
34
-     * Reference user
35
-     * @var UserInterface $user
36
-     */
37
-    private $user;
38
-
39
-    /**
40
-     * Reference tree
41
-     * @var Tree $tree
42
-     */
43
-    private $tree;
44
-
45
-    /**
46
-     * Constructor for Sosa Statistics Service
47
-     *
48
-     * @param Tree $tree
49
-     * @param UserInterface $user
50
-     */
51
-    public function __construct(Tree $tree, UserInterface $user)
52
-    {
53
-        $this->tree = $tree;
54
-        $this->user = $user;
55
-    }
56
-
57
-    /**
58
-     * Return the root individual for the reference tree and user.
59
-     *
60
-     * @return Individual|NULL
61
-     */
62
-    public function rootIndividual(): ?Individual
63
-    {
64
-        $root_indi_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
65
-        return Registry::individualFactory()->make($root_indi_id, $this->tree);
66
-    }
67
-
68
-    /**
69
-     * Get the highest generation for the reference tree and user.
70
-     *
71
-     * @return int
72
-     */
73
-    public function maxGeneration(): int
74
-    {
75
-        return (int) DB::table('maj_sosa')
76
-            ->where('majs_gedcom_id', '=', $this->tree->id())
77
-            ->where('majs_user_id', '=', $this->user->id())
78
-            ->max('majs_gen');
79
-    }
80
-
81
-    /**
82
-     * Get the total count of individuals in the tree.
83
-     *
84
-     * @return int
85
-     */
86
-    public function totalIndividuals(): int
87
-    {
88
-        return DB::table('individuals')
89
-            ->where('i_file', '=', $this->tree->id())
90
-            ->count();
91
-    }
92
-
93
-    /**
94
-     * Get the total count of Sosa ancestors for all generations
95
-     *
96
-     * @return int
97
-     */
98
-    public function totalAncestors(): int
99
-    {
100
-        return DB::table('maj_sosa')
101
-            ->where('majs_gedcom_id', '=', $this->tree->id())
102
-            ->where('majs_user_id', '=', $this->user->id())
103
-            ->count();
104
-    }
105
-
106
-    /**
107
-     * Get the total count of Sosa ancestors for a generation
108
-     *
109
-     * @return int
110
-     */
111
-    public function totalAncestorsAtGeneration(int $gen): int
112
-    {
113
-        return DB::table('maj_sosa')
114
-            ->where('majs_gedcom_id', '=', $this->tree->id())
115
-            ->where('majs_user_id', '=', $this->user->id())
116
-            ->where('majs_gen', '=', $gen)
117
-            ->count();
118
-    }
119
-
120
-    /**
121
-     * Get the total count of distinct Sosa ancestors for all generations
122
-     *
123
-     * @return int
124
-     */
125
-    public function totalDistinctAncestors(): int
126
-    {
127
-        return DB::table('maj_sosa')
128
-            ->where('majs_gedcom_id', '=', $this->tree->id())
129
-            ->where('majs_user_id', '=', $this->user->id())
130
-            ->distinct()
131
-            ->count('majs_i_id');
132
-    }
133
-
134
-    /**
135
-     * Get the mean generation time, as the slope of the linear regression of birth years vs generations
136
-     *
137
-     * @return float
138
-     */
139
-    public function meanGenerationTime(): float
140
-    {
141
-        $row = DB::table('maj_sosa')
142
-            ->where('majs_gedcom_id', '=', $this->tree->id())
143
-            ->where('majs_user_id', '=', $this->user->id())
144
-            ->whereNotNull('majs_birth_year')
145
-            ->selectRaw('COUNT(majs_sosa) AS n')
146
-            ->selectRaw('SUM(majs_gen * majs_birth_year) AS sum_xy')
147
-            ->selectRaw('SUM(majs_gen) AS sum_x')
148
-            ->selectRaw('SUM(majs_birth_year) AS sum_y')
149
-            ->selectRaw('SUM(majs_gen * majs_gen) AS sum_x2')
150
-            ->get()->first();
151
-
152
-        return $row->n == 0 ? 0 :
153
-            -($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / ($row->n * $row->sum_x2 - pow($row->sum_x, 2));
154
-    }
155
-
156
-    /**
157
-     * Get the statistic array detailed by generation.
158
-     * Statistics for each generation are:
159
-     *  - The number of Sosa in generation
160
-     *  - The number of Sosa up to generation
161
-     *  - The number of distinct Sosa up to generation
162
-     *  - The year of the first birth in generation
163
-     *  - The year of the first estimated birth in generation
164
-     *  - The year of the last birth in generation
165
-     *  - The year of the last estimated birth in generation
166
-     *  - The average year of birth in generation
167
-     *
168
-     * @return array<int, array<string, int|null>> Statistics array
169
-     */
170
-    public function statisticsByGenerations(): array
171
-    {
172
-        $stats_by_gen = $this->statisticsByGenerationBasicData();
173
-        $cumul_stats_by_gen = $this->statisticsByGenerationCumulativeData();
174
-
175
-        $statistics_by_gen = [];
176
-        foreach ($stats_by_gen as $gen => $stats_gen) {
177
-            $statistics_by_gen[(int) $stats_gen->gen] = array(
178
-                'sosaCount'             =>  (int) $stats_gen->total_sosa,
179
-                'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
180
-                'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
181
-                'firstBirth'            =>  $stats_gen->first_year,
182
-                'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
183
-                'lastBirth'             =>  $stats_gen->last_year,
184
-                'lastEstimatedBirth'    =>  $stats_gen->last_est_year
185
-            );
186
-        }
187
-
188
-        return $statistics_by_gen;
189
-    }
190
-
191
-    /**
192
-     * Returns the basic statistics data by generation.
193
-     *
194
-     * @return Collection<int, \stdClass>
195
-     */
196
-    private function statisticsByGenerationBasicData(): Collection
197
-    {
198
-        return DB::table('maj_sosa')
199
-            ->where('majs_gedcom_id', '=', $this->tree->id())
200
-            ->where('majs_user_id', '=', $this->user->id())
201
-            ->groupBy('majs_gen')
202
-            ->orderBy('majs_gen', 'asc')
203
-            ->select('majs_gen AS gen')
204
-            ->selectRaw('COUNT(majs_sosa) AS total_sosa')
205
-            ->selectRaw('MIN(majs_birth_year) AS first_year')
206
-            ->selectRaw('MIN(majs_birth_year_est) AS first_est_year')
207
-            ->selectRaw('MAX(majs_birth_year) AS last_year')
208
-            ->selectRaw('MAX(majs_birth_year_est) AS last_est_year')
209
-            ->get()->keyBy('gen');
210
-    }
211
-
212
-    /**
213
-     * Returns the cumulative statistics data by generation
214
-     *
215
-     * @return Collection<int, \stdClass>
216
-     */
217
-    private function statisticsByGenerationCumulativeData(): Collection
218
-    {
219
-        $list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
220
-            ->where('majs_gedcom_id', '=', $this->tree->id())
221
-            ->where('majs_user_id', '=', $this->user->id());
222
-
223
-        return DB::table('maj_sosa')
224
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
225
-                $join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
226
-                ->where('majs_gedcom_id', '=', $this->tree->id())
227
-                ->where('majs_user_id', '=', $this->user->id());
228
-            })
229
-            ->groupBy('list_gen.majs_gen')
230
-            ->select('list_gen.majs_gen AS gen')
231
-            ->selectRaw('COUNT(majs_i_id) AS total_cumul')
232
-            ->selectRaw('COUNT(DISTINCT majs_i_id) AS total_distinct_cumul')
233
-            ->selectRaw('1 - COUNT(DISTINCT majs_i_id) / COUNT(majs_i_id) AS pedi_collapse_simple')
234
-            ->get()->keyBy('gen');
235
-    }
236
-
237
-    /**
238
-     * Returns the pedigree collapse improved calculation by generation.
239
-     *
240
-     * Format:
241
-     *  - key : generation
242
-     *  - values:
243
-     *      - pedi_collapse_roots : pedigree collapse of ancestor roots for the generation
244
-     *      - pedi_collapse_xgen : pedigree cross-generation shrinkage for the generation
245
-     *
246
-     * @return array<int, array<string, float>>
247
-     */
248
-    public function pedigreeCollapseByGenerationData(): array
249
-    {
250
-        $table_prefix = DB::connection()->getTablePrefix();
251
-
252
-        $list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
253
-            ->where('majs_gedcom_id', '=', $this->tree->id())
254
-            ->where('majs_user_id', '=', $this->user->id());
255
-
256
-        /* Compute the contributions of nodes of previous generations to the current generation */
257
-        $root_ancestors_contributions = DB::table('maj_sosa AS sosa')
258
-            ->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
259
-            ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
260
-            ->selectRaw(
261
-                '(CASE ' .
262
-                    ' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
263
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
264
-                    ' ELSE 0 ' .
265
-                ' END)' .
266
-                ' + (CASE ' .
267
-                    ' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
268
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
269
-                    ' ELSE 0 ' .
270
-                ' END) contrib'
271
-            )
272
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
273
-                $join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
274
-                    ->where('majs_gedcom_id', '=', $this->tree->id())
275
-                    ->where('majs_user_id', '=', $this->user->id());
276
-            })
277
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
278
-                // Link to sosa's father
279
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
280
-                    ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
281
-                    ->where('sosa_fat.majs_user_id', '=', $this->user->id());
282
-            })
283
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
284
-                // Link to sosa's mother
285
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
286
-                    ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
287
-                    ->where('sosa_mot.majs_user_id', '=', $this->user->id());
288
-            })
289
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
290
-            ->where('sosa.majs_user_id', '=', $this->user->id())
291
-            ->where(function (Builder $query): void {
292
-                $query->whereNull('sosa_fat.majs_i_id')
293
-                ->orWhereNull('sosa_mot.majs_i_id');
294
-            });
295
-
296
-        /* Identify nodes in the generations with ancestors who are also in the same generation.
33
+	/**
34
+	 * Reference user
35
+	 * @var UserInterface $user
36
+	 */
37
+	private $user;
38
+
39
+	/**
40
+	 * Reference tree
41
+	 * @var Tree $tree
42
+	 */
43
+	private $tree;
44
+
45
+	/**
46
+	 * Constructor for Sosa Statistics Service
47
+	 *
48
+	 * @param Tree $tree
49
+	 * @param UserInterface $user
50
+	 */
51
+	public function __construct(Tree $tree, UserInterface $user)
52
+	{
53
+		$this->tree = $tree;
54
+		$this->user = $user;
55
+	}
56
+
57
+	/**
58
+	 * Return the root individual for the reference tree and user.
59
+	 *
60
+	 * @return Individual|NULL
61
+	 */
62
+	public function rootIndividual(): ?Individual
63
+	{
64
+		$root_indi_id = $this->tree->getUserPreference($this->user, 'MAJ_SOSA_ROOT_ID');
65
+		return Registry::individualFactory()->make($root_indi_id, $this->tree);
66
+	}
67
+
68
+	/**
69
+	 * Get the highest generation for the reference tree and user.
70
+	 *
71
+	 * @return int
72
+	 */
73
+	public function maxGeneration(): int
74
+	{
75
+		return (int) DB::table('maj_sosa')
76
+			->where('majs_gedcom_id', '=', $this->tree->id())
77
+			->where('majs_user_id', '=', $this->user->id())
78
+			->max('majs_gen');
79
+	}
80
+
81
+	/**
82
+	 * Get the total count of individuals in the tree.
83
+	 *
84
+	 * @return int
85
+	 */
86
+	public function totalIndividuals(): int
87
+	{
88
+		return DB::table('individuals')
89
+			->where('i_file', '=', $this->tree->id())
90
+			->count();
91
+	}
92
+
93
+	/**
94
+	 * Get the total count of Sosa ancestors for all generations
95
+	 *
96
+	 * @return int
97
+	 */
98
+	public function totalAncestors(): int
99
+	{
100
+		return DB::table('maj_sosa')
101
+			->where('majs_gedcom_id', '=', $this->tree->id())
102
+			->where('majs_user_id', '=', $this->user->id())
103
+			->count();
104
+	}
105
+
106
+	/**
107
+	 * Get the total count of Sosa ancestors for a generation
108
+	 *
109
+	 * @return int
110
+	 */
111
+	public function totalAncestorsAtGeneration(int $gen): int
112
+	{
113
+		return DB::table('maj_sosa')
114
+			->where('majs_gedcom_id', '=', $this->tree->id())
115
+			->where('majs_user_id', '=', $this->user->id())
116
+			->where('majs_gen', '=', $gen)
117
+			->count();
118
+	}
119
+
120
+	/**
121
+	 * Get the total count of distinct Sosa ancestors for all generations
122
+	 *
123
+	 * @return int
124
+	 */
125
+	public function totalDistinctAncestors(): int
126
+	{
127
+		return DB::table('maj_sosa')
128
+			->where('majs_gedcom_id', '=', $this->tree->id())
129
+			->where('majs_user_id', '=', $this->user->id())
130
+			->distinct()
131
+			->count('majs_i_id');
132
+	}
133
+
134
+	/**
135
+	 * Get the mean generation time, as the slope of the linear regression of birth years vs generations
136
+	 *
137
+	 * @return float
138
+	 */
139
+	public function meanGenerationTime(): float
140
+	{
141
+		$row = DB::table('maj_sosa')
142
+			->where('majs_gedcom_id', '=', $this->tree->id())
143
+			->where('majs_user_id', '=', $this->user->id())
144
+			->whereNotNull('majs_birth_year')
145
+			->selectRaw('COUNT(majs_sosa) AS n')
146
+			->selectRaw('SUM(majs_gen * majs_birth_year) AS sum_xy')
147
+			->selectRaw('SUM(majs_gen) AS sum_x')
148
+			->selectRaw('SUM(majs_birth_year) AS sum_y')
149
+			->selectRaw('SUM(majs_gen * majs_gen) AS sum_x2')
150
+			->get()->first();
151
+
152
+		return $row->n == 0 ? 0 :
153
+			-($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / ($row->n * $row->sum_x2 - pow($row->sum_x, 2));
154
+	}
155
+
156
+	/**
157
+	 * Get the statistic array detailed by generation.
158
+	 * Statistics for each generation are:
159
+	 *  - The number of Sosa in generation
160
+	 *  - The number of Sosa up to generation
161
+	 *  - The number of distinct Sosa up to generation
162
+	 *  - The year of the first birth in generation
163
+	 *  - The year of the first estimated birth in generation
164
+	 *  - The year of the last birth in generation
165
+	 *  - The year of the last estimated birth in generation
166
+	 *  - The average year of birth in generation
167
+	 *
168
+	 * @return array<int, array<string, int|null>> Statistics array
169
+	 */
170
+	public function statisticsByGenerations(): array
171
+	{
172
+		$stats_by_gen = $this->statisticsByGenerationBasicData();
173
+		$cumul_stats_by_gen = $this->statisticsByGenerationCumulativeData();
174
+
175
+		$statistics_by_gen = [];
176
+		foreach ($stats_by_gen as $gen => $stats_gen) {
177
+			$statistics_by_gen[(int) $stats_gen->gen] = array(
178
+				'sosaCount'             =>  (int) $stats_gen->total_sosa,
179
+				'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
180
+				'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
181
+				'firstBirth'            =>  $stats_gen->first_year,
182
+				'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
183
+				'lastBirth'             =>  $stats_gen->last_year,
184
+				'lastEstimatedBirth'    =>  $stats_gen->last_est_year
185
+			);
186
+		}
187
+
188
+		return $statistics_by_gen;
189
+	}
190
+
191
+	/**
192
+	 * Returns the basic statistics data by generation.
193
+	 *
194
+	 * @return Collection<int, \stdClass>
195
+	 */
196
+	private function statisticsByGenerationBasicData(): Collection
197
+	{
198
+		return DB::table('maj_sosa')
199
+			->where('majs_gedcom_id', '=', $this->tree->id())
200
+			->where('majs_user_id', '=', $this->user->id())
201
+			->groupBy('majs_gen')
202
+			->orderBy('majs_gen', 'asc')
203
+			->select('majs_gen AS gen')
204
+			->selectRaw('COUNT(majs_sosa) AS total_sosa')
205
+			->selectRaw('MIN(majs_birth_year) AS first_year')
206
+			->selectRaw('MIN(majs_birth_year_est) AS first_est_year')
207
+			->selectRaw('MAX(majs_birth_year) AS last_year')
208
+			->selectRaw('MAX(majs_birth_year_est) AS last_est_year')
209
+			->get()->keyBy('gen');
210
+	}
211
+
212
+	/**
213
+	 * Returns the cumulative statistics data by generation
214
+	 *
215
+	 * @return Collection<int, \stdClass>
216
+	 */
217
+	private function statisticsByGenerationCumulativeData(): Collection
218
+	{
219
+		$list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
220
+			->where('majs_gedcom_id', '=', $this->tree->id())
221
+			->where('majs_user_id', '=', $this->user->id());
222
+
223
+		return DB::table('maj_sosa')
224
+			->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
225
+				$join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
226
+				->where('majs_gedcom_id', '=', $this->tree->id())
227
+				->where('majs_user_id', '=', $this->user->id());
228
+			})
229
+			->groupBy('list_gen.majs_gen')
230
+			->select('list_gen.majs_gen AS gen')
231
+			->selectRaw('COUNT(majs_i_id) AS total_cumul')
232
+			->selectRaw('COUNT(DISTINCT majs_i_id) AS total_distinct_cumul')
233
+			->selectRaw('1 - COUNT(DISTINCT majs_i_id) / COUNT(majs_i_id) AS pedi_collapse_simple')
234
+			->get()->keyBy('gen');
235
+	}
236
+
237
+	/**
238
+	 * Returns the pedigree collapse improved calculation by generation.
239
+	 *
240
+	 * Format:
241
+	 *  - key : generation
242
+	 *  - values:
243
+	 *      - pedi_collapse_roots : pedigree collapse of ancestor roots for the generation
244
+	 *      - pedi_collapse_xgen : pedigree cross-generation shrinkage for the generation
245
+	 *
246
+	 * @return array<int, array<string, float>>
247
+	 */
248
+	public function pedigreeCollapseByGenerationData(): array
249
+	{
250
+		$table_prefix = DB::connection()->getTablePrefix();
251
+
252
+		$list_gen = DB::table('maj_sosa')->select('majs_gen')->distinct()
253
+			->where('majs_gedcom_id', '=', $this->tree->id())
254
+			->where('majs_user_id', '=', $this->user->id());
255
+
256
+		/* Compute the contributions of nodes of previous generations to the current generation */
257
+		$root_ancestors_contributions = DB::table('maj_sosa AS sosa')
258
+			->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
259
+			->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
260
+			->selectRaw(
261
+				'(CASE ' .
262
+					' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
263
+					' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
264
+					' ELSE 0 ' .
265
+				' END)' .
266
+				' + (CASE ' .
267
+					' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
268
+					' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
269
+					' ELSE 0 ' .
270
+				' END) contrib'
271
+			)
272
+			->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
273
+				$join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
274
+					->where('majs_gedcom_id', '=', $this->tree->id())
275
+					->where('majs_user_id', '=', $this->user->id());
276
+			})
277
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
278
+				// Link to sosa's father
279
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
280
+					->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
281
+					->where('sosa_fat.majs_user_id', '=', $this->user->id());
282
+			})
283
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
284
+				// Link to sosa's mother
285
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
286
+					->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
287
+					->where('sosa_mot.majs_user_id', '=', $this->user->id());
288
+			})
289
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
290
+			->where('sosa.majs_user_id', '=', $this->user->id())
291
+			->where(function (Builder $query): void {
292
+				$query->whereNull('sosa_fat.majs_i_id')
293
+				->orWhereNull('sosa_mot.majs_i_id');
294
+			});
295
+
296
+		/* Identify nodes in the generations with ancestors who are also in the same generation.
297 297
          * This is the vertical/generational collapse that will reduce the number or roots.
298 298
          */
299
-        $non_roots_ancestors = DB::table('maj_sosa AS sosa')
300
-            ->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
301
-            ->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
302
-                ' AS full_ancestors')
303
-            ->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
304
-                $join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
305
-                    ->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
306
-                        $table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
307
-                        $table_prefix . 'sosa.majs_sosa')
308
-                    ->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
309
-                    ->where('sosa_anc.majs_user_id', '=', $this->user->id());
310
-            })
311
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
312
-            ->where('sosa.majs_user_id', '=', $this->user->id())
313
-            ->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
314
-                $query->from('maj_sosa AS sosa_gen')
315
-                ->select('sosa_gen.majs_i_id')->distinct()
316
-                ->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
317
-                ->where('sosa_gen.majs_user_id', '=', $this->user->id())
318
-                ->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
319
-            })
320
-            ->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
321
-                'sosa.majs_sosa', 'sosa.majs_i_id']);
322
-
323
-        /* Compute the contribution of the nodes in the generation,
299
+		$non_roots_ancestors = DB::table('maj_sosa AS sosa')
300
+			->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
301
+			->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
302
+				' AS full_ancestors')
303
+			->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
304
+				$join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
305
+					->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
306
+						$table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
307
+						$table_prefix . 'sosa.majs_sosa')
308
+					->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
309
+					->where('sosa_anc.majs_user_id', '=', $this->user->id());
310
+			})
311
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
312
+			->where('sosa.majs_user_id', '=', $this->user->id())
313
+			->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
314
+				$query->from('maj_sosa AS sosa_gen')
315
+				->select('sosa_gen.majs_i_id')->distinct()
316
+				->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
317
+				->where('sosa_gen.majs_user_id', '=', $this->user->id())
318
+				->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
319
+			})
320
+			->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
321
+				'sosa.majs_sosa', 'sosa.majs_i_id']);
322
+
323
+		/* Compute the contribution of the nodes in the generation,
324 324
          * excluding the nodes with ancestors in the same generation.
325 325
          * Nodes with a parent missing are not excluded to cater for the missing one.
326 326
          */
327
-        $known_ancestors_contributions = DB::table('maj_sosa AS sosa')
328
-            ->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
329
-            ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
330
-            ->selectRaw('1 AS contrib')
331
-            ->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
332
-                $join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
333
-                    ->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
334
-                    ->where('nonroot.full_ancestors', '>', 0)
335
-                    ->where('nonroot.majs_gedcom_id', '=', $this->tree->id())
336
-                    ->where('nonroot.majs_user_id', '=', $this->user->id());
337
-            })
338
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
339
-            ->where('sosa.majs_user_id', '=', $this->user->id())
340
-            ->whereNull('nonroot.majs_sosa');
341
-
342
-        /* Aggregate both queries, and calculate the sum of contributions by generation roots.
327
+		$known_ancestors_contributions = DB::table('maj_sosa AS sosa')
328
+			->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
329
+			->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
330
+			->selectRaw('1 AS contrib')
331
+			->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
332
+				$join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
333
+					->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
334
+					->where('nonroot.full_ancestors', '>', 0)
335
+					->where('nonroot.majs_gedcom_id', '=', $this->tree->id())
336
+					->where('nonroot.majs_user_id', '=', $this->user->id());
337
+			})
338
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
339
+			->where('sosa.majs_user_id', '=', $this->user->id())
340
+			->whereNull('nonroot.majs_sosa');
341
+
342
+		/* Aggregate both queries, and calculate the sum of contributions by generation roots.
343 343
          * Exclude as well nodes that already appear in lower generations, as their branche has already been reduced.
344 344
          */
345
-        $ancestors_contributions_sum = DB::connection()->query()
346
-            ->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
347
-            ->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
348
-            ->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
349
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
350
-                $table_prefix . 'sosa_contribs.contrib AS totalContrib')
351
-            ->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
352
-                $join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
353
-                    ->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
354
-                    ->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
355
-                    ->where('sosa_low.majs_user_id', '=', $this->user->id());
356
-            })
357
-            ->whereNull('sosa_low.majs_sosa')
358
-            ->groupBy(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id',
359
-                'sosa_contribs.majs_i_id', 'sosa_contribs.contrib']);
360
-
361
-        // Aggregate all generation roots to compute root and generation pedigree collapse
362
-        $pedi_collapse_coll = DB::connection()->query()->fromSub($ancestors_contributions_sum, 'sosa_contribs_sum')
363
-            ->select(['gen'])->selectRaw('SUM(contrib), SUM(totalContrib)')
364
-            ->selectRaw('1 - SUM(contrib) / SUM(totalContrib) AS pedi_collapse_roots')  // Roots/horizontal collapse
365
-            ->selectRaw('1 - SUM(totalContrib) / POWER ( 2, gen - 1) AS pedi_collapse_xgen') // Crossgeneration collapse
366
-            ->groupBy(['gen', 'majs_gedcom_id', 'majs_user_id'])
367
-            ->orderBy('gen')
368
-            ->get();
369
-
370
-        $pedi_collapse_by_gen = [];
371
-        foreach ($pedi_collapse_coll as $collapse_gen) {
372
-            $pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
373
-                'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
374
-                'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
375
-            );
376
-        }
377
-        return $pedi_collapse_by_gen;
378
-    }
379
-
380
-    /**
381
-     * Return a Collection of the mean generation depth and deviation for all Sosa ancestors at a given generation.
382
-     * Sosa 1 is of generation 1.
383
-     *
384
-     * Mean generation depth and deviation are calculated based on the works of Marie-Héléne Cazes and Pierre Cazes,
385
-     * published in Population (French Edition), Vol. 51, No. 1 (Jan. - Feb., 1996), pp. 117-140
386
-     * http://kintip.net/index.php?option=com_jdownloads&task=download.send&id=9&catid=4&m=0
387
-     *
388
-     * Format:
389
-     *  - key : sosa number of the ancestor
390
-     *  - values:
391
-     *      - root_ancestor_id : ID of the ancestor
392
-     *      - mean_gen_depth : Mean generation depth
393
-     *      - stddev_gen_depth : Standard deviation of generation depth
394
-     *
395
-     * @param int $gen Sosa generation
396
-     * @return Collection<int, \stdClass>
397
-     */
398
-    public function generationDepthStatsAtGeneration(int $gen): Collection
399
-    {
400
-        $table_prefix = DB::connection()->getTablePrefix();
401
-        $missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
402
-            ->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
403
-            ->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
404
-            ->selectRaw('SUM(CASE WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL AND ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL THEN 1 ELSE 0 END) AS full_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
405
-            ->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
406
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
407
-                // Link to sosa's father
408
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
409
-                ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
410
-                ->where('sosa_fat.majs_user_id', '=', $this->user->id());
411
-            })
412
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
413
-                // Link to sosa's mother
414
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
415
-                ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
416
-                ->where('sosa_mot.majs_user_id', '=', $this->user->id());
417
-            })
418
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
419
-            ->where('sosa.majs_user_id', '=', $this->user->id())
420
-            ->where('sosa.majs_gen', '>=', $gen)
421
-            ->where(function (Builder $query): void {
422
-                $query->whereNull('sosa_fat.majs_i_id')
423
-                    ->orWhereNull('sosa_mot.majs_i_id');
424
-            })
425
-            ->groupBy(['sosa.majs_gen', 'root_ancestor']);
426
-
427
-        return DB::table('maj_sosa AS sosa_list')
428
-            ->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
429
-            ->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
430
-            ->selectRaw(' SQRT(' .
431
-                '   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
432
-                '   - 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
433
-                ' ) AS stddev_gen_depth')
434
-            ->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
435
-                $join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
436
-                    ->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
437
-                    ->where('sosa_list.majs_user_id', '=', $this->user->id());
438
-            })
439
-            ->groupBy(['stats_by_gen.root_ancestor', 'sosa_list.majs_i_id'])
440
-            ->orderBy('stats_by_gen.root_ancestor')
441
-            ->get()->keyBy('root_ancestor_sosa');
442
-    }
443
-
444
-    /**
445
-     * Return a collection of the most duplicated root Sosa ancestors.
446
-     * The number of ancestors to return is limited by the parameter $limit.
447
-     * If several individuals are tied when reaching the limit, none of them are returned,
448
-     * which means that there can be less individuals returned than requested.
449
-     *
450
-     * Format:
451
-     *  - value:
452
-     *      - sosa_i_id : sosa individual
453
-     *      - sosa_count: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
454
-     *
455
-     * @param int $limit
456
-     * @return Collection<\stdClass>
457
-     */
458
-    public function topMultipleAncestorsWithNoTies(int $limit): Collection
459
-    {
460
-        $table_prefix = DB::connection()->getTablePrefix();
461
-        $multiple_ancestors = DB::table('maj_sosa AS sosa')
462
-            ->select('sosa.majs_i_id AS sosa_i_id')
463
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
464
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
465
-                // Link to sosa's father
466
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
467
-                    ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
468
-                    ->where('sosa_fat.majs_user_id', '=', $this->user->id());
469
-            })
470
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
471
-                // Link to sosa's mother
472
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
473
-                ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
474
-                ->where('sosa_mot.majs_user_id', '=', $this->user->id());
475
-            })
476
-            ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
477
-            ->where('sosa.majs_user_id', '=', $this->user->id())
478
-            ->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
479
-            ->whereNull('sosa_mot.majs_sosa')
480
-            ->groupBy('sosa.majs_i_id')
481
-            ->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
482
-            ->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
483
-            ->limit($limit + 1)     // We want to select one more than required, for ties
484
-            ->get();
485
-
486
-        if ($multiple_ancestors->count() > $limit) {
487
-            $last_count = $multiple_ancestors->last()->sosa_count;
488
-            $multiple_ancestors = $multiple_ancestors->reject(function (stdClass $element) use ($last_count): bool {
489
-                return $element->sosa_count ==  $last_count;
490
-            });
491
-        }
492
-        return $multiple_ancestors;
493
-    }
494
-
495
-    /**
496
-     * Return a computed array of statistics about the dispersion of ancestors across the ancestors
497
-     * at a specified generation.
498
-     *
499
-     * Format:
500
-     *  - key : rank of the ancestor in generation G for which exclusive ancestors have been found
501
-     *          For instance 3 represent the maternal grand father
502
-     *          0 is used for shared ancestors
503
-     *  - values: number of ancestors exclusively in the ancestors of the ancestor in key
504
-     *
505
-     *  For instance a result at generation 3 could be :
506
-     *      array (   0     =>  12      -> 12 ancestors are shared by the grand-parents
507
-     *                1     =>  32      -> 32 ancestors are exclusive to the paternal grand-father
508
-     *                2     =>  25      -> 25 ancestors are exclusive to the paternal grand-mother
509
-     *                3     =>  12      -> 12 ancestors are exclusive to the maternal grand-father
510
-     *                4     =>  30      -> 30 ancestors are exclusive to the maternal grand-mother
511
-     *            )
512
-     *
513
-     * @param int $gen
514
-     * @return Collection<int, int>
515
-     */
516
-    public function ancestorsDispersionForGeneration(int $gen): Collection
517
-    {
518
-        $ancestors_branches = DB::table('maj_sosa')
519
-            ->select('majs_i_id AS i_id')
520
-            ->selectRaw('FLOOR(majs_sosa / POW(2, (majs_gen - ?))) - POW(2, ? -1) + 1 AS branch', [$gen, $gen])
521
-            ->where('majs_gedcom_id', '=', $this->tree->id())
522
-            ->where('majs_user_id', '=', $this->user->id())
523
-            ->where('majs_gen', '>=', $gen)
524
-            ->groupBy('majs_i_id', 'branch');
525
-
526
-
527
-        $consolidated_ancestors_branches = DB::table('maj_sosa')
528
-            ->fromSub($ancestors_branches, 'indi_branch')
529
-            ->select('i_id')
530
-            ->selectRaw('CASE WHEN COUNT(branch) > 1 THEN 0 ELSE MIN(branch) END AS branches')
531
-            ->groupBy('i_id');
532
-
533
-        return DB::table('maj_sosa')
534
-            ->fromSub($consolidated_ancestors_branches, 'indi_branch_consolidated')
535
-            ->select('branches')
536
-            ->selectRaw('COUNT(i_id) AS count_indi')
537
-            ->groupBy('branches')
538
-            ->get()->pluck('count_indi', 'branches');
539
-    }
345
+		$ancestors_contributions_sum = DB::connection()->query()
346
+			->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
347
+			->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
348
+			->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
349
+			->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
350
+				$table_prefix . 'sosa_contribs.contrib AS totalContrib')
351
+			->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
352
+				$join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
353
+					->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
354
+					->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
355
+					->where('sosa_low.majs_user_id', '=', $this->user->id());
356
+			})
357
+			->whereNull('sosa_low.majs_sosa')
358
+			->groupBy(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id',
359
+				'sosa_contribs.majs_i_id', 'sosa_contribs.contrib']);
360
+
361
+		// Aggregate all generation roots to compute root and generation pedigree collapse
362
+		$pedi_collapse_coll = DB::connection()->query()->fromSub($ancestors_contributions_sum, 'sosa_contribs_sum')
363
+			->select(['gen'])->selectRaw('SUM(contrib), SUM(totalContrib)')
364
+			->selectRaw('1 - SUM(contrib) / SUM(totalContrib) AS pedi_collapse_roots')  // Roots/horizontal collapse
365
+			->selectRaw('1 - SUM(totalContrib) / POWER ( 2, gen - 1) AS pedi_collapse_xgen') // Crossgeneration collapse
366
+			->groupBy(['gen', 'majs_gedcom_id', 'majs_user_id'])
367
+			->orderBy('gen')
368
+			->get();
369
+
370
+		$pedi_collapse_by_gen = [];
371
+		foreach ($pedi_collapse_coll as $collapse_gen) {
372
+			$pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
373
+				'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
374
+				'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
375
+			);
376
+		}
377
+		return $pedi_collapse_by_gen;
378
+	}
379
+
380
+	/**
381
+	 * Return a Collection of the mean generation depth and deviation for all Sosa ancestors at a given generation.
382
+	 * Sosa 1 is of generation 1.
383
+	 *
384
+	 * Mean generation depth and deviation are calculated based on the works of Marie-Héléne Cazes and Pierre Cazes,
385
+	 * published in Population (French Edition), Vol. 51, No. 1 (Jan. - Feb., 1996), pp. 117-140
386
+	 * http://kintip.net/index.php?option=com_jdownloads&task=download.send&id=9&catid=4&m=0
387
+	 *
388
+	 * Format:
389
+	 *  - key : sosa number of the ancestor
390
+	 *  - values:
391
+	 *      - root_ancestor_id : ID of the ancestor
392
+	 *      - mean_gen_depth : Mean generation depth
393
+	 *      - stddev_gen_depth : Standard deviation of generation depth
394
+	 *
395
+	 * @param int $gen Sosa generation
396
+	 * @return Collection<int, \stdClass>
397
+	 */
398
+	public function generationDepthStatsAtGeneration(int $gen): Collection
399
+	{
400
+		$table_prefix = DB::connection()->getTablePrefix();
401
+		$missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
402
+			->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
403
+			->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
404
+			->selectRaw('SUM(CASE WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL AND ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL THEN 1 ELSE 0 END) AS full_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
405
+			->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
406
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
407
+				// Link to sosa's father
408
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
409
+				->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
410
+				->where('sosa_fat.majs_user_id', '=', $this->user->id());
411
+			})
412
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
413
+				// Link to sosa's mother
414
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
415
+				->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
416
+				->where('sosa_mot.majs_user_id', '=', $this->user->id());
417
+			})
418
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
419
+			->where('sosa.majs_user_id', '=', $this->user->id())
420
+			->where('sosa.majs_gen', '>=', $gen)
421
+			->where(function (Builder $query): void {
422
+				$query->whereNull('sosa_fat.majs_i_id')
423
+					->orWhereNull('sosa_mot.majs_i_id');
424
+			})
425
+			->groupBy(['sosa.majs_gen', 'root_ancestor']);
426
+
427
+		return DB::table('maj_sosa AS sosa_list')
428
+			->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
429
+			->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
430
+			->selectRaw(' SQRT(' .
431
+				'   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
432
+				'   - 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
433
+				' ) AS stddev_gen_depth')
434
+			->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
435
+				$join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
436
+					->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
437
+					->where('sosa_list.majs_user_id', '=', $this->user->id());
438
+			})
439
+			->groupBy(['stats_by_gen.root_ancestor', 'sosa_list.majs_i_id'])
440
+			->orderBy('stats_by_gen.root_ancestor')
441
+			->get()->keyBy('root_ancestor_sosa');
442
+	}
443
+
444
+	/**
445
+	 * Return a collection of the most duplicated root Sosa ancestors.
446
+	 * The number of ancestors to return is limited by the parameter $limit.
447
+	 * If several individuals are tied when reaching the limit, none of them are returned,
448
+	 * which means that there can be less individuals returned than requested.
449
+	 *
450
+	 * Format:
451
+	 *  - value:
452
+	 *      - sosa_i_id : sosa individual
453
+	 *      - sosa_count: number of duplications of the ancestor (e.g. 3 if it appears 3 times)
454
+	 *
455
+	 * @param int $limit
456
+	 * @return Collection<\stdClass>
457
+	 */
458
+	public function topMultipleAncestorsWithNoTies(int $limit): Collection
459
+	{
460
+		$table_prefix = DB::connection()->getTablePrefix();
461
+		$multiple_ancestors = DB::table('maj_sosa AS sosa')
462
+			->select('sosa.majs_i_id AS sosa_i_id')
463
+			->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
464
+			->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
465
+				// Link to sosa's father
466
+				$join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
467
+					->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
468
+					->where('sosa_fat.majs_user_id', '=', $this->user->id());
469
+			})
470
+			->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
471
+				// Link to sosa's mother
472
+				$join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
473
+				->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
474
+				->where('sosa_mot.majs_user_id', '=', $this->user->id());
475
+			})
476
+			->where('sosa.majs_gedcom_id', '=', $this->tree->id())
477
+			->where('sosa.majs_user_id', '=', $this->user->id())
478
+			->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
479
+			->whereNull('sosa_mot.majs_sosa')
480
+			->groupBy('sosa.majs_i_id')
481
+			->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
482
+			->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
483
+			->limit($limit + 1)     // We want to select one more than required, for ties
484
+			->get();
485
+
486
+		if ($multiple_ancestors->count() > $limit) {
487
+			$last_count = $multiple_ancestors->last()->sosa_count;
488
+			$multiple_ancestors = $multiple_ancestors->reject(function (stdClass $element) use ($last_count): bool {
489
+				return $element->sosa_count ==  $last_count;
490
+			});
491
+		}
492
+		return $multiple_ancestors;
493
+	}
494
+
495
+	/**
496
+	 * Return a computed array of statistics about the dispersion of ancestors across the ancestors
497
+	 * at a specified generation.
498
+	 *
499
+	 * Format:
500
+	 *  - key : rank of the ancestor in generation G for which exclusive ancestors have been found
501
+	 *          For instance 3 represent the maternal grand father
502
+	 *          0 is used for shared ancestors
503
+	 *  - values: number of ancestors exclusively in the ancestors of the ancestor in key
504
+	 *
505
+	 *  For instance a result at generation 3 could be :
506
+	 *      array (   0     =>  12      -> 12 ancestors are shared by the grand-parents
507
+	 *                1     =>  32      -> 32 ancestors are exclusive to the paternal grand-father
508
+	 *                2     =>  25      -> 25 ancestors are exclusive to the paternal grand-mother
509
+	 *                3     =>  12      -> 12 ancestors are exclusive to the maternal grand-father
510
+	 *                4     =>  30      -> 30 ancestors are exclusive to the maternal grand-mother
511
+	 *            )
512
+	 *
513
+	 * @param int $gen
514
+	 * @return Collection<int, int>
515
+	 */
516
+	public function ancestorsDispersionForGeneration(int $gen): Collection
517
+	{
518
+		$ancestors_branches = DB::table('maj_sosa')
519
+			->select('majs_i_id AS i_id')
520
+			->selectRaw('FLOOR(majs_sosa / POW(2, (majs_gen - ?))) - POW(2, ? -1) + 1 AS branch', [$gen, $gen])
521
+			->where('majs_gedcom_id', '=', $this->tree->id())
522
+			->where('majs_user_id', '=', $this->user->id())
523
+			->where('majs_gen', '>=', $gen)
524
+			->groupBy('majs_i_id', 'branch');
525
+
526
+
527
+		$consolidated_ancestors_branches = DB::table('maj_sosa')
528
+			->fromSub($ancestors_branches, 'indi_branch')
529
+			->select('i_id')
530
+			->selectRaw('CASE WHEN COUNT(branch) > 1 THEN 0 ELSE MIN(branch) END AS branches')
531
+			->groupBy('i_id');
532
+
533
+		return DB::table('maj_sosa')
534
+			->fromSub($consolidated_ancestors_branches, 'indi_branch_consolidated')
535
+			->select('branches')
536
+			->selectRaw('COUNT(i_id) AS count_indi')
537
+			->groupBy('branches')
538
+			->get()->pluck('count_indi', 'branches');
539
+	}
540 540
 }
Please login to merge, or discard this patch.
Spacing   +58 added lines, -59 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
      */
73 73
     public function maxGeneration(): int
74 74
     {
75
-        return (int) DB::table('maj_sosa')
75
+        return (int)DB::table('maj_sosa')
76 76
             ->where('majs_gedcom_id', '=', $this->tree->id())
77 77
             ->where('majs_user_id', '=', $this->user->id())
78 78
             ->max('majs_gen');
@@ -149,8 +149,7 @@  discard block
 block discarded – undo
149 149
             ->selectRaw('SUM(majs_gen * majs_gen) AS sum_x2')
150 150
             ->get()->first();
151 151
 
152
-        return $row->n == 0 ? 0 :
153
-            -($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / ($row->n * $row->sum_x2 - pow($row->sum_x, 2));
152
+        return $row->n == 0 ? 0 : -($row->n * $row->sum_xy - $row->sum_x * $row->sum_y) / ($row->n * $row->sum_x2 - pow($row->sum_x, 2));
154 153
     }
155 154
 
156 155
     /**
@@ -174,10 +173,10 @@  discard block
 block discarded – undo
174 173
 
175 174
         $statistics_by_gen = [];
176 175
         foreach ($stats_by_gen as $gen => $stats_gen) {
177
-            $statistics_by_gen[(int) $stats_gen->gen] = array(
178
-                'sosaCount'             =>  (int) $stats_gen->total_sosa,
179
-                'sosaTotalCount'        =>  (int) $cumul_stats_by_gen[$gen]->total_cumul,
180
-                'diffSosaTotalCount'    =>  (int) $cumul_stats_by_gen[$gen]->total_distinct_cumul,
176
+            $statistics_by_gen[(int)$stats_gen->gen] = array(
177
+                'sosaCount'             =>  (int)$stats_gen->total_sosa,
178
+                'sosaTotalCount'        =>  (int)$cumul_stats_by_gen[$gen]->total_cumul,
179
+                'diffSosaTotalCount'    =>  (int)$cumul_stats_by_gen[$gen]->total_distinct_cumul,
181 180
                 'firstBirth'            =>  $stats_gen->first_year,
182 181
                 'firstEstimatedBirth'   =>  $stats_gen->first_est_year,
183 182
                 'lastBirth'             =>  $stats_gen->last_year,
@@ -221,7 +220,7 @@  discard block
 block discarded – undo
221 220
             ->where('majs_user_id', '=', $this->user->id());
222 221
 
223 222
         return DB::table('maj_sosa')
224
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
223
+            ->joinSub($list_gen, 'list_gen', function(JoinClause $join): void {
225 224
                 $join->on('maj_sosa.majs_gen', '<=', 'list_gen.majs_gen')
226 225
                 ->where('majs_gedcom_id', '=', $this->tree->id())
227 226
                 ->where('majs_user_id', '=', $this->user->id());
@@ -258,37 +257,37 @@  discard block
 block discarded – undo
258 257
             ->select(['list_gen.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
259 258
             ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
260 259
             ->selectRaw(
261
-                '(CASE ' .
262
-                    ' WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL' .
263
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
264
-                    ' ELSE 0 ' .
265
-                ' END)' .
266
-                ' + (CASE ' .
267
-                    ' WHEN ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL' .
268
-                    ' THEN POWER(2, ' . $table_prefix . 'list_gen.majs_gen - ' . $table_prefix . 'sosa.majs_gen - 1)' .
269
-                    ' ELSE 0 ' .
260
+                '(CASE '.
261
+                    ' WHEN '.$table_prefix.'sosa_fat.majs_i_id IS NULL'.
262
+                    ' THEN POWER(2, '.$table_prefix.'list_gen.majs_gen - '.$table_prefix.'sosa.majs_gen - 1)'.
263
+                    ' ELSE 0 '.
264
+                ' END)'.
265
+                ' + (CASE '.
266
+                    ' WHEN '.$table_prefix.'sosa_mot.majs_i_id IS NULL'.
267
+                    ' THEN POWER(2, '.$table_prefix.'list_gen.majs_gen - '.$table_prefix.'sosa.majs_gen - 1)'.
268
+                    ' ELSE 0 '.
270 269
                 ' END) contrib'
271 270
             )
272
-            ->joinSub($list_gen, 'list_gen', function (JoinClause $join): void {
271
+            ->joinSub($list_gen, 'list_gen', function(JoinClause $join): void {
273 272
                 $join->on('sosa.majs_gen', '<', 'list_gen.majs_gen')
274 273
                     ->where('majs_gedcom_id', '=', $this->tree->id())
275 274
                     ->where('majs_user_id', '=', $this->user->id());
276 275
             })
277
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
276
+            ->leftJoin('maj_sosa AS sosa_fat', function(JoinClause $join) use ($table_prefix): void {
278 277
                 // Link to sosa's father
279
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
278
+                $join->whereRaw($table_prefix.'sosa_fat.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa')
280 279
                     ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
281 280
                     ->where('sosa_fat.majs_user_id', '=', $this->user->id());
282 281
             })
283
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
282
+            ->leftJoin('maj_sosa AS sosa_mot', function(JoinClause $join) use ($table_prefix): void {
284 283
                 // Link to sosa's mother
285
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
284
+                $join->whereRaw($table_prefix.'sosa_mot.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa + 1')
286 285
                     ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
287 286
                     ->where('sosa_mot.majs_user_id', '=', $this->user->id());
288 287
             })
289 288
             ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
290 289
             ->where('sosa.majs_user_id', '=', $this->user->id())
291
-            ->where(function (Builder $query): void {
290
+            ->where(function(Builder $query): void {
292 291
                 $query->whereNull('sosa_fat.majs_i_id')
293 292
                 ->orWhereNull('sosa_mot.majs_i_id');
294 293
             });
@@ -298,24 +297,24 @@  discard block
 block discarded – undo
298 297
          */
299 298
         $non_roots_ancestors = DB::table('maj_sosa AS sosa')
300 299
             ->select(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id', 'sosa.majs_sosa'])
301
-            ->selectRaw('MAX(' . $table_prefix . 'sosa_anc.majs_sosa) - MIN(' . $table_prefix . 'sosa_anc.majs_sosa)' .
300
+            ->selectRaw('MAX('.$table_prefix.'sosa_anc.majs_sosa) - MIN('.$table_prefix.'sosa_anc.majs_sosa)'.
302 301
                 ' AS full_ancestors')
303
-            ->join('maj_sosa AS sosa_anc', function (JoinClause $join) use ($table_prefix): void {
302
+            ->join('maj_sosa AS sosa_anc', function(JoinClause $join) use ($table_prefix): void {
304 303
                 $join->on('sosa.majs_gen', '<', 'sosa_anc.majs_gen')
305
-                    ->whereRaw('FLOOR(' . $table_prefix . 'sosa_anc.majs_sosa / POWER(2, ' .
306
-                        $table_prefix . 'sosa_anc.majs_gen - ' . $table_prefix . 'sosa.majs_gen)) = ' .
307
-                        $table_prefix . 'sosa.majs_sosa')
304
+                    ->whereRaw('FLOOR('.$table_prefix.'sosa_anc.majs_sosa / POWER(2, '.
305
+                        $table_prefix.'sosa_anc.majs_gen - '.$table_prefix.'sosa.majs_gen)) = '.
306
+                        $table_prefix.'sosa.majs_sosa')
308 307
                     ->where('sosa_anc.majs_gedcom_id', '=', $this->tree->id())
309 308
                     ->where('sosa_anc.majs_user_id', '=', $this->user->id());
310 309
             })
311 310
             ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
312 311
             ->where('sosa.majs_user_id', '=', $this->user->id())
313
-            ->whereIn('sosa_anc.majs_i_id', function (Builder $query) use ($table_prefix): void {
312
+            ->whereIn('sosa_anc.majs_i_id', function(Builder $query) use ($table_prefix): void {
314 313
                 $query->from('maj_sosa AS sosa_gen')
315 314
                 ->select('sosa_gen.majs_i_id')->distinct()
316 315
                 ->where('sosa_gen.majs_gedcom_id', '=', $this->tree->id())
317 316
                 ->where('sosa_gen.majs_user_id', '=', $this->user->id())
318
-                ->whereRaw($table_prefix . 'sosa_gen.majs_gen = ' . $table_prefix . 'sosa.majs_gen');
317
+                ->whereRaw($table_prefix.'sosa_gen.majs_gen = '.$table_prefix.'sosa.majs_gen');
319 318
             })
320 319
             ->groupBy(['sosa.majs_gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id',
321 320
                 'sosa.majs_sosa', 'sosa.majs_i_id']);
@@ -328,7 +327,7 @@  discard block
 block discarded – undo
328 327
             ->select(['sosa.majs_gen AS gen', 'sosa.majs_gedcom_id', 'sosa.majs_user_id'])
329 328
             ->addSelect(['sosa.majs_i_id', 'sosa.majs_gen'])
330 329
             ->selectRaw('1 AS contrib')
331
-            ->leftJoinSub($non_roots_ancestors, 'nonroot', function (JoinClause $join): void {
330
+            ->leftJoinSub($non_roots_ancestors, 'nonroot', function(JoinClause $join): void {
332 331
                 $join->on('sosa.majs_gen', '=', 'nonroot.majs_gen')
333 332
                     ->on('sosa.majs_sosa', '=', 'nonroot.majs_sosa')
334 333
                     ->where('nonroot.full_ancestors', '>', 0)
@@ -346,9 +345,9 @@  discard block
 block discarded – undo
346 345
             ->fromSub($root_ancestors_contributions->unionAll($known_ancestors_contributions), 'sosa_contribs')
347 346
             ->select(['sosa_contribs.gen', 'sosa_contribs.majs_gedcom_id', 'sosa_contribs.majs_user_id'])
348 347
             ->addSelect(['sosa_contribs.majs_i_id', 'sosa_contribs.contrib'])
349
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa_contribs.majs_i_id) * ' .
350
-                $table_prefix . 'sosa_contribs.contrib AS totalContrib')
351
-            ->leftJoin('maj_sosa AS sosa_low', function (JoinClause $join): void {
348
+            ->selectRaw('COUNT('.$table_prefix.'sosa_contribs.majs_i_id) * '.
349
+                $table_prefix.'sosa_contribs.contrib AS totalContrib')
350
+            ->leftJoin('maj_sosa AS sosa_low', function(JoinClause $join): void {
352 351
                 $join->on('sosa_low.majs_gen', '<', 'sosa_contribs.majs_gen')
353 352
                     ->on('sosa_low.majs_i_id', '=', 'sosa_contribs.majs_i_id')
354 353
                     ->where('sosa_low.majs_gedcom_id', '=', $this->tree->id())
@@ -369,9 +368,9 @@  discard block
 block discarded – undo
369 368
 
370 369
         $pedi_collapse_by_gen = [];
371 370
         foreach ($pedi_collapse_coll as $collapse_gen) {
372
-            $pedi_collapse_by_gen[(int) $collapse_gen->gen] = array(
373
-                'pedi_collapse_roots'   =>  (float) $collapse_gen->pedi_collapse_roots,
374
-                'pedi_collapse_xgen'   =>  (float) $collapse_gen->pedi_collapse_xgen
371
+            $pedi_collapse_by_gen[(int)$collapse_gen->gen] = array(
372
+                'pedi_collapse_roots'   =>  (float)$collapse_gen->pedi_collapse_roots,
373
+                'pedi_collapse_xgen'   =>  (float)$collapse_gen->pedi_collapse_xgen
375 374
             );
376 375
         }
377 376
         return $pedi_collapse_by_gen;
@@ -399,26 +398,26 @@  discard block
 block discarded – undo
399 398
     {
400 399
         $table_prefix = DB::connection()->getTablePrefix();
401 400
         $missing_ancestors_by_gen = DB::table('maj_sosa AS sosa')
402
-            ->selectRaw($table_prefix . 'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
403
-            ->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
404
-            ->selectRaw('SUM(CASE WHEN ' . $table_prefix . 'sosa_fat.majs_i_id IS NULL AND ' . $table_prefix . 'sosa_mot.majs_i_id IS NULL THEN 1 ELSE 0 END) AS full_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
405
-            ->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
406
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
401
+            ->selectRaw($table_prefix.'sosa.majs_gen - ? AS majs_gen_norm', [$gen])
402
+            ->selectRaw('FLOOR((('.$table_prefix.'sosa.majs_sosa / POW(2, '.$table_prefix.'sosa.majs_gen -1 )) - 1) * POWER(2, ? - 1)) + POWER(2, ? - 1) AS root_ancestor', [$gen, $gen])   //@phpcs:ignore Generic.Files.LineLength.TooLong
403
+            ->selectRaw('SUM(CASE WHEN '.$table_prefix.'sosa_fat.majs_i_id IS NULL AND '.$table_prefix.'sosa_mot.majs_i_id IS NULL THEN 1 ELSE 0 END) AS full_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
404
+            ->selectRaw('SUM(CASE WHEN '.$table_prefix.'sosa_fat.majs_i_id IS NULL AND '.$table_prefix.'sosa_mot.majs_i_id IS NULL THEN 0 ELSE 1 END) As semi_root_count')  //@phpcs:ignore Generic.Files.LineLength.TooLong
405
+            ->leftJoin('maj_sosa AS sosa_fat', function(JoinClause $join) use ($table_prefix): void {
407 406
                 // Link to sosa's father
408
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
407
+                $join->whereRaw($table_prefix.'sosa_fat.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa')
409 408
                 ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
410 409
                 ->where('sosa_fat.majs_user_id', '=', $this->user->id());
411 410
             })
412
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
411
+            ->leftJoin('maj_sosa AS sosa_mot', function(JoinClause $join) use ($table_prefix): void {
413 412
                 // Link to sosa's mother
414
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
413
+                $join->whereRaw($table_prefix.'sosa_mot.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa + 1')
415 414
                 ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
416 415
                 ->where('sosa_mot.majs_user_id', '=', $this->user->id());
417 416
             })
418 417
             ->where('sosa.majs_gedcom_id', '=', $this->tree->id())
419 418
             ->where('sosa.majs_user_id', '=', $this->user->id())
420 419
             ->where('sosa.majs_gen', '>=', $gen)
421
-            ->where(function (Builder $query): void {
420
+            ->where(function(Builder $query): void {
422 421
                 $query->whereNull('sosa_fat.majs_i_id')
423 422
                     ->orWhereNull('sosa_mot.majs_i_id');
424 423
             })
@@ -427,11 +426,11 @@  discard block
 block discarded – undo
427 426
         return DB::table('maj_sosa AS sosa_list')
428 427
             ->select(['stats_by_gen.root_ancestor AS root_ancestor_sosa', 'sosa_list.majs_i_id as root_ancestor_id'])
429 428
             ->selectRaw('1 + SUM( (majs_gen_norm) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm))) AS mean_gen_depth')  //@phpcs:ignore Generic.Files.LineLength.TooLong
430
-            ->selectRaw(' SQRT(' .
431
-                '   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
432
-                '   - 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
429
+            ->selectRaw(' SQRT('.
430
+                '   SUM(POWER(majs_gen_norm, 2) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm)))'.//@phpcs:ignore Generic.Files.LineLength.TooLong
431
+                '   - POWER( SUM( (majs_gen_norm) * ( 2 * full_root_count + semi_root_count) /  (2 * POWER(2, majs_gen_norm))), 2)'.//@phpcs:ignore Generic.Files.LineLength.TooLong
433 432
                 ' ) AS stddev_gen_depth')
434
-            ->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function (JoinClause $join): void {
433
+            ->joinSub($missing_ancestors_by_gen, 'stats_by_gen', function(JoinClause $join): void {
435 434
                 $join->on('sosa_list.majs_sosa', '=', 'stats_by_gen.root_ancestor')
436 435
                     ->where('sosa_list.majs_gedcom_id', '=', $this->tree->id())
437 436
                     ->where('sosa_list.majs_user_id', '=', $this->user->id());
@@ -460,16 +459,16 @@  discard block
 block discarded – undo
460 459
         $table_prefix = DB::connection()->getTablePrefix();
461 460
         $multiple_ancestors = DB::table('maj_sosa AS sosa')
462 461
             ->select('sosa.majs_i_id AS sosa_i_id')
463
-            ->selectRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) AS sosa_count')
464
-            ->leftJoin('maj_sosa AS sosa_fat', function (JoinClause $join) use ($table_prefix): void {
462
+            ->selectRaw('COUNT('.$table_prefix.'sosa.majs_sosa) AS sosa_count')
463
+            ->leftJoin('maj_sosa AS sosa_fat', function(JoinClause $join) use ($table_prefix): void {
465 464
                 // Link to sosa's father
466
-                $join->whereRaw($table_prefix . 'sosa_fat.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa')
465
+                $join->whereRaw($table_prefix.'sosa_fat.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa')
467 466
                     ->where('sosa_fat.majs_gedcom_id', '=', $this->tree->id())
468 467
                     ->where('sosa_fat.majs_user_id', '=', $this->user->id());
469 468
             })
470
-            ->leftJoin('maj_sosa AS sosa_mot', function (JoinClause $join) use ($table_prefix): void {
469
+            ->leftJoin('maj_sosa AS sosa_mot', function(JoinClause $join) use ($table_prefix): void {
471 470
                 // Link to sosa's mother
472
-                $join->whereRaw($table_prefix . 'sosa_mot.majs_sosa = 2 * ' . $table_prefix . 'sosa.majs_sosa + 1')
471
+                $join->whereRaw($table_prefix.'sosa_mot.majs_sosa = 2 * '.$table_prefix.'sosa.majs_sosa + 1')
473 472
                 ->where('sosa_mot.majs_gedcom_id', '=', $this->tree->id())
474 473
                 ->where('sosa_mot.majs_user_id', '=', $this->user->id());
475 474
             })
@@ -478,15 +477,15 @@  discard block
 block discarded – undo
478 477
             ->whereNull('sosa_fat.majs_sosa')   // We keep only root individuals, i.e. those with no father or mother
479 478
             ->whereNull('sosa_mot.majs_sosa')
480 479
             ->groupBy('sosa.majs_i_id')
481
-            ->havingRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
482
-            ->orderByRaw('COUNT(' . $table_prefix . 'sosa.majs_sosa) DESC, MIN(' . $table_prefix . 'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
480
+            ->havingRaw('COUNT('.$table_prefix.'sosa.majs_sosa) > 1')    // Limit to the duplicate sosas.
481
+            ->orderByRaw('COUNT('.$table_prefix.'sosa.majs_sosa) DESC, MIN('.$table_prefix.'sosa.majs_sosa) ASC')   //@phpcs:ignore Generic.Files.LineLength.TooLong
483 482
             ->limit($limit + 1)     // We want to select one more than required, for ties
484 483
             ->get();
485 484
 
486 485
         if ($multiple_ancestors->count() > $limit) {
487 486
             $last_count = $multiple_ancestors->last()->sosa_count;
488
-            $multiple_ancestors = $multiple_ancestors->reject(function (stdClass $element) use ($last_count): bool {
489
-                return $element->sosa_count ==  $last_count;
487
+            $multiple_ancestors = $multiple_ancestors->reject(function(stdClass $element) use ($last_count): bool {
488
+                return $element->sosa_count == $last_count;
490 489
             });
491 490
         }
492 491
         return $multiple_ancestors;
Please login to merge, or discard this patch.
app/Module/Sosa/GeoAnalyses/SosaByGenerationGeoAnalysis.php 2 patches
Indentation   +97 added lines, -97 removed lines patch added patch discarded remove patch
@@ -31,101 +31,101 @@
 block discarded – undo
31 31
  */
32 32
 class SosaByGenerationGeoAnalysis implements GeoAnalysisInterface
33 33
 {
34
-    private SosaRecordsService $records_service;
35
-
36
-    /**
37
-     * Constructor for SosaByGenerationGeoAnalysis
38
-     *
39
-     * @param SosaRecordsService $records_service
40
-     */
41
-    public function __construct(SosaRecordsService $records_service)
42
-    {
43
-        $this->records_service = $records_service;
44
-    }
45
-
46
-    /**
47
-     * {@inheritDoc}
48
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::title()
49
-     */
50
-    public function title(): string
51
-    {
52
-        return I18N::translate('Sosa ancestors places by generation');
53
-    }
54
-
55
-    /**
56
-     * {@inheritDoc}
57
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::itemsDescription()
58
-     */
59
-    public function itemsDescription(): callable
60
-    {
61
-        return fn(int $count): string => I18N::plural('ancestor', 'ancestors', $count);
62
-    }
63
-
64
-    /**
65
-     * {@inheritDoc}
66
-     * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::results()
67
-     */
68
-    public function results(Tree $tree, int $depth): GeoAnalysisResults
69
-    {
70
-        $results = new GeoAnalysisResults();
71
-
72
-        $unique_ancestors = $this->records_service
73
-            ->listAncestors($tree, Auth::user())
74
-            ->uniqueStrict(fn(stdClass $item): string => $item->majs_i_id);
75
-
76
-        foreach ($unique_ancestors as $item) {
77
-            $ancestor = Registry::individualFactory()->make($item->majs_i_id, $tree);
78
-            if ($ancestor === null || !$ancestor->canShow()) {
79
-                continue;
80
-            }
81
-            $generation = $this->records_service->generation((int) $item->majs_sosa);
82
-            $significantplace = new GeoAnalysisPlace($tree, null, $depth);
83
-            foreach ($this->significantPlaces($ancestor) as $place) {
84
-                $significantplace = new GeoAnalysisPlace($tree, $place, $depth, true);
85
-                if ($significantplace->isKnown()) {
86
-                    break;
87
-                }
88
-            }
89
-            $results->addPlace($significantplace);
90
-            $results->addPlaceInCategory(
91
-                I18N::translate('Generation %s', I18N::number($generation)),
92
-                $generation,
93
-                $significantplace
94
-            );
95
-        }
96
-
97
-        return $results;
98
-    }
99
-
100
-    /**
101
-     * Returns significant places in order of priority for an individual
102
-     *
103
-     * @param Individual $individual
104
-     * @return Generator<\Fisharebest\Webtrees\Place>
105
-     */
106
-    protected function significantPlaces(Individual $individual): Generator
107
-    {
108
-        yield $individual->getBirthPlace();
109
-
110
-        /** @var \Fisharebest\Webtrees\Fact $fact */
111
-        foreach ($individual->facts(['RESI']) as $fact) {
112
-            yield $fact->place();
113
-        }
114
-
115
-        yield $individual->getDeathPlace();
116
-
117
-        /** @var \Fisharebest\Webtrees\Family $family */
118
-        foreach ($individual->childFamilies() as $family) {
119
-            foreach ($family->facts(['RESI']) as $fact) {
120
-                yield $fact->place();
121
-            }
122
-        }
123
-
124
-        /** @var \Fisharebest\Webtrees\Family $family */
125
-        foreach ($individual->spouseFamilies() as $family) {
126
-            foreach ($family->facts(['RESI']) as $fact) {
127
-                yield $fact->place();
128
-            }
129
-        }
130
-    }
34
+	private SosaRecordsService $records_service;
35
+
36
+	/**
37
+	 * Constructor for SosaByGenerationGeoAnalysis
38
+	 *
39
+	 * @param SosaRecordsService $records_service
40
+	 */
41
+	public function __construct(SosaRecordsService $records_service)
42
+	{
43
+		$this->records_service = $records_service;
44
+	}
45
+
46
+	/**
47
+	 * {@inheritDoc}
48
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::title()
49
+	 */
50
+	public function title(): string
51
+	{
52
+		return I18N::translate('Sosa ancestors places by generation');
53
+	}
54
+
55
+	/**
56
+	 * {@inheritDoc}
57
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::itemsDescription()
58
+	 */
59
+	public function itemsDescription(): callable
60
+	{
61
+		return fn(int $count): string => I18N::plural('ancestor', 'ancestors', $count);
62
+	}
63
+
64
+	/**
65
+	 * {@inheritDoc}
66
+	 * @see \MyArtJaub\Webtrees\Contracts\GeoDispersion\GeoAnalysisInterface::results()
67
+	 */
68
+	public function results(Tree $tree, int $depth): GeoAnalysisResults
69
+	{
70
+		$results = new GeoAnalysisResults();
71
+
72
+		$unique_ancestors = $this->records_service
73
+			->listAncestors($tree, Auth::user())
74
+			->uniqueStrict(fn(stdClass $item): string => $item->majs_i_id);
75
+
76
+		foreach ($unique_ancestors as $item) {
77
+			$ancestor = Registry::individualFactory()->make($item->majs_i_id, $tree);
78
+			if ($ancestor === null || !$ancestor->canShow()) {
79
+				continue;
80
+			}
81
+			$generation = $this->records_service->generation((int) $item->majs_sosa);
82
+			$significantplace = new GeoAnalysisPlace($tree, null, $depth);
83
+			foreach ($this->significantPlaces($ancestor) as $place) {
84
+				$significantplace = new GeoAnalysisPlace($tree, $place, $depth, true);
85
+				if ($significantplace->isKnown()) {
86
+					break;
87
+				}
88
+			}
89
+			$results->addPlace($significantplace);
90
+			$results->addPlaceInCategory(
91
+				I18N::translate('Generation %s', I18N::number($generation)),
92
+				$generation,
93
+				$significantplace
94
+			);
95
+		}
96
+
97
+		return $results;
98
+	}
99
+
100
+	/**
101
+	 * Returns significant places in order of priority for an individual
102
+	 *
103
+	 * @param Individual $individual
104
+	 * @return Generator<\Fisharebest\Webtrees\Place>
105
+	 */
106
+	protected function significantPlaces(Individual $individual): Generator
107
+	{
108
+		yield $individual->getBirthPlace();
109
+
110
+		/** @var \Fisharebest\Webtrees\Fact $fact */
111
+		foreach ($individual->facts(['RESI']) as $fact) {
112
+			yield $fact->place();
113
+		}
114
+
115
+		yield $individual->getDeathPlace();
116
+
117
+		/** @var \Fisharebest\Webtrees\Family $family */
118
+		foreach ($individual->childFamilies() as $family) {
119
+			foreach ($family->facts(['RESI']) as $fact) {
120
+				yield $fact->place();
121
+			}
122
+		}
123
+
124
+		/** @var \Fisharebest\Webtrees\Family $family */
125
+		foreach ($individual->spouseFamilies() as $family) {
126
+			foreach ($family->facts(['RESI']) as $fact) {
127
+				yield $fact->place();
128
+			}
129
+		}
130
+	}
131 131
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -78,7 +78,7 @@
 block discarded – undo
78 78
             if ($ancestor === null || !$ancestor->canShow()) {
79 79
                 continue;
80 80
             }
81
-            $generation = $this->records_service->generation((int) $item->majs_sosa);
81
+            $generation = $this->records_service->generation((int)$item->majs_sosa);
82 82
             $significantplace = new GeoAnalysisPlace($tree, null, $depth);
83 83
             foreach ($this->significantPlaces($ancestor) as $place) {
84 84
                 $significantplace = new GeoAnalysisPlace($tree, $place, $depth, true);
Please login to merge, or discard this patch.