summaryrefslogtreecommitdiffstats
path: root/vendor/gipfl/icinga-cli-daemon/src/IcingaCliRunner.php
blob: 60a25cc6edc99bd327ff669088b9e1bbcc142d22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php

namespace gipfl\IcingaCliDaemon;

use React\ChildProcess\Process;
use gipfl\Cli\Process as CliProcess;

class IcingaCliRunner
{
    /** @var string */
    protected $binary;

    /** @var string|null */
    protected $cwd;

    /** @var array|null */
    protected $env;

    public function __construct($binary = null)
    {
        if ($binary === null) {
            $this->binary = CliProcess::getBinaryPath();
            $this->cwd = CliProcess::getInitialCwd();
        } else {
            $this->binary = $binary;
        }
    }

    /**
     * @param mixed array|...$arguments
     * @return Process
     */
    public function command($arguments = null)
    {
        if (! \is_array($arguments)) {
            $arguments = \func_get_args();
        }

        return new Process(
            $this->escapedCommand($arguments),
            $this->cwd,
            $this->env
        );
    }

    /**
     * @param string|null $cwd
     */
    public function setCwd($cwd)
    {
        if ($cwd === null) {
            $this->cwd = $cwd;
        } else {
            $this->cwd = (string) $cwd;
        }
    }

    /**
     * @param array|null $env
     */
    public function setEnv($env)
    {
        if ($env === null) {
            $this->env = $env;
        } else {
            $this->env = (array) $env;
        }
    }

    /**
     * @param $arguments
     * @return string
     */
    protected function escapedCommand($arguments)
    {
        $command = ['exec', \escapeshellcmd($this->binary)];

        foreach ($arguments as $argument) {
            if (\ctype_alnum(preg_replace('/^-{1,2}/', '', $argument))) {
                $command[] = $argument;
            } else {
                $command[] = \escapeshellarg($argument);
            }
        }

        return \implode(' ', $command);
    }
}