Passed
Branch main (f9aaf7)
by Jonathan
14:43
created
app/Module/Certificates/Elements/SourceCertificate.php 2 patches
Indentation   +52 added lines, -52 removed lines patch added patch discarded remove patch
@@ -28,61 +28,61 @@
 block discarded – undo
28 28
  */
29 29
 class SourceCertificate extends AbstractElement
30 30
 {
31
-    protected CertificatesModule $module;
32
-    protected CertificateFilesystemService $certif_filesystem;
33
-    protected UrlObfuscatorService $url_obfuscator_service;
31
+	protected CertificatesModule $module;
32
+	protected CertificateFilesystemService $certif_filesystem;
33
+	protected UrlObfuscatorService $url_obfuscator_service;
34 34
 
35
-    /**
36
-     * Constructor for SourceCertificate element
37
-     *
38
-     * @param string $label
39
-     * @param CertificatesModule $module
40
-     * @param CertificateFilesystemService $certif_filesystem
41
-     * @param UrlObfuscatorService $url_obfuscator_service
42
-     */
43
-    public function __construct(
44
-        string $label,
45
-        CertificatesModule $module,
46
-        CertificateFilesystemService $certif_filesystem = null,
47
-        UrlObfuscatorService $url_obfuscator_service = null
48
-    ) {
49
-        parent::__construct($label, null);
50
-        $this->module = $module;
51
-        $this->certif_filesystem = $certif_filesystem ?? app(CertificateFilesystemService::class);
52
-        $this->url_obfuscator_service = $url_obfuscator_service ?? app(UrlObfuscatorService::class);
53
-    }
35
+	/**
36
+	 * Constructor for SourceCertificate element
37
+	 *
38
+	 * @param string $label
39
+	 * @param CertificatesModule $module
40
+	 * @param CertificateFilesystemService $certif_filesystem
41
+	 * @param UrlObfuscatorService $url_obfuscator_service
42
+	 */
43
+	public function __construct(
44
+		string $label,
45
+		CertificatesModule $module,
46
+		CertificateFilesystemService $certif_filesystem = null,
47
+		UrlObfuscatorService $url_obfuscator_service = null
48
+	) {
49
+		parent::__construct($label, null);
50
+		$this->module = $module;
51
+		$this->certif_filesystem = $certif_filesystem ?? app(CertificateFilesystemService::class);
52
+		$this->url_obfuscator_service = $url_obfuscator_service ?? app(UrlObfuscatorService::class);
53
+	}
54 54
 
55
-    /**
56
-     * {@inheritDoc}
57
-     * @see \Fisharebest\Webtrees\Elements\AbstractElement::canonical()
58
-     */
59
-    public function canonical($value): string
60
-    {
61
-        return strtr($value, '\\', '/');
62
-    }
55
+	/**
56
+	 * {@inheritDoc}
57
+	 * @see \Fisharebest\Webtrees\Elements\AbstractElement::canonical()
58
+	 */
59
+	public function canonical($value): string
60
+	{
61
+		return strtr($value, '\\', '/');
62
+	}
63 63
 
64
-    /**
65
-     * {@inheritDoc}
66
-     * @see \Fisharebest\Webtrees\Elements\AbstractElement::edit()
67
-     */
68
-    public function edit(string $id, string $name, string $value, Tree $tree): string
69
-    {
70
-        list($city, $file) = explode('/', $this->canonical($value), 2) + ['', ''];
64
+	/**
65
+	 * {@inheritDoc}
66
+	 * @see \Fisharebest\Webtrees\Elements\AbstractElement::edit()
67
+	 */
68
+	public function edit(string $id, string $name, string $value, Tree $tree): string
69
+	{
70
+		list($city, $file) = explode('/', $this->canonical($value), 2) + ['', ''];
71 71
 
72
-        $cities = array_map(function (string $item): array {
73
-            return [$this->url_obfuscator_service->obfuscate($item), $item];
74
-        }, $this->certif_filesystem->cities($tree));
72
+		$cities = array_map(function (string $item): array {
73
+			return [$this->url_obfuscator_service->obfuscate($item), $item];
74
+		}, $this->certif_filesystem->cities($tree));
75 75
 
76
-        return view($this->module->name() . '::components/edit-certificate', [
77
-            'module_name'   =>  $this->module->name(),
78
-            'tree'          =>  $tree,
79
-            'id'            =>  $id,
80
-            'name'          =>  $name,
81
-            'cities'        =>  $cities,
82
-            'value'         =>  $this->canonical($value),
83
-            'value_city'    =>  $city,
84
-            'value_file'    =>  $file,
85
-            'js_script_url' =>  $this->module->assetUrl('js/certificates.min.js')
86
-        ]);
87
-    }
76
+		return view($this->module->name() . '::components/edit-certificate', [
77
+			'module_name'   =>  $this->module->name(),
78
+			'tree'          =>  $tree,
79
+			'id'            =>  $id,
80
+			'name'          =>  $name,
81
+			'cities'        =>  $cities,
82
+			'value'         =>  $this->canonical($value),
83
+			'value_city'    =>  $city,
84
+			'value_file'    =>  $file,
85
+			'js_script_url' =>  $this->module->assetUrl('js/certificates.min.js')
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
@@ -69,11 +69,11 @@
 block discarded – undo
69 69
     {
70 70
         list($city, $file) = explode('/', $this->canonical($value), 2) + ['', ''];
71 71
 
72
-        $cities = array_map(function (string $item): array {
72
+        $cities = array_map(function(string $item): array {
73 73
             return [$this->url_obfuscator_service->obfuscate($item), $item];
74 74
         }, $this->certif_filesystem->cities($tree));
75 75
 
76
-        return view($this->module->name() . '::components/edit-certificate', [
76
+        return view($this->module->name().'::components/edit-certificate', [
77 77
             'module_name'   =>  $this->module->name(),
78 78
             'tree'          =>  $tree,
79 79
             'id'            =>  $id,
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TasksList.php 2 patches
Indentation   +82 added lines, -82 removed lines patch added patch discarded remove patch
@@ -31,90 +31,90 @@
 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'   =>  '<span dir="auto">' . e($task_name) . '</span>',
86
-                        'raw'       =>  $task_name
87
-                    ],
88
-                    'last_run'  =>  [
89
-                        'display'   =>  $schedule->lastRunTime()->unix() === 0 ?
90
-                            view('components/datetime', ['timestamp' => $schedule->lastRunTime()]) :
91
-                            view('components/datetime-diff', ['timestamp' => $schedule->lastRunTime()]),
92
-                        'raw'       =>  $schedule->lastRunTime()->unix()
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' =>  '<span dir="auto">' . e($schedule->frequency()->cascade()->forHumans()) . '</span>',
101
-                    'nb_occurrences'    =>  $schedule->remainingOccurences() > 0 ?
102
-                        I18N::number($schedule->remainingOccurences()) :
103
-                        I18N::translate('Unlimited'),
104
-                    'running'   =>  view($module_name . '::components/yes-no-icons', [
105
-                        'yes' => $schedule->isRunning(),
106
-                        'text_yes' => I18N::translate('Running'),
107
-                        'text_no' => I18N::translate('Not running')
108
-                    ]),
109
-                    'run'       =>  view($module_name . '::admin/tasks-table-run', [
110
-                        'task_sched_id' => $schedule->id(),
111
-                        'run_route' => route(TaskTrigger::class, [
112
-                            'task'  =>  $schedule->taskId(),
113
-                            'force' =>  $module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN')
114
-                        ])
115
-                    ])
116
-                ];
117
-            })
118
-        ]);
119
-    }
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'   =>  '<span dir="auto">' . e($task_name) . '</span>',
86
+						'raw'       =>  $task_name
87
+					],
88
+					'last_run'  =>  [
89
+						'display'   =>  $schedule->lastRunTime()->unix() === 0 ?
90
+							view('components/datetime', ['timestamp' => $schedule->lastRunTime()]) :
91
+							view('components/datetime-diff', ['timestamp' => $schedule->lastRunTime()]),
92
+						'raw'       =>  $schedule->lastRunTime()->unix()
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' =>  '<span dir="auto">' . e($schedule->frequency()->cascade()->forHumans()) . '</span>',
101
+					'nb_occurrences'    =>  $schedule->remainingOccurences() > 0 ?
102
+						I18N::number($schedule->remainingOccurences()) :
103
+						I18N::translate('Unlimited'),
104
+					'running'   =>  view($module_name . '::components/yes-no-icons', [
105
+						'yes' => $schedule->isRunning(),
106
+						'text_yes' => I18N::translate('Running'),
107
+						'text_no' => I18N::translate('Not running')
108
+					]),
109
+					'run'       =>  view($module_name . '::admin/tasks-table-run', [
110
+						'task_sched_id' => $schedule->id(),
111
+						'run_route' => route(TaskTrigger::class, [
112
+							'task'  =>  $schedule->taskId(),
113
+							'force' =>  $module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN')
114
+						])
115
+					])
116
+				];
117
+			})
118
+		]);
119
+	}
120 120
 }
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,37 +76,35 @@  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'   =>  '<span dir="auto">' . e($task_name) . '</span>',
85
+                        'display'   =>  '<span dir="auto">'.e($task_name).'</span>',
86 86
                         'raw'       =>  $task_name
87 87
                     ],
88 88
                     'last_run'  =>  [
89 89
                         'display'   =>  $schedule->lastRunTime()->unix() === 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()->unix()
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
-                    'frequency' =>  '<span dir="auto">' . e($schedule->frequency()->cascade()->forHumans()) . '</span>',
99
+                    'frequency' =>  '<span dir="auto">'.e($schedule->frequency()->cascade()->forHumans()).'</span>',
101 100
                     'nb_occurrences'    =>  $schedule->remainingOccurences() > 0 ?
102
-                        I18N::number($schedule->remainingOccurences()) :
103
-                        I18N::translate('Unlimited'),
104
-                    'running'   =>  view($module_name . '::components/yes-no-icons', [
101
+                        I18N::number($schedule->remainingOccurences()) : I18N::translate('Unlimited'),
102
+                    'running'   =>  view($module_name.'::components/yes-no-icons', [
105 103
                         'yes' => $schedule->isRunning(),
106 104
                         'text_yes' => I18N::translate('Running'),
107 105
                         'text_no' => I18N::translate('Not running')
108 106
                     ]),
109
-                    'run'       =>  view($module_name . '::admin/tasks-table-run', [
107
+                    'run'       =>  view($module_name.'::admin/tasks-table-run', [
110 108
                         'task_sched_id' => $schedule->id(),
111 109
                         'run_route' => route(TaskTrigger::class, [
112 110
                             'task'  =>  $schedule->taskId(),
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TaskEditAction.php 2 patches
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -33,151 +33,151 @@
 block discarded – undo
33 33
  */
34 34
 class TaskEditAction implements RequestHandlerInterface
35 35
 {
36
-    private ?AdminTasksModule $module;
37
-    private TaskScheduleService $taskschedules_service;
38
-
39
-    /**
40
-     * Constructor for TaskEditAction 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
-
51
-    /**
52
-     * {@inheritDoc}
53
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
-     */
55
-    public function handle(ServerRequestInterface $request): ResponseInterface
56
-    {
57
-        $admin_config_route = route(AdminConfigPage::class);
58
-
59
-        if ($this->module === null) {
60
-            FlashMessages::addMessage(
61
-                I18N::translate('The attached module could not be found.'),
62
-                'danger'
63
-            );
64
-            return redirect($admin_config_route);
65
-        }
66
-
67
-        $task_sched_id = (int) $request->getAttribute('task');
68
-        $task_schedule = $this->taskschedules_service->find($task_sched_id);
69
-
70
-        if ($task_schedule === null) {
71
-            FlashMessages::addMessage(
72
-                I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
73
-                'danger'
74
-            );
75
-            return redirect($admin_config_route);
76
-        }
77
-
78
-        $success = $this->updateGeneralSettings($task_schedule, $request);
79
-        $success = $success && $this->updateSpecificSettings($task_schedule, $request);
80
-
81
-        if ($success) {
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
-        }
89
-
90
-        return redirect($admin_config_route);
91
-    }
92
-
93
-    /**
94
-     * Update general settings for the task, based on the request parameters
95
-     *
96
-     * @param TaskSchedule $task_schedule
97
-     * @param ServerRequestInterface $request
98
-     * @return bool
99
-     */
100
-    private function updateGeneralSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
101
-    {
102
-        if ($this->module === null) {
103
-            return false;
104
-        }
105
-
106
-        $params = (array) $request->getParsedBody();
107
-
108
-        $frequency = (int) $params['frequency'];
109
-        if ($frequency > 0) {
110
-            $task_schedule->setFrequency(CarbonInterval::minutes($frequency));
111
-        } else {
112
-            FlashMessages::addMessage(I18N::translate('The frequency is not in a valid format.'), 'danger');
113
-        }
114
-
115
-        $is_limited = (bool) $params['is_limited'];
116
-        $nb_occur = (int) $params['nb_occur'];
117
-
118
-        if ($is_limited) {
119
-            if ($nb_occur > 0) {
120
-                $task_schedule->setRemainingOccurences($nb_occur);
121
-            } else {
122
-                FlashMessages::addMessage(
123
-                    I18N::translate('The number of remaining occurences is not in a valid format.'),
124
-                    'danger'
125
-                );
126
-            }
127
-        } else {
128
-            $task_schedule->setRemainingOccurences(0);
129
-        }
130
-
131
-        try {
132
-            $this->taskschedules_service->update($task_schedule);
133
-            return true;
134
-        } catch (Throwable $ex) {
135
-            Log::addErrorLog(
136
-                sprintf(
137
-                    'Error while updating the Task Schedule "%s". Exception: %s',
138
-                    $task_schedule->id(),
139
-                    $ex->getMessage()
140
-                )
141
-            );
142
-        }
143
-
144
-        FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task.'), 'danger');
145
-        //@phpcs:ignore Generic.Files.LineLength.TooLong
146
-        Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
147
-        return false;
148
-    }
149
-
150
-    /**
151
-     * Update general settings for the task, based on the request parameters
152
-     *
153
-     * @param TaskSchedule $task_schedule
154
-     * @param ServerRequestInterface $request
155
-     * @return bool
156
-     */
157
-    private function updateSpecificSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
158
-    {
159
-        if ($this->module === null) {
160
-            return false;
161
-        }
162
-
163
-        $task = $this->taskschedules_service->findTask($task_schedule->taskId());
164
-        if ($task === null || !($task instanceof ConfigurableTaskInterface)) {
165
-            return true;
166
-        }
167
-
168
-        /** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
169
-        if (!$task->updateConfig($request, $task_schedule)) {
170
-            FlashMessages::addMessage(
171
-                I18N::translate(
172
-                    'An error occured while updating the specific settings of administrative task “%s”.',
173
-                    $task->name()
174
-                ),
175
-                'danger'
176
-            );
177
-            //phpcs:ignore Generic.Files.LineLength.TooLong
178
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
179
-        }
180
-
181
-        return true;
182
-    }
36
+	private ?AdminTasksModule $module;
37
+	private TaskScheduleService $taskschedules_service;
38
+
39
+	/**
40
+	 * Constructor for TaskEditAction 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
+
51
+	/**
52
+	 * {@inheritDoc}
53
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
54
+	 */
55
+	public function handle(ServerRequestInterface $request): ResponseInterface
56
+	{
57
+		$admin_config_route = route(AdminConfigPage::class);
58
+
59
+		if ($this->module === null) {
60
+			FlashMessages::addMessage(
61
+				I18N::translate('The attached module could not be found.'),
62
+				'danger'
63
+			);
64
+			return redirect($admin_config_route);
65
+		}
66
+
67
+		$task_sched_id = (int) $request->getAttribute('task');
68
+		$task_schedule = $this->taskschedules_service->find($task_sched_id);
69
+
70
+		if ($task_schedule === null) {
71
+			FlashMessages::addMessage(
72
+				I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
73
+				'danger'
74
+			);
75
+			return redirect($admin_config_route);
76
+		}
77
+
78
+		$success = $this->updateGeneralSettings($task_schedule, $request);
79
+		$success = $success && $this->updateSpecificSettings($task_schedule, $request);
80
+
81
+		if ($success) {
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
+		}
89
+
90
+		return redirect($admin_config_route);
91
+	}
92
+
93
+	/**
94
+	 * Update general settings for the task, based on the request parameters
95
+	 *
96
+	 * @param TaskSchedule $task_schedule
97
+	 * @param ServerRequestInterface $request
98
+	 * @return bool
99
+	 */
100
+	private function updateGeneralSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
101
+	{
102
+		if ($this->module === null) {
103
+			return false;
104
+		}
105
+
106
+		$params = (array) $request->getParsedBody();
107
+
108
+		$frequency = (int) $params['frequency'];
109
+		if ($frequency > 0) {
110
+			$task_schedule->setFrequency(CarbonInterval::minutes($frequency));
111
+		} else {
112
+			FlashMessages::addMessage(I18N::translate('The frequency is not in a valid format.'), 'danger');
113
+		}
114
+
115
+		$is_limited = (bool) $params['is_limited'];
116
+		$nb_occur = (int) $params['nb_occur'];
117
+
118
+		if ($is_limited) {
119
+			if ($nb_occur > 0) {
120
+				$task_schedule->setRemainingOccurences($nb_occur);
121
+			} else {
122
+				FlashMessages::addMessage(
123
+					I18N::translate('The number of remaining occurences is not in a valid format.'),
124
+					'danger'
125
+				);
126
+			}
127
+		} else {
128
+			$task_schedule->setRemainingOccurences(0);
129
+		}
130
+
131
+		try {
132
+			$this->taskschedules_service->update($task_schedule);
133
+			return true;
134
+		} catch (Throwable $ex) {
135
+			Log::addErrorLog(
136
+				sprintf(
137
+					'Error while updating the Task Schedule "%s". Exception: %s',
138
+					$task_schedule->id(),
139
+					$ex->getMessage()
140
+				)
141
+			);
142
+		}
143
+
144
+		FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task.'), 'danger');
145
+		//@phpcs:ignore Generic.Files.LineLength.TooLong
146
+		Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
147
+		return false;
148
+	}
149
+
150
+	/**
151
+	 * Update general settings for the task, based on the request parameters
152
+	 *
153
+	 * @param TaskSchedule $task_schedule
154
+	 * @param ServerRequestInterface $request
155
+	 * @return bool
156
+	 */
157
+	private function updateSpecificSettings(TaskSchedule $task_schedule, ServerRequestInterface $request): bool
158
+	{
159
+		if ($this->module === null) {
160
+			return false;
161
+		}
162
+
163
+		$task = $this->taskschedules_service->findTask($task_schedule->taskId());
164
+		if ($task === null || !($task instanceof ConfigurableTaskInterface)) {
165
+			return true;
166
+		}
167
+
168
+		/** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
169
+		if (!$task->updateConfig($request, $task_schedule)) {
170
+			FlashMessages::addMessage(
171
+				I18N::translate(
172
+					'An error occured while updating the specific settings of administrative task “%s”.',
173
+					$task->name()
174
+				),
175
+				'danger'
176
+			);
177
+			//phpcs:ignore Generic.Files.LineLength.TooLong
178
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
179
+		}
180
+
181
+		return true;
182
+	}
183 183
 }
Please login to merge, or discard this patch.
Spacing   +8 added lines, -8 removed lines patch added patch discarded remove patch
@@ -64,7 +64,7 @@  discard block
 block discarded – undo
64 64
             return redirect($admin_config_route);
65 65
         }
66 66
 
67
-        $task_sched_id = (int) $request->getAttribute('task');
67
+        $task_sched_id = (int)$request->getAttribute('task');
68 68
         $task_schedule = $this->taskschedules_service->find($task_sched_id);
69 69
 
70 70
         if ($task_schedule === null) {
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
                 'success'
85 85
             );
86 86
             //phpcs:ignore Generic.Files.LineLength.TooLong
87
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
87
+            Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” has been updated.');
88 88
         }
89 89
 
90 90
         return redirect($admin_config_route);
@@ -103,17 +103,17 @@  discard block
 block discarded – undo
103 103
             return false;
104 104
         }
105 105
 
106
-        $params = (array) $request->getParsedBody();
106
+        $params = (array)$request->getParsedBody();
107 107
 
108
-        $frequency = (int) $params['frequency'];
108
+        $frequency = (int)$params['frequency'];
109 109
         if ($frequency > 0) {
110 110
             $task_schedule->setFrequency(CarbonInterval::minutes($frequency));
111 111
         } else {
112 112
             FlashMessages::addMessage(I18N::translate('The frequency is not in a valid format.'), 'danger');
113 113
         }
114 114
 
115
-        $is_limited = (bool) $params['is_limited'];
116
-        $nb_occur = (int) $params['nb_occur'];
115
+        $is_limited = (bool)$params['is_limited'];
116
+        $nb_occur = (int)$params['nb_occur'];
117 117
 
118 118
         if ($is_limited) {
119 119
             if ($nb_occur > 0) {
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 
144 144
         FlashMessages::addMessage(I18N::translate('An error occured while updating the scheduled task.'), 'danger');
145 145
         //@phpcs:ignore Generic.Files.LineLength.TooLong
146
-        Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
146
+        Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” could not be updated. See error log.');
147 147
         return false;
148 148
     }
149 149
 
@@ -175,7 +175,7 @@  discard block
 block discarded – undo
175 175
                 'danger'
176 176
             );
177 177
             //phpcs:ignore Generic.Files.LineLength.TooLong
178
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : AdminTask “' . $task->name() . '” specific settings could not be updated. See error log.');
178
+            Log::addConfigurationLog('Module '.$this->module->title().' : AdminTask “'.$task->name().'” specific settings could not be updated. See error log.');
179 179
         }
180 180
 
181 181
         return true;
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TaskStatusAction.php 2 patches
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -29,68 +29,68 @@
 block discarded – undo
29 29
  */
30 30
 class TaskStatusAction 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 TaskStatusAction Request Handler
37
-     *
38
-     * @param ModuleService $module_service
39
-     * @param TaskScheduleService $taskschedules_service
40
-     */
41
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
42
-    {
43
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
44
-        $this->taskschedules_service = $taskschedules_service;
45
-    }
35
+	/**
36
+	 * Constructor for TaskStatusAction Request Handler
37
+	 *
38
+	 * @param ModuleService $module_service
39
+	 * @param TaskScheduleService $taskschedules_service
40
+	 */
41
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
42
+	{
43
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
44
+		$this->taskschedules_service = $taskschedules_service;
45
+	}
46 46
 
47
-    /**
48
-     * {@inheritDoc}
49
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
50
-     */
51
-    public function handle(ServerRequestInterface $request): ResponseInterface
52
-    {
53
-        $admin_config_route = route(AdminConfigPage::class);
47
+	/**
48
+	 * {@inheritDoc}
49
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
50
+	 */
51
+	public function handle(ServerRequestInterface $request): ResponseInterface
52
+	{
53
+		$admin_config_route = route(AdminConfigPage::class);
54 54
 
55
-        if ($this->module === null) {
56
-            FlashMessages::addMessage(
57
-                I18N::translate('The attached module could not be found.'),
58
-                'danger'
59
-            );
60
-            return redirect($admin_config_route);
61
-        }
55
+		if ($this->module === null) {
56
+			FlashMessages::addMessage(
57
+				I18N::translate('The attached module could not be found.'),
58
+				'danger'
59
+			);
60
+			return redirect($admin_config_route);
61
+		}
62 62
 
63
-        $task_sched_id = (int) $request->getAttribute('task');
64
-        $task_schedule = $this->taskschedules_service->find($task_sched_id);
63
+		$task_sched_id = (int) $request->getAttribute('task');
64
+		$task_schedule = $this->taskschedules_service->find($task_sched_id);
65 65
 
66
-        $admin_config_route = route(AdminConfigPage::class);
66
+		$admin_config_route = route(AdminConfigPage::class);
67 67
 
68
-        if ($task_schedule === null) {
69
-            FlashMessages::addMessage(
70
-                I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
71
-                'danger'
72
-            );
73
-            return redirect($admin_config_route);
74
-        }
68
+		if ($task_schedule === null) {
69
+			FlashMessages::addMessage(
70
+				I18N::translate('The task shedule with ID “%s” does not exist.', I18N::number($task_sched_id)),
71
+				'danger'
72
+			);
73
+			return redirect($admin_config_route);
74
+		}
75 75
 
76
-        ((bool) $request->getAttribute('enable', false)) ? $task_schedule->enable() : $task_schedule->disable();
76
+		((bool) $request->getAttribute('enable', false)) ? $task_schedule->enable() : $task_schedule->disable();
77 77
 
78
-        if ($this->taskschedules_service->update($task_schedule) > 0) {
79
-            FlashMessages::addMessage(
80
-                I18N::translate('The scheduled task has been successfully updated.'),
81
-                'success'
82
-            );
83
-            //phpcs:ignore Generic.Files.LineLength.TooLong
84
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
85
-        } else {
86
-            FlashMessages::addMessage(
87
-                I18N::translate('An error occured while updating the scheduled task.'),
88
-                'danger'
89
-            );
90
-            //phpcs:ignore Generic.Files.LineLength.TooLong
91
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
92
-        }
78
+		if ($this->taskschedules_service->update($task_schedule) > 0) {
79
+			FlashMessages::addMessage(
80
+				I18N::translate('The scheduled task has been successfully updated.'),
81
+				'success'
82
+			);
83
+			//phpcs:ignore Generic.Files.LineLength.TooLong
84
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
85
+		} else {
86
+			FlashMessages::addMessage(
87
+				I18N::translate('An error occured while updating the scheduled task.'),
88
+				'danger'
89
+			);
90
+			//phpcs:ignore Generic.Files.LineLength.TooLong
91
+			Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
92
+		}
93 93
 
94
-        return redirect($admin_config_route);
95
-    }
94
+		return redirect($admin_config_route);
95
+	}
96 96
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -60,7 +60,7 @@  discard block
 block discarded – undo
60 60
             return redirect($admin_config_route);
61 61
         }
62 62
 
63
-        $task_sched_id = (int) $request->getAttribute('task');
63
+        $task_sched_id = (int)$request->getAttribute('task');
64 64
         $task_schedule = $this->taskschedules_service->find($task_sched_id);
65 65
 
66 66
         $admin_config_route = route(AdminConfigPage::class);
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
             return redirect($admin_config_route);
74 74
         }
75 75
 
76
-        ((bool) $request->getAttribute('enable', false)) ? $task_schedule->enable() : $task_schedule->disable();
76
+        ((bool)$request->getAttribute('enable', false)) ? $task_schedule->enable() : $task_schedule->disable();
77 77
 
78 78
         if ($this->taskschedules_service->update($task_schedule) > 0) {
79 79
             FlashMessages::addMessage(
@@ -81,14 +81,14 @@  discard block
 block discarded – undo
81 81
                 'success'
82 82
             );
83 83
             //phpcs:ignore Generic.Files.LineLength.TooLong
84
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” has been updated.');
84
+            Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” has been updated.');
85 85
         } else {
86 86
             FlashMessages::addMessage(
87 87
                 I18N::translate('An error occured while updating the scheduled task.'),
88 88
                 'danger'
89 89
             );
90 90
             //phpcs:ignore Generic.Files.LineLength.TooLong
91
-            Log::addConfigurationLog('Module ' . $this->module->title() . ' : Task Schedule “' . $task_schedule->id() . '” could not be updated. See error log.');
91
+            Log::addConfigurationLog('Module '.$this->module->title().' : Task Schedule “'.$task_schedule->id().'” could not be updated. See error log.');
92 92
         }
93 93
 
94 94
         return redirect($admin_config_route);
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/AdminConfigPage.php 1 patch
Indentation   +37 added lines, -37 removed lines patch added patch discarded remove patch
@@ -29,47 +29,47 @@
 block discarded – undo
29 29
  */
30 30
 class AdminConfigPage implements RequestHandlerInterface
31 31
 {
32
-    use ViewResponseTrait;
32
+	use ViewResponseTrait;
33 33
 
34
-    private ?AdminTasksModule $module;
35
-    private TokenService $token_service;
34
+	private ?AdminTasksModule $module;
35
+	private TokenService $token_service;
36 36
 
37
-    /**
38
-     * Constructor for Admin Config request handler
39
-     *
40
-     * @param ModuleService $module_service
41
-     */
42
-    public function __construct(ModuleService $module_service, TokenService $token_service)
43
-    {
44
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
45
-        $this->token_service = $token_service;
46
-    }
37
+	/**
38
+	 * Constructor for Admin Config request handler
39
+	 *
40
+	 * @param ModuleService $module_service
41
+	 */
42
+	public function __construct(ModuleService $module_service, TokenService $token_service)
43
+	{
44
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
45
+		$this->token_service = $token_service;
46
+	}
47 47
 
48
-    /**
49
-     * {@inheritDoc}
50
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
-     */
52
-    public function handle(ServerRequestInterface $request): ResponseInterface
53
-    {
54
-        $this->layout = 'layouts/administration';
48
+	/**
49
+	 * {@inheritDoc}
50
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
51
+	 */
52
+	public function handle(ServerRequestInterface $request): ResponseInterface
53
+	{
54
+		$this->layout = 'layouts/administration';
55 55
 
56
-        if ($this->module === null) {
57
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
58
-        }
56
+		if ($this->module === null) {
57
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
58
+		}
59 59
 
60
-        $token = $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN');
61
-        if ($token === '') {
62
-            $token = $this->token_service->generateRandomToken();
63
-            $this->module->setPreference('PAT_FORCE_EXEC_TOKEN', $token);
64
-        }
60
+		$token = $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN');
61
+		if ($token === '') {
62
+			$token = $this->token_service->generateRandomToken();
63
+			$this->module->setPreference('PAT_FORCE_EXEC_TOKEN', $token);
64
+		}
65 65
 
66
-        return $this->viewResponse($this->module->name() . '::admin/config', [
67
-            'title'             =>  $this->module->title(),
68
-            'trigger_token'     =>  $token,
69
-            'trigger_route'     =>  route(TaskTrigger::class, ['task' => '__TASKNAME__', 'force' => '__TOKEN__']),
70
-            'new_token_route'   =>  route(TokenGenerate::class),
71
-            'tasks_data_route'  =>  route(TasksList::class),
72
-            'js_script_url'     =>  $this->module->assetUrl('js/admintasks.min.js')
73
-        ]);
74
-    }
66
+		return $this->viewResponse($this->module->name() . '::admin/config', [
67
+			'title'             =>  $this->module->title(),
68
+			'trigger_token'     =>  $token,
69
+			'trigger_route'     =>  route(TaskTrigger::class, ['task' => '__TASKNAME__', 'force' => '__TOKEN__']),
70
+			'new_token_route'   =>  route(TokenGenerate::class),
71
+			'tasks_data_route'  =>  route(TasksList::class),
72
+			'js_script_url'     =>  $this->module->assetUrl('js/admintasks.min.js')
73
+		]);
74
+	}
75 75
 }
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
@@ -28,41 +28,41 @@
 block discarded – undo
28 28
  */
29 29
 class TaskTrigger implements RequestHandlerInterface
30 30
 {
31
-    private ?AdminTasksModule $module;
32
-    private TaskScheduleService $taskschedules_service;
31
+	private ?AdminTasksModule $module;
32
+	private TaskScheduleService $taskschedules_service;
33 33
 
34
-    /**
35
-     * Constructor for TaskTrigger request handler
36
-     * @param ModuleService $module_service
37
-     * @param TaskScheduleService $taskschedules_service
38
-     */
39
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
40
-    {
41
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
42
-        $this->taskschedules_service = $taskschedules_service;
43
-    }
34
+	/**
35
+	 * Constructor for TaskTrigger request handler
36
+	 * @param ModuleService $module_service
37
+	 * @param TaskScheduleService $taskschedules_service
38
+	 */
39
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
40
+	{
41
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
42
+		$this->taskschedules_service = $taskschedules_service;
43
+	}
44 44
 
45
-    /**
46
-     * {@inheritDoc}
47
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
48
-     */
49
-    public function handle(ServerRequestInterface $request): ResponseInterface
50
-    {
51
-        if ($this->module === null) {
52
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
53
-        }
45
+	/**
46
+	 * {@inheritDoc}
47
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
48
+	 */
49
+	public function handle(ServerRequestInterface $request): ResponseInterface
50
+	{
51
+		if ($this->module === null) {
52
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
53
+		}
54 54
 
55
-        $task_id = $request->getAttribute('task');
56
-        $token = $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN');
57
-        $force_token = $request->getQueryParams()['force'] ?? '';
58
-        $force = $token == $force_token;
55
+		$task_id = $request->getAttribute('task');
56
+		$token = $this->module->getPreference('MAJ_AT_FORCE_EXEC_TOKEN');
57
+		$force_token = $request->getQueryParams()['force'] ?? '';
58
+		$force = $token == $force_token;
59 59
 
60
-        $task_schedules = $this->taskschedules_service->findTasksToRun($force, $task_id);
60
+		$task_schedules = $this->taskschedules_service->findTasksToRun($force, $task_id);
61 61
 
62
-        foreach ($task_schedules as $task_schedule) {
63
-            $this->taskschedules_service->run($task_schedule, $force);
64
-        }
62
+		foreach ($task_schedules as $task_schedule) {
63
+			$this->taskschedules_service->run($task_schedule, $force);
64
+		}
65 65
 
66
-        return response();
67
-    }
66
+		return response();
67
+	}
68 68
 }
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
@@ -30,58 +30,58 @@
 block discarded – undo
30 30
  */
31 31
 class TaskEditPage implements RequestHandlerInterface
32 32
 {
33
-    use ViewResponseTrait;
33
+	use ViewResponseTrait;
34 34
 
35
-    private ?AdminTasksModule $module;
36
-    private TaskScheduleService $taskschedules_service;
35
+	private ?AdminTasksModule $module;
36
+	private TaskScheduleService $taskschedules_service;
37 37
 
38
-    /**
39
-     * Constructor for TaskEditPage Request Handler
40
-     *
41
-     * @param ModuleService $module_service
42
-     * @param TaskScheduleService $taskschedules_service
43
-     */
44
-    public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
45
-    {
46
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
47
-        $this->taskschedules_service = $taskschedules_service;
48
-    }
38
+	/**
39
+	 * Constructor for TaskEditPage Request Handler
40
+	 *
41
+	 * @param ModuleService $module_service
42
+	 * @param TaskScheduleService $taskschedules_service
43
+	 */
44
+	public function __construct(ModuleService $module_service, TaskScheduleService $taskschedules_service)
45
+	{
46
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
47
+		$this->taskschedules_service = $taskschedules_service;
48
+	}
49 49
 
50
-    /**
51
-     * {@inheritDoc}
52
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
53
-     */
54
-    public function handle(ServerRequestInterface $request): ResponseInterface
55
-    {
56
-        $this->layout = 'layouts/administration';
50
+	/**
51
+	 * {@inheritDoc}
52
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
53
+	 */
54
+	public function handle(ServerRequestInterface $request): ResponseInterface
55
+	{
56
+		$this->layout = 'layouts/administration';
57 57
 
58
-        if ($this->module === null) {
59
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
60
-        }
58
+		if ($this->module === null) {
59
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
60
+		}
61 61
 
62
-        $task_sched_id = (int) $request->getAttribute('task');
63
-        $task_schedule = $this->taskschedules_service->find($task_sched_id);
62
+		$task_sched_id = (int) $request->getAttribute('task');
63
+		$task_schedule = $this->taskschedules_service->find($task_sched_id);
64 64
 
65
-        if ($task_schedule === null) {
66
-            throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
67
-        }
65
+		if ($task_schedule === null) {
66
+			throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
67
+		}
68 68
 
69
-        $task = $this->taskschedules_service->findTask($task_schedule->taskId());
69
+		$task = $this->taskschedules_service->findTask($task_schedule->taskId());
70 70
 
71
-        if ($task === null) {
72
-            throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
73
-        }
71
+		if ($task === null) {
72
+			throw new HttpNotFoundException(I18N::translate('The Task schedule could not be found.'));
73
+		}
74 74
 
75
-        $has_task_config = $task instanceof ConfigurableTaskInterface;
76
-        /** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
75
+		$has_task_config = $task instanceof ConfigurableTaskInterface;
76
+		/** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
77 77
 
78
-        return $this->viewResponse($this->module->name() . '::admin/tasks-edit', [
79
-            'module'            =>  $this->module,
80
-            'title'             =>  I18N::translate('Edit the administrative task') . ' - ' . $task->name(),
81
-            'task_schedule'     =>  $task_schedule,
82
-            'task'              =>  $task,
83
-            'has_task_config'   =>  $has_task_config,
84
-            'task_config_view'  =>  $has_task_config ? $task->configView($request) : ''
85
-        ]);
86
-    }
78
+		return $this->viewResponse($this->module->name() . '::admin/tasks-edit', [
79
+			'module'            =>  $this->module,
80
+			'title'             =>  I18N::translate('Edit the administrative task') . ' - ' . $task->name(),
81
+			'task_schedule'     =>  $task_schedule,
82
+			'task'              =>  $task,
83
+			'has_task_config'   =>  $has_task_config,
84
+			'task_config_view'  =>  $has_task_config ? $task->configView($request) : ''
85
+		]);
86
+	}
87 87
 }
Please login to merge, or discard this patch.
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -59,7 +59,7 @@  discard block
 block discarded – undo
59 59
             throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
60 60
         }
61 61
 
62
-        $task_sched_id = (int) $request->getAttribute('task');
62
+        $task_sched_id = (int)$request->getAttribute('task');
63 63
         $task_schedule = $this->taskschedules_service->find($task_sched_id);
64 64
 
65 65
         if ($task_schedule === null) {
@@ -75,9 +75,9 @@  discard block
 block discarded – undo
75 75
         $has_task_config = $task instanceof ConfigurableTaskInterface;
76 76
         /** @var \MyArtJaub\Webtrees\Contracts\Tasks\TaskInterface&\MyArtJaub\Webtrees\Contracts\Tasks\ConfigurableTaskInterface $task */
77 77
 
78
-        return $this->viewResponse($this->module->name() . '::admin/tasks-edit', [
78
+        return $this->viewResponse($this->module->name().'::admin/tasks-edit', [
79 79
             'module'            =>  $this->module,
80
-            'title'             =>  I18N::translate('Edit the administrative task') . ' - ' . $task->name(),
80
+            'title'             =>  I18N::translate('Edit the administrative task').' - '.$task->name(),
81 81
             'task_schedule'     =>  $task_schedule,
82 82
             'task'              =>  $task,
83 83
             'has_task_config'   =>  $has_task_config,
Please login to merge, or discard this patch.
app/Module/AdminTasks/Http/RequestHandlers/TokenGenerate.php 2 patches
Indentation   +30 added lines, -30 removed lines patch added patch discarded remove patch
@@ -30,34 +30,34 @@
 block discarded – undo
30 30
  */
31 31
 class TokenGenerate implements RequestHandlerInterface
32 32
 {
33
-    private ?AdminTasksModule $module;
34
-    private TokenService $token_service;
35
-
36
-    /**
37
-     * Constructor for TokenGenerate request handler
38
-     *
39
-     * @param ModuleService $module_service
40
-     */
41
-    public function __construct(ModuleService $module_service, TokenService $token_service)
42
-    {
43
-        $this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
44
-        $this->token_service = $token_service;
45
-    }
46
-
47
-    /**
48
-     * {@inheritDoc}
49
-     * @see \Psr\Http\Server\RequestHandlerInterface::handle()
50
-     */
51
-    public function handle(ServerRequestInterface $request): ResponseInterface
52
-    {
53
-        if ($this->module === null) {
54
-            throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
55
-        }
56
-
57
-        $token = $this->token_service->generateRandomToken();
58
-        $this->module->setPreference('MAJ_AT_FORCE_EXEC_TOKEN', $token);
59
-        Log::addConfigurationLog($this->module->title() . ' : New token generated.');
60
-
61
-        return response(['token' => $token]);
62
-    }
33
+	private ?AdminTasksModule $module;
34
+	private TokenService $token_service;
35
+
36
+	/**
37
+	 * Constructor for TokenGenerate request handler
38
+	 *
39
+	 * @param ModuleService $module_service
40
+	 */
41
+	public function __construct(ModuleService $module_service, TokenService $token_service)
42
+	{
43
+		$this->module = $module_service->findByInterface(AdminTasksModule::class)->first();
44
+		$this->token_service = $token_service;
45
+	}
46
+
47
+	/**
48
+	 * {@inheritDoc}
49
+	 * @see \Psr\Http\Server\RequestHandlerInterface::handle()
50
+	 */
51
+	public function handle(ServerRequestInterface $request): ResponseInterface
52
+	{
53
+		if ($this->module === null) {
54
+			throw new HttpNotFoundException(I18N::translate('The attached module could not be found.'));
55
+		}
56
+
57
+		$token = $this->token_service->generateRandomToken();
58
+		$this->module->setPreference('MAJ_AT_FORCE_EXEC_TOKEN', $token);
59
+		Log::addConfigurationLog($this->module->title() . ' : New token generated.');
60
+
61
+		return response(['token' => $token]);
62
+	}
63 63
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -56,7 +56,7 @@
 block discarded – undo
56 56
 
57 57
         $token = $this->token_service->generateRandomToken();
58 58
         $this->module->setPreference('MAJ_AT_FORCE_EXEC_TOKEN', $token);
59
-        Log::addConfigurationLog($this->module->title() . ' : New token generated.');
59
+        Log::addConfigurationLog($this->module->title().' : New token generated.');
60 60
 
61 61
         return response(['token' => $token]);
62 62
     }
Please login to merge, or discard this patch.
app/Module/AdminTasks/Services/TaskScheduleService.php 2 patches
Indentation   +257 added lines, -257 removed lines patch added patch discarded remove patch
@@ -36,261 +36,261 @@
 block discarded – undo
36 36
  */
37 37
 class TaskScheduleService
38 38
 {
39
-    /**
40
-     * Time-out after which the task will be considered not running any more.
41
-     * In seconds, default 5 mins.
42
-     * @var integer
43
-     */
44
-    public const TASK_TIME_OUT = 600;
45
-
46
-    private ModuleService $module_service;
47
-
48
-    /**
49
-     * Constructor for TaskScheduleService
50
-     *
51
-     * @param ModuleService $module_service
52
-     */
53
-    public function __construct(ModuleService $module_service)
54
-    {
55
-        $this->module_service = $module_service;
56
-    }
57
-
58
-    /**
59
-     * Returns all Tasks schedules in database.
60
-     * Stored records can be synchronised with the tasks actually available to the system.
61
-     *
62
-     * @param bool $sync_available Should tasks synchronised with available ones
63
-     * @param bool $include_disabled Should disabled tasks be returned
64
-     * @return Collection<TaskSchedule> Collection of TaskSchedule
65
-     */
66
-    public function all(bool $sync_available = false, bool $include_disabled = true): Collection
67
-    {
68
-        $tasks_schedules = DB::table('maj_admintasks')
69
-        ->select()
70
-        ->get()
71
-        ->map(self::rowMapper());
72
-
73
-        if ($sync_available) {
74
-            $available_tasks = clone $this->available();
75
-            foreach ($tasks_schedules as $task_schedule) {
76
-                /** @var TaskSchedule $task_schedule */
77
-                if ($available_tasks->has($task_schedule->taskId())) {
78
-                    $available_tasks->forget($task_schedule->taskId());
79
-                } else {
80
-                    $this->delete($task_schedule);
81
-                }
82
-            }
83
-
84
-            foreach ($available_tasks as $task_name => $task) {
85
-                /** @var TaskInterface $task */
86
-                $this->insertTask($task_name, $task->defaultFrequency());
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<array<string, string>>
99
-     */
100
-    public function available(): Collection
101
-    {
102
-        return Registry::cache()->array()->remember('maj-available-admintasks', function () {
103
-            return $this->module_service
104
-                ->findByInterface(ModuleTasksProviderInterface::class)
105
-                ->flatMap(fn(ModuleTasksProviderInterface $module) => $module->listTasks());
106
-        });
107
-    }
108
-
109
-    /**
110
-     * Find a task schedule by its ID.
111
-     *
112
-     * @param int $task_schedule_id
113
-     * @return TaskSchedule|NULL
114
-     */
115
-    public function find(int $task_schedule_id): ?TaskSchedule
116
-    {
117
-        return DB::table('maj_admintasks')
118
-            ->select()
119
-            ->where('majat_id', '=', $task_schedule_id)
120
-            ->get()
121
-            ->map(self::rowMapper())
122
-            ->first();
123
-    }
124
-
125
-    /**
126
-     * Add a new task schedule with the specified task ID, and frequency if defined.
127
-     * Uses default for other settings.
128
-     *
129
-     * @param string $task_id
130
-     * @param int $frequency
131
-     * @return bool
132
-     */
133
-    public function insertTask(string $task_id, int $frequency = 0): bool
134
-    {
135
-        $values = ['majat_task_id' => $task_id];
136
-        if ($frequency > 0) {
137
-            $values['majat_frequency'] = $frequency;
138
-        }
139
-
140
-        return DB::table('maj_admintasks')
141
-            ->insert($values);
142
-    }
143
-
144
-    /**
145
-     * Update a task schedule.
146
-     * Returns the number of tasks schedules updated.
147
-     *
148
-     * @param TaskSchedule $task_schedule
149
-     * @return int
150
-     */
151
-    public function update(TaskSchedule $task_schedule): int
152
-    {
153
-        return DB::table('maj_admintasks')
154
-            ->where('majat_id', '=', $task_schedule->id())
155
-            ->update([
156
-                'majat_status'      =>  $task_schedule->isEnabled() ? 'enabled' : 'disabled',
157
-                'majat_last_run'    =>  $task_schedule->lastRunTime(),
158
-                'majat_last_result' =>  $task_schedule->wasLastRunSuccess(),
159
-                'majat_frequency'   =>  $task_schedule->frequency()->totalMinutes,
160
-                'majat_nb_occur'    =>  $task_schedule->remainingOccurences(),
161
-                'majat_running'     =>  $task_schedule->isRunning()
162
-            ]);
163
-    }
164
-
165
-    /**
166
-     * Delete a task schedule.
167
-     *
168
-     * @param TaskSchedule $task_schedule
169
-     * @return int
170
-     */
171
-    public function delete(TaskSchedule $task_schedule): int
172
-    {
173
-        return DB::table('maj_admintasks')
174
-            ->where('majat_id', '=', $task_schedule->id())
175
-            ->delete();
176
-    }
177
-
178
-    /**
179
-     * Find a task by its name
180
-     *
181
-     * @param string $task_id
182
-     * @return TaskInterface|NULL
183
-     */
184
-    public function findTask(string $task_id): ?TaskInterface
185
-    {
186
-        if ($this->available()->has($task_id)) {
187
-            return app($this->available()->get($task_id));
188
-        }
189
-        return null;
190
-    }
191
-
192
-    /**
193
-     * Retrieve all tasks that are candidates to be run.
194
-     *
195
-     * @param bool $force Should the run be forced
196
-     * @param string $task_id Specific task ID to be run
197
-     * @return Collection<TaskSchedule>
198
-     */
199
-    public function findTasksToRun(bool $force, string $task_id = null): Collection
200
-    {
201
-        $query = DB::table('maj_admintasks')
202
-            ->select()
203
-            ->where('majat_status', '=', 'enabled')
204
-            ->where(function (Builder $query): void {
205
-
206
-                $query->where('majat_running', '=', 0)
207
-                ->orWhere('majat_last_run', '<=', Carbon::now()->subSeconds(self::TASK_TIME_OUT));
208
-            });
209
-
210
-        if (!$force) {
211
-            $query->where(function (Builder $query): void {
212
-
213
-                $query->where('majat_running', '=', 0)
214
-                    ->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
215
-            });
216
-        }
217
-
218
-        if ($task_id !== null) {
219
-            $query->where('majat_task_id', '=', $task_id);
220
-        }
221
-
222
-        return $query->get()->map(self::rowMapper());
223
-    }
224
-
225
-    /**
226
-     * Run the task associated with the schedule.
227
-     * The task will run if either forced to, or its next scheduled run time has been exceeded.
228
-     * The last run time is recorded only if the task is successful.
229
-     *
230
-     * @param TaskSchedule $task_schedule
231
-     * @param boolean $force
232
-     */
233
-    public function run(TaskSchedule $task_schedule, $force = false): void
234
-    {
235
-        $task_schedule = DB::table('maj_admintasks')
236
-            ->select()
237
-            ->where('majat_id', '=', $task_schedule->id())
238
-            ->lockForUpdate()
239
-            ->get()
240
-            ->map(self::rowMapper())
241
-            ->first();
242
-
243
-        if (
244
-            !$task_schedule->isRunning() &&
245
-            ($force || $task_schedule->lastRunTime()->add($task_schedule->frequency())->lessThan(Carbon::now()))
246
-        ) {
247
-            $task_schedule->setLastResult(false);
248
-
249
-            $task = $this->findTask($task_schedule->taskId());
250
-            if ($task !== null) {
251
-                $task_schedule->startRunning();
252
-                $this->update($task_schedule);
253
-
254
-                $first_error = $task_schedule->wasLastRunSuccess();
255
-                try {
256
-                    $task_schedule->setLastResult($task->run($task_schedule));
257
-                } catch (Throwable $ex) {
258
-                    if ($first_error) { // Only record the first error, as this could fill the log.
259
-                        Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()) . ' ' .
260
-                            '[' . get_class($ex) . '] ' . $ex->getMessage() . ' ' . $ex->getFile() . ':'
261
-                            . $ex->getLine() . PHP_EOL . $ex->getTraceAsString());
262
-                    }
263
-                }
264
-
265
-                if ($task_schedule->wasLastRunSuccess()) {
266
-                    $task_schedule->setLastRunTime(Carbon::now());
267
-                    $task_schedule->decrementRemainingOccurences();
268
-                }
269
-                $task_schedule->stopRunning();
270
-            }
271
-            $this->update($task_schedule);
272
-        }
273
-    }
274
-
275
-    /**
276
-     * Mapper to return a TaskSchedule object from an object.
277
-     *
278
-     * @return Closure(stdClass $row): TaskSchedule
279
-     */
280
-    public static function rowMapper(): Closure
281
-    {
282
-        return static function (stdClass $row): TaskSchedule {
283
-
284
-            return new TaskSchedule(
285
-                (int) $row->majat_id,
286
-                $row->majat_task_id,
287
-                $row->majat_status === 'enabled',
288
-                Carbon::parse($row->majat_last_run),
289
-                (bool) $row->majat_last_result,
290
-                CarbonInterval::minutes($row->majat_frequency),
291
-                (int) $row->majat_nb_occur,
292
-                (bool) $row->majat_running
293
-            );
294
-        };
295
-    }
39
+	/**
40
+	 * Time-out after which the task will be considered not running any more.
41
+	 * In seconds, default 5 mins.
42
+	 * @var integer
43
+	 */
44
+	public const TASK_TIME_OUT = 600;
45
+
46
+	private ModuleService $module_service;
47
+
48
+	/**
49
+	 * Constructor for TaskScheduleService
50
+	 *
51
+	 * @param ModuleService $module_service
52
+	 */
53
+	public function __construct(ModuleService $module_service)
54
+	{
55
+		$this->module_service = $module_service;
56
+	}
57
+
58
+	/**
59
+	 * Returns all Tasks schedules in database.
60
+	 * Stored records can be synchronised with the tasks actually available to the system.
61
+	 *
62
+	 * @param bool $sync_available Should tasks synchronised with available ones
63
+	 * @param bool $include_disabled Should disabled tasks be returned
64
+	 * @return Collection<TaskSchedule> Collection of TaskSchedule
65
+	 */
66
+	public function all(bool $sync_available = false, bool $include_disabled = true): Collection
67
+	{
68
+		$tasks_schedules = DB::table('maj_admintasks')
69
+		->select()
70
+		->get()
71
+		->map(self::rowMapper());
72
+
73
+		if ($sync_available) {
74
+			$available_tasks = clone $this->available();
75
+			foreach ($tasks_schedules as $task_schedule) {
76
+				/** @var TaskSchedule $task_schedule */
77
+				if ($available_tasks->has($task_schedule->taskId())) {
78
+					$available_tasks->forget($task_schedule->taskId());
79
+				} else {
80
+					$this->delete($task_schedule);
81
+				}
82
+			}
83
+
84
+			foreach ($available_tasks as $task_name => $task) {
85
+				/** @var TaskInterface $task */
86
+				$this->insertTask($task_name, $task->defaultFrequency());
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<array<string, string>>
99
+	 */
100
+	public function available(): Collection
101
+	{
102
+		return Registry::cache()->array()->remember('maj-available-admintasks', function () {
103
+			return $this->module_service
104
+				->findByInterface(ModuleTasksProviderInterface::class)
105
+				->flatMap(fn(ModuleTasksProviderInterface $module) => $module->listTasks());
106
+		});
107
+	}
108
+
109
+	/**
110
+	 * Find a task schedule by its ID.
111
+	 *
112
+	 * @param int $task_schedule_id
113
+	 * @return TaskSchedule|NULL
114
+	 */
115
+	public function find(int $task_schedule_id): ?TaskSchedule
116
+	{
117
+		return DB::table('maj_admintasks')
118
+			->select()
119
+			->where('majat_id', '=', $task_schedule_id)
120
+			->get()
121
+			->map(self::rowMapper())
122
+			->first();
123
+	}
124
+
125
+	/**
126
+	 * Add a new task schedule with the specified task ID, and frequency if defined.
127
+	 * Uses default for other settings.
128
+	 *
129
+	 * @param string $task_id
130
+	 * @param int $frequency
131
+	 * @return bool
132
+	 */
133
+	public function insertTask(string $task_id, int $frequency = 0): bool
134
+	{
135
+		$values = ['majat_task_id' => $task_id];
136
+		if ($frequency > 0) {
137
+			$values['majat_frequency'] = $frequency;
138
+		}
139
+
140
+		return DB::table('maj_admintasks')
141
+			->insert($values);
142
+	}
143
+
144
+	/**
145
+	 * Update a task schedule.
146
+	 * Returns the number of tasks schedules updated.
147
+	 *
148
+	 * @param TaskSchedule $task_schedule
149
+	 * @return int
150
+	 */
151
+	public function update(TaskSchedule $task_schedule): int
152
+	{
153
+		return DB::table('maj_admintasks')
154
+			->where('majat_id', '=', $task_schedule->id())
155
+			->update([
156
+				'majat_status'      =>  $task_schedule->isEnabled() ? 'enabled' : 'disabled',
157
+				'majat_last_run'    =>  $task_schedule->lastRunTime(),
158
+				'majat_last_result' =>  $task_schedule->wasLastRunSuccess(),
159
+				'majat_frequency'   =>  $task_schedule->frequency()->totalMinutes,
160
+				'majat_nb_occur'    =>  $task_schedule->remainingOccurences(),
161
+				'majat_running'     =>  $task_schedule->isRunning()
162
+			]);
163
+	}
164
+
165
+	/**
166
+	 * Delete a task schedule.
167
+	 *
168
+	 * @param TaskSchedule $task_schedule
169
+	 * @return int
170
+	 */
171
+	public function delete(TaskSchedule $task_schedule): int
172
+	{
173
+		return DB::table('maj_admintasks')
174
+			->where('majat_id', '=', $task_schedule->id())
175
+			->delete();
176
+	}
177
+
178
+	/**
179
+	 * Find a task by its name
180
+	 *
181
+	 * @param string $task_id
182
+	 * @return TaskInterface|NULL
183
+	 */
184
+	public function findTask(string $task_id): ?TaskInterface
185
+	{
186
+		if ($this->available()->has($task_id)) {
187
+			return app($this->available()->get($task_id));
188
+		}
189
+		return null;
190
+	}
191
+
192
+	/**
193
+	 * Retrieve all tasks that are candidates to be run.
194
+	 *
195
+	 * @param bool $force Should the run be forced
196
+	 * @param string $task_id Specific task ID to be run
197
+	 * @return Collection<TaskSchedule>
198
+	 */
199
+	public function findTasksToRun(bool $force, string $task_id = null): Collection
200
+	{
201
+		$query = DB::table('maj_admintasks')
202
+			->select()
203
+			->where('majat_status', '=', 'enabled')
204
+			->where(function (Builder $query): void {
205
+
206
+				$query->where('majat_running', '=', 0)
207
+				->orWhere('majat_last_run', '<=', Carbon::now()->subSeconds(self::TASK_TIME_OUT));
208
+			});
209
+
210
+		if (!$force) {
211
+			$query->where(function (Builder $query): void {
212
+
213
+				$query->where('majat_running', '=', 0)
214
+					->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
215
+			});
216
+		}
217
+
218
+		if ($task_id !== null) {
219
+			$query->where('majat_task_id', '=', $task_id);
220
+		}
221
+
222
+		return $query->get()->map(self::rowMapper());
223
+	}
224
+
225
+	/**
226
+	 * Run the task associated with the schedule.
227
+	 * The task will run if either forced to, or its next scheduled run time has been exceeded.
228
+	 * The last run time is recorded only if the task is successful.
229
+	 *
230
+	 * @param TaskSchedule $task_schedule
231
+	 * @param boolean $force
232
+	 */
233
+	public function run(TaskSchedule $task_schedule, $force = false): void
234
+	{
235
+		$task_schedule = DB::table('maj_admintasks')
236
+			->select()
237
+			->where('majat_id', '=', $task_schedule->id())
238
+			->lockForUpdate()
239
+			->get()
240
+			->map(self::rowMapper())
241
+			->first();
242
+
243
+		if (
244
+			!$task_schedule->isRunning() &&
245
+			($force || $task_schedule->lastRunTime()->add($task_schedule->frequency())->lessThan(Carbon::now()))
246
+		) {
247
+			$task_schedule->setLastResult(false);
248
+
249
+			$task = $this->findTask($task_schedule->taskId());
250
+			if ($task !== null) {
251
+				$task_schedule->startRunning();
252
+				$this->update($task_schedule);
253
+
254
+				$first_error = $task_schedule->wasLastRunSuccess();
255
+				try {
256
+					$task_schedule->setLastResult($task->run($task_schedule));
257
+				} catch (Throwable $ex) {
258
+					if ($first_error) { // Only record the first error, as this could fill the log.
259
+						Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()) . ' ' .
260
+							'[' . get_class($ex) . '] ' . $ex->getMessage() . ' ' . $ex->getFile() . ':'
261
+							. $ex->getLine() . PHP_EOL . $ex->getTraceAsString());
262
+					}
263
+				}
264
+
265
+				if ($task_schedule->wasLastRunSuccess()) {
266
+					$task_schedule->setLastRunTime(Carbon::now());
267
+					$task_schedule->decrementRemainingOccurences();
268
+				}
269
+				$task_schedule->stopRunning();
270
+			}
271
+			$this->update($task_schedule);
272
+		}
273
+	}
274
+
275
+	/**
276
+	 * Mapper to return a TaskSchedule object from an object.
277
+	 *
278
+	 * @return Closure(stdClass $row): TaskSchedule
279
+	 */
280
+	public static function rowMapper(): Closure
281
+	{
282
+		return static function (stdClass $row): TaskSchedule {
283
+
284
+			return new TaskSchedule(
285
+				(int) $row->majat_id,
286
+				$row->majat_task_id,
287
+				$row->majat_status === 'enabled',
288
+				Carbon::parse($row->majat_last_run),
289
+				(bool) $row->majat_last_result,
290
+				CarbonInterval::minutes($row->majat_frequency),
291
+				(int) $row->majat_nb_occur,
292
+				(bool) $row->majat_running
293
+			);
294
+		};
295
+	}
296 296
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -99,7 +99,7 @@  discard block
 block discarded – undo
99 99
      */
100 100
     public function available(): Collection
101 101
     {
102
-        return Registry::cache()->array()->remember('maj-available-admintasks', function () {
102
+        return Registry::cache()->array()->remember('maj-available-admintasks', function() {
103 103
             return $this->module_service
104 104
                 ->findByInterface(ModuleTasksProviderInterface::class)
105 105
                 ->flatMap(fn(ModuleTasksProviderInterface $module) => $module->listTasks());
@@ -201,14 +201,14 @@  discard block
 block discarded – undo
201 201
         $query = DB::table('maj_admintasks')
202 202
             ->select()
203 203
             ->where('majat_status', '=', 'enabled')
204
-            ->where(function (Builder $query): void {
204
+            ->where(function(Builder $query): void {
205 205
 
206 206
                 $query->where('majat_running', '=', 0)
207 207
                 ->orWhere('majat_last_run', '<=', Carbon::now()->subSeconds(self::TASK_TIME_OUT));
208 208
             });
209 209
 
210 210
         if (!$force) {
211
-            $query->where(function (Builder $query): void {
211
+            $query->where(function(Builder $query): void {
212 212
 
213 213
                 $query->where('majat_running', '=', 0)
214 214
                     ->orWhereRaw('DATE_ADD(majat_last_run, INTERVAL majat_frequency MINUTE) <= NOW()');
@@ -256,9 +256,9 @@  discard block
 block discarded – undo
256 256
                     $task_schedule->setLastResult($task->run($task_schedule));
257 257
                 } catch (Throwable $ex) {
258 258
                     if ($first_error) { // Only record the first error, as this could fill the log.
259
-                        Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()) . ' ' .
260
-                            '[' . get_class($ex) . '] ' . $ex->getMessage() . ' ' . $ex->getFile() . ':'
261
-                            . $ex->getLine() . PHP_EOL . $ex->getTraceAsString());
259
+                        Log::addErrorLog(I18N::translate('Error while running task %s:', $task->name()).' '.
260
+                            '['.get_class($ex).'] '.$ex->getMessage().' '.$ex->getFile().':'
261
+                            . $ex->getLine().PHP_EOL.$ex->getTraceAsString());
262 262
                     }
263 263
                 }
264 264
 
@@ -279,17 +279,17 @@  discard block
 block discarded – undo
279 279
      */
280 280
     public static function rowMapper(): Closure
281 281
     {
282
-        return static function (stdClass $row): TaskSchedule {
282
+        return static function(stdClass $row): TaskSchedule {
283 283
 
284 284
             return new TaskSchedule(
285
-                (int) $row->majat_id,
285
+                (int)$row->majat_id,
286 286
                 $row->majat_task_id,
287 287
                 $row->majat_status === 'enabled',
288 288
                 Carbon::parse($row->majat_last_run),
289
-                (bool) $row->majat_last_result,
289
+                (bool)$row->majat_last_result,
290 290
                 CarbonInterval::minutes($row->majat_frequency),
291
-                (int) $row->majat_nb_occur,
292
-                (bool) $row->majat_running
291
+                (int)$row->majat_nb_occur,
292
+                (bool)$row->majat_running
293 293
             );
294 294
         };
295 295
     }
Please login to merge, or discard this patch.