Completed
Push — master ( e37ae2...a63d79 )
by Paulo Rodrigues
06:49
created

InstallCommand::commandExists()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 6

Importance

Changes 0
Metric Value
dl 0
loc 11
c 0
b 0
f 0
rs 9.4285
ccs 0
cts 6
cp 0
cc 2
eloc 6
nc 2
nop 1
crap 6
1
<?php
2
3
namespace Rj\FrontendBundle\Command;
4
5
use Symfony\Component\Console\Command\Command;
6
use Symfony\Component\Console\Input\InputInterface;
7
use Symfony\Component\Console\Output\OutputInterface;
8
use Symfony\Component\Process\Process;
9
10
class InstallCommand extends Command
11
{
12
    /**
13
     * {@inheritdoc}
14
     */
15 18
    protected function configure()
16
    {
17
        $this
18 18
            ->setName('rj_frontend:install')
19 18
            ->setDescription('Install npm and bower dependencies')
20
        ;
21 18
    }
22
23
    /**
24
     * {@inheritdoc}
25
     */
26 9
    protected function execute(InputInterface $input, OutputInterface $output)
27
    {
28 9
        if (!$this->commandExists('npm')) {
29 7
            return $output->writeln(
30 7
'<error>npm is not installed</error>
31
32
node.js is probably not installed on your system. For node.js installation
33
instructions, refer to https://nodejs.org/en/download/package-manager
34
'
35
            );
36
        }
37
38 2
        if (!$this->commandExists('bower')) {
39 1
            return $output->writeln(
40 1
'<error>bower is not installed</error>
41
42
You can install bower using npm:
43
npm install -g bower
44
'
45
            );
46
        }
47
48 1
        $output->writeln('<info>Running `npm install`</info>');
49 1
        $this->runProcess($output, 'npm install');
50
51 1
        $output->writeln('<info>Running `bower install`</info>');
52 1
        $this->runProcess($output, 'bower install');
53 1
    }
54
55
    /**
56
     * @param OutputInterface $output
57
     * @param string          $command
58
     */
59
    protected function runProcess($output, $command)
60
    {
61
        $process = new Process($command);
62
63
        $process->run(function ($type, $buffer) use ($output) {
64
            if (Process::ERR === $type) {
65
                $output->writeln("<error>$buffer</error>");
66
            } else {
67
                $output->writeln($buffer);
68
            }
69
        });
70
71
        if (!$process->isSuccessful()) {
72
            throw new \RuntimeException($process->getErrorOutput());
73
        }
74
    }
75
76
    /**
77
     * @param string $command
78
     *
79
     * @return bool
80
     */
81
    protected function commandExists($command)
82
    {
83
        $process = new Process("$command -v");
84
        $process->run();
85
86
        if (!$process->isSuccessful()) {
87
            return !preg_match('/: not found/', $process->getErrorOutput());
88
        }
89
90
        return true;
91
    }
92
}
93