Completed
Push — master ( 9b1383...69eea5 )
by Greg
01:24
created

ExecWithRedactionTrait::interpolate()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 13
rs 9.5222
c 0
b 0
f 0
cc 5
nc 3
nop 2
1
<?php
2
namespace Hubph\Util;
3
4
trait ExecWithRedactionTrait
5
{
6
    protected function execWithRedaction($cmd, $replacements = [], $redacted = [])
7
    {
8
        $redactedReplacements = $this->redactedReplacements($replacements, $redacted);
9
        $redactions = $this->redactions($redactedReplacements, $replacements);
10
        $redactedCommand = $this->interpolate($cmd, $redactedReplacements + $replacements);
11
        $command = $this->interpolate("$cmd{redactions}", ['redactions' => $redactions] + $replacements);
12
13
        if (isset($this->logger)) {
14
            $this->logger->notice('Executing {command}', ['command' => $redactedCommand]);
0 ignored issues
show
Bug introduced by
The property logger does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
15
        }
16
        exec($command, $output, $result);
17
        if ($result != 0) {
0 ignored issues
show
Bug introduced by
It seems like you are loosely comparing $result of type integer|null to 0; this is ambiguous as not only 0 == 0 is true, but null == 0 is true, too. Consider using a strict comparison ===.
Loading history...
18
            throw new \Exception("Command `$redactedCommand` failed with exit code $result");
19
        }
20
        return $output;
21
    }
22
23
    private function redactedReplacements($replacements, $redacted)
0 ignored issues
show
Unused Code introduced by
The parameter $replacements is not used and could be removed.

This check looks from parameters that have been defined for a function or method, but which are not used in the method body.

Loading history...
24
    {
25
        $result = [];
26
        foreach ($redacted as $key => $value) {
27
            if (is_numeric($key)) {
28
                $result[$value] = '[REDACTED]';
29
            } else {
30
                $result[$key] = $value;
31
            }
32
        }
33
        return $result;
34
    }
35
36
    private function redactions($redactedReplacements, $replacements)
37
    {
38
        if (empty($redactedReplacements)) {
39
            return '';
40
        }
41
42
        // Make a simple array (with numeric keys) whose values
43
        // are the values of the items in $replacements whose keys
44
        // appear in $redactedReplacements.
45
        $values = array_map(
46
            function ($item) use ($replacements) {
47
                return $replacements[$item];
48
            },
49
            array_keys($redactedReplacements)
50
        );
51
52
        // If any redacted value contains a # or a ', then simply turn off output
53
        if ($this->unsafe($values)) {
54
            return ' >/dev/null 2>&1';
55
        }
56
57
        // Create 'sed' expressions to replace the redactions.
58
        $redactions = array_map(
59
            function ($value) {
60
                return "-e 's#$value#[REDACTED]#'";
61
            },
62
            $values
63
        );
64
65
        return ' 2>&1 | sed ' . implode(' ', $redactions);
66
    }
67
68
    private function unsafe($values)
69
    {
70
        foreach ($values as $value) {
71
            if ((strpos($value, "'") !== false) || (strpos($value, "#") !== false)) {
72
                return true;
73
            }
74
        }
75
        return false;
76
    }
77
78
    private function interpolate($str, array $context)
79
    {
80
        // build a replacement array with braces around the context keys
81
        $replace = array();
82
        foreach ($context as $key => $val) {
83
            if (!is_array($val) && (!is_object($val) || method_exists($val, '__toString'))) {
84
                $replace[sprintf('{%s}', $key)] = $val;
85
            }
86
        }
87
88
        // interpolate replacement values into the message and return
89
        return strtr($str, $replace);
90
    }
91
}
92