Passed
Push — master ( 99a46c...41b437 )
by Dāvis
05:13
created

RedisFlushCommand::execute()   B

Complexity

Conditions 6
Paths 7

Size

Total Lines 19
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
eloc 13
nc 7
nop 2
dl 0
loc 19
rs 8.8571
c 1
b 0
f 0
1
<?php
2
3
namespace Sludio\HelperBundle\Script\Command;
4
5
use Predis\Client;
6
use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
7
use Symfony\Component\Console\Input\InputArgument;
8
use Symfony\Component\Console\Input\InputDefinition;
9
use Symfony\Component\Console\Input\InputInterface;
10
use Symfony\Component\Console\Output\OutputInterface;
11
12
class RedisFlushCommand extends ContainerAwareCommand
13
{
14
    protected function configure()
15
    {
16
        $this->setName('sludio:redis:flush')->setDefinition(new InputDefinition([
17
            new InputArgument('clients', InputArgument::IS_ARRAY | InputArgument::OPTIONAL),
18
        ]));
19
    }
20
21
    private function getClients($services)
22
    {
23
        $clients = [];
24
        /** @var array $services */
25
        foreach ($services as $id) {
26
            if (0 === strpos($id, 'snc_redis') && $this->getContainer()->get($id) instanceof Client) {
27
                $clients[] = $id;
28
            }
29
        }
30
31
        return $clients;
32
    }
33
34
    protected function execute(InputInterface $input, OutputInterface $output)
35
    {
36
        $clients = $this->getClients($this->getContainer()->getServiceIds());
37
38
        if (!empty($clients)) {
39
            $allowed = $clients;
40
            $clientsInput = $input->getArgument('clients');
41
            if (!empty($clientsInput)) {
42
                /** @var $clientsInput array */
43
                foreach ($clientsInput as &$client) {
44
                    $client = 'snc_redis.'.$client;
45
                }
46
                unset($client);
47
                $allowed = array_intersect($clients, $clientsInput);
48
            }
49
            foreach ($clients as $snc) {
50
                if (\in_array($snc, $allowed, true)) {
51
                    $this->getContainer()->get($snc)->flushdb();
52
                    $output->writeln('redis database '.$snc.' flushed');
53
                }
54
            }
55
        }
56
    }
57
}
58