|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace TreeHouse\KeystoneBundle\Command; |
|
4
|
|
|
|
|
5
|
|
|
use Doctrine\Common\Persistence\ObjectManager; |
|
6
|
|
|
use Doctrine\ORM\EntityRepository; |
|
7
|
|
|
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand; |
|
8
|
|
|
use Symfony\Component\Console\Input\InputArgument; |
|
9
|
|
|
use Symfony\Component\Console\Input\InputInterface; |
|
10
|
|
|
use Symfony\Component\Console\Output\OutputInterface; |
|
11
|
|
|
use TreeHouse\KeystoneBundle\Entity\Token; |
|
12
|
|
|
|
|
13
|
|
|
class TokenCleanupCommand extends ContainerAwareCommand |
|
14
|
|
|
{ |
|
15
|
|
|
protected function configure() |
|
16
|
|
|
{ |
|
17
|
|
|
$this->setName('keystone:token:cleanup'); |
|
18
|
|
|
$this->setDescription('Cleanup expired tokens.'); |
|
19
|
|
|
$this->addArgument( |
|
20
|
|
|
'expired-since', |
|
21
|
|
|
InputArgument::OPTIONAL, |
|
22
|
|
|
'Sets the time the token has to be expired for. Can be any valid DateTime constructor string.', |
|
23
|
|
|
'3 hours ago' |
|
24
|
|
|
); |
|
25
|
|
|
} |
|
26
|
|
|
|
|
27
|
|
|
protected function execute(InputInterface $input, OutputInterface $output) |
|
28
|
|
|
{ |
|
29
|
|
|
$purgeDate = new \DateTime($input->getArgument('expired-since')); |
|
30
|
|
|
|
|
31
|
|
|
/** @var EntityRepository $tokenRepository */ |
|
32
|
|
|
$tokenRepository = $this->getContainer()->get('doctrine')->getRepository('TreeHouseKeystoneBundle:Token'); |
|
33
|
|
|
|
|
34
|
|
|
/** @var ObjectManager $entityManager */ |
|
35
|
|
|
$entityManager = $this->getContainer()->get('doctrine')->getManager(); |
|
36
|
|
|
|
|
37
|
|
|
$queryBuilder = $tokenRepository->createQueryBuilder('t'); |
|
38
|
|
|
$queryBuilder->where('t.expiresAt < :date'); |
|
39
|
|
|
$queryBuilder->setParameter('date', $purgeDate->format('Y-m-d H:i:s')); |
|
40
|
|
|
$queryBuilder->setMaxResults(1000); |
|
41
|
|
|
|
|
42
|
|
|
$counter = 0; |
|
43
|
|
|
|
|
44
|
|
|
/** @var Token[] $tokens */ |
|
45
|
|
|
while ($tokens = $queryBuilder->getQuery()->getResult()) { |
|
46
|
|
|
foreach ($tokens as $token) { |
|
47
|
|
|
$output->writeln(sprintf('Removing token %s', $token->getId()), OutputInterface::VERBOSITY_VERBOSE); |
|
48
|
|
|
$entityManager->remove($token); |
|
49
|
|
|
$entityManager->flush(); |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
$counter += count($tokens); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
$output->writeln(sprintf('All done. Removed %d tokens.', $counter)); |
|
56
|
|
|
} |
|
57
|
|
|
} |
|
58
|
|
|
|