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