Passed
Branch feature/2.0 (d2af8f)
by Jonathan
13:07
created
src/Webtrees/Module/AdminTasks/Services/TaskScheduleService.php 2 patches
Indentation   +249 added lines, -249 removed lines patch added patch discarded remove patch
@@ -33,253 +33,253 @@
 block discarded – undo
33 33
  */
34 34
 class TaskScheduleService
35 35
 {
36
-    /**
37
-     * Time-out after which the task will be considered not running any more.
38
-     * In seconds, default 5 mins.
39
-     * @var integer
40
-     */
41
-    public const TASK_TIME_OUT = 600;
42
-
43
-    /**
44
-     * @var Collection $available_tasks
45
-     */
46
-    private $available_tasks;
47
-
48
-    /**
49
-     * Returns all Tasks schedules in database.
50
-     * Stored records can be synchronised with the tasks actually available to the system.
51
-     *
52
-     * @param bool $sync_available Should tasks synchronised with available ones
53
-     * @param bool $include_disabled Should disabled tasks be returned
54
-     * @return Collection Collection of TaskSchedule
55
-     */
56
-    public function all(bool $sync_available = false, bool $include_disabled = true): Collection
57
-    {
58
-        $tasks_schedules = DB::table('maj_admintasks')
59
-        ->select()
60
-        ->get()
61
-        ->map(self::rowMapper());
62
-
63
-        if ($sync_available) {
64
-            $available_tasks = clone $this->available();
65
-            foreach ($tasks_schedules as $task_schedule) {
66
-                /** @var TaskSchedule $task_schedule */
67
-                if ($available_tasks->has($task_schedule->taskId())) {
68
-                    $available_tasks->forget($task_schedule->taskId());
69
-                } else {
70
-                    $this->delete($task_schedule);
71
-                }
72
-            }
73
-
74
-            foreach ($available_tasks as $task_name => $task) {
75
-                /** @var TaskInterface $task */
76
-                $this->insertTask($task_name, $task->defaultFrequency());
77
-            }
78
-
79
-            return $this->all(false, $include_disabled);
80
-        }
81
-
82
-        return $tasks_schedules;
83
-    }
84
-
85
-    /**
86
-     * Returns tasks exposed through modules implementing ModuleTasksProviderInterface.
87
-     *
88
-     * @return Collection
89
-     */
90
-    public function available(): Collection
91
-    {
92
-        if ($this->available_tasks === null) {
93
-            $tasks_providers = app(ModuleService::class)->findByInterface(ModuleTasksProviderInterface::class);
94
-
95
-            $this->available_tasks = new Collection();
96
-            foreach ($tasks_providers as $task_provider) {
97
-                $this->available_tasks = $this->available_tasks->merge($task_provider->listTasks());
98
-            }
99
-        }
100
-        return $this->available_tasks;
101
-    }
102
-
103
-    /**
104
-     * Find a task schedule by its ID.
105
-     *
106
-     * @param int $task_schedule_id
107
-     * @return TaskSchedule|NULL
108
-     */
109
-    public function find(int $task_schedule_id): ?TaskSchedule
110
-    {
111
-        return DB::table('maj_admintasks')
112
-            ->select()
113
-            ->where('majat_id', '=', $task_schedule_id)
114
-            ->get()
115
-            ->map(self::rowMapper())
116
-            ->first();
117
-    }
118
-
119
-    /**
120
-     * Add a new task schedule with the specified task ID, and frequency if defined.
121
-     * Uses default for other settings.
122
-     *
123
-     * @param string $task_id
124
-     * @param int $frequency
125
-     * @return bool
126
-     */
127
-    public function insertTask(string $task_id, int $frequency = 0): bool
128
-    {
129
-        $values = ['majat_task_id' => $task_id];
130
-        if ($frequency > 0) {
131
-            $values['majat_frequency'] = $frequency;
132
-        }
133
-
134
-        return DB::table('maj_admintasks')
135
-            ->insert($values);
136
-    }
137
-
138
-    /**
139
-     * Update a task schedule.
140
-     * Returns the number of tasks schedules updated.
141
-     *
142
-     * @param TaskSchedule $task_schedule
143
-     * @return int
144
-     */
145
-    public function update(TaskSchedule $task_schedule): int
146
-    {
147
-        return DB::table('maj_admintasks')
148
-            ->where('majat_id', '=', $task_schedule->id())
149
-            ->update([
150
-                'majat_status'      =>  $task_schedule->isEnabled() ? 'enabled' : 'disabled',
151
-                'majat_last_run'    =>  $task_schedule->lastRunTime(),
152
-                'majat_last_result' =>  $task_schedule->wasLastRunSuccess(),
153
-                'majat_frequency'   =>  $task_schedule->frequency()->totalMinutes,
154
-                'majat_nb_occur'    =>  $task_schedule->remainingOccurences(),
155
-                'majat_running'     =>  $task_schedule->isRunning()
156
-            ]);
157
-    }
158
-
159
-    /**
160
-     * Delete a task schedule.
161
-     *
162
-     * @param TaskSchedule $task_schedule
163
-     * @return int
164
-     */
165
-    public function delete(TaskSchedule $task_schedule): int
166
-    {
167
-        return DB::table('maj_admintasks')
168
-            ->where('majat_id', '=', $task_schedule->id())
169
-            ->delete();
170
-    }
171
-
172
-    /**
173
-     * Find a task by its name
174
-     *
175
-     * @param string $task_id
176
-     * @return TaskInterface|NULL
177
-     */
178
-    public function findTask(string $task_id): ?TaskInterface
179
-    {
180
-        if ($this->available()->has($task_id)) {
181
-            return app($this->available()->get($task_id));
182
-        }
183
-        return null;
184
-    }
185
-
186
-    /**
187
-     * Retrieve all tasks that are candidates to be run.
188
-     *
189
-     * @param bool $force Should the run be forced
190
-     * @param string $task_id Specific task ID to be run
191
-     * @return Collection
192
-     */
193
-    public function findTasksToRun(bool $force, string $task_id = null): Collection
194
-    {
195
-        $query = DB::table('maj_admintasks')
196
-            ->select()
197
-            ->where('majat_status', '=', 'enabled')
198
-            ->where(function (Builder $query): void {
199
-
200
-                $query->where('majat_running', '=', 0)
201
-                ->orWhere('majat_last_run', '<=', Carbon::now()->subSeconds(self::TASK_TIME_OUT));
202
-            });
203
-
204
-        if (!$force) {
205
-            $query->where(function (Builder $query): void {
206
-
207
-                $query->where('majat_running', '=', 0)
208
-                    ->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
209
-            });
210
-        }
211
-
212
-        if ($task_id !== null) {
213
-            $query->where('majat_task_id', '=', $task_id);
214
-        }
215
-
216
-        return $query->get()->map(self::rowMapper());
217
-    }
218
-
219
-    /**
220
-     * Run the task associated with the schedule.
221
-     * The task will run if either forced to, or its next scheduled run time has been exceeded.
222
-     * The last run time is recorded only if the task is successful.
223
-     *
224
-     * @param TaskSchedule $task_schedule
225
-     * @param boolean $force
226
-     */
227
-    public function run(TaskSchedule $task_schedule, $force = false): void
228
-    {
229
-        /** @var TaskSchedule $task_schedule */
230
-        $task_schedule = DB::table('maj_admintasks')
231
-            ->select()
232
-            ->where('majat_id', '=', $task_schedule->id())
233
-            ->lockForUpdate()
234
-            ->get()
235
-            ->map(self::rowMapper())
236
-            ->first();
237
-
238
-        if (
239
-            !$task_schedule->isRunning() &&
240
-            ($force || $task_schedule->lastRunTime()->add($task_schedule->frequency())->lessThan(Carbon::now()))
241
-        ) {
242
-            $task_schedule->setLastResult(false);
243
-
244
-            $task = $this->findTask($task_schedule->taskId());
245
-            if ($task !== null) {
246
-                $task_schedule->startRunning();
247
-                $this->update($task_schedule);
248
-
249
-                try {
250
-                    $task_schedule->setLastResult($task->run($task_schedule));
251
-                } catch (Exception $ex) {
252
-                }
253
-
254
-                if ($task_schedule->wasLastRunSuccess()) {
255
-                    $task_schedule->setLastRunTime(Carbon::now());
256
-                    $task_schedule->decrementRemainingOccurences();
257
-                }
258
-                $task_schedule->stopRunning();
259
-            }
260
-            $this->update($task_schedule);
261
-        }
262
-    }
263
-
264
-    /**
265
-     * Mapper to return a TaskSchedule object from an object.
266
-     *
267
-     * @return Closure
268
-     */
269
-    public static function rowMapper(): Closure
270
-    {
271
-        return static function (stdClass $row): TaskSchedule {
272
-
273
-            return new TaskSchedule(
274
-                (int) $row->majat_id,
275
-                $row->majat_task_id,
276
-                $row->majat_status === 'enabled',
277
-                Carbon::parse($row->majat_last_run),
278
-                (bool) $row->majat_last_result,
279
-                CarbonInterval::minutes($row->majat_frequency),
280
-                (int) $row->majat_nb_occur,
281
-                (bool) $row->majat_running
282
-            );
283
-        };
284
-    }
36
+	/**
37
+	 * Time-out after which the task will be considered not running any more.
38
+	 * In seconds, default 5 mins.
39
+	 * @var integer
40
+	 */
41
+	public const TASK_TIME_OUT = 600;
42
+
43
+	/**
44
+	 * @var Collection $available_tasks
45
+	 */
46
+	private $available_tasks;
47
+
48
+	/**
49
+	 * Returns all Tasks schedules in database.
50
+	 * Stored records can be synchronised with the tasks actually available to the system.
51
+	 *
52
+	 * @param bool $sync_available Should tasks synchronised with available ones
53
+	 * @param bool $include_disabled Should disabled tasks be returned
54
+	 * @return Collection Collection of TaskSchedule
55
+	 */
56
+	public function all(bool $sync_available = false, bool $include_disabled = true): Collection
57
+	{
58
+		$tasks_schedules = DB::table('maj_admintasks')
59
+		->select()
60
+		->get()
61
+		->map(self::rowMapper());
62
+
63
+		if ($sync_available) {
64
+			$available_tasks = clone $this->available();
65
+			foreach ($tasks_schedules as $task_schedule) {
66
+				/** @var TaskSchedule $task_schedule */
67
+				if ($available_tasks->has($task_schedule->taskId())) {
68
+					$available_tasks->forget($task_schedule->taskId());
69
+				} else {
70
+					$this->delete($task_schedule);
71
+				}
72
+			}
73
+
74
+			foreach ($available_tasks as $task_name => $task) {
75
+				/** @var TaskInterface $task */
76
+				$this->insertTask($task_name, $task->defaultFrequency());
77
+			}
78
+
79
+			return $this->all(false, $include_disabled);
80
+		}
81
+
82
+		return $tasks_schedules;
83
+	}
84
+
85
+	/**
86
+	 * Returns tasks exposed through modules implementing ModuleTasksProviderInterface.
87
+	 *
88
+	 * @return Collection
89
+	 */
90
+	public function available(): Collection
91
+	{
92
+		if ($this->available_tasks === null) {
93
+			$tasks_providers = app(ModuleService::class)->findByInterface(ModuleTasksProviderInterface::class);
94
+
95
+			$this->available_tasks = new Collection();
96
+			foreach ($tasks_providers as $task_provider) {
97
+				$this->available_tasks = $this->available_tasks->merge($task_provider->listTasks());
98
+			}
99
+		}
100
+		return $this->available_tasks;
101
+	}
102
+
103
+	/**
104
+	 * Find a task schedule by its ID.
105
+	 *
106
+	 * @param int $task_schedule_id
107
+	 * @return TaskSchedule|NULL
108
+	 */
109
+	public function find(int $task_schedule_id): ?TaskSchedule
110
+	{
111
+		return DB::table('maj_admintasks')
112
+			->select()
113
+			->where('majat_id', '=', $task_schedule_id)
114
+			->get()
115
+			->map(self::rowMapper())
116
+			->first();
117
+	}
118
+
119
+	/**
120
+	 * Add a new task schedule with the specified task ID, and frequency if defined.
121
+	 * Uses default for other settings.
122
+	 *
123
+	 * @param string $task_id
124
+	 * @param int $frequency
125
+	 * @return bool
126
+	 */
127
+	public function insertTask(string $task_id, int $frequency = 0): bool
128
+	{
129
+		$values = ['majat_task_id' => $task_id];
130
+		if ($frequency > 0) {
131
+			$values['majat_frequency'] = $frequency;
132
+		}
133
+
134
+		return DB::table('maj_admintasks')
135
+			->insert($values);
136
+	}
137
+
138
+	/**
139
+	 * Update a task schedule.
140
+	 * Returns the number of tasks schedules updated.
141
+	 *
142
+	 * @param TaskSchedule $task_schedule
143
+	 * @return int
144
+	 */
145
+	public function update(TaskSchedule $task_schedule): int
146
+	{
147
+		return DB::table('maj_admintasks')
148
+			->where('majat_id', '=', $task_schedule->id())
149
+			->update([
150
+				'majat_status'      =>  $task_schedule->isEnabled() ? 'enabled' : 'disabled',
151
+				'majat_last_run'    =>  $task_schedule->lastRunTime(),
152
+				'majat_last_result' =>  $task_schedule->wasLastRunSuccess(),
153
+				'majat_frequency'   =>  $task_schedule->frequency()->totalMinutes,
154
+				'majat_nb_occur'    =>  $task_schedule->remainingOccurences(),
155
+				'majat_running'     =>  $task_schedule->isRunning()
156
+			]);
157
+	}
158
+
159
+	/**
160
+	 * Delete a task schedule.
161
+	 *
162
+	 * @param TaskSchedule $task_schedule
163
+	 * @return int
164
+	 */
165
+	public function delete(TaskSchedule $task_schedule): int
166
+	{
167
+		return DB::table('maj_admintasks')
168
+			->where('majat_id', '=', $task_schedule->id())
169
+			->delete();
170
+	}
171
+
172
+	/**
173
+	 * Find a task by its name
174
+	 *
175
+	 * @param string $task_id
176
+	 * @return TaskInterface|NULL
177
+	 */
178
+	public function findTask(string $task_id): ?TaskInterface
179
+	{
180
+		if ($this->available()->has($task_id)) {
181
+			return app($this->available()->get($task_id));
182
+		}
183
+		return null;
184
+	}
185
+
186
+	/**
187
+	 * Retrieve all tasks that are candidates to be run.
188
+	 *
189
+	 * @param bool $force Should the run be forced
190
+	 * @param string $task_id Specific task ID to be run
191
+	 * @return Collection
192
+	 */
193
+	public function findTasksToRun(bool $force, string $task_id = null): Collection
194
+	{
195
+		$query = DB::table('maj_admintasks')
196
+			->select()
197
+			->where('majat_status', '=', 'enabled')
198
+			->where(function (Builder $query): void {
199
+
200
+				$query->where('majat_running', '=', 0)
201
+				->orWhere('majat_last_run', '<=', Carbon::now()->subSeconds(self::TASK_TIME_OUT));
202
+			});
203
+
204
+		if (!$force) {
205
+			$query->where(function (Builder $query): void {
206
+
207
+				$query->where('majat_running', '=', 0)
208
+					->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
209
+			});
210
+		}
211
+
212
+		if ($task_id !== null) {
213
+			$query->where('majat_task_id', '=', $task_id);
214
+		}
215
+
216
+		return $query->get()->map(self::rowMapper());
217
+	}
218
+
219
+	/**
220
+	 * Run the task associated with the schedule.
221
+	 * The task will run if either forced to, or its next scheduled run time has been exceeded.
222
+	 * The last run time is recorded only if the task is successful.
223
+	 *
224
+	 * @param TaskSchedule $task_schedule
225
+	 * @param boolean $force
226
+	 */
227
+	public function run(TaskSchedule $task_schedule, $force = false): void
228
+	{
229
+		/** @var TaskSchedule $task_schedule */
230
+		$task_schedule = DB::table('maj_admintasks')
231
+			->select()
232
+			->where('majat_id', '=', $task_schedule->id())
233
+			->lockForUpdate()
234
+			->get()
235
+			->map(self::rowMapper())
236
+			->first();
237
+
238
+		if (
239
+			!$task_schedule->isRunning() &&
240
+			($force || $task_schedule->lastRunTime()->add($task_schedule->frequency())->lessThan(Carbon::now()))
241
+		) {
242
+			$task_schedule->setLastResult(false);
243
+
244
+			$task = $this->findTask($task_schedule->taskId());
245
+			if ($task !== null) {
246
+				$task_schedule->startRunning();
247
+				$this->update($task_schedule);
248
+
249
+				try {
250
+					$task_schedule->setLastResult($task->run($task_schedule));
251
+				} catch (Exception $ex) {
252
+				}
253
+
254
+				if ($task_schedule->wasLastRunSuccess()) {
255
+					$task_schedule->setLastRunTime(Carbon::now());
256
+					$task_schedule->decrementRemainingOccurences();
257
+				}
258
+				$task_schedule->stopRunning();
259
+			}
260
+			$this->update($task_schedule);
261
+		}
262
+	}
263
+
264
+	/**
265
+	 * Mapper to return a TaskSchedule object from an object.
266
+	 *
267
+	 * @return Closure
268
+	 */
269
+	public static function rowMapper(): Closure
270
+	{
271
+		return static function (stdClass $row): TaskSchedule {
272
+
273
+			return new TaskSchedule(
274
+				(int) $row->majat_id,
275
+				$row->majat_task_id,
276
+				$row->majat_status === 'enabled',
277
+				Carbon::parse($row->majat_last_run),
278
+				(bool) $row->majat_last_result,
279
+				CarbonInterval::minutes($row->majat_frequency),
280
+				(int) $row->majat_nb_occur,
281
+				(bool) $row->majat_running
282
+			);
283
+		};
284
+	}
285 285
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -195,14 +195,14 @@  discard block
 block discarded – undo
195 195
         $query = DB::table('maj_admintasks')
196 196
             ->select()
197 197
             ->where('majat_status', '=', 'enabled')
198
-            ->where(function (Builder $query): void {
198
+            ->where(function(Builder $query): void {
199 199
 
200 200
                 $query->where('majat_running', '=', 0)
201 201
                 ->orWhere('majat_last_run', '<=', Carbon::now()->subSeconds(self::TASK_TIME_OUT));
202 202
             });
203 203
 
204 204
         if (!$force) {
205
-            $query->where(function (Builder $query): void {
205
+            $query->where(function(Builder $query): void {
206 206
 
207 207
                 $query->where('majat_running', '=', 0)
208 208
                     ->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
@@ -268,17 +268,17 @@  discard block
 block discarded – undo
268 268
      */
269 269
     public static function rowMapper(): Closure
270 270
     {
271
-        return static function (stdClass $row): TaskSchedule {
271
+        return static function(stdClass $row): TaskSchedule {
272 272
 
273 273
             return new TaskSchedule(
274
-                (int) $row->majat_id,
274
+                (int)$row->majat_id,
275 275
                 $row->majat_task_id,
276 276
                 $row->majat_status === 'enabled',
277 277
                 Carbon::parse($row->majat_last_run),
278
-                (bool) $row->majat_last_result,
278
+                (bool)$row->majat_last_result,
279 279
                 CarbonInterval::minutes($row->majat_frequency),
280
-                (int) $row->majat_nb_occur,
281
-                (bool) $row->majat_running
280
+                (int)$row->majat_nb_occur,
281
+                (bool)$row->majat_running
282 282
             );
283 283
         };
284 284
     }
Please login to merge, or discard this patch.
src/Webtrees/Module/AdminTasks/Services/HealthCheckService.php 2 patches
Indentation   +93 added lines, -93 removed lines patch added patch discarded remove patch
@@ -27,101 +27,101 @@
 block discarded – undo
27 27
  */
28 28
 class HealthCheckService
29 29
 {
30
-    /**
31
-     * Returns a query collating all gedcom records, for use in other queries
32
-     *
33
-     * @param Tree $tree
34
-     * @return Builder
35
-     */
36
-    private function allGedcomRecords(Tree $tree): Builder
37
-    {
38
-        return DB::table('individuals')
39
-            ->select(DB::raw("'indi' AS ged_type"), 'i_id AS ged_id')->where('i_file', '=', $tree->id())
40
-            ->unionAll(DB::table('families')
41
-                ->select(DB::raw("'fam' AS ged_type"), 'f_id AS ged_id')->where('f_file', '=', $tree->id()))
42
-            ->unionAll(DB::table('sources')
43
-                ->select(DB::raw("'sour' AS ged_type"), 's_id AS ged_id')->where('s_file', '=', $tree->id()))
44
-            ->unionAll(DB::table('media')
45
-                ->select(DB::raw("'media' AS ged_type"), 'm_id AS ged_id')->where('m_file', '=', $tree->id()))
46
-            ->unionAll(DB::table('other')
47
-                ->select(DB::raw('LOWER(o_type) AS ged_type'), 'o_id AS ged_id')->where('o_file', '=', $tree->id()));
48
-    }
30
+	/**
31
+	 * Returns a query collating all gedcom records, for use in other queries
32
+	 *
33
+	 * @param Tree $tree
34
+	 * @return Builder
35
+	 */
36
+	private function allGedcomRecords(Tree $tree): Builder
37
+	{
38
+		return DB::table('individuals')
39
+			->select(DB::raw("'indi' AS ged_type"), 'i_id AS ged_id')->where('i_file', '=', $tree->id())
40
+			->unionAll(DB::table('families')
41
+				->select(DB::raw("'fam' AS ged_type"), 'f_id AS ged_id')->where('f_file', '=', $tree->id()))
42
+			->unionAll(DB::table('sources')
43
+				->select(DB::raw("'sour' AS ged_type"), 's_id AS ged_id')->where('s_file', '=', $tree->id()))
44
+			->unionAll(DB::table('media')
45
+				->select(DB::raw("'media' AS ged_type"), 'm_id AS ged_id')->where('m_file', '=', $tree->id()))
46
+			->unionAll(DB::table('other')
47
+				->select(DB::raw('LOWER(o_type) AS ged_type'), 'o_id AS ged_id')->where('o_file', '=', $tree->id()));
48
+	}
49 49
 
50
-    /**
51
-     * Returns the count of gedcom records by type in a Tree, as a keyed Collection.
52
-     *
53
-     * Collection output:
54
-     *      - Key : gedcom record type
55
-     *      - Value: count of records
56
-     *
57
-     * @param Tree $tree
58
-     * @return Collection
59
-     */
60
-    public function countByRecordType(Tree $tree): Collection
61
-    {
62
-        return DB::query()
63
-            ->fromSub($this->allGedcomRecords($tree), 'gedrecords')
64
-            ->select('ged_type', new Expression('COUNT(ged_id) AS total'))
65
-            ->groupBy('ged_type')
66
-            ->pluck('total', 'ged_type');
67
-    }
50
+	/**
51
+	 * Returns the count of gedcom records by type in a Tree, as a keyed Collection.
52
+	 *
53
+	 * Collection output:
54
+	 *      - Key : gedcom record type
55
+	 *      - Value: count of records
56
+	 *
57
+	 * @param Tree $tree
58
+	 * @return Collection
59
+	 */
60
+	public function countByRecordType(Tree $tree): Collection
61
+	{
62
+		return DB::query()
63
+			->fromSub($this->allGedcomRecords($tree), 'gedrecords')
64
+			->select('ged_type', new Expression('COUNT(ged_id) AS total'))
65
+			->groupBy('ged_type')
66
+			->pluck('total', 'ged_type');
67
+	}
68 68
 
69
-    /**
70
-     * Returns the count of gedcom records changes by type in a Tree across a number of days, as a keyed Collection.
71
-     *
72
-     * Collection output:
73
-     *      - Key : gedcom record type
74
-     *      - Value: count of changes
75
-     *
76
-     * @param Tree $tree
77
-     * @return Collection
78
-     */
79
-    public function changesByRecordType(Tree $tree, int $nb_days): Collection
80
-    {
81
-        return DB::table('change')
82
-            ->joinSub($this->allGedcomRecords($tree), 'gedrecords', function (JoinClause $join) use ($tree): void {
69
+	/**
70
+	 * Returns the count of gedcom records changes by type in a Tree across a number of days, as a keyed Collection.
71
+	 *
72
+	 * Collection output:
73
+	 *      - Key : gedcom record type
74
+	 *      - Value: count of changes
75
+	 *
76
+	 * @param Tree $tree
77
+	 * @return Collection
78
+	 */
79
+	public function changesByRecordType(Tree $tree, int $nb_days): Collection
80
+	{
81
+		return DB::table('change')
82
+			->joinSub($this->allGedcomRecords($tree), 'gedrecords', function (JoinClause $join) use ($tree): void {
83 83
 
84
-                $join->on('change.xref', '=', 'gedrecords.ged_id')
85
-                    ->where('change.gedcom_id', '=', $tree->id());
86
-            })
87
-            ->select('ged_type AS type', new Expression('COUNT(change_id) AS count'))
88
-            ->where('change.status', '', 'accepted')
89
-            ->where('change.change_time', '>=', Carbon::now()->subDays($nb_days))
90
-            ->groupBy('ged_type')
91
-            ->pluck('total', 'ged_type');
92
-    }
84
+				$join->on('change.xref', '=', 'gedrecords.ged_id')
85
+					->where('change.gedcom_id', '=', $tree->id());
86
+			})
87
+			->select('ged_type AS type', new Expression('COUNT(change_id) AS count'))
88
+			->where('change.status', '', 'accepted')
89
+			->where('change.change_time', '>=', Carbon::now()->subDays($nb_days))
90
+			->groupBy('ged_type')
91
+			->pluck('total', 'ged_type');
92
+	}
93 93
 
94
-    /**
95
-     * Return the error logs associated with a tree across a number of days, grouped by error message, as a Collection.
96
-     *
97
-     * Collection output:
98
-     *      - Value: stdClass object
99
-     *          - log message:  Error log message
100
-     *          - type:         'site' if no associated Tree, the Tree ID otherwise
101
-     *          - nblogs:       The number of occurence of the same error message
102
-     *          - lastoccurred: Date/time of the last occurence of the error message
103
-     *
104
-     * @param Tree $tree
105
-     * @param int $nb_days
106
-     * @return Collection
107
-     */
108
-    public function errorLogs(Tree $tree, int $nb_days): Collection
109
-    {
110
-        return DB::table('log')
111
-            ->select(
112
-                'log_message',
113
-                new Expression("IFNULL(gedcom_id, 'site') as type"),
114
-                new Expression('COUNT(log_id) AS nblogs'),
115
-                new Expression('MAX(log_time) AS lastoccurred')
116
-            )
117
-            ->where('log_type', '=', 'error')
118
-            ->where(function (Builder $query) use ($tree): void {
119
-                $query->where('gedcom_id', '=', $tree->id())
120
-                    ->orWhereNull('gedcom_id');
121
-            })
122
-            ->where('log_time', '>=', Carbon::now()->subDays($nb_days))
123
-            ->groupBy('log_message', 'gedcom_id')
124
-            ->orderByDesc('lastoccurred')
125
-            ->get();
126
-    }
94
+	/**
95
+	 * Return the error logs associated with a tree across a number of days, grouped by error message, as a Collection.
96
+	 *
97
+	 * Collection output:
98
+	 *      - Value: stdClass object
99
+	 *          - log message:  Error log message
100
+	 *          - type:         'site' if no associated Tree, the Tree ID otherwise
101
+	 *          - nblogs:       The number of occurence of the same error message
102
+	 *          - lastoccurred: Date/time of the last occurence of the error message
103
+	 *
104
+	 * @param Tree $tree
105
+	 * @param int $nb_days
106
+	 * @return Collection
107
+	 */
108
+	public function errorLogs(Tree $tree, int $nb_days): Collection
109
+	{
110
+		return DB::table('log')
111
+			->select(
112
+				'log_message',
113
+				new Expression("IFNULL(gedcom_id, 'site') as type"),
114
+				new Expression('COUNT(log_id) AS nblogs'),
115
+				new Expression('MAX(log_time) AS lastoccurred')
116
+			)
117
+			->where('log_type', '=', 'error')
118
+			->where(function (Builder $query) use ($tree): void {
119
+				$query->where('gedcom_id', '=', $tree->id())
120
+					->orWhereNull('gedcom_id');
121
+			})
122
+			->where('log_time', '>=', Carbon::now()->subDays($nb_days))
123
+			->groupBy('log_message', 'gedcom_id')
124
+			->orderByDesc('lastoccurred')
125
+			->get();
126
+	}
127 127
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -79,7 +79,7 @@  discard block
 block discarded – undo
79 79
     public function changesByRecordType(Tree $tree, int $nb_days): Collection
80 80
     {
81 81
         return DB::table('change')
82
-            ->joinSub($this->allGedcomRecords($tree), 'gedrecords', function (JoinClause $join) use ($tree): void {
82
+            ->joinSub($this->allGedcomRecords($tree), 'gedrecords', function(JoinClause $join) use ($tree): void {
83 83
 
84 84
                 $join->on('change.xref', '=', 'gedrecords.ged_id')
85 85
                     ->where('change.gedcom_id', '=', $tree->id());
@@ -115,7 +115,7 @@  discard block
 block discarded – undo
115 115
                 new Expression('MAX(log_time) AS lastoccurred')
116 116
             )
117 117
             ->where('log_type', '=', 'error')
118
-            ->where(function (Builder $query) use ($tree): void {
118
+            ->where(function(Builder $query) use ($tree): void {
119 119
                 $query->where('gedcom_id', '=', $tree->id())
120 120
                     ->orWhereNull('gedcom_id');
121 121
             })
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/SosaConfigAction.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -31,50 +31,50 @@
 block discarded – undo
31 31
  */
32 32
 class SosaConfigAction implements RequestHandlerInterface
33 33
 {
34
-    /**
35
-     * @var UserService $user_service
36
-     */
37
-    private $user_service;
34
+	/**
35
+	 * @var UserService $user_service
36
+	 */
37
+	private $user_service;
38 38
     
39
-    /**
40
-     * Constructor for SosaConfigAction Request Handler
41
-     * 
42
-     * @param UserService $user_service
43
-     */
44
-    public function __construct(UserService $user_service)
45
-    {
46
-        $this->user_service = $user_service;
47
-    }
39
+	/**
40
+	 * Constructor for SosaConfigAction Request Handler
41
+	 * 
42
+	 * @param UserService $user_service
43
+	 */
44
+	public function __construct(UserService $user_service)
45
+	{
46
+		$this->user_service = $user_service;
47
+	}
48 48
     
49
-    /**
50
-     * {@inheritDoc}
51
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
52
-     */
53
-    public function handle(ServerRequestInterface $request): ResponseInterface
54
-    {
55
-        assert($this->user_service instanceof UserService);
49
+	/**
50
+	 * {@inheritDoc}
51
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
52
+	 */
53
+	public function handle(ServerRequestInterface $request): ResponseInterface
54
+	{
55
+		assert($this->user_service instanceof UserService);
56 56
         
57
-        $tree = $request->getAttribute('tree');
58
-        assert($tree instanceof Tree);
57
+		$tree = $request->getAttribute('tree');
58
+		assert($tree instanceof Tree);
59 59
         
60
-        $params = $request->getParsedBody();
61
-        $user_id = (int) $params['sosa-userid'];
62
-        $root_id = $params['sosa-rootid'] ?? '';
60
+		$params = $request->getParsedBody();
61
+		$user_id = (int) $params['sosa-userid'];
62
+		$root_id = $params['sosa-rootid'] ?? '';
63 63
         
64
-        if(Auth::id() == $user_id || ($user_id == -1 && Auth::isManager($tree))) {
65
-            $user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
66
-            if($user !== null && $root_indi = Registry::individualFactory()->make($root_id, $tree)) {
67
-                $tree->setUserPreference($user, 'MAJ_SOSA_ROOT_ID', $root_indi->xref());
68
-                FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
69
-                return redirect(route(SosaConfig::class, [
70
-                    'tree' => $tree->name(),
71
-                    'compute' => 'yes',
72
-                    'user_id' => $user_id
73
-                ]));
74
-            }
75
-        }
64
+		if(Auth::id() == $user_id || ($user_id == -1 && Auth::isManager($tree))) {
65
+			$user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
66
+			if($user !== null && $root_indi = Registry::individualFactory()->make($root_id, $tree)) {
67
+				$tree->setUserPreference($user, 'MAJ_SOSA_ROOT_ID', $root_indi->xref());
68
+				FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
69
+				return redirect(route(SosaConfig::class, [
70
+					'tree' => $tree->name(),
71
+					'compute' => 'yes',
72
+					'user_id' => $user_id
73
+				]));
74
+			}
75
+		}
76 76
         
77
-        FlashMessages::addMessage(I18N::translate('The root individual could not be updated.'), 'danger');
78
-        return redirect(route(SosaConfig::class, ['tree' => $tree->name()]));
79
-    }
77
+		FlashMessages::addMessage(I18N::translate('The root individual could not be updated.'), 'danger');
78
+		return redirect(route(SosaConfig::class, ['tree' => $tree->name()]));
79
+	}
80 80
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -58,12 +58,12 @@
 block discarded – undo
58 58
         assert($tree instanceof Tree);
59 59
         
60 60
         $params = $request->getParsedBody();
61
-        $user_id = (int) $params['sosa-userid'];
61
+        $user_id = (int)$params['sosa-userid'];
62 62
         $root_id = $params['sosa-rootid'] ?? '';
63 63
         
64
-        if(Auth::id() == $user_id || ($user_id == -1 && Auth::isManager($tree))) {
64
+        if (Auth::id() == $user_id || ($user_id == -1 && Auth::isManager($tree))) {
65 65
             $user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
66
-            if($user !== null && $root_indi = Registry::individualFactory()->make($root_id, $tree)) {
66
+            if ($user !== null && $root_indi = Registry::individualFactory()->make($root_id, $tree)) {
67 67
                 $tree->setUserPreference($user, 'MAJ_SOSA_ROOT_ID', $root_indi->xref());
68 68
                 FlashMessages::addMessage(I18N::translate('The root individual has been updated.'));
69 69
                 return redirect(route(SosaConfig::class, [
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/SosaStatistics.php 2 patches
Indentation   +107 added lines, -107 removed lines patch added patch discarded remove patch
@@ -34,125 +34,125 @@
 block discarded – undo
34 34
  */
35 35
 class SosaStatistics implements RequestHandlerInterface
36 36
 {
37
-    use ViewResponseTrait;
37
+	use ViewResponseTrait;
38 38
     
39
-    /**
40
-     * @var SosaModule $module
41
-     */
42
-    private $module;
39
+	/**
40
+	 * @var SosaModule $module
41
+	 */
42
+	private $module;
43 43
     
44
-    /**
45
-     * Constructor for AncestorsList Request Handler
46
-     *
47
-     * @param ModuleService $module_service
48
-     */
49
-    public function __construct(
50
-        ModuleService $module_service
51
-    ) {
52
-        $this->module = $module_service->findByInterface(SosaModule::class)->first();
53
-    }
44
+	/**
45
+	 * Constructor for AncestorsList Request Handler
46
+	 *
47
+	 * @param ModuleService $module_service
48
+	 */
49
+	public function __construct(
50
+		ModuleService $module_service
51
+	) {
52
+		$this->module = $module_service->findByInterface(SosaModule::class)->first();
53
+	}
54 54
     
55
-    /**
56
-     * {@inheritDoc}
57
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
58
-     */
59
-    public function handle(ServerRequestInterface $request): ResponseInterface
60
-    {
61
-        if ($this->module === null) {
62
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
63
-        }
55
+	/**
56
+	 * {@inheritDoc}
57
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
58
+	 */
59
+	public function handle(ServerRequestInterface $request): ResponseInterface
60
+	{
61
+		if ($this->module === null) {
62
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
63
+		}
64 64
         
65
-        $tree = $request->getAttribute('tree');
66
-        assert($tree instanceof Tree);
65
+		$tree = $request->getAttribute('tree');
66
+		assert($tree instanceof Tree);
67 67
         
68
-        $user = Auth::check() ? $request->getAttribute('user') : new DefaultUser();
68
+		$user = Auth::check() ? $request->getAttribute('user') : new DefaultUser();
69 69
         
70
-        /** @var SosaStatisticsService $sosa_stats_service */
71
-        $sosa_stats_service = app()->makeWith(SosaStatisticsService::class, ['tree' => $tree, 'user' => $user]);
70
+		/** @var SosaStatisticsService $sosa_stats_service */
71
+		$sosa_stats_service = app()->makeWith(SosaStatisticsService::class, ['tree' => $tree, 'user' => $user]);
72 72
         
73
-        return $this->viewResponse($this->module->name() . '::statistics-page', [
74
-            'module_name'       =>  $this->module->name(),
75
-            'title'             =>  I18N::translate('Sosa Statistics'),
76
-            'tree'              =>  $tree,
77
-            'theme'             =>  app(ModuleThemeInterface::class),
78
-            'root_indi'         =>  $sosa_stats_service->rootIndividual(),
79
-            'general_stats'     =>  $this->statisticsGeneral($sosa_stats_service),
80
-            'generation_stats'  =>  $this->statisticsByGenerations($sosa_stats_service),
81
-            'generation_depth'  =>  $sosa_stats_service->generationDepthStatsAtGeneration(1)->first(),
82
-            'multiple_sosas'    =>  $sosa_stats_service->topMultipleAncestorsWithNoTies(10)->groupBy('sosa_count'),
83
-            'sosa_dispersion_g2'=>  $sosa_stats_service->ancestorsDispersionForGeneration(2),
84
-            'sosa_dispersion_g3'=>  $sosa_stats_service->ancestorsDispersionForGeneration(3),
85
-            'gen_depth_g3'      =>  $sosa_stats_service->generationDepthStatsAtGeneration(3)
86
-        ]);
87
-    }
73
+		return $this->viewResponse($this->module->name() . '::statistics-page', [
74
+			'module_name'       =>  $this->module->name(),
75
+			'title'             =>  I18N::translate('Sosa Statistics'),
76
+			'tree'              =>  $tree,
77
+			'theme'             =>  app(ModuleThemeInterface::class),
78
+			'root_indi'         =>  $sosa_stats_service->rootIndividual(),
79
+			'general_stats'     =>  $this->statisticsGeneral($sosa_stats_service),
80
+			'generation_stats'  =>  $this->statisticsByGenerations($sosa_stats_service),
81
+			'generation_depth'  =>  $sosa_stats_service->generationDepthStatsAtGeneration(1)->first(),
82
+			'multiple_sosas'    =>  $sosa_stats_service->topMultipleAncestorsWithNoTies(10)->groupBy('sosa_count'),
83
+			'sosa_dispersion_g2'=>  $sosa_stats_service->ancestorsDispersionForGeneration(2),
84
+			'sosa_dispersion_g3'=>  $sosa_stats_service->ancestorsDispersionForGeneration(3),
85
+			'gen_depth_g3'      =>  $sosa_stats_service->generationDepthStatsAtGeneration(3)
86
+		]);
87
+	}
88 88
     
89
-    /**
90
-     * Retrieve and compute the global statistics of ancestors for the tree.
91
-     * Statistics include the number of ancestors, the number of different ancestors, pedigree collapse...
92
-     * 
93
-     * @param SosaStatisticsService sosa_stats_service
94
-     * @return array<string, int|float>
95
-     */
96
-    private function statisticsGeneral(SosaStatisticsService $sosa_stats_service) : array
97
-    {
98
-        $ancestors_count = $sosa_stats_service->totalAncestors();
99
-        $ancestors_distinct_count = $sosa_stats_service->totalDistinctAncestors();
100
-        $individual_count = $sosa_stats_service->totalIndividuals();
89
+	/**
90
+	 * Retrieve and compute the global statistics of ancestors for the tree.
91
+	 * Statistics include the number of ancestors, the number of different ancestors, pedigree collapse...
92
+	 * 
93
+	 * @param SosaStatisticsService sosa_stats_service
94
+	 * @return array<string, int|float>
95
+	 */
96
+	private function statisticsGeneral(SosaStatisticsService $sosa_stats_service) : array
97
+	{
98
+		$ancestors_count = $sosa_stats_service->totalAncestors();
99
+		$ancestors_distinct_count = $sosa_stats_service->totalDistinctAncestors();
100
+		$individual_count = $sosa_stats_service->totalIndividuals();
101 101
         
102
-        return [
103
-            'sosa_count'            =>  $ancestors_count,
104
-            'distinct_count'        =>  $ancestors_distinct_count,
105
-            'sosa_rate'             =>  $this->safeDivision($ancestors_distinct_count, $individual_count),
106
-            'pedi_collapse'         =>  1 - $this->safeDivision($ancestors_distinct_count, $ancestors_count),
107
-            'mean_gen_time'         =>  $sosa_stats_service->meanGenerationTime()
108
-        ];
109
-    }
102
+		return [
103
+			'sosa_count'            =>  $ancestors_count,
104
+			'distinct_count'        =>  $ancestors_distinct_count,
105
+			'sosa_rate'             =>  $this->safeDivision($ancestors_distinct_count, $individual_count),
106
+			'pedi_collapse'         =>  1 - $this->safeDivision($ancestors_distinct_count, $ancestors_count),
107
+			'mean_gen_time'         =>  $sosa_stats_service->meanGenerationTime()
108
+		];
109
+	}
110 110
     
111
-    /**
112
-     * Retrieve and compute the statistics of ancestors by generations.
113
-     * Statistics include the number of ancestors, the number of different ancestors, cumulative statistics...
114
-     * 
115
-     * @param SosaStatisticsService $sosa_stats_service
116
-     * @return array<int, array<string, int|float>
117
-     */
118
-    private function statisticsByGenerations(SosaStatisticsService $sosa_stats_service) : array
119
-    {
120
-        $stats_by_gen = $sosa_stats_service->statisticsByGenerations();
111
+	/**
112
+	 * Retrieve and compute the statistics of ancestors by generations.
113
+	 * Statistics include the number of ancestors, the number of different ancestors, cumulative statistics...
114
+	 * 
115
+	 * @param SosaStatisticsService $sosa_stats_service
116
+	 * @return array<int, array<string, int|float>
117
+	 */
118
+	private function statisticsByGenerations(SosaStatisticsService $sosa_stats_service) : array
119
+	{
120
+		$stats_by_gen = $sosa_stats_service->statisticsByGenerations();
121 121
         
122
-        $generation_stats = array();
122
+		$generation_stats = array();
123 123
         
124
-        foreach($stats_by_gen as $gen => $stats_gen){
125
-            $gen_diff = $gen > 1 ?$stats_gen['diffSosaTotalCount'] - $stats_by_gen[$gen - 1]['diffSosaTotalCount'] : 1;
126
-            $generation_stats[$gen] = array(
127
-                'gen_min_birth' => $stats_gen['firstBirth'] ?? $stats_gen['firstEstimatedBirth'],
128
-                'gen_max_birth' => $stats_gen['lastBirth'] ?? $stats_gen['lastEstimatedBirth'],
129
-                'theoretical' => pow(2, $gen - 1),
130
-                'known' => $stats_gen['sosaCount'],
131
-                'perc_known' => $this->safeDivision($stats_gen['sosaCount'], pow(2, $gen - 1)),
132
-                'missing' => $gen > 1 ? 2 * $stats_by_gen[$gen - 1]['sosaCount'] - $stats_gen['sosaCount'] : 0,
133
-                'perc_missing' => $gen > 1 ? 1 - $this->safeDivision($stats_gen['sosaCount'],  2 * $stats_by_gen[$gen - 1]['sosaCount']) : 0,
134
-                'total_known' => $stats_gen['sosaTotalCount'],
135
-                'perc_total_known' => $this->safeDivision($stats_gen['sosaTotalCount'], pow(2, $gen) - 1),
136
-                'different' => $gen_diff,
137
-                'perc_different' => $this->safeDivision($gen_diff, $stats_gen['sosaCount']),
138
-                'total_different' => $stats_gen['diffSosaTotalCount'],
139
-                'pedi_collapse' => 1 - $this->safeDivision($stats_gen['diffSosaTotalCount'], $stats_gen['sosaTotalCount'])
140
-            );
141
-        }
124
+		foreach($stats_by_gen as $gen => $stats_gen){
125
+			$gen_diff = $gen > 1 ?$stats_gen['diffSosaTotalCount'] - $stats_by_gen[$gen - 1]['diffSosaTotalCount'] : 1;
126
+			$generation_stats[$gen] = array(
127
+				'gen_min_birth' => $stats_gen['firstBirth'] ?? $stats_gen['firstEstimatedBirth'],
128
+				'gen_max_birth' => $stats_gen['lastBirth'] ?? $stats_gen['lastEstimatedBirth'],
129
+				'theoretical' => pow(2, $gen - 1),
130
+				'known' => $stats_gen['sosaCount'],
131
+				'perc_known' => $this->safeDivision($stats_gen['sosaCount'], pow(2, $gen - 1)),
132
+				'missing' => $gen > 1 ? 2 * $stats_by_gen[$gen - 1]['sosaCount'] - $stats_gen['sosaCount'] : 0,
133
+				'perc_missing' => $gen > 1 ? 1 - $this->safeDivision($stats_gen['sosaCount'],  2 * $stats_by_gen[$gen - 1]['sosaCount']) : 0,
134
+				'total_known' => $stats_gen['sosaTotalCount'],
135
+				'perc_total_known' => $this->safeDivision($stats_gen['sosaTotalCount'], pow(2, $gen) - 1),
136
+				'different' => $gen_diff,
137
+				'perc_different' => $this->safeDivision($gen_diff, $stats_gen['sosaCount']),
138
+				'total_different' => $stats_gen['diffSosaTotalCount'],
139
+				'pedi_collapse' => 1 - $this->safeDivision($stats_gen['diffSosaTotalCount'], $stats_gen['sosaTotalCount'])
140
+			);
141
+		}
142 142
         
143
-        return $generation_stats;
144
-    }
143
+		return $generation_stats;
144
+	}
145 145
     
146
-    /**
147
-     * Return the result of a division, and a default value if denominator is 0
148
-     * 
149
-     * @param int $p Numerator
150
-     * @param int $q Denominator
151
-     * @param float $default Value if denominator is 0
152
-     * @return float
153
-     */
154
-    private function safeDivision(int $p, int $q, float $default = 0) : float
155
-    {
156
-        return $q == 0 ? $default : $p / $q;
157
-    }
146
+	/**
147
+	 * Return the result of a division, and a default value if denominator is 0
148
+	 * 
149
+	 * @param int $p Numerator
150
+	 * @param int $q Denominator
151
+	 * @param float $default Value if denominator is 0
152
+	 * @return float
153
+	 */
154
+	private function safeDivision(int $p, int $q, float $default = 0) : float
155
+	{
156
+		return $q == 0 ? $default : $p / $q;
157
+	}
158 158
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
         /** @var SosaStatisticsService $sosa_stats_service */
71 71
         $sosa_stats_service = app()->makeWith(SosaStatisticsService::class, ['tree' => $tree, 'user' => $user]);
72 72
         
73
-        return $this->viewResponse($this->module->name() . '::statistics-page', [
73
+        return $this->viewResponse($this->module->name().'::statistics-page', [
74 74
             'module_name'       =>  $this->module->name(),
75 75
             'title'             =>  I18N::translate('Sosa Statistics'),
76 76
             'tree'              =>  $tree,
@@ -121,8 +121,8 @@  discard block
 block discarded – undo
121 121
         
122 122
         $generation_stats = array();
123 123
         
124
-        foreach($stats_by_gen as $gen => $stats_gen){
125
-            $gen_diff = $gen > 1 ?$stats_gen['diffSosaTotalCount'] - $stats_by_gen[$gen - 1]['diffSosaTotalCount'] : 1;
124
+        foreach ($stats_by_gen as $gen => $stats_gen) {
125
+            $gen_diff = $gen > 1 ? $stats_gen['diffSosaTotalCount'] - $stats_by_gen[$gen - 1]['diffSosaTotalCount'] : 1;
126 126
             $generation_stats[$gen] = array(
127 127
                 'gen_min_birth' => $stats_gen['firstBirth'] ?? $stats_gen['firstEstimatedBirth'],
128 128
                 'gen_max_birth' => $stats_gen['lastBirth'] ?? $stats_gen['lastEstimatedBirth'],
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
                 'known' => $stats_gen['sosaCount'],
131 131
                 'perc_known' => $this->safeDivision($stats_gen['sosaCount'], pow(2, $gen - 1)),
132 132
                 'missing' => $gen > 1 ? 2 * $stats_by_gen[$gen - 1]['sosaCount'] - $stats_gen['sosaCount'] : 0,
133
-                'perc_missing' => $gen > 1 ? 1 - $this->safeDivision($stats_gen['sosaCount'],  2 * $stats_by_gen[$gen - 1]['sosaCount']) : 0,
133
+                'perc_missing' => $gen > 1 ? 1 - $this->safeDivision($stats_gen['sosaCount'], 2 * $stats_by_gen[$gen - 1]['sosaCount']) : 0,
134 134
                 'total_known' => $stats_gen['sosaTotalCount'],
135 135
                 'perc_total_known' => $this->safeDivision($stats_gen['sosaTotalCount'], pow(2, $gen) - 1),
136 136
                 'different' => $gen_diff,
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/SosaComputeAction.php 2 patches
Indentation   +36 added lines, -36 removed lines patch added patch discarded remove patch
@@ -32,48 +32,48 @@
 block discarded – undo
32 32
  */
33 33
 class SosaComputeAction implements RequestHandlerInterface
34 34
 {
35
-    /**
36
-     * @var UserService $user_service
37
-     */
38
-    private $user_service;
35
+	/**
36
+	 * @var UserService $user_service
37
+	 */
38
+	private $user_service;
39 39
     
40
-    /**
41
-     * Constructor for SosaConfigAction Request Handler
42
-     * 
43
-     * @param UserService $user_service
44
-     */
45
-    public function __construct(UserService $user_service)
46
-    {
47
-        $this->user_service = $user_service;
48
-    }
40
+	/**
41
+	 * Constructor for SosaConfigAction Request Handler
42
+	 * 
43
+	 * @param UserService $user_service
44
+	 */
45
+	public function __construct(UserService $user_service)
46
+	{
47
+		$this->user_service = $user_service;
48
+	}
49 49
     
50
-    /**
51
-     * {@inheritDoc}
52
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
53
-     */
54
-    public function handle(ServerRequestInterface $request): ResponseInterface
55
-    {
56
-        $tree = $request->getAttribute('tree');
57
-        assert($tree instanceof Tree);
50
+	/**
51
+	 * {@inheritDoc}
52
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
53
+	 */
54
+	public function handle(ServerRequestInterface $request): ResponseInterface
55
+	{
56
+		$tree = $request->getAttribute('tree');
57
+		assert($tree instanceof Tree);
58 58
         
59
-        $user_id = (int) ($request->getParsedBody()['user_id'] ?? 0);
60
-        $partial_from = $request->getParsedBody()['partial_from'] ?? null;
59
+		$user_id = (int) ($request->getParsedBody()['user_id'] ?? 0);
60
+		$partial_from = $request->getParsedBody()['partial_from'] ?? null;
61 61
         
62
-        if(($user_id == -1 && Auth::isManager($tree)) || Auth::id() == $user_id) {
63
-            $user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
62
+		if(($user_id == -1 && Auth::isManager($tree)) || Auth::id() == $user_id) {
63
+			$user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
64 64
             
65
-            /** @var SosaCalculatorService $sosa_calc_service */
66
-            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
65
+			/** @var SosaCalculatorService $sosa_calc_service */
66
+			$sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
67 67
             
68
-            if($partial_from !== null && $sosa_from = Registry::individualFactory()->make($partial_from, $tree)) {
69
-                $res = $sosa_calc_service->computeFromIndividual($sosa_from);
70
-            } else {
71
-                $res = $sosa_calc_service->computeAll();
72
-            }
68
+			if($partial_from !== null && $sosa_from = Registry::individualFactory()->make($partial_from, $tree)) {
69
+				$res = $sosa_calc_service->computeFromIndividual($sosa_from);
70
+			} else {
71
+				$res = $sosa_calc_service->computeAll();
72
+			}
73 73
             
74
-            return $res ? response('', 200) : response(I18N::translate('An error occurred during Sosa computation.'), 500);
74
+			return $res ? response('', 200) : response(I18N::translate('An error occurred during Sosa computation.'), 500);
75 75
             
76
-        }
77
-        throw new HttpAccessDeniedException(I18N::translate("You do not have permission to modify the user"));
78
-    }
76
+		}
77
+		throw new HttpAccessDeniedException(I18N::translate("You do not have permission to modify the user"));
78
+	}
79 79
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -56,16 +56,16 @@
 block discarded – undo
56 56
         $tree = $request->getAttribute('tree');
57 57
         assert($tree instanceof Tree);
58 58
         
59
-        $user_id = (int) ($request->getParsedBody()['user_id'] ?? 0);
59
+        $user_id = (int)($request->getParsedBody()['user_id'] ?? 0);
60 60
         $partial_from = $request->getParsedBody()['partial_from'] ?? null;
61 61
         
62
-        if(($user_id == -1 && Auth::isManager($tree)) || Auth::id() == $user_id) {
62
+        if (($user_id == -1 && Auth::isManager($tree)) || Auth::id() == $user_id) {
63 63
             $user = $user_id == -1 ? new DefaultUser() : $this->user_service->find($user_id);
64 64
             
65 65
             /** @var SosaCalculatorService $sosa_calc_service */
66
-            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, [ 'tree' => $tree, 'user' => $user]);
66
+            $sosa_calc_service = app()->makeWith(SosaCalculatorService::class, ['tree' => $tree, 'user' => $user]);
67 67
             
68
-            if($partial_from !== null && $sosa_from = Registry::individualFactory()->make($partial_from, $tree)) {
68
+            if ($partial_from !== null && $sosa_from = Registry::individualFactory()->make($partial_from, $tree)) {
69 69
                 $res = $sosa_calc_service->computeFromIndividual($sosa_from);
70 70
             } else {
71 71
                 $res = $sosa_calc_service->computeAll();
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Http/RequestHandlers/SosaConfig.php 2 patches
Indentation   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -32,58 +32,58 @@
 block discarded – undo
32 32
  */
33 33
 class SosaConfig implements RequestHandlerInterface
34 34
 {
35
-    use ViewResponseTrait;
35
+	use ViewResponseTrait;
36 36
     
37
-    /**
38
-     * @var SosaModule $module
39
-     */
40
-    private $module;
37
+	/**
38
+	 * @var SosaModule $module
39
+	 */
40
+	private $module;
41 41
     
42
-    /**
43
-     * Constructor for SosaConfig Request Handler
44
-     *
45
-     * @param ModuleService $module_service
46
-     */
47
-    public function __construct(
48
-        ModuleService $module_service
49
-    ) {
50
-        $this->module = $module_service->findByInterface(SosaModule::class)->first();
51
-    }
42
+	/**
43
+	 * Constructor for SosaConfig Request Handler
44
+	 *
45
+	 * @param ModuleService $module_service
46
+	 */
47
+	public function __construct(
48
+		ModuleService $module_service
49
+	) {
50
+		$this->module = $module_service->findByInterface(SosaModule::class)->first();
51
+	}
52 52
     
53
-    /**
54
-     * {@inheritDoc}
55
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
56
-     */
57
-    public function handle(ServerRequestInterface $request): ResponseInterface
58
-    {
59
-        if ($this->module === null) {
60
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
61
-        }
53
+	/**
54
+	 * {@inheritDoc}
55
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
56
+	 */
57
+	public function handle(ServerRequestInterface $request): ResponseInterface
58
+	{
59
+		if ($this->module === null) {
60
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
61
+		}
62 62
         
63
-        /** @var Tree $tree */
64
-        $tree = $request->getAttribute('tree');
65
-        assert($tree instanceof Tree);
63
+		/** @var Tree $tree */
64
+		$tree = $request->getAttribute('tree');
65
+		assert($tree instanceof Tree);
66 66
         
67
-        $users_root = array();
68
-        if(Auth::check()) {
69
-            /** @var \Fisharebest\Webtrees\User $user */
70
-            $user = Auth::user();
71
-            $users_root[] = ['user' => $user, 'root_id' => $tree->getUserPreference($user, 'MAJ_SOSA_ROOT_ID')];
67
+		$users_root = array();
68
+		if(Auth::check()) {
69
+			/** @var \Fisharebest\Webtrees\User $user */
70
+			$user = Auth::user();
71
+			$users_root[] = ['user' => $user, 'root_id' => $tree->getUserPreference($user, 'MAJ_SOSA_ROOT_ID')];
72 72
             
73
-            if(Auth::isManager($tree)) {
74
-                $default_user = new DefaultUser();
75
-                $users_root[] = ['user' => $default_user, 'root_id' => $tree->getUserPreference($default_user, 'MAJ_SOSA_ROOT_ID')];
76
-            }
77
-        }
73
+			if(Auth::isManager($tree)) {
74
+				$default_user = new DefaultUser();
75
+				$users_root[] = ['user' => $default_user, 'root_id' => $tree->getUserPreference($default_user, 'MAJ_SOSA_ROOT_ID')];
76
+			}
77
+		}
78 78
         
79
-        return $this->viewResponse($this->module->name() . '::config-page', [
80
-            'module_name'       =>  $this->module->name(),
81
-            'title'             =>  I18N::translate('Sosa Configuration'),
82
-            'tree'              =>  $tree,
83
-            'user_id'           =>  $request->getAttribute('user'),
84
-            'selected_user_id'  =>  (int) ($request->getQueryParams()['user_id'] ?? 0),
85
-            'immediate_compute' =>  ($request->getQueryParams()['compute'] ?? '') == 'yes',
86
-            'users_root'        =>  $users_root
87
-        ]);
88
-    }
79
+		return $this->viewResponse($this->module->name() . '::config-page', [
80
+			'module_name'       =>  $this->module->name(),
81
+			'title'             =>  I18N::translate('Sosa Configuration'),
82
+			'tree'              =>  $tree,
83
+			'user_id'           =>  $request->getAttribute('user'),
84
+			'selected_user_id'  =>  (int) ($request->getQueryParams()['user_id'] ?? 0),
85
+			'immediate_compute' =>  ($request->getQueryParams()['compute'] ?? '') == 'yes',
86
+			'users_root'        =>  $users_root
87
+		]);
88
+	}
89 89
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -65,23 +65,23 @@
 block discarded – undo
65 65
         assert($tree instanceof Tree);
66 66
         
67 67
         $users_root = array();
68
-        if(Auth::check()) {
68
+        if (Auth::check()) {
69 69
             /** @var \Fisharebest\Webtrees\User $user */
70 70
             $user = Auth::user();
71 71
             $users_root[] = ['user' => $user, 'root_id' => $tree->getUserPreference($user, 'MAJ_SOSA_ROOT_ID')];
72 72
             
73
-            if(Auth::isManager($tree)) {
73
+            if (Auth::isManager($tree)) {
74 74
                 $default_user = new DefaultUser();
75 75
                 $users_root[] = ['user' => $default_user, 'root_id' => $tree->getUserPreference($default_user, 'MAJ_SOSA_ROOT_ID')];
76 76
             }
77 77
         }
78 78
         
79
-        return $this->viewResponse($this->module->name() . '::config-page', [
79
+        return $this->viewResponse($this->module->name().'::config-page', [
80 80
             'module_name'       =>  $this->module->name(),
81 81
             'title'             =>  I18N::translate('Sosa Configuration'),
82 82
             'tree'              =>  $tree,
83 83
             'user_id'           =>  $request->getAttribute('user'),
84
-            'selected_user_id'  =>  (int) ($request->getQueryParams()['user_id'] ?? 0),
84
+            'selected_user_id'  =>  (int)($request->getQueryParams()['user_id'] ?? 0),
85 85
             'immediate_compute' =>  ($request->getQueryParams()['compute'] ?? '') == 'yes',
86 86
             'users_root'        =>  $users_root
87 87
         ]);
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Schema/Migration1.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -22,12 +22,12 @@
 block discarded – undo
22 22
 class Migration1 implements MigrationInterface
23 23
 {
24 24
     
25
-    /**
26
-     * {@inheritDoc}
27
-     * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
28
-     */
29
-    public function upgrade(): void
30
-    {
31
-        // These migrations have been merged into migration 2.
32
-    }
25
+	/**
26
+	 * {@inheritDoc}
27
+	 * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
28
+	 */
29
+	public function upgrade(): void
30
+	{
31
+		// These migrations have been merged into migration 2.
32
+	}
33 33
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Schema/Migration0.php 1 patch
Indentation   +5 added lines, -5 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
-     */
25
+	/**
26
+	 * {@inheritDoc}
27
+	 * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
28
+	 */
29 29
 	public function upgrade(): void
30 30
 	{
31
-	    // These migrations have been merged into migration 2.
31
+		// These migrations have been merged into migration 2.
32 32
 	}
33 33
 }
Please login to merge, or discard this patch.
src/Webtrees/Module/Sosa/Schema/Migration2.php 2 patches
Indentation   +23 added lines, -23 removed lines patch added patch discarded remove patch
@@ -23,36 +23,36 @@
 block discarded – undo
23 23
  */
24 24
 class Migration2 implements MigrationInterface {
25 25
     
26
-    /**
27
-     * {@inheritDoc}
28
-     * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
29
-     */
26
+	/**
27
+	 * {@inheritDoc}
28
+	 * @see \Fisharebest\Webtrees\Schema\MigrationInterface::upgrade()
29
+	 */
30 30
 	public function upgrade(): void
31 31
 	{
32 32
 	    
33
-	    // Clean up previous sosa table if it exists
34
-	    DB::schema()->dropIfExists('maj_sosa');
33
+		// Clean up previous sosa table if it exists
34
+		DB::schema()->dropIfExists('maj_sosa');
35 35
 	    
36
-	    DB::schema()->create('maj_sosa', static function (Blueprint $table): void {
36
+		DB::schema()->create('maj_sosa', static function (Blueprint $table): void {
37 37
 	        
38
-	        $table->integer('majs_gedcom_id');
39
-	        $table->integer('majs_user_id')->default(-1);
40
-	        $table->bigInteger('majs_sosa')->unsigned(); // Allow to calculate sosa on 64 generations
41
-	        $table->string('majs_i_id', 20);
42
-	        $table->tinyInteger('majs_gen')->nullable();
43
-	        $table->smallInteger('majs_birth_year')->nullable();
44
-	        $table->smallInteger('majs_birth_year_est')->nullable();
45
-	        $table->smallInteger('majs_death_year')->nullable();
46
-	        $table->smallInteger('majs_death_year_est')->nullable();
38
+			$table->integer('majs_gedcom_id');
39
+			$table->integer('majs_user_id')->default(-1);
40
+			$table->bigInteger('majs_sosa')->unsigned(); // Allow to calculate sosa on 64 generations
41
+			$table->string('majs_i_id', 20);
42
+			$table->tinyInteger('majs_gen')->nullable();
43
+			$table->smallInteger('majs_birth_year')->nullable();
44
+			$table->smallInteger('majs_birth_year_est')->nullable();
45
+			$table->smallInteger('majs_death_year')->nullable();
46
+			$table->smallInteger('majs_death_year_est')->nullable();
47 47
 	        
48
-	        $table->primary(['majs_gedcom_id', 'majs_user_id', 'majs_sosa']);
48
+			$table->primary(['majs_gedcom_id', 'majs_user_id', 'majs_sosa']);
49 49
 	        
50
-	        $table->index(['majs_gedcom_id', 'majs_user_id']);
51
-	        $table->index(['majs_gedcom_id', 'majs_user_id', 'majs_i_id']);
52
-	        $table->index(['majs_gedcom_id', 'majs_user_id', 'majs_gen']);
50
+			$table->index(['majs_gedcom_id', 'majs_user_id']);
51
+			$table->index(['majs_gedcom_id', 'majs_user_id', 'majs_i_id']);
52
+			$table->index(['majs_gedcom_id', 'majs_user_id', 'majs_gen']);
53 53
 	        
54
-	        $table->foreign('majs_gedcom_id')->references('gedcom_id')->on('gedcom')->onDelete('cascade');
55
-	        $table->foreign('majs_user_id')->references('user_id')->on('user')->onDelete('cascade');
56
-	    });
54
+			$table->foreign('majs_gedcom_id')->references('gedcom_id')->on('gedcom')->onDelete('cascade');
55
+			$table->foreign('majs_user_id')->references('user_id')->on('user')->onDelete('cascade');
56
+		});
57 57
 	}
58 58
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -33,7 +33,7 @@
 block discarded – undo
33 33
 	    // Clean up previous sosa table if it exists
34 34
 	    DB::schema()->dropIfExists('maj_sosa');
35 35
 	    
36
-	    DB::schema()->create('maj_sosa', static function (Blueprint $table): void {
36
+	    DB::schema()->create('maj_sosa', static function(Blueprint $table): void {
37 37
 	        
38 38
 	        $table->integer('majs_gedcom_id');
39 39
 	        $table->integer('majs_user_id')->default(-1);
Please login to merge, or discard this patch.