UrlEncodedFormatter.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\httpclient;
  8. use Yii;
  9. use yii\base\Object;
  10. /**
  11. * UrlEncodedFormatter formats HTTP message as 'application/x-www-form-urlencoded'.
  12. *
  13. * @author Paul Klimov <klimov.paul@gmail.com>
  14. * @since 2.0
  15. */
  16. class UrlEncodedFormatter extends Object implements FormatterInterface
  17. {
  18. /**
  19. * @var int URL encoding type.
  20. * Possible values are:
  21. * - PHP_QUERY_RFC1738 - encoding is performed per 'RFC 1738' and the 'application/x-www-form-urlencoded' media type,
  22. * which implies that spaces are encoded as plus (+) signs. This is most common encoding type used by most web
  23. * applications.
  24. * - PHP_QUERY_RFC3986 - then encoding is performed according to 'RFC 3986', and spaces will be percent encoded (%20).
  25. * This encoding type is required by OpenID and OAuth protocols.
  26. */
  27. public $encodingType = PHP_QUERY_RFC1738;
  28. /**
  29. * @var string the content charset. If not set, it will use the value of [[\yii\base\Application::charset]].
  30. * @since 2.0.1
  31. */
  32. public $charset;
  33. /**
  34. * @inheritdoc
  35. */
  36. public function format(Request $request)
  37. {
  38. if (($data = $request->getData()) !== null) {
  39. $content = http_build_query((array)$data, '', '&', $this->encodingType);
  40. }
  41. if (strcasecmp('get', $request->getMethod()) === 0) {
  42. if (!empty($content)) {
  43. $request->setFullUrl(null);
  44. $url = $request->getFullUrl();
  45. $url .= (strpos($url, '?') === false) ? '?' : '&';
  46. $url .= $content;
  47. $request->setFullUrl($url);
  48. }
  49. return $request;
  50. }
  51. $charset = $this->charset === null ? Yii::$app->charset : $this->charset;
  52. $request->getHeaders()->set('Content-Type', 'application/x-www-form-urlencoded; charset=' . $charset);
  53. if (isset($content)) {
  54. $request->setContent($content);
  55. }
  56. return $request;
  57. }
  58. }