Test Failed
Push — develop ( bbcebd...48e203 )
by Nikita
06:27
created

ServerRepository::updateAutostart()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 19
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 2

Importance

Changes 0
Metric Value
eloc 12
c 0
b 0
f 0
dl 0
loc 19
ccs 0
cts 13
cp 0
rs 9.8666
cc 1
nc 1
nop 2
crap 2
1
<?php
2
3
namespace Gameap\Repositories;
4
5
use Gameap\Models\DedicatedServer;
6
use Gameap\Models\Game;
7
use Gameap\Models\Server;
8
use Gameap\Models\GameMod;
9
use Gameap\Models\ServerSetting;
10
use Illuminate\Support\Str;
11
use Gameap\Http\Requests\ServerVarsRequest;
12
use Illuminate\Support\Facades\Auth;
13
use Illuminate\Support\Facades\DB;
14
15
class ServerRepository
16
{
17
    const DEFAULT_RCON_PASSWORD_LENGTH = 10;
18
19
    const DEFAULT_PER_PAGE = 20;
20
21
    /**
22
     * @var Server
23
     */
24
    protected $model;
25
26
    /**
27
     * @var GdaemonTaskRepository
28
     */
29
    protected $gdaemonTaskRepository;
30
31
    /**
32
     * ServerRepository constructor.
33
     * @param Server $server
34
     * @param GdaemonTaskRepository $gdaemonTaskRepository
35
     */
36 30
    public function __construct(Server $server, GdaemonTaskRepository $gdaemonTaskRepository)
37
    {
38 30
        $this->model = $server;
39 30
        $this->gdaemonTaskRepository = $gdaemonTaskRepository;
40 30
    }
41
42
    /**
43
     * @param int $perPage
44
     * @return mixed
45
     */
46 3
    public function getAll($perPage = self::DEFAULT_PER_PAGE)
47
    {
48 3
        $servers = Server::orderBy('id')->with('game')->paginate($perPage);
49
50 3
        return $servers;
51
    }
52
53
    /**
54
     * Store server
55
     *
56
     * @param array $attributes
57
     * @throws \Gameap\Exceptions\Repositories\RecordExistExceptions
58
     */
59
    public function store(array $attributes)
60
    {
61
        $attributes['uuid'] = Str::orderedUuid()->toString();
62
        $attributes['uuid_short'] = Str::substr($attributes['uuid'], 0, 8);
63
        
64
        $attributes['enabled'] = true;
65
        $attributes['blocked'] = false;
66
67
        $addInstallTask = false;
68
        if (isset($attributes['install'])) {
69
            $attributes['installed'] = ! $attributes['install'];
70
            $addInstallTask = true;
71
72
            unset($attributes['install']);
73
        }
74
75
        if (empty($attributes['rcon'])) {
76
             $attributes['rcon'] = Str::random(self::DEFAULT_RCON_PASSWORD_LENGTH);
77
        }
78
79
        $dedicatedServer = DedicatedServer::findOrFail($attributes['ds_id']);
80
81
        if (empty($attributes['start_command'])) {
82
            $gameMod = GameMod::select('default_start_cmd_linux', 'default_start_cmd_windows')->where('id', '=', $attributes['game_mod_id'])->firstOrFail();
83
84
            $attributes['start_command'] =
85
                $dedicatedServer->isLinux()
86
                    ? $gameMod->default_start_cmd_linux
87
                    : $gameMod->default_start_cmd_windows;
88
        }
89
90
        if (empty($attributes['dir'])) {
91
            $attributes['dir'] = 'servers/' . $attributes['uuid'];
92
        }
93
94
        // Fix path. Remove absolute dedicated server path
95
        $attributes['dir'] = $this->fixPath($attributes['dir'], $dedicatedServer->work_path);
96
97
        $server = Server::create($attributes);
98
99
        if ($addInstallTask) {
100
            $this->gdaemonTaskRepository->addServerUpdate($server);
101
        }
102
    }
103
104
    /**
105
     * Get Servers list for Dedicated server
106
     *
107
     * @param int $dedicatedServerId
108
     * @return mixed
109
     */
110
    public function getServersListForDedicatedServer(int $dedicatedServerId)
111
    {
112
        return $this->model->select('*')
113
            ->where('ds_id', '=', $dedicatedServerId)
114
            ->get();
115
    }
116
117
118
    /**
119
     * Get Servers id list for Dedicated server
120
     *
121
     * @param int $dedicatedServerId
122
     * @return mixed
123
     */
124
    public function getServerIdsForDedicatedServer(int $dedicatedServerId)
125
    {
126
        return $this->model->select('id')
127
            ->where('ds_id', '=', $dedicatedServerId)
128
            ->get();
129
    }
130
131
    /**
132
     * @return mixed
133
     */
134
    public function getServersForAuth()
135
    {
136
        if (Auth::user()->can('admin roles & permissions')) {
137
            return $this->getAll();
138
        } else {
139
            return Auth::user()->servers->paginate(self::DEFAULT_PER_PAGE);
0 ignored issues
show
Bug introduced by
Accessing servers on the interface Illuminate\Contracts\Auth\Authenticatable suggest that you code against a concrete implementation. How about adding an instanceof check?
Loading history...
140
        }
141
    }
142
143
    /**
144
     * @param array $engines
145
     * @param int|array $dedicatedServers
146
     * @return \Illuminate\Support\Collection
147
     */
148
    public function getServersForEngine(array $engines, $dedicatedServers = [], $excludeIds = [])
149
    {
150
        if (is_int($dedicatedServers)) {
151
            $dedicatedServers = [$dedicatedServers];
152
        }
153
154
        $serversTable = $this->model->getTable();
155
        $gamesTable = (new Game)->getTable();
156
157
        $query = DB::table($serversTable)
158
            ->selectRaw("{$serversTable}.*, {$gamesTable}.name as game_name")
159
            ->whereIn('game_id', function($query) use ($engines, $serversTable, $gamesTable) {
0 ignored issues
show
Unused Code introduced by
The import $serversTable is not used and could be removed.

This check looks for imports that have been defined, but are not used in the scope.

Loading history...
160
                $query->select('code')
161
                    ->from($gamesTable)
162
                    ->whereIn('engine', $engines);
163
            })
164
            ->where('deleted_at', null)
165
            ->join($gamesTable, "{$serversTable}.game_id", '=', "{$gamesTable}.code");
166
167
        if (!empty($dedicatedServers)) {
168
            $query->whereIn('ds_id', $dedicatedServers);
169
        }
170
171
        if (!empty($excludeIds)) {
172
            $query->whereNotIn('id', $excludeIds);
173
        }
174
175
        return $query->get();
176
    }
177
178
    /**
179
     * @param $query
180
     * @return mixed
181
     */
182
    public function search($query)
183
    {
184
        return $this->model->select(['id', 'name', 'server_ip', 'server_port', 'game_id', 'game_mod_id'])
185
            ->with(['game' => function($query) {
186
                $query->select('code','name');
187
            }])
188
            ->where('name', 'LIKE', '%' . $query . '%')
189
            ->get();
190
    }
191
192
    /**
193
     * @param Server $server
194
     * @param array  $attributes
195
     */
196
    public function update(Server $server, array $attributes)
197
    {
198
        $attributes['enabled'] = (bool)array_key_exists('enabled', $attributes);
199
        $attributes['blocked'] = (bool)array_key_exists('blocked', $attributes);
200
        $attributes['installed'] = (bool)array_key_exists('installed', $attributes);
201
202
        if (isset($attributes['ds_id'])) {
203
            $server->ds_id = $attributes['ds_id'];
204
        }
205
206
        // Fix path. Remove absolute dedicated server path
207
        $attributes['dir'] = $this->fixPath($attributes['dir'], $server->dedicatedServer->work_path);
208
209
        $server->update($attributes);
210
    }
211
212
    /**
213
     * @param Server            $server
214
     * @param ServerVarsRequest $request
215
     */
216
    public function updateVars(Server $server, ServerVarsRequest $request)
217
    {
218
        $only = [];
219
        foreach ($server->gameMod->vars as $var) {
0 ignored issues
show
Bug introduced by
The expression $server->gameMod->vars of type string is not traversable.
Loading history...
220
            if (!empty($var['admin_var']) && Auth::user()->cannot('admin roles & permissions')) {
221
                continue;
222
            }
223
224
            $only[] = 'vars.' . $var['var'];
225
        }
226
227
        $server->update($request->only($only));
228
    }
229
230
    /**
231
     * @param Server $server
232
     * @param bool $autostart
233
     */
234
    public function updateAutostart(Server $server, bool $autostart)
235
    {
236
        $autostartSetting = $server->settings->where('name', 'autostart')->first()
237
            ?? new ServerSetting([
238
                'server_id' => $server->id,
239
                'name'      => 'autostart',
240
            ]);
241
242
        $autostartSetting->value = $autostart;
243
        $autostartSetting->save();
244
245
        $autostartCurrentSetting = $server->settings->where('name', 'autostart_current')->first()
246
            ?? new ServerSetting([
247
                'server_id' => $server->id,
248
                'name'      => 'autostart_current',
249
            ]);
250
251
        $autostartCurrentSetting->value = $autostart;
252
        $autostartCurrentSetting->save();
253
    }
254
255
    /**
256
     * @param $path
257
     * @param $dsWorkPath
258
     * @return string
259
     */
260
    private function fixPath($path, $dsWorkPath)
261
    {
262
        if (substr($path, 0, strlen($dsWorkPath)) == $dsWorkPath) {
263
            $path = substr($path, strlen($dsWorkPath));
264
        }
265
266
        $path = ltrim($path, '/\\');
267
268
        return $path;
269
    }
270
}