Passed
Push — feature/code-analysis ( e964aa...4fe35d )
by Jonathan
14:33
created
app/Module/AdminTasks/Schema/Migration0.php 1 patch
Indentation   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -21,12 +21,12 @@
 block discarded – undo
21 21
  */
22 22
 class Migration0 implements MigrationInterface
23 23
 {
24
-    /**
25
-     * {@inheritDoc}
26
-     * @see MigrationInterface::upgrade()
27
-     */
28
-    public function upgrade(): void
29
-    {
30
-        // These migrations have been merged into migration 1.
31
-    }
24
+	/**
25
+	 * {@inheritDoc}
26
+	 * @see MigrationInterface::upgrade()
27
+	 */
28
+	public function upgrade(): void
29
+	{
30
+		// These migrations have been merged into migration 1.
31
+	}
32 32
 }
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TasksList.php 2 patches
Indentation   +83 added lines, -83 removed lines patch added patch discarded remove patch
@@ -31,91 +31,91 @@
 block discarded – undo
31 31
  */
32 32
 class TasksList implements RequestHandlerInterface
33 33
 {
34
-    private ?AdminTasksModule $module;
35
-    private TaskScheduleService $taskschedules_service;
34
+	private ?AdminTasksModule $module;
35
+	private TaskScheduleService $taskschedules_service;
36 36
 
37
-    /**
38
-     * Constructor for TasksList Request Handler
39
-     *
40
-     * @param ModuleService $module_service
41
-     * @param TaskScheduleService $taskschedules_service
42
-     */
43
-    public function __construct(
44
-        ModuleService $module_service,
45
-        TaskScheduleService $taskschedules_service
46
-    ) {
47
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
48
-        $this->taskschedules_service = $taskschedules_service;
49
-    }
37
+	/**
38
+	 * Constructor for TasksList Request Handler
39
+	 *
40
+	 * @param ModuleService $module_service
41
+	 * @param TaskScheduleService $taskschedules_service
42
+	 */
43
+	public function __construct(
44
+		ModuleService $module_service,
45
+		TaskScheduleService $taskschedules_service
46
+	) {
47
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
48
+		$this->taskschedules_service = $taskschedules_service;
49
+	}
50 50
 
51
-    /**
52
-     * {@inheritDoc}
53
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
-     */
55
-    public function handle(ServerRequestInterface $request): ResponseInterface
56
-    {
57
-        if ($this->module === null) {
58
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
59
-        }
51
+	/**
52
+	 * {@inheritDoc}
53
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
+	 */
55
+	public function handle(ServerRequestInterface $request): ResponseInterface
56
+	{
57
+		if ($this->module === null) {
58
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
59
+		}
60 60
 
61
-        $module = $this->module;
62
-        $module_name = $this->module->name();
63
-        return response(['data' => $this->taskschedules_service->all(true, true)
64
-            ->map(function (TaskSchedule $schedule) use ($module, $module_name): array {
65
-                $task = $this->taskschedules_service->findTask($schedule->taskId());
66
-                $task_name = $task !== null ? $task->name() : I18N::translate('Task not found');
61
+		$module = $this->module;
62
+		$module_name = $this->module->name();
63
+		return response(['data' => $this->taskschedules_service->all(true, true)
64
+			->map(function (TaskSchedule $schedule) use ($module, $module_name): array {
65
+				$task = $this->taskschedules_service->findTask($schedule->taskId());
66
+				$task_name = $task !== null ? $task->name() : I18N::translate('Task not found');
67 67
 
68
-                return [
69
-                    'edit' =>   view($module_name . '::admin/tasks-table-options', [
70
-                        'task_sched_id' => $schedule->id(),
71
-                        'task_sched_enabled' => $schedule->isEnabled(),
72
-                        'task_edit_route' => route(TaskEditPage::class, ['task' => $schedule->id()]),
73
-                        'task_status_route' => route(TaskStatusAction::class, [
74
-                            'task' => $schedule->id(),
75
-                            'enable' => $schedule->isEnabled() ? 0 : 1
76
-                        ])
77
-                    ]),
78
-                    'status'    =>  [
79
-                        'display'   =>  view($module_name . '::components/yes-no-icons', [
80
-                            'yes' => $schedule->isEnabled()
81
-                        ]),
82
-                        'raw'       =>  $schedule->isEnabled() ? 1 : 0
83
-                    ],
84
-                    'task_name' =>  [
85
-                        'display'   =>  '<bdi>' . e($task_name) . '</bdi>',
86
-                        'raw'       =>  $task_name
87
-                    ],
88
-                    'last_run'  =>  [
89
-                        'display'   =>  $schedule->lastRunTime()->timestamp() === 0 ?
90
-                            view('components/datetime', ['timestamp' => $schedule->lastRunTime()]) :
91
-                            view('components/datetime-diff', ['timestamp' => $schedule->lastRunTime()]),
92
-                        'raw'       =>  $schedule->lastRunTime()->timestamp()
93
-                    ],
94
-                    'last_result'   =>  [
95
-                        'display'   => view($module_name . '::components/yes-no-icons', [
96
-                            'yes' => $schedule->wasLastRunSuccess()
97
-                        ]),
98
-                        'raw'       =>  $schedule->wasLastRunSuccess() ? 1 : 0
99
-                    ],
100
-                    'frequency' =>
101
-                        '<bdi>' . e(CarbonInterval::minutes($schedule->frequency())->cascade()->forHumans()) . '</bdi>',
102
-                    'nb_occurrences'    =>  $schedule->remainingOccurrences() > 0 ?
103
-                        I18N::number($schedule->remainingOccurrences()) :
104
-                        I18N::translate('Unlimited'),
105
-                    'running'   =>  view($module_name . '::components/yes-no-icons', [
106
-                        'yes' => $schedule->isRunning(),
107
-                        'text_yes' => I18N::translate('Running'),
108
-                        'text_no' => I18N::translate('Not running')
109
-                    ]),
110
-                    'run'       =>  view($module_name . '::admin/tasks-table-run', [
111
-                        'task_sched_id' => $schedule->id(),
112
-                        'run_route' => route(TaskTrigger::class, [
113
-                            'task'  =>  $schedule->taskId(),
114
-                            'force' =>  $module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN')
115
-                        ])
116
-                    ])
117
-                ];
118
-            })
119
-        ]);
120
-    }
68
+				return [
69
+					'edit' =>   view($module_name . '::admin/tasks-table-options', [
70
+						'task_sched_id' => $schedule->id(),
71
+						'task_sched_enabled' => $schedule->isEnabled(),
72
+						'task_edit_route' => route(TaskEditPage::class, ['task' => $schedule->id()]),
73
+						'task_status_route' => route(TaskStatusAction::class, [
74
+							'task' => $schedule->id(),
75
+							'enable' => $schedule->isEnabled() ? 0 : 1
76
+						])
77
+					]),
78
+					'status'    =>  [
79
+						'display'   =>  view($module_name . '::components/yes-no-icons', [
80
+							'yes' => $schedule->isEnabled()
81
+						]),
82
+						'raw'       =>  $schedule->isEnabled() ? 1 : 0
83
+					],
84
+					'task_name' =>  [
85
+						'display'   =>  '<bdi>' . e($task_name) . '</bdi>',
86
+						'raw'       =>  $task_name
87
+					],
88
+					'last_run'  =>  [
89
+						'display'   =>  $schedule->lastRunTime()->timestamp() === 0 ?
90
+							view('components/datetime', ['timestamp' => $schedule->lastRunTime()]) :
91
+							view('components/datetime-diff', ['timestamp' => $schedule->lastRunTime()]),
92
+						'raw'       =>  $schedule->lastRunTime()->timestamp()
93
+					],
94
+					'last_result'   =>  [
95
+						'display'   => view($module_name . '::components/yes-no-icons', [
96
+							'yes' => $schedule->wasLastRunSuccess()
97
+						]),
98
+						'raw'       =>  $schedule->wasLastRunSuccess() ? 1 : 0
99
+					],
100
+					'frequency' =>
101
+						'<bdi>' . e(CarbonInterval::minutes($schedule->frequency())->cascade()->forHumans()) . '</bdi>',
102
+					'nb_occurrences'    =>  $schedule->remainingOccurrences() > 0 ?
103
+						I18N::number($schedule->remainingOccurrences()) :
104
+						I18N::translate('Unlimited'),
105
+					'running'   =>  view($module_name . '::components/yes-no-icons', [
106
+						'yes' => $schedule->isRunning(),
107
+						'text_yes' => I18N::translate('Running'),
108
+						'text_no' => I18N::translate('Not running')
109
+					]),
110
+					'run'       =>  view($module_name . '::admin/tasks-table-run', [
111
+						'task_sched_id' => $schedule->id(),
112
+						'run_route' => route(TaskTrigger::class, [
113
+							'task'  =>  $schedule->taskId(),
114
+							'force' =>  $module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN')
115
+						])
116
+					])
117
+				];
118
+			})
119
+		]);
120
+	}
121 121
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -12 removed lines patch added patch discarded remove patch
@@ -61,12 +61,12 @@  discard block
 block discarded – undo
61 61
         $module = $this->module;
62 62
         $module_name = $this->module->name();
63 63
         return response(['data' => $this->taskschedules_service->all(true, true)
64
-            ->map(function (TaskSchedule $schedule) use ($module, $module_name): array {
64
+            ->map(function(TaskSchedule $schedule) use ($module, $module_name): array {
65 65
                 $task = $this->taskschedules_service->findTask($schedule->taskId());
66 66
                 $task_name = $task !== null ? $task->name() : I18N::translate('Task not found');
67 67
 
68 68
                 return [
69
-                    'edit' =>   view($module_name . '::admin/tasks-table-options', [
69
+                    'edit' =>   view($module_name.'::admin/tasks-table-options', [
70 70
                         'task_sched_id' => $schedule->id(),
71 71
                         'task_sched_enabled' => $schedule->isEnabled(),
72 72
                         'task_edit_route' => route(TaskEditPage::class, ['task' => $schedule->id()]),
@@ -76,38 +76,36 @@  discard block
 block discarded – undo
76 76
                         ])
77 77
                     ]),
78 78
                     'status'    =>  [
79
-                        'display'   =>  view($module_name . '::components/yes-no-icons', [
79
+                        'display'   =>  view($module_name.'::components/yes-no-icons', [
80 80
                             'yes' => $schedule->isEnabled()
81 81
                         ]),
82 82
                         'raw'       =>  $schedule->isEnabled() ? 1 : 0
83 83
                     ],
84 84
                     'task_name' =>  [
85
-                        'display'   =>  '<bdi>' . e($task_name) . '</bdi>',
85
+                        'display'   =>  '<bdi>'.e($task_name).'</bdi>',
86 86
                         'raw'       =>  $task_name
87 87
                     ],
88 88
                     'last_run'  =>  [
89 89
                         'display'   =>  $schedule->lastRunTime()->timestamp() === 0 ?
90
-                            view('components/datetime', ['timestamp' => $schedule->lastRunTime()]) :
91
-                            view('components/datetime-diff', ['timestamp' => $schedule->lastRunTime()]),
90
+                            view('components/datetime', ['timestamp' => $schedule->lastRunTime()]) : view('components/datetime-diff', ['timestamp' => $schedule->lastRunTime()]),
92 91
                         'raw'       =>  $schedule->lastRunTime()->timestamp()
93 92
                     ],
94 93
                     'last_result'   =>  [
95
-                        'display'   => view($module_name . '::components/yes-no-icons', [
94
+                        'display'   => view($module_name.'::components/yes-no-icons', [
96 95
                             'yes' => $schedule->wasLastRunSuccess()
97 96
                         ]),
98 97
                         'raw'       =>  $schedule->wasLastRunSuccess() ? 1 : 0
99 98
                     ],
100 99
                     'frequency' =>
101
-                        '<bdi>' . e(CarbonInterval::minutes($schedule->frequency())->cascade()->forHumans()) . '</bdi>',
100
+                        '<bdi>'.e(CarbonInterval::minutes($schedule->frequency())->cascade()->forHumans()).'</bdi>',
102 101
                     'nb_occurrences'    =>  $schedule->remainingOccurrences() > 0 ?
103
-                        I18N::number($schedule->remainingOccurrences()) :
104
-                        I18N::translate('Unlimited'),
105
-                    'running'   =>  view($module_name . '::components/yes-no-icons', [
102
+                        I18N::number($schedule->remainingOccurrences()) : I18N::translate('Unlimited'),
103
+                    'running'   =>  view($module_name.'::components/yes-no-icons', [
106 104
                         'yes' => $schedule->isRunning(),
107 105
                         'text_yes' => I18N::translate('Running'),
108 106
                         'text_no' => I18N::translate('Not running')
109 107
                     ]),
110
-                    'run'       =>  view($module_name . '::admin/tasks-table-run', [
108
+                    'run'       =>  view($module_name.'::admin/tasks-table-run', [
111 109
                         'task_sched_id' => $schedule->id(),
112 110
                         'run_route' => route(TaskTrigger::class, [
113 111
                             'task'  =>  $schedule->taskId(),
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TaskStatusAction.php 2 patches
Indentation   +57 added lines, -57 removed lines patch added patch discarded remove patch
@@ -30,70 +30,70 @@
 block discarded – undo
30 30
  */
31 31
 class TaskStatusAction implements RequestHandlerInterface
32 32
 {
33
-    private ?AdminTasksModule $module;
34
-    private TaskScheduleService $taskschedules_service;
33
+	private ?AdminTasksModule $module;
34
+	private TaskScheduleService $taskschedules_service;
35 35
 
36
-    /**
37
-     * Constructor for TaskStatusAction Request Handler
38
-     *
39
-     * @param ModuleService $module_service
40
-     * @param TaskScheduleService $taskschedules_service
41
-     */
42
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
43
-    {
44
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
45
-        $this->taskschedules_service = $taskschedules_service;
46
-    }
36
+	/**
37
+	 * Constructor for TaskStatusAction Request Handler
38
+	 *
39
+	 * @param ModuleService $module_service
40
+	 * @param TaskScheduleService $taskschedules_service
41
+	 */
42
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
43
+	{
44
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
45
+		$this->taskschedules_service = $taskschedules_service;
46
+	}
47 47
 
48
-    /**
49
-     * {@inheritDoc}
50
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
-     */
52
-    public function handle(ServerRequestInterface $request): ResponseInterface
53
-    {
54
-        $admin_config_route = route(AdminConfigPage::class);
48
+	/**
49
+	 * {@inheritDoc}
50
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
+	 */
52
+	public function handle(ServerRequestInterface $request): ResponseInterface
53
+	{
54
+		$admin_config_route = route(AdminConfigPage::class);
55 55
 
56
-        if ($this->module === null) {
57
-            FlashMessages::addMessage(
58
-                I18N::translate('The attached module could not be found.'),
59
-                'danger'
60
-            );
61
-            return redirect($admin_config_route);
62
-        }
56
+		if ($this->module === null) {
57
+			FlashMessages::addMessage(
58
+				I18N::translate('The attached module could not be found.'),
59
+				'danger'
60
+			);
61
+			return redirect($admin_config_route);
62
+		}
63 63
 
64
-        $task_sched_id = Validator::attributes($request)->integer('task', -1);
65
-        $task_schedule = $this->taskschedules_service->find($task_sched_id);
64
+		$task_sched_id = Validator::attributes($request)->integer('task', -1);
65
+		$task_schedule = $this->taskschedules_service->find($task_sched_id);
66 66
 
67
-        $admin_config_route = route(AdminConfigPage::class);
67
+		$admin_config_route = route(AdminConfigPage::class);
68 68
 
69
-        if ($task_schedule === null) {
70
-            FlashMessages::addMessage(
71
-                I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
72
-                'danger'
73
-            );
74
-            return redirect($admin_config_route);
75
-        }
69
+		if ($task_schedule === null) {
70
+			FlashMessages::addMessage(
71
+				I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
72
+				'danger'
73
+			);
74
+			return redirect($admin_config_route);
75
+		}
76 76
 
77
-        Validator::attributes($request)->boolean('enable', false) ?
78
-            $task_schedule->enable() :
79
-            $task_schedule->disable();
77
+		Validator::attributes($request)->boolean('enable', false) ?
78
+			$task_schedule->enable() :
79
+			$task_schedule->disable();
80 80
 
81
-        if ($this->taskschedules_service->update($task_schedule) > 0) {
82
-            FlashMessages::addMessage(
83
-                I18N::translate('The scheduled task has been successfully updated.'),
84
-                'success'
85
-            );
86
-            //phpcs:ignore Generic.Files.LineLength.TooLong
87
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
88
-        } else {
89
-            FlashMessages::addMessage(
90
-                I18N::translate('An error occured while updating the scheduled task.'),
91
-                'danger'
92
-            );
93
-            //phpcs:ignore Generic.Files.LineLength.TooLong
94
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
95
-        }
81
+		if ($this->taskschedules_service->update($task_schedule) > 0) {
82
+			FlashMessages::addMessage(
83
+				I18N::translate('The scheduled task has been successfully updated.'),
84
+				'success'
85
+			);
86
+			//phpcs:ignore Generic.Files.LineLength.TooLong
87
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
88
+		} else {
89
+			FlashMessages::addMessage(
90
+				I18N::translate('An error occured while updating the scheduled task.'),
91
+				'danger'
92
+			);
93
+			//phpcs:ignore Generic.Files.LineLength.TooLong
94
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
95
+		}
96 96
 
97
-        return redirect($admin_config_route);
98
-    }
97
+		return redirect($admin_config_route);
98
+	}
99 99
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -4 removed lines patch added patch discarded remove patch
@@ -75,8 +75,7 @@  discard block
 block discarded – undo
75 75
         }
76 76
 
77 77
         Validator::attributes($request)->boolean('enable', false) ?
78
-            $task_schedule->enable() :
79
-            $task_schedule->disable();
78
+            $task_schedule->enable() : $task_schedule->disable();
80 79
 
81 80
         if ($this->taskschedules_service->update($task_schedule) > 0) {
82 81
             FlashMessages::addMessage(
@@ -84,14 +83,14 @@  discard block
 block discarded – undo
84 83
                 'success'
85 84
             );
86 85
             //phpcs:ignore Generic.Files.LineLength.TooLong
87
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
86
+            Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” has been updated.');
88 87
         } else {
89 88
             FlashMessages::addMessage(
90 89
                 I18N::translate('An error occured while updating the scheduled task.'),
91 90
                 'danger'
92 91
             );
93 92
             //phpcs:ignore Generic.Files.LineLength.TooLong
94
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
93
+            Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” could not be updated. See error log.');
95 94
         }
96 95
 
97 96
         return redirect($admin_config_route);
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TaskEditAction.php 2 patches
Indentation   +144 added lines, -144 removed lines patch added patch discarded remove patch
@@ -34,148 +34,148 @@
 block discarded – undo
34 34
  */
35 35
 class TaskEditAction implements RequestHandlerInterface
36 36
 {
37
-    private ?AdminTasksModule $module;
38
-    private TaskScheduleService $taskschedules_service;
39
-
40
-    /**
41
-     * Constructor for TaskEditAction Request Handler
42
-     *
43
-     * @param ModuleService $module_service
44
-     * @param TaskScheduleService $taskschedules_service
45
-     */
46
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
47
-    {
48
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
49
-        $this->taskschedules_service = $taskschedules_service;
50
-    }
51
-
52
-    /**
53
-     * {@inheritDoc}
54
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
55
-     */
56
-    public function handle(ServerRequestInterface $request): ResponseInterface
57
-    {
58
-        $admin_config_route = route(AdminConfigPage::class);
59
-
60
-        if ($this->module === null) {
61
-            FlashMessages::addMessage(
62
-                I18N::translate('The attached module could not be found.'),
63
-                'danger'
64
-            );
65
-            return redirect($admin_config_route);
66
-        }
67
-
68
-        $task_sched_id = Validator::attributes($request)->integer('task', -1);
69
-        $task_schedule = $this->taskschedules_service->find($task_sched_id);
70
-
71
-        if ($task_schedule === null) {
72
-            FlashMessages::addMessage(
73
-                I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
74
-                'danger'
75
-            );
76
-            return redirect($admin_config_route);
77
-        }
78
-
79
-        $success = $this->updateGeneralSettings($task_schedule, $request);
80
-        $success = $success && $this->updateSpecificSettings($task_schedule, $request);
81
-
82
-        if ($success) {
83
-            FlashMessages::addMessage(
84
-                I18N::translate('The scheduled task has been successfully updated.'),
85
-                'success'
86
-            );
87
-            //phpcs:ignore Generic.Files.LineLength.TooLong
88
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
89
-        }
90
-
91
-        return redirect($admin_config_route);
92
-    }
93
-
94
-    /**
95
-     * Update general settings for the task, based on the request parameters
96
-     *
97
-     * @param TaskSchedule $task_schedule
98
-     * @param ServerRequestInterface $request
99
-     * @return bool
100
-     */
101
-    private function updateGeneralSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
102
-    {
103
-        if ($this->module === null) {
104
-            return false;
105
-        }
106
-
107
-        $frequency = Validator::parsedBody($request)->integer('frequency', 0);
108
-        if ($frequency > 0) {
109
-            $task_schedule->setFrequency($frequency);
110
-        } else {
111
-            FlashMessages::addMessage(I18N::translate('The frequency is not in a valid format.'), 'danger');
112
-        }
113
-
114
-        $is_limited = Validator::parsedBody($request)->boolean('is_limited', false);
115
-        $nb_occur = Validator::parsedBody($request)->integer('nb_occur', 1);
116
-        if ($is_limited) {
117
-            if ($nb_occur > 0) {
118
-                $task_schedule->setRemainingOccurrences($nb_occur);
119
-            } else {
120
-                FlashMessages::addMessage(
121
-                    I18N::translate('The number of remaining occurrences is not in a valid format.'),
122
-                    'danger'
123
-                );
124
-            }
125
-        } else {
126
-            $task_schedule->setRemainingOccurrences(0);
127
-        }
128
-
129
-        try {
130
-            $this->taskschedules_service->update($task_schedule);
131
-            return true;
132
-        } catch (Throwable $ex) {
133
-            Log::addErrorLog(
134
-                sprintf(
135
-                    'Error while updating the Task Schedule "%s". Exception: %s',
136
-                    $task_schedule->id(),
137
-                    $ex->getMessage()
138
-                )
139
-            );
140
-        }
141
-
142
-        FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task.'), 'danger');
143
-        //@phpcs:ignore Generic.Files.LineLength.TooLong
144
-        Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
145
-        return false;
146
-    }
147
-
148
-    /**
149
-     * Update general settings for the task, based on the request parameters
150
-     *
151
-     * @param TaskSchedule $task_schedule
152
-     * @param ServerRequestInterface $request
153
-     * @return bool
154
-     */
155
-    private function updateSpecificSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
156
-    {
157
-        if ($this->module === null) {
158
-            return false;
159
-        }
160
-
161
-        $task = $this->taskschedules_service->findTask($task_schedule->taskId());
162
-        if ($task === null || !($task instanceof ConfigurableTaskInterface)) {
163
-            return true;
164
-        }
165
-
166
-        /** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
167
-        if (!$task->updateConfig($request, $task_schedule)) {
168
-            FlashMessages::addMessage(
169
-                I18N::translate(
170
-                    'An error occured while updating the specific settings of administrative task “%s”.',
171
-                    $task->name()
172
-                ),
173
-                'danger'
174
-            );
175
-            //phpcs:ignore Generic.Files.LineLength.TooLong
176
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
177
-        }
178
-
179
-        return true;
180
-    }
37
+	private ?AdminTasksModule $module;
38
+	private TaskScheduleService $taskschedules_service;
39
+
40
+	/**
41
+	 * Constructor for TaskEditAction Request Handler
42
+	 *
43
+	 * @param ModuleService $module_service
44
+	 * @param TaskScheduleService $taskschedules_service
45
+	 */
46
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
47
+	{
48
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
49
+		$this->taskschedules_service = $taskschedules_service;
50
+	}
51
+
52
+	/**
53
+	 * {@inheritDoc}
54
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
55
+	 */
56
+	public function handle(ServerRequestInterface $request): ResponseInterface
57
+	{
58
+		$admin_config_route = route(AdminConfigPage::class);
59
+
60
+		if ($this->module === null) {
61
+			FlashMessages::addMessage(
62
+				I18N::translate('The attached module could not be found.'),
63
+				'danger'
64
+			);
65
+			return redirect($admin_config_route);
66
+		}
67
+
68
+		$task_sched_id = Validator::attributes($request)->integer('task', -1);
69
+		$task_schedule = $this->taskschedules_service->find($task_sched_id);
70
+
71
+		if ($task_schedule === null) {
72
+			FlashMessages::addMessage(
73
+				I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
74
+				'danger'
75
+			);
76
+			return redirect($admin_config_route);
77
+		}
78
+
79
+		$success = $this->updateGeneralSettings($task_schedule, $request);
80
+		$success = $success && $this->updateSpecificSettings($task_schedule, $request);
81
+
82
+		if ($success) {
83
+			FlashMessages::addMessage(
84
+				I18N::translate('The scheduled task has been successfully updated.'),
85
+				'success'
86
+			);
87
+			//phpcs:ignore Generic.Files.LineLength.TooLong
88
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
89
+		}
90
+
91
+		return redirect($admin_config_route);
92
+	}
93
+
94
+	/**
95
+	 * Update general settings for the task, based on the request parameters
96
+	 *
97
+	 * @param TaskSchedule $task_schedule
98
+	 * @param ServerRequestInterface $request
99
+	 * @return bool
100
+	 */
101
+	private function updateGeneralSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
102
+	{
103
+		if ($this->module === null) {
104
+			return false;
105
+		}
106
+
107
+		$frequency = Validator::parsedBody($request)->integer('frequency', 0);
108
+		if ($frequency > 0) {
109
+			$task_schedule->setFrequency($frequency);
110
+		} else {
111
+			FlashMessages::addMessage(I18N::translate('The frequency is not in a valid format.'), 'danger');
112
+		}
113
+
114
+		$is_limited = Validator::parsedBody($request)->boolean('is_limited', false);
115
+		$nb_occur = Validator::parsedBody($request)->integer('nb_occur', 1);
116
+		if ($is_limited) {
117
+			if ($nb_occur > 0) {
118
+				$task_schedule->setRemainingOccurrences($nb_occur);
119
+			} else {
120
+				FlashMessages::addMessage(
121
+					I18N::translate('The number of remaining occurrences is not in a valid format.'),
122
+					'danger'
123
+				);
124
+			}
125
+		} else {
126
+			$task_schedule->setRemainingOccurrences(0);
127
+		}
128
+
129
+		try {
130
+			$this->taskschedules_service->update($task_schedule);
131
+			return true;
132
+		} catch (Throwable $ex) {
133
+			Log::addErrorLog(
134
+				sprintf(
135
+					'Error while updating the Task Schedule "%s". Exception: %s',
136
+					$task_schedule->id(),
137
+					$ex->getMessage()
138
+				)
139
+			);
140
+		}
141
+
142
+		FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task.'), 'danger');
143
+		//@phpcs:ignore Generic.Files.LineLength.TooLong
144
+		Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
145
+		return false;
146
+	}
147
+
148
+	/**
149
+	 * Update general settings for the task, based on the request parameters
150
+	 *
151
+	 * @param TaskSchedule $task_schedule
152
+	 * @param ServerRequestInterface $request
153
+	 * @return bool
154
+	 */
155
+	private function updateSpecificSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
156
+	{
157
+		if ($this->module === null) {
158
+			return false;
159
+		}
160
+
161
+		$task = $this->taskschedules_service->findTask($task_schedule->taskId());
162
+		if ($task === null || !($task instanceof ConfigurableTaskInterface)) {
163
+			return true;
164
+		}
165
+
166
+		/** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
167
+		if (!$task->updateConfig($request, $task_schedule)) {
168
+			FlashMessages::addMessage(
169
+				I18N::translate(
170
+					'An error occured while updating the specific settings of administrative task “%s”.',
171
+					$task->name()
172
+				),
173
+				'danger'
174
+			);
175
+			//phpcs:ignore Generic.Files.LineLength.TooLong
176
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
177
+		}
178
+
179
+		return true;
180
+	}
181 181
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
                 'success'
86 86
             );
87 87
             //phpcs:ignore Generic.Files.LineLength.TooLong
88
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
88
+            Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” has been updated.');
89 89
         }
90 90
 
91 91
         return redirect($admin_config_route);
@@ -141,7 +141,7 @@  discard block
 block discarded – undo
141 141
 
142 142
         FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task.'), 'danger');
143 143
         //@phpcs:ignore Generic.Files.LineLength.TooLong
144
-        Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
144
+        Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” could not be updated. See error log.');
145 145
         return false;
146 146
     }
147 147
 
@@ -173,7 +173,7 @@  discard block
 block discarded – undo
173 173
                 'danger'
174 174
             );
175 175
             //phpcs:ignore Generic.Files.LineLength.TooLong
176
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
176
+            Log::addConfigurationLog('Module '.$this->module->title().' : AdminTask “'.$task->name().'” specific settings could not be updated. See error log.');
177 177
         }
178 178
 
179 179
         return true;
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TaskEditPage.php 2 patches
Indentation   +44 added lines, -44 removed lines patch added patch discarded remove patch
@@ -31,58 +31,58 @@
 block discarded – undo
31 31
  */
32 32
 class TaskEditPage implements RequestHandlerInterface
33 33
 {
34
-    use ViewResponseTrait;
34
+	use ViewResponseTrait;
35 35
 
36
-    private ?AdminTasksModule $module;
37
-    private TaskScheduleService $taskschedules_service;
36
+	private ?AdminTasksModule $module;
37
+	private TaskScheduleService $taskschedules_service;
38 38
 
39
-    /**
40
-     * Constructor for TaskEditPage Request Handler
41
-     *
42
-     * @param ModuleService $module_service
43
-     * @param TaskScheduleService $taskschedules_service
44
-     */
45
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
46
-    {
47
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
48
-        $this->taskschedules_service = $taskschedules_service;
49
-    }
39
+	/**
40
+	 * Constructor for TaskEditPage Request Handler
41
+	 *
42
+	 * @param ModuleService $module_service
43
+	 * @param TaskScheduleService $taskschedules_service
44
+	 */
45
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
46
+	{
47
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
48
+		$this->taskschedules_service = $taskschedules_service;
49
+	}
50 50
 
51
-    /**
52
-     * {@inheritDoc}
53
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
-     */
55
-    public function handle(ServerRequestInterface $request): ResponseInterface
56
-    {
57
-        $this->layout = 'layouts/administration';
51
+	/**
52
+	 * {@inheritDoc}
53
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
+	 */
55
+	public function handle(ServerRequestInterface $request): ResponseInterface
56
+	{
57
+		$this->layout = 'layouts/administration';
58 58
 
59
-        if ($this->module === null) {
60
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
61
-        }
59
+		if ($this->module === null) {
60
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
61
+		}
62 62
 
63
-        $task_sched_id = Validator::attributes($request)->integer('task', -1);
64
-        $task_schedule = $this->taskschedules_service->find($task_sched_id);
63
+		$task_sched_id = Validator::attributes($request)->integer('task', -1);
64
+		$task_schedule = $this->taskschedules_service->find($task_sched_id);
65 65
 
66
-        if ($task_schedule === null) {
67
-            throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
68
-        }
66
+		if ($task_schedule === null) {
67
+			throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
68
+		}
69 69
 
70
-        $task = $this->taskschedules_service->findTask($task_schedule->taskId());
70
+		$task = $this->taskschedules_service->findTask($task_schedule->taskId());
71 71
 
72
-        if ($task === null) {
73
-            throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
74
-        }
72
+		if ($task === null) {
73
+			throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
74
+		}
75 75
 
76
-        $has_task_config = $task instanceof ConfigurableTaskInterface;
77
-        /** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
76
+		$has_task_config = $task instanceof ConfigurableTaskInterface;
77
+		/** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
78 78
 
79
-        return $this->viewResponse($this->module->name() . '::admin/tasks-edit', [
80
-            'module'            =>  $this->module,
81
-            'title'             =>  I18N::translate('Edit the administrative task') . ' - ' . $task->name(),
82
-            'task_schedule'     =>  $task_schedule,
83
-            'task'              =>  $task,
84
-            'has_task_config'   =>  $has_task_config,
85
-            'task_config_view'  =>  $has_task_config ? $task->configView($request) : ''
86
-        ]);
87
-    }
79
+		return $this->viewResponse($this->module->name() . '::admin/tasks-edit', [
80
+			'module'            =>  $this->module,
81
+			'title'             =>  I18N::translate('Edit the administrative task') . ' - ' . $task->name(),
82
+			'task_schedule'     =>  $task_schedule,
83
+			'task'              =>  $task,
84
+			'has_task_config'   =>  $has_task_config,
85
+			'task_config_view'  =>  $has_task_config ? $task->configView($request) : ''
86
+		]);
87
+	}
88 88
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -76,9 +76,9 @@
 block discarded – undo
76 76
         $has_task_config = $task instanceof ConfigurableTaskInterface;
77 77
         /** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
78 78
 
79
-        return $this->viewResponse($this->module->name() . '::admin/tasks-edit', [
79
+        return $this->viewResponse($this->module->name().'::admin/tasks-edit', [
80 80
             'module'            =>  $this->module,
81
-            'title'             =>  I18N::translate('Edit the administrative task') . ' - ' . $task->name(),
81
+            'title'             =>  I18N::translate('Edit the administrative task').' - '.$task->name(),
82 82
             'task_schedule'     =>  $task_schedule,
83 83
             'task'              =>  $task,
84 84
             'has_task_config'   =>  $has_task_config,
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TaskTrigger.php 1 patch
Indentation   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -29,41 +29,41 @@
 block discarded – undo
29 29
  */
30 30
 class TaskTrigger implements RequestHandlerInterface
31 31
 {
32
-    private ?AdminTasksModule $module;
33
-    private TaskScheduleService $taskschedules_service;
32
+	private ?AdminTasksModule $module;
33
+	private TaskScheduleService $taskschedules_service;
34 34
 
35
-    /**
36
-     * Constructor for TaskTrigger request handler
37
-     * @param ModuleService $module_service
38
-     * @param TaskScheduleService $taskschedules_service
39
-     */
40
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
41
-    {
42
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
43
-        $this->taskschedules_service = $taskschedules_service;
44
-    }
35
+	/**
36
+	 * Constructor for TaskTrigger request handler
37
+	 * @param ModuleService $module_service
38
+	 * @param TaskScheduleService $taskschedules_service
39
+	 */
40
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
41
+	{
42
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
43
+		$this->taskschedules_service = $taskschedules_service;
44
+	}
45 45
 
46
-    /**
47
-     * {@inheritDoc}
48
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
49
-     */
50
-    public function handle(ServerRequestInterface $request): ResponseInterface
51
-    {
52
-        if ($this->module === null) {
53
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
54
-        }
46
+	/**
47
+	 * {@inheritDoc}
48
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
49
+	 */
50
+	public function handle(ServerRequestInterface $request): ResponseInterface
51
+	{
52
+		if ($this->module === null) {
53
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
54
+		}
55 55
 
56
-        $task_id = Validator::attributes($request)->string('task', '');
57
-        $token = $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN');
58
-        $force_token = Validator::queryParams($request)->string('force', '');
59
-        $force = $token == $force_token;
56
+		$task_id = Validator::attributes($request)->string('task', '');
57
+		$token = $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN');
58
+		$force_token = Validator::queryParams($request)->string('force', '');
59
+		$force = $token == $force_token;
60 60
 
61
-        $task_schedules = $this->taskschedules_service->findTasksToRun($force, $task_id);
61
+		$task_schedules = $this->taskschedules_service->findTasksToRun($force, $task_id);
62 62
 
63
-        foreach ($task_schedules as $task_schedule) {
64
-            $this->taskschedules_service->run($task_schedule, $force);
65
-        }
63
+		foreach ($task_schedules as $task_schedule) {
64
+			$this->taskschedules_service->run($task_schedule, $force);
65
+		}
66 66
 
67
-        return response();
68
-    }
67
+		return response();
68
+	}
69 69
 }
Please login to merge, or discard this patch.
app/Module/AdminTasks/Tasks/HealthCheckEmailTask.php 2 patches
Indentation   +162 added lines, -162 removed lines patch added patch discarded remove patch
@@ -41,166 +41,166 @@
 block discarded – undo
41 41
  */
42 42
 class HealthCheckEmailTask implements TaskInterface, ConfigurableTaskInterface
43 43
 {
44
-    /**
45
-     * Name of the Tree preference to check if the task is enabled for that tree
46
-     * @var string
47
-     */
48
-    public const TREE_PREFERENCE_NAME = 'MAJ_AT_HEALTHCHECK_ENABLED';
49
-
50
-    private ?AdminTasksModule $module;
51
-    private HealthCheckService $healthcheck_service;
52
-    private EmailService $email_service;
53
-    private UserService $user_service;
54
-    private TreeService $tree_service;
55
-    private UpgradeService $upgrade_service;
56
-
57
-    /**
58
-     * Constructor for HealthCheckTask
59
-     *
60
-     * @param ModuleService $module_service
61
-     * @param HealthCheckService $healthcheck_service
62
-     * @param EmailService $email_service
63
-     * @param UserService $user_service
64
-     * @param TreeService $tree_service
65
-     * @param UpgradeService $upgrade_service
66
-     */
67
-    public function __construct(
68
-        ModuleService $module_service,
69
-        HealthCheckService $healthcheck_service,
70
-        EmailService $email_service,
71
-        UserService $user_service,
72
-        TreeService $tree_service,
73
-        UpgradeService $upgrade_service
74
-    ) {
75
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
76
-        $this->healthcheck_service = $healthcheck_service;
77
-        $this->email_service = $email_service;
78
-        $this->user_service = $user_service;
79
-        $this->tree_service = $tree_service;
80
-        $this->upgrade_service = $upgrade_service;
81
-    }
82
-
83
-
84
-    /**
85
-     * {@inheritDoc}
86
-     * @see \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface::name()
87
-     */
88
-    public function name(): string
89
-    {
90
-        return I18N::translate('Healthcheck Email');
91
-    }
92
-
93
-    /**
94
-     * {@inheritDoc}
95
-     * @see \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface::defaultFrequency()
96
-     */
97
-    public function defaultFrequency(): int
98
-    {
99
-        return 10080; // = 1 week = 7 * 24 * 60 min
100
-    }
101
-
102
-    /**
103
-     * {@inheritDoc}
104
-     * @see \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface::run()
105
-     */
106
-    public function run(TaskSchedule $task_schedule): bool
107
-    {
108
-        if ($this->module === null) {
109
-            return false;
110
-        }
111
-
112
-        $res = true;
113
-
114
-        // Compute the number of days to compute
115
-        $interval_lastrun =
116
-            Registry::timestampFactory()->now()->timestamp() -  $task_schedule->lastRunTime()->timestamp();
117
-        $task_freq_seconds = 60 * $task_schedule->frequency();
118
-        $interval = $interval_lastrun > $task_freq_seconds ? $interval_lastrun : $task_freq_seconds;
119
-        $nb_days = (int) CarbonInterval::seconds($interval)->ceilDay()->totalDays;
120
-
121
-        $view_params_site = [
122
-            'nb_days'               =>  $nb_days,
123
-            'upgrade_available'     =>  $this->upgrade_service->isUpgradeAvailable(),
124
-            'latest_version'        =>  $this->upgrade_service->latestVersion(),
125
-            'download_url'          =>  $this->upgrade_service->downloadUrl(),
126
-            'all_users'             =>  $this->user_service->all(),
127
-            'unapproved'            =>  $this->user_service->unapproved(),
128
-            'unverified'            =>  $this->user_service->unverified(),
129
-        ];
130
-
131
-        foreach ($this->tree_service->all() as $tree) {
132
-        /** @var Tree $tree */
133
-
134
-            if ($tree->getPreference(self::TREE_PREFERENCE_NAME) !== '1') {
135
-                continue;
136
-            }
137
-
138
-            $webmaster = $this->user_service->find((int) $tree->getPreference('WEBMASTER_USER_ID'));
139
-            if ($webmaster === null) {
140
-                continue;
141
-            }
142
-            I18N::init($webmaster->getPreference('language'));
143
-
144
-            $error_logs = $this->healthcheck_service->errorLogs($tree, $nb_days);
145
-            $nb_errors = $error_logs->sum('nblogs');
146
-
147
-            $view_params = $view_params_site + [
148
-                'tree'              =>  $tree,
149
-                'total_by_type'     =>  $this->healthcheck_service->countByRecordType($tree),
150
-                'change_by_type'    =>  $this->healthcheck_service->changesByRecordType($tree, $nb_days),
151
-                'error_logs'        =>  $error_logs,
152
-                'nb_errors'         =>  $nb_errors
153
-            ];
154
-
155
-            $res = $res && $this->email_service->send(
156
-                new TreeUser($tree),
157
-                $webmaster,
158
-                new NoReplyUser(),
159
-                I18N::translate('Health Check Report') . ' - ' . I18N::translate('Tree %s', $tree->name()),
160
-                view($this->module->name() . '::tasks/healthcheck/email-healthcheck-text', $view_params),
161
-                view($this->module->name() . '::tasks/healthcheck/email-healthcheck-html', $view_params)
162
-            );
163
-        }
164
-
165
-        return $res;
166
-    }
167
-
168
-    /**
169
-     * {@inheritDoc}
170
-     * @see \MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface::configView()
171
-     */
172
-    public function configView(ServerRequestInterface $request): string
173
-    {
174
-        return $this->module === null ? '' : view($this->module->name() . '::tasks/healthcheck/config', [
175
-            'all_trees'     =>  $this->tree_service->all()
176
-        ]);
177
-    }
178
-
179
-    /**
180
-     * {@inheritDoc}
181
-     * @see \MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface::updateConfig()
182
-     */
183
-    public function updateConfig(ServerRequestInterface $request, TaskSchedule $task_schedule): bool
184
-    {
185
-        try {
186
-            $validator = Validator::parsedBody($request);
187
-
188
-            foreach ($this->tree_service->all() as $tree) {
189
-                if (Auth::isManager($tree)) {
190
-                    $tree_enabled = $validator->boolean('HEALTHCHECK_ENABLED_' . $tree->id(), false);
191
-                    $tree->setPreference(self::TREE_PREFERENCE_NAME, $tree_enabled ? '1' : '0');
192
-                }
193
-            }
194
-            return true;
195
-        } catch (Throwable $ex) {
196
-            Log::addErrorLog(
197
-                sprintf(
198
-                    'Error while updating the Task schedule "%s". Exception: %s',
199
-                    $task_schedule->id(),
200
-                    $ex->getMessage()
201
-                )
202
-            );
203
-        }
204
-        return false;
205
-    }
44
+	/**
45
+	 * Name of the Tree preference to check if the task is enabled for that tree
46
+	 * @var string
47
+	 */
48
+	public const TREE_PREFERENCE_NAME = 'MAJ_AT_HEALTHCHECK_ENABLED';
49
+
50
+	private ?AdminTasksModule $module;
51
+	private HealthCheckService $healthcheck_service;
52
+	private EmailService $email_service;
53
+	private UserService $user_service;
54
+	private TreeService $tree_service;
55
+	private UpgradeService $upgrade_service;
56
+
57
+	/**
58
+	 * Constructor for HealthCheckTask
59
+	 *
60
+	 * @param ModuleService $module_service
61
+	 * @param HealthCheckService $healthcheck_service
62
+	 * @param EmailService $email_service
63
+	 * @param UserService $user_service
64
+	 * @param TreeService $tree_service
65
+	 * @param UpgradeService $upgrade_service
66
+	 */
67
+	public function __construct(
68
+		ModuleService $module_service,
69
+		HealthCheckService $healthcheck_service,
70
+		EmailService $email_service,
71
+		UserService $user_service,
72
+		TreeService $tree_service,
73
+		UpgradeService $upgrade_service
74
+	) {
75
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
76
+		$this->healthcheck_service = $healthcheck_service;
77
+		$this->email_service = $email_service;
78
+		$this->user_service = $user_service;
79
+		$this->tree_service = $tree_service;
80
+		$this->upgrade_service = $upgrade_service;
81
+	}
82
+
83
+
84
+	/**
85
+	 * {@inheritDoc}
86
+	 * @see \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface::name()
87
+	 */
88
+	public function name(): string
89
+	{
90
+		return I18N::translate('Healthcheck Email');
91
+	}
92
+
93
+	/**
94
+	 * {@inheritDoc}
95
+	 * @see \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface::defaultFrequency()
96
+	 */
97
+	public function defaultFrequency(): int
98
+	{
99
+		return 10080; // = 1 week = 7 * 24 * 60 min
100
+	}
101
+
102
+	/**
103
+	 * {@inheritDoc}
104
+	 * @see \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface::run()
105
+	 */
106
+	public function run(TaskSchedule $task_schedule): bool
107
+	{
108
+		if ($this->module === null) {
109
+			return false;
110
+		}
111
+
112
+		$res = true;
113
+
114
+		// Compute the number of days to compute
115
+		$interval_lastrun =
116
+			Registry::timestampFactory()->now()->timestamp() -  $task_schedule->lastRunTime()->timestamp();
117
+		$task_freq_seconds = 60 * $task_schedule->frequency();
118
+		$interval = $interval_lastrun > $task_freq_seconds ? $interval_lastrun : $task_freq_seconds;
119
+		$nb_days = (int) CarbonInterval::seconds($interval)->ceilDay()->totalDays;
120
+
121
+		$view_params_site = [
122
+			'nb_days'               =>  $nb_days,
123
+			'upgrade_available'     =>  $this->upgrade_service->isUpgradeAvailable(),
124
+			'latest_version'        =>  $this->upgrade_service->latestVersion(),
125
+			'download_url'          =>  $this->upgrade_service->downloadUrl(),
126
+			'all_users'             =>  $this->user_service->all(),
127
+			'unapproved'            =>  $this->user_service->unapproved(),
128
+			'unverified'            =>  $this->user_service->unverified(),
129
+		];
130
+
131
+		foreach ($this->tree_service->all() as $tree) {
132
+		/** @var Tree $tree */
133
+
134
+			if ($tree->getPreference(self::TREE_PREFERENCE_NAME) !== '1') {
135
+				continue;
136
+			}
137
+
138
+			$webmaster = $this->user_service->find((int) $tree->getPreference('WEBMASTER_USER_ID'));
139
+			if ($webmaster === null) {
140
+				continue;
141
+			}
142
+			I18N::init($webmaster->getPreference('language'));
143
+
144
+			$error_logs = $this->healthcheck_service->errorLogs($tree, $nb_days);
145
+			$nb_errors = $error_logs->sum('nblogs');
146
+
147
+			$view_params = $view_params_site + [
148
+				'tree'              =>  $tree,
149
+				'total_by_type'     =>  $this->healthcheck_service->countByRecordType($tree),
150
+				'change_by_type'    =>  $this->healthcheck_service->changesByRecordType($tree, $nb_days),
151
+				'error_logs'        =>  $error_logs,
152
+				'nb_errors'         =>  $nb_errors
153
+			];
154
+
155
+			$res = $res && $this->email_service->send(
156
+				new TreeUser($tree),
157
+				$webmaster,
158
+				new NoReplyUser(),
159
+				I18N::translate('Health Check Report') . ' - ' . I18N::translate('Tree %s', $tree->name()),
160
+				view($this->module->name() . '::tasks/healthcheck/email-healthcheck-text', $view_params),
161
+				view($this->module->name() . '::tasks/healthcheck/email-healthcheck-html', $view_params)
162
+			);
163
+		}
164
+
165
+		return $res;
166
+	}
167
+
168
+	/**
169
+	 * {@inheritDoc}
170
+	 * @see \MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface::configView()
171
+	 */
172
+	public function configView(ServerRequestInterface $request): string
173
+	{
174
+		return $this->module === null ? '' : view($this->module->name() . '::tasks/healthcheck/config', [
175
+			'all_trees'     =>  $this->tree_service->all()
176
+		]);
177
+	}
178
+
179
+	/**
180
+	 * {@inheritDoc}
181
+	 * @see \MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface::updateConfig()
182
+	 */
183
+	public function updateConfig(ServerRequestInterface $request, TaskSchedule $task_schedule): bool
184
+	{
185
+		try {
186
+			$validator = Validator::parsedBody($request);
187
+
188
+			foreach ($this->tree_service->all() as $tree) {
189
+				if (Auth::isManager($tree)) {
190
+					$tree_enabled = $validator->boolean('HEALTHCHECK_ENABLED_' . $tree->id(), false);
191
+					$tree->setPreference(self::TREE_PREFERENCE_NAME, $tree_enabled ? '1' : '0');
192
+				}
193
+			}
194
+			return true;
195
+		} catch (Throwable $ex) {
196
+			Log::addErrorLog(
197
+				sprintf(
198
+					'Error while updating the Task schedule "%s". Exception: %s',
199
+					$task_schedule->id(),
200
+					$ex->getMessage()
201
+				)
202
+			);
203
+		}
204
+		return false;
205
+	}
206 206
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -113,10 +113,10 @@  discard block
 block discarded – undo
113 113
 
114 114
         // Compute the number of days to compute
115 115
         $interval_lastrun =
116
-            Registry::timestampFactory()->now()->timestamp() -  $task_schedule->lastRunTime()->timestamp();
116
+            Registry::timestampFactory()->now()->timestamp() - $task_schedule->lastRunTime()->timestamp();
117 117
         $task_freq_seconds = 60 * $task_schedule->frequency();
118 118
         $interval = $interval_lastrun > $task_freq_seconds ? $interval_lastrun : $task_freq_seconds;
119
-        $nb_days = (int) CarbonInterval::seconds($interval)->ceilDay()->totalDays;
119
+        $nb_days = (int)CarbonInterval::seconds($interval)->ceilDay()->totalDays;
120 120
 
121 121
         $view_params_site = [
122 122
             'nb_days'               =>  $nb_days,
@@ -135,7 +135,7 @@  discard block
 block discarded – undo
135 135
                 continue;
136 136
             }
137 137
 
138
-            $webmaster = $this->user_service->find((int) $tree->getPreference('WEBMASTER_USER_ID'));
138
+            $webmaster = $this->user_service->find((int)$tree->getPreference('WEBMASTER_USER_ID'));
139 139
             if ($webmaster === null) {
140 140
                 continue;
141 141
             }
@@ -156,9 +156,9 @@  discard block
 block discarded – undo
156 156
                 new TreeUser($tree),
157 157
                 $webmaster,
158 158
                 new NoReplyUser(),
159
-                I18N::translate('Health Check Report') . ' - ' . I18N::translate('Tree %s', $tree->name()),
160
-                view($this->module->name() . '::tasks/healthcheck/email-healthcheck-text', $view_params),
161
-                view($this->module->name() . '::tasks/healthcheck/email-healthcheck-html', $view_params)
159
+                I18N::translate('Health Check Report').' - '.I18N::translate('Tree %s', $tree->name()),
160
+                view($this->module->name().'::tasks/healthcheck/email-healthcheck-text', $view_params),
161
+                view($this->module->name().'::tasks/healthcheck/email-healthcheck-html', $view_params)
162 162
             );
163 163
         }
164 164
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
      */
172 172
     public function configView(ServerRequestInterface $request): string
173 173
     {
174
-        return $this->module === null ? '' : view($this->module->name() . '::tasks/healthcheck/config', [
174
+        return $this->module === null ? '' : view($this->module->name().'::tasks/healthcheck/config', [
175 175
             'all_trees'     =>  $this->tree_service->all()
176 176
         ]);
177 177
     }
@@ -187,7 +187,7 @@  discard block
 block discarded – undo
187 187
 
188 188
             foreach ($this->tree_service->all() as $tree) {
189 189
                 if (Auth::isManager($tree)) {
190
-                    $tree_enabled = $validator->boolean('HEALTHCHECK_ENABLED_' . $tree->id(), false);
190
+                    $tree_enabled = $validator->boolean('HEALTHCHECK_ENABLED_'.$tree->id(), false);
191 191
                     $tree->setPreference(self::TREE_PREFERENCE_NAME, $tree_enabled ? '1' : '0');
192 192
                 }
193 193
             }
Please login to merge, or discard this patch.
app/Module/AdminTasks/Services/TaskScheduleService.php 2 patches
Indentation   +271 added lines, -271 removed lines patch added patch discarded remove patch
@@ -35,275 +35,275 @@
 block discarded – undo
35 35
  */
36 36
 class TaskScheduleService
37 37
 {
38
-    /**
39
-     * Time-out after which the task will be considered not running any more.
40
-     * In seconds, default 5 mins.
41
-     * @var integer
42
-     */
43
-    public const TASK_TIME_OUT = 600;
44
-
45
-    private ModuleService $module_service;
46
-
47
-    /**
48
-     * Constructor for TaskScheduleService
49
-     *
50
-     * @param ModuleService $module_service
51
-     */
52
-    public function __construct(ModuleService $module_service)
53
-    {
54
-        $this->module_service = $module_service;
55
-    }
56
-
57
-    /**
58
-     * Returns all Tasks schedules in database.
59
-     * Stored records can be synchronised with the tasks actually available to the system.
60
-     *
61
-     * @param bool $sync_available Should tasks synchronised with available ones
62
-     * @param bool $include_disabled Should disabled tasks be returned
63
-     * @return Collection<TaskSchedule> Collection of TaskSchedule
64
-     */
65
-    public function all(bool $sync_available = false, bool $include_disabled = true): Collection
66
-    {
67
-        $tasks_schedules = DB::table('maj_admintasks')
68
-            ->select()
69
-            ->get()
70
-            ->map(self::rowMapper());
71
-
72
-        if ($sync_available) {
73
-            $available_tasks = clone $this->available();
74
-            foreach ($tasks_schedules as $task_schedule) {
75
-                /** @var TaskSchedule $task_schedule */
76
-                if ($available_tasks->has($task_schedule->taskId())) {
77
-                    $available_tasks->forget($task_schedule->taskId());
78
-                } else {
79
-                    $this->delete($task_schedule);
80
-                }
81
-            }
82
-
83
-            foreach ($available_tasks as $task_name => $task_class) {
84
-                if (null !== $task = app($task_class)) {
85
-                    $this->insertTask($task_name, $task->defaultFrequency());
86
-                }
87
-            }
88
-
89
-            return $this->all(false, $include_disabled);
90
-        }
91
-
92
-        return $tasks_schedules;
93
-    }
94
-
95
-    /**
96
-     * Returns tasks exposed through modules implementing ModuleTasksProviderInterface.
97
-     *
98
-     * @return Collection<string, string>
99
-     */
100
-    public function available(): Collection
101
-    {
102
-        return Registry::cache()->array()->remember(
103
-            'maj-available-admintasks',
104
-            function (): Collection {
105
-                /** @var Collection<string, string> $tasks */
106
-                $tasks = $this->module_service
107
-                    ->findByInterface(ModuleTasksProviderInterface::class)
108
-                    ->flatMap(fn(ModuleTasksProviderInterface $module) => $module->listTasks());
109
-                return $tasks;
110
-            }
111
-        );
112
-    }
113
-
114
-    /**
115
-     * Find a task schedule by its ID.
116
-     *
117
-     * @param int $task_schedule_id
118
-     * @return TaskSchedule|NULL
119
-     */
120
-    public function find(int $task_schedule_id): ?TaskSchedule
121
-    {
122
-        return DB::table('maj_admintasks')
123
-            ->select()
124
-            ->where('majat_id', '=', $task_schedule_id)
125
-            ->get()
126
-            ->map(self::rowMapper())
127
-            ->first();
128
-    }
129
-
130
-    /**
131
-     * Add a new task schedule with the specified task ID, and frequency if defined.
132
-     * Uses default for other settings.
133
-     *
134
-     * @param string $task_id
135
-     * @param int $frequency
136
-     * @return bool
137
-     */
138
-    public function insertTask(string $task_id, int $frequency = 0): bool
139
-    {
140
-        $values = ['majat_task_id' => $task_id];
141
-        if ($frequency > 0) {
142
-            $values['majat_frequency'] = $frequency;
143
-        }
144
-
145
-        return DB::table('maj_admintasks')
146
-            ->insert($values);
147
-    }
148
-
149
-    /**
150
-     * Update a task schedule.
151
-     * Returns the number of tasks schedules updated.
152
-     *
153
-     * @param TaskSchedule $task_schedule
154
-     * @return int
155
-     */
156
-    public function update(TaskSchedule $task_schedule): int
157
-    {
158
-        return DB::table('maj_admintasks')
159
-            ->where('majat_id', '=', $task_schedule->id())
160
-            ->update([
161
-                'majat_status'      =>  $task_schedule->isEnabled() ? 'enabled' : 'disabled',
162
-                'majat_last_run'    =>  $task_schedule->lastRunTime()->toDateTimeString(),
163
-                'majat_last_result' =>  $task_schedule->wasLastRunSuccess(),
164
-                'majat_frequency'   =>  $task_schedule->frequency(),
165
-                'majat_nb_occur'    =>  $task_schedule->remainingOccurrences(),
166
-                'majat_running'     =>  $task_schedule->isRunning()
167
-            ]);
168
-    }
169
-
170
-    /**
171
-     * Delete a task schedule.
172
-     *
173
-     * @param TaskSchedule $task_schedule
174
-     * @return int
175
-     */
176
-    public function delete(TaskSchedule $task_schedule): int
177
-    {
178
-        return DB::table('maj_admintasks')
179
-            ->where('majat_id', '=', $task_schedule->id())
180
-            ->delete();
181
-    }
182
-
183
-    /**
184
-     * Find a task by its name
185
-     *
186
-     * @param string $task_id
187
-     * @return TaskInterface|NULL
188
-     */
189
-    public function findTask(string $task_id): ?TaskInterface
190
-    {
191
-        if ($this->available()->has($task_id)) {
192
-            return app($this->available()->get($task_id));
193
-        }
194
-        return null;
195
-    }
196
-
197
-    /**
198
-     * Retrieve all tasks that are candidates to be run.
199
-     *
200
-     * @param bool $force Should the run be forced
201
-     * @param string $task_id Specific task ID to be run
202
-     * @return Collection<TaskSchedule>
203
-     */
204
-    public function findTasksToRun(bool $force, string $task_id = null): Collection
205
-    {
206
-        $query = DB::table('maj_admintasks')
207
-            ->select()
208
-            ->where('majat_status', '=', 'enabled')
209
-            ->where(function (Builder $query): void {
210
-
211
-                $query->where('majat_running', '=', 0)
212
-                ->orWhere(
213
-                    'majat_last_run',
214
-                    '<=',
215
-                    Registry::timestampFactory()->now()->addSeconds(-self::TASK_TIME_OUT)->toDateTimeString()
216
-                );
217
-            });
218
-
219
-        if (!$force) {
220
-            $query->where(function (Builder $query): void {
221
-
222
-                $query->where('majat_running', '=', 0)
223
-                    ->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
224
-            });
225
-        }
226
-
227
-        if ($task_id !== null) {
228
-            $query->where('majat_task_id', '=', $task_id);
229
-        }
230
-
231
-        return $query->get()->map(self::rowMapper());
232
-    }
233
-
234
-    /**
235
-     * Run the task associated with the schedule.
236
-     * The task will run if either forced to, or its next scheduled run time has been exceeded.
237
-     * The last run time is recorded only if the task is successful.
238
-     *
239
-     * @param TaskSchedule $task_schedule
240
-     * @param boolean $force
241
-     */
242
-    public function run(TaskSchedule $task_schedule, $force = false): void
243
-    {
244
-        /** @var TaskSchedule $task_schedule */
245
-        $task_schedule = DB::table('maj_admintasks')
246
-            ->select()
247
-            ->where('majat_id', '=', $task_schedule->id())
248
-            ->lockForUpdate()
249
-            ->get()
250
-            ->map(self::rowMapper())
251
-            ->first();
252
-
253
-        if (
254
-            !$task_schedule->isRunning() &&
255
-            ($force ||
256
-                $task_schedule->lastRunTime()->addMinutes($task_schedule->frequency())
257
-                    ->compare(Registry::timestampFactory()->now()) < 0
258
-            )
259
-        ) {
260
-            $task_schedule->setLastResult(false);
261
-
262
-            $task = $this->findTask($task_schedule->taskId());
263
-            if ($task !== null) {
264
-                $task_schedule->startRunning();
265
-                $this->update($task_schedule);
266
-
267
-                $first_error = $task_schedule->wasLastRunSuccess();
268
-                try {
269
-                    $task_schedule->setLastResult($task->run($task_schedule));
270
-                } catch (Throwable $ex) {
271
-                    if ($first_error) { // Only record the first error, as this could fill the log.
272
-                        Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()) . ' ' .
273
-                            '[' . get_class($ex) . '] ' . $ex->getMessage() . ' ' . $ex->getFile() . ':'
274
-                            . $ex->getLine() . PHP_EOL . $ex->getTraceAsString());
275
-                    }
276
-                }
277
-
278
-                if ($task_schedule->wasLastRunSuccess()) {
279
-                    $task_schedule->setLastRunTime(Registry::timestampFactory()->now());
280
-                    $task_schedule->decrementRemainingOccurrences();
281
-                }
282
-                $task_schedule->stopRunning();
283
-            }
284
-            $this->update($task_schedule);
285
-        }
286
-    }
287
-
288
-    /**
289
-     * Mapper to return a TaskSchedule object from an object.
290
-     *
291
-     * @return Closure(stdClass $row): TaskSchedule
292
-     */
293
-    public static function rowMapper(): Closure
294
-    {
295
-        return static function (stdClass $row): TaskSchedule {
296
-
297
-            return new TaskSchedule(
298
-                (int) $row->majat_id,
299
-                $row->majat_task_id,
300
-                $row->majat_status === 'enabled',
301
-                Registry::timestampFactory()->fromString($row->majat_last_run),
302
-                (bool) $row->majat_last_result,
303
-                (int) $row->majat_frequency,
304
-                (int) $row->majat_nb_occur,
305
-                (bool) $row->majat_running
306
-            );
307
-        };
308
-    }
38
+	/**
39
+	 * Time-out after which the task will be considered not running any more.
40
+	 * In seconds, default 5 mins.
41
+	 * @var integer
42
+	 */
43
+	public const TASK_TIME_OUT = 600;
44
+
45
+	private ModuleService $module_service;
46
+
47
+	/**
48
+	 * Constructor for TaskScheduleService
49
+	 *
50
+	 * @param ModuleService $module_service
51
+	 */
52
+	public function __construct(ModuleService $module_service)
53
+	{
54
+		$this->module_service = $module_service;
55
+	}
56
+
57
+	/**
58
+	 * Returns all Tasks schedules in database.
59
+	 * Stored records can be synchronised with the tasks actually available to the system.
60
+	 *
61
+	 * @param bool $sync_available Should tasks synchronised with available ones
62
+	 * @param bool $include_disabled Should disabled tasks be returned
63
+	 * @return Collection<TaskSchedule> Collection of TaskSchedule
64
+	 */
65
+	public function all(bool $sync_available = false, bool $include_disabled = true): Collection
66
+	{
67
+		$tasks_schedules = DB::table('maj_admintasks')
68
+			->select()
69
+			->get()
70
+			->map(self::rowMapper());
71
+
72
+		if ($sync_available) {
73
+			$available_tasks = clone $this->available();
74
+			foreach ($tasks_schedules as $task_schedule) {
75
+				/** @var TaskSchedule $task_schedule */
76
+				if ($available_tasks->has($task_schedule->taskId())) {
77
+					$available_tasks->forget($task_schedule->taskId());
78
+				} else {
79
+					$this->delete($task_schedule);
80
+				}
81
+			}
82
+
83
+			foreach ($available_tasks as $task_name => $task_class) {
84
+				if (null !== $task = app($task_class)) {
85
+					$this->insertTask($task_name, $task->defaultFrequency());
86
+				}
87
+			}
88
+
89
+			return $this->all(false, $include_disabled);
90
+		}
91
+
92
+		return $tasks_schedules;
93
+	}
94
+
95
+	/**
96
+	 * Returns tasks exposed through modules implementing ModuleTasksProviderInterface.
97
+	 *
98
+	 * @return Collection<string, string>
99
+	 */
100
+	public function available(): Collection
101
+	{
102
+		return Registry::cache()->array()->remember(
103
+			'maj-available-admintasks',
104
+			function (): Collection {
105
+				/** @var Collection<string, string> $tasks */
106
+				$tasks = $this->module_service
107
+					->findByInterface(ModuleTasksProviderInterface::class)
108
+					->flatMap(fn(ModuleTasksProviderInterface $module) => $module->listTasks());
109
+				return $tasks;
110
+			}
111
+		);
112
+	}
113
+
114
+	/**
115
+	 * Find a task schedule by its ID.
116
+	 *
117
+	 * @param int $task_schedule_id
118
+	 * @return TaskSchedule|NULL
119
+	 */
120
+	public function find(int $task_schedule_id): ?TaskSchedule
121
+	{
122
+		return DB::table('maj_admintasks')
123
+			->select()
124
+			->where('majat_id', '=', $task_schedule_id)
125
+			->get()
126
+			->map(self::rowMapper())
127
+			->first();
128
+	}
129
+
130
+	/**
131
+	 * Add a new task schedule with the specified task ID, and frequency if defined.
132
+	 * Uses default for other settings.
133
+	 *
134
+	 * @param string $task_id
135
+	 * @param int $frequency
136
+	 * @return bool
137
+	 */
138
+	public function insertTask(string $task_id, int $frequency = 0): bool
139
+	{
140
+		$values = ['majat_task_id' => $task_id];
141
+		if ($frequency > 0) {
142
+			$values['majat_frequency'] = $frequency;
143
+		}
144
+
145
+		return DB::table('maj_admintasks')
146
+			->insert($values);
147
+	}
148
+
149
+	/**
150
+	 * Update a task schedule.
151
+	 * Returns the number of tasks schedules updated.
152
+	 *
153
+	 * @param TaskSchedule $task_schedule
154
+	 * @return int
155
+	 */
156
+	public function update(TaskSchedule $task_schedule): int
157
+	{
158
+		return DB::table('maj_admintasks')
159
+			->where('majat_id', '=', $task_schedule->id())
160
+			->update([
161
+				'majat_status'      =>  $task_schedule->isEnabled() ? 'enabled' : 'disabled',
162
+				'majat_last_run'    =>  $task_schedule->lastRunTime()->toDateTimeString(),
163
+				'majat_last_result' =>  $task_schedule->wasLastRunSuccess(),
164
+				'majat_frequency'   =>  $task_schedule->frequency(),
165
+				'majat_nb_occur'    =>  $task_schedule->remainingOccurrences(),
166
+				'majat_running'     =>  $task_schedule->isRunning()
167
+			]);
168
+	}
169
+
170
+	/**
171
+	 * Delete a task schedule.
172
+	 *
173
+	 * @param TaskSchedule $task_schedule
174
+	 * @return int
175
+	 */
176
+	public function delete(TaskSchedule $task_schedule): int
177
+	{
178
+		return DB::table('maj_admintasks')
179
+			->where('majat_id', '=', $task_schedule->id())
180
+			->delete();
181
+	}
182
+
183
+	/**
184
+	 * Find a task by its name
185
+	 *
186
+	 * @param string $task_id
187
+	 * @return TaskInterface|NULL
188
+	 */
189
+	public function findTask(string $task_id): ?TaskInterface
190
+	{
191
+		if ($this->available()->has($task_id)) {
192
+			return app($this->available()->get($task_id));
193
+		}
194
+		return null;
195
+	}
196
+
197
+	/**
198
+	 * Retrieve all tasks that are candidates to be run.
199
+	 *
200
+	 * @param bool $force Should the run be forced
201
+	 * @param string $task_id Specific task ID to be run
202
+	 * @return Collection<TaskSchedule>
203
+	 */
204
+	public function findTasksToRun(bool $force, string $task_id = null): Collection
205
+	{
206
+		$query = DB::table('maj_admintasks')
207
+			->select()
208
+			->where('majat_status', '=', 'enabled')
209
+			->where(function (Builder $query): void {
210
+
211
+				$query->where('majat_running', '=', 0)
212
+				->orWhere(
213
+					'majat_last_run',
214
+					'<=',
215
+					Registry::timestampFactory()->now()->addSeconds(-self::TASK_TIME_OUT)->toDateTimeString()
216
+				);
217
+			});
218
+
219
+		if (!$force) {
220
+			$query->where(function (Builder $query): void {
221
+
222
+				$query->where('majat_running', '=', 0)
223
+					->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
224
+			});
225
+		}
226
+
227
+		if ($task_id !== null) {
228
+			$query->where('majat_task_id', '=', $task_id);
229
+		}
230
+
231
+		return $query->get()->map(self::rowMapper());
232
+	}
233
+
234
+	/**
235
+	 * Run the task associated with the schedule.
236
+	 * The task will run if either forced to, or its next scheduled run time has been exceeded.
237
+	 * The last run time is recorded only if the task is successful.
238
+	 *
239
+	 * @param TaskSchedule $task_schedule
240
+	 * @param boolean $force
241
+	 */
242
+	public function run(TaskSchedule $task_schedule, $force = false): void
243
+	{
244
+		/** @var TaskSchedule $task_schedule */
245
+		$task_schedule = DB::table('maj_admintasks')
246
+			->select()
247
+			->where('majat_id', '=', $task_schedule->id())
248
+			->lockForUpdate()
249
+			->get()
250
+			->map(self::rowMapper())
251
+			->first();
252
+
253
+		if (
254
+			!$task_schedule->isRunning() &&
255
+			($force ||
256
+				$task_schedule->lastRunTime()->addMinutes($task_schedule->frequency())
257
+					->compare(Registry::timestampFactory()->now()) < 0
258
+			)
259
+		) {
260
+			$task_schedule->setLastResult(false);
261
+
262
+			$task = $this->findTask($task_schedule->taskId());
263
+			if ($task !== null) {
264
+				$task_schedule->startRunning();
265
+				$this->update($task_schedule);
266
+
267
+				$first_error = $task_schedule->wasLastRunSuccess();
268
+				try {
269
+					$task_schedule->setLastResult($task->run($task_schedule));
270
+				} catch (Throwable $ex) {
271
+					if ($first_error) { // Only record the first error, as this could fill the log.
272
+						Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()) . ' ' .
273
+							'[' . get_class($ex) . '] ' . $ex->getMessage() . ' ' . $ex->getFile() . ':'
274
+							. $ex->getLine() . PHP_EOL . $ex->getTraceAsString());
275
+					}
276
+				}
277
+
278
+				if ($task_schedule->wasLastRunSuccess()) {
279
+					$task_schedule->setLastRunTime(Registry::timestampFactory()->now());
280
+					$task_schedule->decrementRemainingOccurrences();
281
+				}
282
+				$task_schedule->stopRunning();
283
+			}
284
+			$this->update($task_schedule);
285
+		}
286
+	}
287
+
288
+	/**
289
+	 * Mapper to return a TaskSchedule object from an object.
290
+	 *
291
+	 * @return Closure(stdClass $row): TaskSchedule
292
+	 */
293
+	public static function rowMapper(): Closure
294
+	{
295
+		return static function (stdClass $row): TaskSchedule {
296
+
297
+			return new TaskSchedule(
298
+				(int) $row->majat_id,
299
+				$row->majat_task_id,
300
+				$row->majat_status === 'enabled',
301
+				Registry::timestampFactory()->fromString($row->majat_last_run),
302
+				(bool) $row->majat_last_result,
303
+				(int) $row->majat_frequency,
304
+				(int) $row->majat_nb_occur,
305
+				(bool) $row->majat_running
306
+			);
307
+		};
308
+	}
309 309
 }
Please login to merge, or discard this patch.
Spacing   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -101,7 +101,7 @@  discard block
 block discarded – undo
101 101
     {
102 102
         return Registry::cache()->array()->remember(
103 103
             'maj-available-admintasks',
104
-            function (): Collection {
104
+            function(): Collection {
105 105
                 /** @var Collection<string, string> $tasks */
106 106
                 $tasks = $this->module_service
107 107
                     ->findByInterface(ModuleTasksProviderInterface::class)
@@ -206,7 +206,7 @@  discard block
 block discarded – undo
206 206
         $query = DB::table('maj_admintasks')
207 207
             ->select()
208 208
             ->where('majat_status', '=', 'enabled')
209
-            ->where(function (Builder $query): void {
209
+            ->where(function(Builder $query): void {
210 210
 
211 211
                 $query->where('majat_running', '=', 0)
212 212
                 ->orWhere(
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
             });
218 218
 
219 219
         if (!$force) {
220
-            $query->where(function (Builder $query): void {
220
+            $query->where(function(Builder $query): void {
221 221
 
222 222
                 $query->where('majat_running', '=', 0)
223 223
                     ->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
@@ -269,9 +269,9 @@  discard block
 block discarded – undo
269 269
                     $task_schedule->setLastResult($task->run($task_schedule));
270 270
                 } catch (Throwable $ex) {
271 271
                     if ($first_error) { // Only record the first error, as this could fill the log.
272
-                        Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()) . ' ' .
273
-                            '[' . get_class($ex) . '] ' . $ex->getMessage() . ' ' . $ex->getFile() . ':'
274
-                            . $ex->getLine() . PHP_EOL . $ex->getTraceAsString());
272
+                        Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()).' '.
273
+                            '['.get_class($ex).'] '.$ex->getMessage().' '.$ex->getFile().':'
274
+                            . $ex->getLine().PHP_EOL.$ex->getTraceAsString());
275 275
                     }
276 276
                 }
277 277
 
@@ -292,17 +292,17 @@  discard block
 block discarded – undo
292 292
      */
293 293
     public static function rowMapper(): Closure
294 294
     {
295
-        return static function (stdClass $row): TaskSchedule {
295
+        return static function(stdClass $row): TaskSchedule {
296 296
 
297 297
             return new TaskSchedule(
298
-                (int) $row->majat_id,
298
+                (int)$row->majat_id,
299 299
                 $row->majat_task_id,
300 300
                 $row->majat_status === 'enabled',
301 301
                 Registry::timestampFactory()->fromString($row->majat_last_run),
302
-                (bool) $row->majat_last_result,
303
-                (int) $row->majat_frequency,
304
-                (int) $row->majat_nb_occur,
305
-                (bool) $row->majat_running
302
+                (bool)$row->majat_last_result,
303
+                (int)$row->majat_frequency,
304
+                (int)$row->majat_nb_occur,
305
+                (bool)$row->majat_running
306 306
             );
307 307
         };
308 308
     }
Please login to merge, or discard this patch.
app/Module/GeoDispersion/Views/GeoAnalysisMap.php 2 patches
Indentation   +113 added lines, -113 removed lines patch added patch discarded remove patch
@@ -32,117 +32,117 @@
 block discarded – undo
32 32
  */
33 33
 class GeoAnalysisMap extends AbstractGeoAnalysisView
34 34
 {
35
-    private ?MapColorsConfig $colors_config = null;
36
-
37
-    public function type(): string
38
-    {
39
-        return I18N::translateContext('GEODISPERSION', 'Map');
40
-    }
41
-
42
-    /**
43
-     * {@inheritDoc}
44
-     * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::icon()
45
-     */
46
-    public function icon(ModuleInterface $module): string
47
-    {
48
-        return view($module->name() . '::icons/view-map', ['type' => $this->type()]);
49
-    }
50
-
51
-    /**
52
-     * {@inheritDoc}
53
-     * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::globalSettingsContent()
54
-     */
55
-    public function globalSettingsContent(ModuleInterface $module): string
56
-    {
57
-        return view($module->name() . '::admin/view-edit-map', [
58
-            'module_name'   =>  $module->name(),
59
-            'view'          =>  $this,
60
-            'colors'        =>  $this->colors(),
61
-            'map_adapters'  =>  app(MapAdapterDataService::class)->allForView($this, true)
62
-        ]);
63
-    }
64
-
65
-    /**
66
-     * {@inheritDoc}
67
-     * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::withGlobalSettingsUpdate()
68
-     * @return static
69
-     */
70
-    public function withGlobalSettingsUpdate(ServerRequestInterface $request): self
71
-    {
72
-        $default_color  = Validator::parsedBody($request)->string('view_map_color_default', '');
73
-        $stroke_color   = Validator::parsedBody($request)->string('view_map_color_stroke', '');
74
-        $maxvalue_color  = Validator::parsedBody($request)->string('view_map_color_maxvalue', '');
75
-        $hover_color  = Validator::parsedBody($request)->string('view_map_color_hover', '');
76
-
77
-        try {
78
-            return $this->withColors(new MapColorsConfig(
79
-                Hex::fromString($default_color),
80
-                Hex::fromString($stroke_color),
81
-                Hex::fromString($maxvalue_color),
82
-                Hex::fromString($hover_color)
83
-            ));
84
-        } catch (InvalidColorValue $ex) {
85
-        }
86
-
87
-        return $this;
88
-    }
89
-
90
-    /**
91
-     * {@inheritDoc}
92
-     * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::globalTabContent()
93
-     */
94
-    public function globalTabContent(GeoDispersionModule $module, GeoAnalysisResult $result, array $params): string
95
-    {
96
-        $map_adapters = app(MapAdapterDataService::class)->allForView($this);
97
-
98
-        $adapter_result = null;
99
-        foreach ($map_adapters as $map_adapter) {
100
-            $adapter_result_tmp = $map_adapter->convert($result);
101
-            $adapter_result = $adapter_result === null ?
102
-                $adapter_result_tmp :
103
-                $adapter_result->merge($adapter_result_tmp);
104
-        }
105
-
106
-        if ($adapter_result === null) {
107
-            return view($module->name() . '::errors/tab-error', [
108
-                'message'   =>  I18N::translate('The map could not be loaded.'),
109
-            ]);
110
-        }
111
-
112
-        return view($module->name() . '::geoanalysisview-tab-glb-map', $params + [
113
-            'result'            =>  $adapter_result->geoAnalysisResult(),
114
-            'features'          =>  $adapter_result->features(),
115
-            'colors'            =>  $this->colors(),
116
-            'leaflet_config'    =>  app(LeafletJsService::class)->config(),
117
-            'js_script_url'     =>  $module->assetUrl('js/geodispersion.min.js')
118
-        ]);
119
-    }
120
-
121
-    /**
122
-     * Get the color scheme configuration for the map view
123
-     *
124
-     * @return MapColorsConfig
125
-     */
126
-    public function colors(): MapColorsConfig
127
-    {
128
-        return $this->colors_config ?? new MapColorsConfig(
129
-            new Rgb(245, 245, 245),
130
-            new Rgb(213, 213, 213),
131
-            new Rgb(4, 147, 171),
132
-            new Rgb(255, 102, 0)
133
-        );
134
-    }
135
-
136
-    /**
137
-     * Returns a map view with a new color scheme configuration
138
-     *
139
-     * @param MapColorsConfig $config
140
-     * @return static
141
-     */
142
-    public function withColors(?MapColorsConfig $config): self
143
-    {
144
-        $new = clone $this;
145
-        $new->colors_config = $config;
146
-        return $new;
147
-    }
35
+	private ?MapColorsConfig $colors_config = null;
36
+
37
+	public function type(): string
38
+	{
39
+		return I18N::translateContext('GEODISPERSION', 'Map');
40
+	}
41
+
42
+	/**
43
+	 * {@inheritDoc}
44
+	 * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::icon()
45
+	 */
46
+	public function icon(ModuleInterface $module): string
47
+	{
48
+		return view($module->name() . '::icons/view-map', ['type' => $this->type()]);
49
+	}
50
+
51
+	/**
52
+	 * {@inheritDoc}
53
+	 * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::globalSettingsContent()
54
+	 */
55
+	public function globalSettingsContent(ModuleInterface $module): string
56
+	{
57
+		return view($module->name() . '::admin/view-edit-map', [
58
+			'module_name'   =>  $module->name(),
59
+			'view'          =>  $this,
60
+			'colors'        =>  $this->colors(),
61
+			'map_adapters'  =>  app(MapAdapterDataService::class)->allForView($this, true)
62
+		]);
63
+	}
64
+
65
+	/**
66
+	 * {@inheritDoc}
67
+	 * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::withGlobalSettingsUpdate()
68
+	 * @return static
69
+	 */
70
+	public function withGlobalSettingsUpdate(ServerRequestInterface $request): self
71
+	{
72
+		$default_color  = Validator::parsedBody($request)->string('view_map_color_default', '');
73
+		$stroke_color   = Validator::parsedBody($request)->string('view_map_color_stroke', '');
74
+		$maxvalue_color  = Validator::parsedBody($request)->string('view_map_color_maxvalue', '');
75
+		$hover_color  = Validator::parsedBody($request)->string('view_map_color_hover', '');
76
+
77
+		try {
78
+			return $this->withColors(new MapColorsConfig(
79
+				Hex::fromString($default_color),
80
+				Hex::fromString($stroke_color),
81
+				Hex::fromString($maxvalue_color),
82
+				Hex::fromString($hover_color)
83
+			));
84
+		} catch (InvalidColorValue $ex) {
85
+		}
86
+
87
+		return $this;
88
+	}
89
+
90
+	/**
91
+	 * {@inheritDoc}
92
+	 * @see \MyArtJaub\Webtrees\Module\GeoDispersion\Views\AbstractGeoAnalysisView::globalTabContent()
93
+	 */
94
+	public function globalTabContent(GeoDispersionModule $module, GeoAnalysisResult $result, array $params): string
95
+	{
96
+		$map_adapters = app(MapAdapterDataService::class)->allForView($this);
97
+
98
+		$adapter_result = null;
99
+		foreach ($map_adapters as $map_adapter) {
100
+			$adapter_result_tmp = $map_adapter->convert($result);
101
+			$adapter_result = $adapter_result === null ?
102
+				$adapter_result_tmp :
103
+				$adapter_result->merge($adapter_result_tmp);
104
+		}
105
+
106
+		if ($adapter_result === null) {
107
+			return view($module->name() . '::errors/tab-error', [
108
+				'message'   =>  I18N::translate('The map could not be loaded.'),
109
+			]);
110
+		}
111
+
112
+		return view($module->name() . '::geoanalysisview-tab-glb-map', $params + [
113
+			'result'            =>  $adapter_result->geoAnalysisResult(),
114
+			'features'          =>  $adapter_result->features(),
115
+			'colors'            =>  $this->colors(),
116
+			'leaflet_config'    =>  app(LeafletJsService::class)->config(),
117
+			'js_script_url'     =>  $module->assetUrl('js/geodispersion.min.js')
118
+		]);
119
+	}
120
+
121
+	/**
122
+	 * Get the color scheme configuration for the map view
123
+	 *
124
+	 * @return MapColorsConfig
125
+	 */
126
+	public function colors(): MapColorsConfig
127
+	{
128
+		return $this->colors_config ?? new MapColorsConfig(
129
+			new Rgb(245, 245, 245),
130
+			new Rgb(213, 213, 213),
131
+			new Rgb(4, 147, 171),
132
+			new Rgb(255, 102, 0)
133
+		);
134
+	}
135
+
136
+	/**
137
+	 * Returns a map view with a new color scheme configuration
138
+	 *
139
+	 * @param MapColorsConfig $config
140
+	 * @return static
141
+	 */
142
+	public function withColors(?MapColorsConfig $config): self
143
+	{
144
+		$new = clone $this;
145
+		$new->colors_config = $config;
146
+		return $new;
147
+	}
148 148
 }
Please login to merge, or discard this patch.
Spacing   +7 added lines, -8 removed lines patch added patch discarded remove patch
@@ -45,7 +45,7 @@  discard block
 block discarded – undo
45 45
      */
46 46
     public function icon(ModuleInterface $module): string
47 47
     {
48
-        return view($module->name() . '::icons/view-map', ['type' => $this->type()]);
48
+        return view($module->name().'::icons/view-map', ['type' => $this->type()]);
49 49
     }
50 50
 
51 51
     /**
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
      */
55 55
     public function globalSettingsContent(ModuleInterface $module): string
56 56
     {
57
-        return view($module->name() . '::admin/view-edit-map', [
57
+        return view($module->name().'::admin/view-edit-map', [
58 58
             'module_name'   =>  $module->name(),
59 59
             'view'          =>  $this,
60 60
             'colors'        =>  $this->colors(),
@@ -71,8 +71,8 @@  discard block
 block discarded – undo
71 71
     {
72 72
         $default_color  = Validator::parsedBody($request)->string('view_map_color_default', '');
73 73
         $stroke_color   = Validator::parsedBody($request)->string('view_map_color_stroke', '');
74
-        $maxvalue_color  = Validator::parsedBody($request)->string('view_map_color_maxvalue', '');
75
-        $hover_color  = Validator::parsedBody($request)->string('view_map_color_hover', '');
74
+        $maxvalue_color = Validator::parsedBody($request)->string('view_map_color_maxvalue', '');
75
+        $hover_color = Validator::parsedBody($request)->string('view_map_color_hover', '');
76 76
 
77 77
         try {
78 78
             return $this->withColors(new MapColorsConfig(
@@ -99,17 +99,16 @@  discard block
 block discarded – undo
99 99
         foreach ($map_adapters as $map_adapter) {
100 100
             $adapter_result_tmp = $map_adapter->convert($result);
101 101
             $adapter_result = $adapter_result === null ?
102
-                $adapter_result_tmp :
103
-                $adapter_result->merge($adapter_result_tmp);
102
+                $adapter_result_tmp : $adapter_result->merge($adapter_result_tmp);
104 103
         }
105 104
 
106 105
         if ($adapter_result === null) {
107
-            return view($module->name() . '::errors/tab-error', [
106
+            return view($module->name().'::errors/tab-error', [
108 107
                 'message'   =>  I18N::translate('The map could not be loaded.'),
109 108
             ]);
110 109
         }
111 110
 
112
-        return view($module->name() . '::geoanalysisview-tab-glb-map', $params + [
111
+        return view($module->name().'::geoanalysisview-tab-glb-map', $params + [
113 112
             'result'            =>  $adapter_result->geoAnalysisResult(),
114 113
             'features'          =>  $adapter_result->features(),
115 114
             'colors'            =>  $this->colors(),
Please login to merge, or discard this patch.