HttpUtils.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: yp-tc-7176
  5. * Date: 17/7/16
  6. * Time: 20:28
  7. */
  8. namespace app\common\modules\yop\sdk\Util;
  9. use app\common\modules\yop\sdk\Util\StringBuilder;
  10. abstract class HttpUtils
  11. {
  12. /**
  13. * Normalize a string for use in url path. The algorithm is:
  14. * <p>
  15. * <p>
  16. * <ol>
  17. * <li>Normalize the string</li>
  18. * <li>replace all "%2F" with "/"</li>
  19. * <li>replace all "//" with "/%2F"</li>
  20. * </ol>
  21. * <p>
  22. * <p>
  23. * object key can contain arbitrary characters, which may result double slash in the url path. Apache http
  24. * client will replace "//" in the path with a single '/', which makes the object key incorrect. Thus we replace
  25. * "//" with "/%2F" here.
  26. *
  27. * @param path the path string to normalize.
  28. * @return the normalized path string.
  29. * @see #normalize(String)
  30. */
  31. public static function normalizePath($path)
  32. {
  33. return str_replace("%2F", "/",HttpUtils::normalize($path));
  34. }
  35. /**
  36. * @param $value
  37. * @return string
  38. */
  39. public static function normalize($value)
  40. {
  41. return rawurlencode($value);
  42. }
  43. public static function startsWith($haystack, $needle) {
  44. // search backwards starting from haystack length characters from the end
  45. return $needle === "" || strrpos($haystack, $needle, -strlen($haystack)) !== FALSE;
  46. }
  47. public static function endsWith($haystack, $needle) {
  48. // search forward starting from end minus needle length characters
  49. return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== FALSE);
  50. }
  51. /**
  52. * @param $path
  53. * @return string
  54. */
  55. public static function getCanonicalURIPath($path)
  56. {
  57. if ($path == null) {
  58. return "/";
  59. } else if (HttpUtils::startsWith($path,'/')) {
  60. return HttpUtils::normalizePath($path);
  61. } else {
  62. return "/" + HttpUtils::normalizePath($path);
  63. }
  64. }
  65. }