Completed
Push — master ( 145693...9a5594 )
by Peter
06:17
created

ScriptHandler::getPhp()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 11
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 12

Importance

Changes 1
Bugs 0 Features 0
Metric Value
dl 0
loc 11
ccs 0
cts 7
cp 0
rs 9.4285
c 1
b 0
f 0
cc 3
eloc 6
nc 3
nop 0
crap 12
1
<?php
2
/**
3
 * GpsLab component.
4
 *
5
 * @author    Peter Gribanov <[email protected]>
6
 * @copyright Copyright (c) 2017, Peter Gribanov
7
 * @license   http://opensource.org/licenses/MIT
8
 */
9
10
namespace GpsLab\Bundle\GeoIP2Bundle\Composer;
11
12
use Composer\Script\Event;
13
use Symfony\Component\Process\PhpExecutableFinder;
14
use Symfony\Component\Process\Process;
15
16
class ScriptHandler
17
{
18
    /**
19
     * @var string|null|false
20
     */
21
    private static $php_path = null;
22
23
    /**
24
     * @param Event $event
25
     */
26
    public static function updateDatabase(Event $event)
27
    {
28
        self::executeCommand($event, 'geoip2:update --no-debug');
29
    }
30
31
    /**
32
     * @param Event $event
33
     * @param string $cmd
34
     * @param int $timeout
35
     */
36
    private static function executeCommand(Event $event, $cmd, $timeout = 300)
37
    {
38
        if ($event->getIO()->isDecorated()) {
39
            $cmd .= ' --ansi';
40
        }
41
42
        $php = escapeshellarg(self::getPhp());
43
44
        $process = new Process($php.' app/console '.$cmd, null, null, null, $timeout);
45
        $process->run(function ($type, $buffer) use ($event) {
46
            $event->getIO()->write($buffer, false);
47
        });
48
49
        if (!$process->isSuccessful()) {
50
            throw new \RuntimeException(sprintf(
51
                "An error occurred when executing the \"%s\" command:\n\n%s\n\n%s.",
52
                escapeshellarg($cmd),
53
                $process->getOutput(),
54
                $process->getErrorOutput()
55
            ));
56
        }
57
    }
58
59
    /**
60
     * Get path to php executable
61
     *
62
     * @throws \RuntimeException
63
     *
64
     * @return string
65
     */
66
    private static function getPhp()
67
    {
68
        if (is_null(self::$php_path)) {
69
            $finder = new PhpExecutableFinder();
70
            if (!(self::$php_path = $finder->find())) {
71
                throw new \RuntimeException('The php executable could not be found, add it to your PATH environment variable and try again');
72
            }
73
        }
74
75
        return self::$php_path;
76
    }
77
}
78