forked from sofascore/purgatory-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDebugCommand.php
More file actions
371 lines (295 loc) · 13.2 KB
/
DebugCommand.php
File metadata and controls
371 lines (295 loc) · 13.2 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
declare(strict_types=1);
namespace Sofascore\PurgatoryBundle\Command;
use Doctrine\Persistence\ManagerRegistry;
use Doctrine\Persistence\Mapping\ClassMetadata;
use Sofascore\PurgatoryBundle\Attribute\RouteParamValue\CompoundValues;
use Sofascore\PurgatoryBundle\Cache\Configuration\Configuration;
use Sofascore\PurgatoryBundle\Cache\Configuration\ConfigurationLoaderInterface;
use Sofascore\PurgatoryBundle\Listener\Enum\Action;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'purgatory:debug',
description: 'Display purge subscription information for an entity or multiple entities',
)]
final class DebugCommand extends Command
{
private ?Configuration $configuration = null;
public function __construct(
private readonly ConfigurationLoaderInterface $configurationLoader,
private readonly ManagerRegistry $managerRegistry,
) {
parent::__construct();
}
protected function configure(): void
{
$this->addArgument('target', InputArgument::OPTIONAL, 'The entity name or a substring of its name', null, array_keys($this->getEntityCollection()));
$this->addOption('subscription', null, InputOption::VALUE_REQUIRED, 'The entity FQCN, optionally followed by a property path separated by "::"');
$this->addOption('with-properties', null, InputOption::VALUE_NONE, 'Display all property subscriptions for an entity');
$this->addOption('route', null, InputOption::VALUE_REQUIRED, 'Display subscriptions for specific route');
$this->addOption('all', null, InputOption::VALUE_NONE, 'Display all subscriptions');
$this->setHelp(<<<'EOF'
To display purge subscriptions for a specific entity, use the <info>--subscription</info> option with its' FQCN:
<info>php %command.full_name% --subscription 'App\Entity\Product'</info>
To display all property subscriptions for an entity, use the <info>--with-properties</info> option:
<info>php %command.full_name% --subscription 'App\Entity\Product' --with-properties</info>
To display purge subscriptions for a specific entity property, add "<info>::</info>" followed by the property name:
<info>php %command.full_name% --subscription 'App\Entity\Product::name'</info>
To display purge subscriptions for a specific route, use the <info>--route</info> option:
<info>php %command.full_name% --route my_route_name</info>
To display all configured purge subscriptions, use the <info>--all</info> option:
<info>php %command.full_name% --all</info>
To enter interactive mode, run the command without arguments:
<info>php %command.full_name%</info>
To filter and display subscriptions by a keyword, pass the keyword as the first argument:
<info>php %command.full_name% keyword</info>
EOF
);
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
if (!($configuration = $this->configuration())->count()) {
$io->note('There are no registered purge subscriptions.');
return self::SUCCESS;
}
if ($input->getOption('all')) {
$this->display($io, $configuration->toArray());
return self::SUCCESS;
}
/** @var non-empty-string|null $subscription */
$subscription = $input->getOption('subscription');
if (null !== $subscription) {
/** @var bool $withProperties */
$withProperties = $input->getOption('with-properties');
if ($withProperties && false !== $propertyPath = strstr($subscription, '::')) {
$io->error(\sprintf('The "--with-properties" option requires an entity FQCN without the property path (%s).', $propertyPath));
return self::FAILURE;
}
if ([] === $filteredConfiguration = $this->findSubscriptions($subscription, $withProperties)) {
$io->warning(\sprintf('No purge subscriptions found matching "%s".', $subscription));
return self::FAILURE;
}
$this->display($io, $filteredConfiguration);
return self::SUCCESS;
}
/** @var ?string $routeName */
$routeName = $input->getOption('route');
if (null !== $routeName) {
if ([] === $filteredConfiguration = $this->findSubscriptionsForRoute($routeName)) {
$io->warning(\sprintf('No purge subscriptions found for route "%s".', $routeName));
return self::FAILURE;
}
$this->display($io, $filteredConfiguration);
return self::SUCCESS;
}
/** @var non-empty-string|null $target */
$target = $input->getArgument('target');
$entities = $this->getEntityCollection();
if (null !== $target) {
$entities = array_filter(
$entities,
static fn (string $name): bool => str_contains(strtolower($name), strtolower($target)),
\ARRAY_FILTER_USE_KEY,
);
if ([] === $entities) {
$io->warning(\sprintf('No purge subscriptions found matching "%s".', $target));
return self::FAILURE;
}
}
if (1 !== \count($entities) || null === $target || !isset($entities[$target])) {
$entityChoices = array_keys($entities);
sort($entityChoices, \SORT_STRING | \SORT_FLAG_CASE);
/** @var string $target */
$target = $io->choice('Select one of the available entities', $entityChoices);
}
/** @var class-string $entity */
$entity = \count($entities[$target]) > 1
? $io->choice('Select on of the available entities', $entities[$target])
: $entities[$target][0];
$metadata = $this->managerRegistry->getManagerForClass($entity)?->getClassMetadata($entity);
if (null === $metadata) {
$io->error(\sprintf('Could not retrieve metadata for the entity "%s".', $entity));
return self::FAILURE;
}
$fields = [...$metadata->getFieldNames(), ...$this->getAssociationFields($metadata)];
sort($fields, \SORT_STRING | \SORT_FLAG_CASE);
$fields = ['*', ...$fields];
/** @var string $field */
$field = $io->choice('Select one of the available fields', $fields);
$withProperties = '*' === $field;
$filteredConfiguration = $this->findSubscriptions(
subscription: $withProperties ? $entity : $entity.'::'.$field,
withProperties: $withProperties,
);
if ([] === $filteredConfiguration) {
$io->warning(\sprintf('No purge subscriptions found matching "%s".', $entity.'::'.$field));
return self::FAILURE;
}
$this->display($io, $filteredConfiguration);
$io->info(\sprintf(
'You can rerun the command with the selected options using:%sphp bin/console purgatory:debug --subscription %s',
\PHP_EOL,
$withProperties ? \sprintf("'%s' --with-properties", $entity) : \sprintf("'%s::%s'", $entity, $field),
));
return self::SUCCESS;
}
/**
* @param non-empty-string $subscription
*
* @return array<non-empty-string, list<array{
* routeName: string,
* routeParams?: array<string, array{type: string, values: list<mixed>, optional?: true}>,
* if?: string,
* actions?: non-empty-list<Action>,
* }>>
*/
private function findSubscriptions(string $subscription, bool $withProperties): array
{
$configuration = $this->configuration()->toArray();
if (!$withProperties) {
return isset($configuration[$subscription]) ? [$subscription => $configuration[$subscription]] : [];
}
return array_filter(
$configuration,
static fn (string $key): bool => str_starts_with($key, $subscription),
\ARRAY_FILTER_USE_KEY,
);
}
/**
* @return array<non-empty-string, list<array{
* routeName: string,
* routeParams?: array<string, array{type: string, values: list<mixed>, optional?: true}>,
* if?: string,
* actions?: non-empty-list<Action>,
* }>>
*/
private function findSubscriptionsForRoute(string $routeName): array
{
return array_filter(
array_map(
static fn (array $subscriptions): array => array_values(array_filter(
$subscriptions,
static fn (array $subscription): bool => $subscription['routeName'] === $routeName,
)),
$this->configuration()->toArray(),
),
);
}
/**
* @param array<non-empty-string, list<array{
* routeName: string,
* routeParams?: array<string, array{type: string, values: list<mixed>, optional?: true}>,
* if?: string,
* actions?: non-empty-list<Action>,
* }>> $configuration
*/
private function display(SymfonyStyle $io, array $configuration): void
{
$io->title('Purge subscriptions');
foreach ($configuration as $key => $subscriptions) {
$entity = explode('::', $key);
foreach ($subscriptions as $subscription) {
$io->table(
['Option', 'Value'],
[
['Entity', $entity[0]],
['Property', $entity[1] ?? 'ANY'],
['Route Name', $subscription['routeName']],
['Route Params', isset($subscription['routeParams']) ? $this->formatRouteParams($subscription['routeParams']) : 'NONE'],
['Condition', $subscription['if'] ?? 'NONE'],
['Actions', isset($subscription['actions']) ? $this->formatActions($subscription['actions']) : 'ANY'],
],
);
}
}
}
/**
* @param array<string, array{type: string, values: list<mixed>, optional?: true}> $routeParams
*/
private function formatRouteParams(array $routeParams): string
{
$values = [];
foreach ($routeParams as $param => $value) {
$values[] = \sprintf('%s: %s', $param, $this->formatRouteParamValue($value['type'], $value['values']));
}
return implode(\PHP_EOL, $values);
}
/**
* @param list<mixed> $values
*/
private function formatRouteParamValue(string $type, array $values): string
{
if (CompoundValues::type() === $type) {
$newValues = [];
/** @var array{type: string, values: list<mixed>} $value */
foreach ($values as $value) {
$newValues[] = $this->formatRouteParamValue($value['type'], $value['values']);
}
$values = $newValues;
} else {
$values = array_map(static fn (mixed $val): string => json_encode($val, flags: \JSON_THROW_ON_ERROR), $values);
}
return \sprintf('%s(%s)', ucfirst($type), implode(', ', $values));
}
/**
* @param non-empty-list<Action> $actions
*/
private function formatActions(array $actions): string
{
return implode(
', ',
array_map(static fn (Action $action): string => strtolower($action->name), $actions),
);
}
private function configuration(): Configuration
{
return $this->configuration ??= $this->configurationLoader->load();
}
/**
* @return array<string, non-empty-list<class-string>>
*/
private function getEntityCollection(): array
{
/** @var array<string, non-empty-list<class-string>> $entities */
$entities = [];
foreach ($this->managerRegistry->getManagers() as $manager) {
foreach ($manager->getMetadataFactory()->getAllMetadata() as $metadata) {
$entityFqcn = $metadata->getName();
$name = strrchr($entityFqcn, '\\');
$name = substr(false === $name ? $entityFqcn : $name, 1);
if (isset($entities[$name])) {
if (!\in_array($entityFqcn, $entities[$name], true)) {
$entities[$name][] = $entityFqcn;
}
} else {
$entities[$name] = [$entityFqcn];
}
}
}
foreach ($entities as &$entityFqcns) {
sort($entityFqcns, \SORT_STRING | \SORT_FLAG_CASE);
}
return $entities;
}
/**
* @param ClassMetadata<object> $metadata
*
* @return list<string>
*/
private function getAssociationFields(ClassMetadata $metadata): array
{
return array_values(
array_filter(
$metadata->getAssociationNames(),
static fn (string $name): bool => !$metadata->isAssociationInverseSide($name),
),
);
}
}