1+ <?php
2+
3+ namespace App \Command ;
4+
5+ use Doctrine \DBAL \Connection ;
6+ use Symfony \Component \Console \Attribute \AsCommand ;
7+ use Symfony \Component \Console \Command \Command ;
8+ use Symfony \Component \Console \Input \InputInterface ;
9+ use Symfony \Component \Console \Output \OutputInterface ;
10+ use Symfony \Component \Console \Style \SymfonyStyle ;
11+
12+ #[AsCommand(
13+ name: 'app:purge-old-data ' ,
14+ description: 'Purges all data older than 10 minutes from the database ' ,
15+ )]
16+ class PurgeOldDataCommand extends Command
17+ {
18+ private Connection $ connection ;
19+
20+ public function __construct (Connection $ connection )
21+ {
22+ parent ::__construct ();
23+ $ this ->connection = $ connection ;
24+ }
25+
26+ protected function execute (InputInterface $ input , OutputInterface $ output ): int
27+ {
28+ $ io = new SymfonyStyle ($ input , $ output );
29+ $ io ->title ('Purging data older than 10 minutes ' );
30+
31+ $ timestamp = new \DateTime ('-10 minutes ' );
32+ $ formattedTimestamp = $ timestamp ->format ('Y-m-d H:i:s ' );
33+
34+ $ tables = [
35+ 'problems ' ,
36+ 'private_problems ' ,
37+ 'private_access ' ,
38+ 'users ' ,
39+ 'feedback '
40+ ];
41+
42+ $ totalDeleted = 0 ;
43+
44+ foreach ($ tables as $ table ) {
45+ $ timestampColumn = 'created_at ' ;
46+
47+ if ($ table === 'feedback ' ) {
48+ $ timestampColumn = 'created_at ' ;
49+ }
50+
51+ $ sql = "DELETE FROM $ table WHERE $ timestampColumn < :timestamp " ;
52+
53+ try {
54+ $ stmt = $ this ->connection ->prepare ($ sql );
55+ $ stmt ->bindValue ('timestamp ' , $ formattedTimestamp );
56+ $ result = $ stmt ->executeStatement ();
57+ $ totalDeleted += $ result ;
58+
59+ $ io ->text (sprintf ('Deleted %d rows from %s ' , $ result , $ table ));
60+ } catch (\Exception $ e ) {
61+ $ io ->error (sprintf ('Error deleting from %s: %s ' , $ table , $ e ->getMessage ()));
62+ }
63+ }
64+
65+ $ io ->success (sprintf ('Successfully purged %d rows older than 10 minutes ' , $ totalDeleted ));
66+
67+ return Command::SUCCESS ;
68+ }
69+ }
0 commit comments