Utils.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | TopThink [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2015 http://www.topthink.com All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Author: zhangyajun <448901948@qq.com>
  8. // +----------------------------------------------------------------------
  9. namespace think\process;
  10. class Utils
  11. {
  12. /**
  13. * 转义字符串
  14. * @param string $argument
  15. * @return string
  16. */
  17. public static function escapeArgument($argument)
  18. {
  19. if ('' === $argument) {
  20. return escapeshellarg($argument);
  21. }
  22. $escapedArgument = '';
  23. $quote = false;
  24. foreach (preg_split('/(")/i', $argument, -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE) as $part) {
  25. if ('"' === $part) {
  26. $escapedArgument .= '\\"';
  27. } elseif (self::isSurroundedBy($part, '%')) {
  28. // Avoid environment variable expansion
  29. $escapedArgument .= '^%"' . substr($part, 1, -1) . '"^%';
  30. } else {
  31. // escape trailing backslash
  32. if ('\\' === substr($part, -1)) {
  33. $part .= '\\';
  34. }
  35. $quote = true;
  36. $escapedArgument .= $part;
  37. }
  38. }
  39. if ($quote) {
  40. $escapedArgument = '"' . $escapedArgument . '"';
  41. }
  42. return $escapedArgument;
  43. }
  44. /**
  45. * 验证并进行规范化Process输入。
  46. * @param string $caller
  47. * @param mixed $input
  48. * @return string
  49. * @throws \InvalidArgumentException
  50. */
  51. public static function validateInput($caller, $input)
  52. {
  53. if (null !== $input) {
  54. if (is_resource($input)) {
  55. return $input;
  56. }
  57. if (is_scalar($input)) {
  58. return (string) $input;
  59. }
  60. throw new \InvalidArgumentException(sprintf('%s only accepts strings or stream resources.', $caller));
  61. }
  62. return $input;
  63. }
  64. private static function isSurroundedBy($arg, $char)
  65. {
  66. return 2 < strlen($arg) && $char === $arg[0] && $char === $arg[strlen($arg) - 1];
  67. }
  68. }