1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Stu\Component\Admin\Reset; |
6
|
|
|
|
7
|
|
|
use Ahc\Cli\IO\Interactor; |
8
|
|
|
use Doctrine\Common\Collections\ArrayCollection; |
9
|
|
|
use Doctrine\ORM\EntityManagerInterface; |
10
|
|
|
use Doctrine\ORM\Mapping\ClassMetadata; |
11
|
|
|
use Generator; |
12
|
|
|
use ReflectionClass; |
13
|
|
|
|
14
|
|
|
class EntityReset |
15
|
|
|
{ |
16
|
2 |
|
public function __construct( |
17
|
|
|
private readonly EntityManagerInterface $entityManager |
18
|
2 |
|
) {} |
19
|
|
|
|
20
|
1 |
|
public function reset(Interactor $io): void |
21
|
|
|
{ |
22
|
1 |
|
$count = 0; |
23
|
|
|
|
24
|
1 |
|
foreach ($this->entityClassesToTruncate() as $reflectionEntry) { |
25
|
1 |
|
$count++; |
26
|
1 |
|
$io->info(sprintf(' - removing all %s entities', $reflectionEntry->getShortName()), true); |
27
|
|
|
|
28
|
1 |
|
$this->entityManager->createQuery( |
29
|
1 |
|
sprintf( |
30
|
1 |
|
'DELETE FROM %s', |
31
|
1 |
|
$reflectionEntry->getClassName() |
32
|
1 |
|
) |
33
|
1 |
|
)->execute(); |
34
|
|
|
} |
35
|
|
|
|
36
|
1 |
|
$io->info(sprintf(' - truncated %d tables', $count), true); |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
/** |
40
|
|
|
* @return Generator<EntityReflectionEntry> |
41
|
|
|
*/ |
42
|
1 |
|
private function entityClassesToTruncate(): Generator |
43
|
|
|
{ |
44
|
|
|
/** @var array<EntityReflectionEntry> */ |
45
|
1 |
|
$toTruncate = (new ArrayCollection($this->entityManager->getMetadataFactory()->getAllMetadata())) |
46
|
1 |
|
->map(fn(ClassMetadata $metadata): EntityReflectionEntry => $this->createReflectionEntry($metadata->getName())) |
47
|
1 |
|
->filter(fn(EntityReflectionEntry $entry): bool => $entry->hasTruncationAttribute()) |
48
|
1 |
|
->toArray(); |
49
|
|
|
|
50
|
1 |
|
usort( |
51
|
1 |
|
$toTruncate, |
52
|
1 |
|
fn(EntityReflectionEntry $a, EntityReflectionEntry $b): int => $b->getPriority() <=> $a->getPriority() |
53
|
1 |
|
); |
54
|
|
|
|
55
|
1 |
|
foreach ($toTruncate as $entry) { |
56
|
1 |
|
yield $entry; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
/** |
61
|
|
|
* @param class-string $className |
|
|
|
|
62
|
|
|
*/ |
63
|
1 |
|
private function createReflectionEntry(string $className): EntityReflectionEntry |
64
|
|
|
{ |
65
|
1 |
|
$reflClass = $this->createReflectionClass($className); |
66
|
|
|
|
67
|
1 |
|
return new EntityReflectionEntry( |
68
|
1 |
|
$className, |
69
|
1 |
|
$reflClass |
70
|
1 |
|
); |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* @param class-string $className |
|
|
|
|
75
|
|
|
* |
76
|
|
|
* @return ReflectionClass<object> |
77
|
|
|
*/ |
78
|
|
|
public function createReflectionClass(string $className): ReflectionClass |
79
|
|
|
{ |
80
|
|
|
return new ReflectionClass($className); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|