Passed
Push — develop ( e53634...2c9913 )
by Nikita
14:18
created

GdaemonTaskRepository::addCmd()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 6
c 0
b 0
f 0
dl 0
loc 8
ccs 0
cts 1
cp 0
rs 10
cc 1
nc 1
nop 3
crap 2
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($server);
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 $cmd
142
     * @param $dedicatedServerId
143
     * @param int $runAftId
144
     * @return mixed
145
     */
146
    public function addCmd($cmd, $dedicatedServerId, int $runAftId = 0)
147
    {
148
        return GdaemonTask::create([
149
            'run_aft_id' => $runAftId,
150
            'dedicated_server_id' => $dedicatedServerId,
151
            'task' => GdaemonTask::TASK_CMD_EXEC,
152
            'cmd' => $cmd,
153
        ])->id;
154
    }
155
156
    /**
157
     * @param int $serverId
158
     * @param string|array $task
159
     * @param string|array $status
160
     *
161
     * @return mixed
162
     */
163
    public function getTasks(int $serverId, $task, $status)
164
    {
165
        if (is_array($task)) {
166
            $taskQuery = GdaemonTask::whereIn(['task', $task])->where([['server_id', '=', $serverId]]);
167
        } else {
168
            $taskQuery = GdaemonTask::where([
169
                ['task', '=', $task],
170
                ['server_id', '=', $serverId]
171
            ]);
172
        }
173
174
        $taskQuery = is_array($status)
175
            ? $taskQuery->whereIn('status', $status)
176
            : $taskQuery->where('status', '=', $status);
177
178
        return $taskQuery->get();
179
    }
180
181
    /**
182
     * Get working or waiting task id. Return 0 if task is not one
183
     *
184
     * @param int $serverId
185
     * @param $task
186
     * @return int
187
     */
188
    public function getOneWorkingTaskId(int $serverId, $task)
189
    {
190
        $tasks = $this->getTasks($serverId, $task, [GdaemonTask::STATUS_WAITING, GdaemonTask::STATUS_WORKING]);
191
192
        return (count($tasks) === 1)
193
            ? $tasks->first()->id
194
            : 0;
195
    }
196
197
    /**
198
     * @param GdaemonTask $gdaemonTask
199
     * @param string $output
200
     */
201
    public function concatOutput(GdaemonTask $gdaemonTask, string $output)
202
    {
203
        if (empty($output)) {
204
            return;
205
        }
206
207
        $qoutedOutput = DB::connection()->getPdo()->quote($output);
208
209
        $dbDriver = DB::connection()->getPDO()->getAttribute(PDO::ATTR_DRIVER_NAME);
210
211
        if ($dbDriver == 'mysql') {
212
            $gdaemonTask->update(['output' => DB::raw("CONCAT(IFNULL(output,''), {$qoutedOutput})")]);
213
        } else if ($dbDriver == 'sqlite' || $dbDriver == 'pgsql') {
214
            $gdaemonTask->update(['output' => DB::raw("COALESCE(output, '') || {$qoutedOutput}")]);
215
        } else {
216
            $gdaemonTask->update(['output' => $gdaemonTask->output . $output]);
217
        }
218
    }
219
220
    /**
221
     * @param GdaemonTask $gdaemonTask
222
     *
223
     * @throws GdaemonTaskRepositoryException
224
     */
225
    public function cancel(GdaemonTask $gdaemonTask)
226
    {
227
        if ($gdaemonTask->status != GdaemonTask::STATUS_WAITING) {
228
            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

228
            throw new GdaemonTaskRepositoryException(/** @scrutinizer ignore-type */ __('gdaemon_tasks.cancel_fail_cannot_be_canceled'));
Loading history...
229
        }
230
231
        $gdaemonTask->status = GdaemonTask::STATUS_CANCELED;
232
        $gdaemonTask->save();
233
    }
234
235
    /**
236
     * @param Server $server
237
     * @param string|array $task task name
238
     * @param string $failMsg Failure message
239
     *
240
     * @throws RecordExistExceptions
241
     */
242
    private function workingTaskNotExistOrFail(Server $server, $task, $failMsg = 'Task is already exists')
243
    {
244
        if (is_array($task)) {
245
            $taskQuery = GdaemonTask::whereIn(['task', $task])->where([['server_id', '=', $server->id]]);
246
        } else {
247
            $taskQuery = GdaemonTask::where([
248
                ['task', '=', $task],
249
                ['server_id', '=', $server->id],
250
                ['dedicated_server_id', '=', $server->ds_id]
251
            ]);
252
        }
253
254
        $taskExist = $taskQuery->whereIn('status', [
255
            GdaemonTask::STATUS_WAITING, 
256
            GdaemonTask::STATUS_WORKING
257
        ])->exists();
258
259
        if ($taskExist) {
260
            throw new RecordExistExceptions($failMsg);
261
        }
262
    }
263
264
    /**
265
     * @param Server $server
266
     *
267
     * @throws InvalidServerStartCommandException
268
     * @throws EmptyServerStartCommandException
269
     */
270
    private function serverCommandCorrectOrFail(Server $server)
271
    {
272
        if (empty($server->start_command)) {
273
            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

273
            throw new EmptyServerStartCommandException(/** @scrutinizer ignore-type */ __('gdaemon_tasks.empty_server_start_command'));
Loading history...
274
        }
275
    }
276
}
277