Passed
Push — master ( 5cca9a...5e004b )
by Nikita
10:18 queued 03:43
created

ServerRepository::find()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
c 0
b 0
f 0
dl 0
loc 3
rs 10
cc 1
nc 1
nop 1
1
<?php
2
3
namespace Gameap\Repositories;
4
5
use Gameap\Helpers\PermissionHelper;
6
use Gameap\Http\Requests\ServerVarsRequest;
7
use Gameap\Models\Game;
8
use Gameap\Models\Server;
9
use Illuminate\Contracts\Auth\Factory as AuthFactory;
10
use Illuminate\Support\Facades\Auth;
11
use Illuminate\Support\Facades\DB;
12
use Mavinoo\Batch\Batch;
13
use Spatie\QueryBuilder\QueryBuilder;
14
15
class ServerRepository
16
{
17
    public const DEFAULT_RCON_PASSWORD_LENGTH = 10;
18
19
    public const DEFAULT_PER_PAGE = 20;
20
21
    /** @var Server */
22
    protected $model;
23
24
    /** @var GdaemonTaskRepository */
25
    protected $gdaemonTaskRepository;
26
27
    /** @var Batch */
28
    protected $mavinooBatch;
29
30
    /** @var AuthFactory */
31
    protected $authFactory;
32
33
    /**
34
     * ServerRepository constructor.
35
     * @param Server $server
36
     * @param GdaemonTaskRepository $gdaemonTaskRepository
37
     */
38
    public function __construct(
39
        Server $server,
40
        GdaemonTaskRepository $gdaemonTaskRepository,
41
        Batch $mavinooBatch,
42
        AuthFactory $auth
43
    ) {
44
        $this->model                 = $server;
45
        $this->gdaemonTaskRepository = $gdaemonTaskRepository;
46
        $this->mavinooBatch          = $mavinooBatch;
47
        $this->authFactory           = $auth;
48
    }
49
50
    public function find(int $id): Server
51
    {
52
        return $this->model->findOrFail($id);
53
    }
54
55
    /**
56
     * @param int $perPage
57
     * @return mixed
58
     */
59
    public function getAll($perPage = self::DEFAULT_PER_PAGE)
60
    {
61
        $servers = Server::orderBy('id')->with('game')->paginate($perPage);
62
63
        return $servers;
64
    }
65
66
    /**
67
     * Get Servers list for Dedicated server
68
     *
69
     * @param int $dedicatedServerId
70
     * @return mixed
71
     */
72
    public function getServersListForDedicatedServer(int $dedicatedServerId)
73
    {
74
        return $this->model->select('*')
75
            ->where('ds_id', '=', $dedicatedServerId)
76
            ->get();
77
    }
78
79
80
    /**
81
     * Get Servers id list for Dedicated server
82
     *
83
     * @param int $dedicatedServerId
84
     * @return mixed
85
     */
86
    public function getServerIdsForDedicatedServer(int $dedicatedServerId)
87
    {
88
        return $this->model->select('id')
89
            ->where('ds_id', '=', $dedicatedServerId)
90
            ->get();
91
    }
92
93
    /**
94
     * @return mixed
95
     */
96
    public function getServersForAuth()
97
    {
98
        $currentUser = $this->authFactory->guard()->user();
99
100
        if ($currentUser->can(PermissionHelper::ADMIN_PERMISSIONS)) {
101
            return $this->getAll();
102
        }
103
104
        return $currentUser->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...
105
    }
106
107
    public function getServersForUser(int $userId)
108
    {
109
        $qb = QueryBuilder::for(Server::class)
110
            ->allowedFilters('ds_id')
111
            ->with('game:code,name,engine,engine_version')
112
            ->whereRaw('id IN(SELECT server_id FROM server_user su WHERE su.user_id = ?)', [$userId]);
113
114
        return $qb->get()->append(['online']);
115
    }
116
117
    public function getAllServers()
118
    {
119
        $qb = QueryBuilder::for(Server::class)
120
            ->allowedFilters('ds_id')
121
            ->allowedAppends(['full_path'])
122
            ->with('game:code,name,engine,engine_version');
123
124
        return $qb->get()->append(['online']);
125
    }
126
127
    /**
128
     * @param array $engines
129
     * @param int|array $dedicatedServers
130
     * @return \Illuminate\Support\Collection
131
     */
132
    public function getServersForEngine(array $engines, $dedicatedServers = [], $excludeIds = [])
133
    {
134
        if (is_int($dedicatedServers)) {
135
            $dedicatedServers = [$dedicatedServers];
136
        }
137
138
        $serversTable = $this->model->getTable();
139
        $gamesTable   = (new Game())->getTable();
140
141
        $query = DB::table($serversTable)
142
            ->selectRaw("{$serversTable}.*, {$gamesTable}.name as game_name")
143
            ->whereIn('game_id', function ($query) use ($engines, $serversTable, $gamesTable): void {
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...
144
                $query->select('code')
145
                    ->from($gamesTable)
146
                    ->whereIn('engine', $engines);
147
            })
148
            ->where('deleted_at', null)
149
            ->join($gamesTable, "{$serversTable}.game_id", '=', "{$gamesTable}.code");
150
151
        if (!empty($dedicatedServers)) {
152
            $query->whereIn('ds_id', $dedicatedServers);
153
        }
154
155
        if (!empty($excludeIds)) {
156
            $query->whereNotIn('id', $excludeIds);
157
        }
158
159
        return $query->get();
160
    }
161
162
    /**
163
     * @param $query
164
     * @return mixed
165
     */
166
    public function search($query)
167
    {
168
        return $this->model->select(['id', 'name', 'server_ip', 'server_port', 'game_id', 'game_mod_id'])
169
            ->with(['game' => function ($query): void {
170
                $query->select('code', 'name');
171
            }])
172
            ->where('name', 'LIKE', '%' . $query . '%')
173
            ->get();
174
    }
175
176
    /**
177
     * @param Server $server
178
     * @param array  $attributes
179
     */
180
    public function update(Server $server, array $attributes): void
181
    {
182
        $attributes['enabled']   = (bool)array_key_exists('enabled', $attributes);
183
        $attributes['blocked']   = (bool)array_key_exists('blocked', $attributes);
184
        $attributes['installed'] = (bool)array_key_exists('installed', $attributes);
185
186
        if (isset($attributes['ds_id'])) {
187
            $server->ds_id = $attributes['ds_id'];
188
        }
189
190
        $server->update($attributes);
191
    }
192
193
    /**
194
     * @param Server            $server
195
     * @param ServerVarsRequest $request
196
     */
197
    public function updateVars(Server $server, ServerVarsRequest $request): void
198
    {
199
        $only = [];
200
        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...
201
            if (!empty($var['admin_var']) && Auth::user()->cannot(PermissionHelper::ADMIN_PERMISSIONS)) {
202
                continue;
203
            }
204
205
            $only[] = 'vars.' . $var['var'];
206
        }
207
208
        $server->update($request->only($only));
209
    }
210
211
    public function updateSettings(Server $server, ServerVarsRequest $request): void
212
    {
213
        $autostartSetting = $server->getSetting($server::AUTOSTART_SETTING_KEY);
214
        $autostartSetting->value = $request->autostart();
215
        $autostartSetting->save();
216
217
        $autostartCurrentSetting = $server->getSetting($server::AUTOSTART_CURRENT_SETTING_KEY);
218
        $autostartCurrentSetting->value = $request->autostart();
219
        $autostartCurrentSetting->save();
220
221
        $updateBeforeStartSetting = $server->getSetting($server::UPDATE_BEFORE_START_SETTING_KEY);
222
        $updateBeforeStartSetting->value = $request->updateBeforeStart();
223
        $updateBeforeStartSetting->save();
224
    }
225
226
    public function save(Server $server): void
227
    {
228
        $server->save();
229
    }
230
231
    public function saveBatch(array $serverValues): void
232
    {
233
        $this->mavinooBatch->update(new Server(), $serverValues, 'id');
234
    }
235
}
236