Completed
Push — master ( ec3284...d3cc4e )
by recca
01:36
created

ProcessUtils   A

Complexity

Total Complexity 11

Size/Duplication

Total Lines 57
Duplicated Lines 0 %

Coupling/Cohesion

Components 0
Dependencies 0

Test Coverage

Coverage 14.29%

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 57
ccs 3
cts 21
cp 0.1429
rs 10
wmc 11
lcom 0
cbo 0

2 Methods

Rating   Name   Duplication   Size   Complexity  
C escapeArgument() 0 36 8
A isSurroundedBy() 0 4 3
1
<?php
2
3
namespace Recca0120\Terminal;
4
5
/**
6
 * ProcessUtils is a bunch of utility methods.
7
 *
8
 * This class was originally copied from Symfony 3.
9
 */
10
class ProcessUtils
11
{
12
    /**
13
     * Escapes a string to be used as a shell argument.
14
     *
15
     * @param  string  $argument
16
     * @return string
17
     */
18 1
    public static function escapeArgument($argument)
19
    {
20
        // Fix for PHP bug #43784 escapeshellarg removes % from given string
21
        // Fix for PHP bug #49446 escapeshellarg doesn't work on Windows
22
        // @see https://bugs.php.net/bug.php?id=43784
23
        // @see https://bugs.php.net/bug.php?id=49446
24 1
        if ('\\' === DIRECTORY_SEPARATOR) {
25
            if ('' === $argument) {
26
                return '""';
27
            }
28
            $escapedArgument = '';
29
            $quote = false;
30
            foreach (preg_split('/(")/', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
31
                if ('"' === $part) {
32
                    $escapedArgument .= '\\"';
33
                } elseif (self::isSurroundedBy($part, '%')) {
34
                    // Avoid environment variable expansion
35
                    $escapedArgument .= '^%"'.substr($part, 1, -1).'"^%';
36
                } else {
37
                    // escape trailing backslash
38
                    if ('\\' === substr($part, -1)) {
39
                        $part .= '\\';
40
                    }
41
                    $quote = true;
42
                    $escapedArgument .= $part;
43
                }
44
            }
45
            if ($quote) {
46
                $escapedArgument = '"'.$escapedArgument.'"';
47
            }
48
49
            return $escapedArgument;
50
        }
51
52 1
        return "'".str_replace("'", "'\\''", $argument)."'";
53
    }
54
55
    /**
56
     * Is the given string surrounded by the given character?
57
     *
58
     * @param  string  $arg
59
     * @param  string  $char
60
     * @return bool
61
     */
62
    protected static function isSurroundedBy($arg, $char)
63
    {
64
        return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
65
    }
66
}
67