/Command/CacheDeleteAllCommand.php

https://github.com/liip/LiipDoctrineCacheBundle · PHP · 72 lines · 48 code · 7 blank · 17 comment · 5 complexity · f87544630d872d397e54fd5c3d70b5e7 MD5 · raw file

  1. <?php
  2. namespace Liip\DoctrineCacheBundle\Command;
  3. use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
  4. use Symfony\Component\Console\Input\InputArgument;
  5. use Symfony\Component\Console\Input\InputInterface;
  6. use Symfony\Component\Console\Output\OutputInterface;
  7. use Doctrine\Common\Cache\CacheProvider;
  8. /**
  9. * CacheDeleteAllCommand
  10. * Allows to launch a delete all on the underlying cache provider
  11. * the main difference with a flush is that only the given namespace
  12. * is affected by the delete command (especially useful when a single
  13. * cache provider hosts multiple namespaces)
  14. */
  15. class CacheDeleteAllCommand extends ContainerAwareCommand
  16. {
  17. /**
  18. * {@inheritdoc}
  19. */
  20. protected function configure()
  21. {
  22. $this->setName('liip:doctrine-cache:delete-all');
  23. $this->setDescription('Clean the given cache');
  24. $this->addArgument(
  25. 'cache-name', InputArgument::REQUIRED, 'Which cache to clean?'
  26. );
  27. $this->addArgument(
  28. 'use-namespace',
  29. InputArgument::OPTIONAL,
  30. 'Which namespace to use (defaults to the one specified in the container configuration)'
  31. );
  32. }
  33. /**
  34. * {@inheritdoc}
  35. */
  36. protected function execute(InputInterface $input, OutputInterface $output)
  37. {
  38. // Retrieve the cache provider associated to the given cache-name
  39. $cacheName = $input->getArgument('cache-name');
  40. $serviceName = 'liip_doctrine_cache.ns.'.$cacheName;
  41. $cacheProvider = $this->getContainer()->get($serviceName);
  42. if ($cacheProvider instanceof CacheProvider) {
  43. // In case we force another namespace, force it in the cache provider
  44. $namespace = $input->getArgument('use-namespace');
  45. if ('' != $namespace) {
  46. $cacheProvider->setNamespace($namespace);
  47. } else {
  48. $namespace = $cacheProvider->getNamespace();
  49. }
  50. // Do the actual cache invalidation for the given namespace
  51. $cacheProvider->deleteAll();
  52. } else {
  53. // Should not happen...
  54. throw new \RuntimeException(sprintf(
  55. 'Unable to get a cache named %s from the container',
  56. $cacheName
  57. ));
  58. }
  59. $output->writeln(sprintf(
  60. 'The namespace %s of cache %s has been fully invalidated',
  61. $namespace,
  62. $cacheName
  63. ));
  64. }
  65. }