1: <?php declare(strict_types=1);
2:
3: /**
4: * Clansuite Server Query
5: *
6: * SPDX-FileCopyrightText: 2003-2025 Jens A. Koch
7: * SPDX-License-Identifier: MIT
8: *
9: * For the full copyright and license information, please view
10: * the LICENSE file that was distributed with this source code.
11: */
12:
13: namespace Clansuite\Capture\CLI;
14:
15: use const JSON_PRETTY_PRINT;
16: use function is_array;
17: use function is_string;
18: use function json_encode;
19: use function strtolower;
20: use Clansuite\Capture\Storage\FixtureStorageInterface;
21:
22: /**
23: * Lists captured game server data stored in fixtures, with optional protocol filtering.
24: */
25: class ListCapturesCommand
26: {
27: /**
28: * Initializes the command with a fixture storage interface.
29: *
30: * @param FixtureStorageInterface $storage Storage interface for accessing captured data
31: */
32: public function __construct(private readonly FixtureStorageInterface $storage)
33: {
34: }
35:
36: /**
37: * Executes the list captures command, outputting stored capture data in JSON format.
38: *
39: * @param array<string> $argv Command line arguments, optionally including a protocol filter
40: *
41: * @return int Exit code (0 for success)
42: */
43: public function run(array $argv): int
44: {
45: // Determine protocol filter robustly:
46: // - If called as `capture list ddnet` argv will be [script, 'list', 'ddnet']
47: // - If called directly as `list ddnet` argv may be [script, 'ddnet']
48: $protocolFilter = null;
49:
50: if (isset($argv[1]) && strtolower($argv[1]) === 'list') {
51: $protocolFilter = isset($argv[2]) && $argv[2] !== '' ? strtolower($argv[2]) : null;
52: } else {
53: $protocolFilter = isset($argv[1]) && $argv[1] !== '' ? strtolower($argv[1]) : null;
54: }
55:
56: $captures = $this->storage->listAll();
57:
58: foreach ($captures as $capture) {
59: if (!is_array($capture)) {
60: continue;
61: }
62:
63: if ($protocolFilter !== null) {
64: $metadata = $capture['metadata'] ?? [];
65:
66: if (!is_array($metadata)) {
67: continue;
68: }
69: $proto = $metadata['protocol'] ?? '';
70:
71: if (!is_string($proto)) {
72: $proto = '';
73: }
74: $metaProto = strtolower($proto);
75:
76: if ($metaProto !== $protocolFilter) {
77: continue;
78: }
79: }
80:
81: print json_encode($capture, JSON_PRETTY_PRINT) . "\n";
82: }
83:
84: return 0;
85: }
86: }
87: