Passed
Push — develop ( a6098c...8f95fb )
by Nikita
13:41
created

GdaemonTaskRepository::getTasks()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 16
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 0
Metric Value
eloc 10
c 0
b 0
f 0
dl 0
loc 16
ccs 0
cts 6
cp 0
rs 9.9332
cc 3
nc 4
nop 3
crap 12
1
<?php
2
3
namespace Gameap\Repositories;
4
5
use Gameap\Exceptions\Repositories\GdaemonTaskRepository\EmptyServerStartCommandException;
6
use Gameap\Exceptions\Repositories\GdaemonTaskRepository\InvalidServerStartCommandException;
7
use Gameap\Models\Server;
8
use Gameap\Models\GdaemonTask;
9
use Gameap\Models\DedicatedServer;
10
use Gameap\Exceptions\Repositories\RecordExistExceptions;
11
use Gameap\Exceptions\Repositories\GdaemonTaskRepository\GdaemonTaskRepositoryException;
12
use Illuminate\Support\Facades\DB;
13
use PDO;
14
15
/**
16
 * Class GdaemonTaskRepository
17
*/
18
class GdaemonTaskRepository extends Repository
19
{
20
    public function __construct(GdaemonTask $gdaemonTask)
21
    {
22
        $this->model = $gdaemonTask;
23
    }
24
    
25
    public function getAll($perPage = 20)
26
    {
27
        $gdaemonTasks = GdaemonTask::orderBy('id', 'DESC')->paginate($perPage);
28
        return $gdaemonTasks;
29
    }
30
31
    /**
32
     * Create new starting of game server task
33
     *
34
     * @param Server $server
35
     * @param int $runAftId
36
     * @return int Gdaemon Task ID
37
     *
38
     * @throws RecordExistExceptions
39
     * @throws InvalidServerStartCommandException
40
     * @throws EmptyServerStartCommandException
41
     */
42
    public function addServerStart(Server $server, int $runAftId = 0)
43
    {
44
        $this->workingTaskNotExistOrFail($server, GdaemonTask::TASK_SERVER_START, 'Server start task is already exists');
45
        $this->serverCommandCorrectOrFail($server);
46
47
        return GdaemonTask::create([
48
            'run_aft_id' => $runAftId,
49
            'dedicated_server_id' => $server->ds_id,
50
            'server_id' => $server->id,
51
            'task' => GdaemonTask::TASK_SERVER_START,
52
        ])->id;
53
    }
54
55
    /**
56
     * Create new stopping of game server task
57
     *
58
     * @param Server $server
59
     * @param int $runAftId
60
     * @return int Gdaemon Task ID
61
     *
62
     * @throws RecordExistExceptions
63
     */
64
    public function addServerStop(Server $server, int $runAftId = 0)
65
    {
66
        $this->workingTaskNotExistOrFail($server, GdaemonTask::TASK_SERVER_STOP, 'Server stop task is already exists');
67
68
        return GdaemonTask::create([
69
            'run_aft_id' => $runAftId,
70
            'dedicated_server_id' => $server->ds_id,
71
            'server_id' => $server->id,
72
            'task' => GdaemonTask::TASK_SERVER_STOP,
73
        ])->id;
74
    }
75
76
    /**
77
     * @param Server $server
78
     * @param int    $runAftId
79
     *
80
     * @return int Gdaemon Task ID
81
     *
82
     * @throws RecordExistExceptions
83
     * @throws InvalidServerStartCommandException
84
     * @throws EmptyServerStartCommandException
85
     */
86
    public function addServerRestart(Server $server, int $runAftId = 0)
87
    {
88
        $this->workingTaskNotExistOrFail($server, GdaemonTask::TASK_SERVER_RESTART, 'Server restart task is already exists');
89
        $this->serverCommandCorrectOrFail();
0 ignored issues
show
Bug introduced by
The call to Gameap\Repositories\Gdae...rCommandCorrectOrFail() has too few arguments starting with server. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

89
        $this->/** @scrutinizer ignore-call */ 
90
               serverCommandCorrectOrFail();

This check compares calls to functions or methods with their respective definitions. If the call has less arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress. Please note the @ignore annotation hint above.

Loading history...
90
91
        return GdaemonTask::create([
92
            'run_aft_id' => $runAftId,
93
            'dedicated_server_id' => $server->ds_id,
94
            'server_id' => $server->id,
95
            'task' => GdaemonTask::TASK_SERVER_RESTART,
96
        ])->id;
97
    }
98
99
    /**
100
     * @param Server $server
101
     * @param int    $runAftId
102
     *
103
     * @return int Gdaemon Task ID
104
     *
105
     * @throws RecordExistExceptions
106
     */
107
    public function addServerUpdate(Server $server, int $runAftId = 0)
108
    {
109
        $this->workingTaskNotExistOrFail($server, GdaemonTask::TASK_SERVER_UPDATE, 'Server update/install task is already exists');
110
        
111
        return GdaemonTask::create([
112
            'run_aft_id' => $runAftId,
113
            'dedicated_server_id' => $server->ds_id,
114
            'server_id' => $server->id,
115
            'task' => GdaemonTask::TASK_SERVER_UPDATE,
116
        ])->id;
117
    }
118
119
    /**
120
     * Remove server files
121
     *
122
     * @param Server $server
123
     * @param int    $runAftId
124
     * @return int Gdaemon Task ID
125
     *
126
     * @throws RecordExistExceptions
127
     */
128
    public function addServerDelete(Server $server, int $runAftId = 0)
129
    {
130
        $this->workingTaskNotExistOrFail($server, GdaemonTask::TASK_SERVER_DELETE, 'Server delete task is already exists');
131
        
132
        return GdaemonTask::create([
133
            'run_aft_id' => $runAftId,
134
            'dedicated_server_id' => $server->ds_id,
135
            'server_id' => $server->id,
136
            'task' => GdaemonTask::TASK_SERVER_DELETE,
137
        ])->id;
138
    }
139
140
    /**
141
     * @param int $serverId
142
     * @param string|array $task
143
     * @param string|array $status
144
     *
145
     * @return mixed
146
     */
147
    public function getTasks(int $serverId, $task, $status)
148
    {
149
        if (is_array($task)) {
150
            $taskQuery = GdaemonTask::whereIn(['task', $task])->where([['server_id', '=', $serverId]]);
151
        } else {
152
            $taskQuery = GdaemonTask::where([
153
                ['task', '=', $task],
154
                ['server_id', '=', $serverId]
155
            ]);
156
        }
157
158
        $taskQuery = is_array($status)
159
            ? $taskQuery->whereIn('status', $status)
160
            : $taskQuery->where('status', '=', $status);
161
162
        return $taskQuery->get();
163
    }
164
165
    /**
166
     * Get working or waiting task id. Return 0 if task is not one
167
     *
168
     * @param int $serverId
169
     * @param $task
170
     * @return int
171
     */
172
    public function getOneWorkingTaskId(int $serverId, $task)
173
    {
174
        $tasks = $this->getTasks($serverId, $task, [GdaemonTask::STATUS_WAITING, GdaemonTask::STATUS_WORKING]);
175
176
        return (count($tasks) === 1)
177
            ? $tasks->first()->id
178
            : 0;
179
    }
180
181
    /**
182
     * @param GdaemonTask $gdaemonTask
183
     * @param string $output
184
     */
185
    public function concatOutput(GdaemonTask $gdaemonTask, string $output)
186
    {
187
        if (empty($output)) {
188
            return;
189
        }
190
191
        $qoutedOutput = DB::connection()->getPdo()->quote($output);
192
193
        $dbDriver = DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);
194
195
        if ($dbDriver == 'mysql') {
196
            $gdaemonTask->update(['output' => DB::raw("CONCAT(IFNULL(output,''), {$qoutedOutput})")]);
197
        } else if ($dbDriver == 'sqlite' || $dbDriver == 'pgsql') {
198
            $gdaemonTask->update(['output' => DB::raw("COALESCE(output, '') || {$qoutedOutput}")]);
199
        } else {
200
            $gdaemonTask->update(['output' => $gdaemonTask->output . $output]);
201
        }
202
    }
203
204
    /**
205
     * @param GdaemonTask $gdaemonTask
206
     *
207
     * @throws GdaemonTaskRepositoryException
208
     */
209
    public function cancel(GdaemonTask $gdaemonTask)
210
    {
211
        if ($gdaemonTask->status != GdaemonTask::STATUS_WAITING) {
212
            throw new GdaemonTaskRepositoryException(__('gdaemon_tasks.cancel_fail_cannot_be_canceled'));
0 ignored issues
show
Bug introduced by
It seems like __('gdaemon_tasks.cancel...il_cannot_be_canceled') can also be of type array; however, parameter $message of Gameap\Exceptions\Reposi...xception::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

212
            throw new GdaemonTaskRepositoryException(/** @scrutinizer ignore-type */ __('gdaemon_tasks.cancel_fail_cannot_be_canceled'));
Loading history...
213
        }
214
215
        $gdaemonTask->status = GdaemonTask::STATUS_CANCELED;
216
        $gdaemonTask->save();
217
    }
218
219
    /**
220
     * @param Server $server
221
     * @param string|array $task task name
222
     * @param string $failMsg Failure message
223
     *
224
     * @throws RecordExistExceptions
225
     */
226
    private function workingTaskNotExistOrFail(Server $server, $task, $failMsg = 'Task is already exists')
227
    {
228
        if (is_array($task)) {
229
            $taskQuery = GdaemonTask::whereIn(['task', $task])->where([['server_id', '=', $server->id]]);
230
        } else {
231
            $taskQuery = GdaemonTask::where([
232
                ['task', '=', $task],
233
                ['server_id', '=', $server->id],
234
                ['dedicated_server_id', '=', $server->ds_id]
235
            ]);
236
        }
237
238
        $taskExist = $taskQuery->whereIn('status', [
239
            GdaemonTask::STATUS_WAITING, 
240
            GdaemonTask::STATUS_WORKING
241
        ])->exists();
242
243
        if ($taskExist) {
244
            throw new RecordExistExceptions($failMsg);
245
        }
246
    }
247
248
    /**
249
     * @param Server $server
250
     *
251
     * @throws InvalidServerStartCommandException
252
     * @throws EmptyServerStartCommandException
253
     */
254
    private function serverCommandCorrectOrFail(Server $server)
255
    {
256
        if (empty($server->start_command)) {
257
            throw new EmptyServerStartCommandException(__('gdaemon_tasks.empty_server_start_command'));
0 ignored issues
show
Bug introduced by
It seems like __('gdaemon_tasks.empty_server_start_command') can also be of type array; however, parameter $message of Gameap\Exceptions\Reposi...xception::__construct() does only seem to accept string, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

257
            throw new EmptyServerStartCommandException(/** @scrutinizer ignore-type */ __('gdaemon_tasks.empty_server_start_command'));
Loading history...
258
        }
259
    }
260
}
261