-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathGameQuery.php
More file actions
83 lines (67 loc) · 2.25 KB
/
GameQuery.php
File metadata and controls
83 lines (67 loc) · 2.25 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
<?php
namespace Boy132\PlayerCounter\Models;
use App\Models\Allocation;
use App\Models\Egg;
use Boy132\PlayerCounter\Extensions\Query\QueryTypeService;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
/**
* @property int $id
* @property string $query_type
* @property ?int $query_port_offset
* @property Collection|Egg[] $eggs
* @property int|null $eggs_count
*/
class GameQuery extends Model
{
protected $fillable = [
'query_type',
'query_port_offset',
];
protected $attributes = [
'query_port_offset' => null,
];
public function eggs(): BelongsToMany
{
return $this->belongsToMany(Egg::class);
}
/** @return ?array{hostname: string, map: string, current_players: int, max_players: int, players: ?array<array{id: string, name: string}>} */
public function runQuery(Allocation $allocation): ?array
{
if (!static::canRunQuery($allocation)) {
return null;
}
$ip = static::resolveIp($allocation);
$ip = is_ipv6($ip) ? '[' . $ip . ']' : $ip;
/** @var QueryTypeService $service */
$service = app(QueryTypeService::class);
$schema = $service->get($this->query_type);
if (!$schema) {
return null;
}
// Allow schema to provide its own port resolution (e.g. from server variables)
if (method_exists($schema, 'resolvePort')) {
$resolvedPort = $schema->resolvePort($allocation);
if ($resolvedPort !== null) {
return $schema->process($ip, $resolvedPort);
}
}
return $schema->process($ip, $allocation->port + ($this->query_port_offset ?? 0));
}
public static function canRunQuery(?Allocation $allocation): bool
{
if (!$allocation) {
return false;
}
$ip = static::resolveIp($allocation);
return !in_array($ip, ['0.0.0.0', '::']);
}
protected static function resolveIp(Allocation $allocation): string
{
if (config('player-counter.use_alias') && !empty($allocation->ip_alias)) {
return $allocation->ip_alias;
}
return $allocation->ip;
}
}