Skip to content

Commit 2ae00ac

Browse files
committed
support int|float
1 parent 39d592c commit 2ae00ac

File tree

1 file changed

+21
-9
lines changed

1 file changed

+21
-9
lines changed
Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,45 @@
11
<?php
2-
declare (strict_types = 1);
2+
3+
declare(strict_types=1);
4+
35
namespace Divinity76\quoteshellarg;
46

57
/**
68
* quotes shell arguments
79
* (doing a better job than escapeshellarg)
810
*
9-
* @param string $arg
10-
* @throws UnexpectedValueException if $arg contains null bytes
11+
* @param string|int|float $arg
12+
* @throws \UnexpectedValueException if $arg contains null bytes
1113
* @return string
1214
*/
1315

14-
function quoteshellarg(string $arg): string
16+
function quoteshellarg($arg): string
1517
{
18+
if (\is_float($arg)) {
19+
// 17: >The 53-bit significand precision gives from 15 to 17 significant decimal digits precision.
20+
return \escapeshellarg(\sprintf('%.17g', $arg));
21+
}
22+
if (\is_int($arg)) {
23+
return \escapeshellarg((string) $arg);
24+
}
25+
if (!\is_string($arg)) {
26+
throw new \InvalidArgumentException('Argument #1 ($arg) must be of type string|int|float, ' . (is_object($arg) ? get_class($arg) : gettype($arg)) . ' given');
27+
}
1628
static $isUnix = null;
1729
if ($isUnix === null) {
18-
$isUnix = in_array(PHP_OS_FAMILY, array('Linux', 'BSD', 'Darwin', 'Solaris'), true) || PHP_OS === 'CYGWIN';
30+
$isUnix = \in_array(PHP_OS_FAMILY, array('Linux', 'BSD', 'Darwin', 'Solaris'), true) || PHP_OS === 'CYGWIN';
1931
}
2032
if ($isUnix) {
2133
// PHP's built-in escapeshellarg() for unix is kindof garbage: https://3v4l.org/Hkv7h
2234
// corrupting-or-stripping UTF-8 unicode characters like "æøå" and non-printable characters like "\x01",
2335
// both of which are fully legal in unix shell arguments.
2436
// In single-quoted-unix-shell-arguments there are only 2 bytes that needs special attention: \x00 and \x27
25-
if (false !== strpos($arg, "\x00")) {
26-
throw new UnexpectedValueException('unix shell arguments cannot contain null bytes!');
37+
if (false !== \strpos($arg, "\x00")) {
38+
throw new \UnexpectedValueException('unix shell arguments cannot contain null bytes!');
2739
}
28-
return "'" . strtr($arg, array("'" => "'\\''")) . "'";
40+
return "'" . \strtr($arg, array("'" => "'\\''")) . "'";
2941
}
3042
// todo: quoteshellarg for windows? it's a nightmare though: https://docs.microsoft.com/en-us/archive/blogs/twistylittlepassagesallalike/everyone-quotes-command-line-arguments-the-wrong-way
3143
// fallback to php's builtin escapeshellarg
32-
return escapeshellarg($arg);
44+
return \escapeshellarg($arg);
3345
}

0 commit comments

Comments
 (0)