4 * Copyright (c) 2007 Andy Smith
6 namespace Abraham\TwitterOAuth;
13 * @return array|mixed|string
15 public static function urlencodeRfc3986($input)
18 if (is_array($input)) {
19 $output = array_map([__NAMESPACE__ . '\Util', 'urlencodeRfc3986'], $input);
20 } elseif (is_scalar($input)) {
21 $output = rawurlencode($input);
27 * @param string $string
31 public static function urldecodeRfc3986($string)
33 return urldecode($string);
37 * This function takes a input like a=b&a=c&d=e and returns the parsed
38 * parameters like this
39 * array('a' => array('b','c'), 'd' => 'e')
41 * @param string $input
45 public static function parseParameters($input)
47 if (!is_string($input)) {
51 $pairs = explode('&', $input);
54 foreach ($pairs as $pair) {
55 $split = explode('=', $pair, 2);
56 $parameter = Util::urldecodeRfc3986($split[0]);
57 $value = isset($split[1]) ? Util::urldecodeRfc3986($split[1]) : '';
59 if (isset($parameters[$parameter])) {
60 // We have already recieved parameter(s) with this name, so add to the list
61 // of parameters with this name
63 if (is_scalar($parameters[$parameter])) {
64 // This is the first duplicate, so transform scalar (string) into an array
65 // so we can add the duplicates
66 $parameters[$parameter] = [$parameters[$parameter]];
69 $parameters[$parameter][] = $value;
71 $parameters[$parameter] = $value;
78 * @param array $params
82 public static function buildHttpQuery(array $params)
88 // Urlencode both keys and values
89 $keys = Util::urlencodeRfc3986(array_keys($params));
90 $values = Util::urlencodeRfc3986(array_values($params));
91 $params = array_combine($keys, $values);
93 // Parameters are sorted by name, using lexicographical byte value ordering.
94 // Ref: Spec: 9.1.1 (1)
95 uksort($params, 'strcmp');
98 foreach ($params as $parameter => $value) {
99 if (is_array($value)) {
100 // If two or more parameters share the same name, they are sorted by their value
101 // Ref: Spec: 9.1.1 (1)
102 // June 12th, 2010 - changed to sort because of issue 164 by hidetaka
103 sort($value, SORT_STRING);
104 foreach ($value as $duplicateValue) {
105 $pairs[] = $parameter . '=' . $duplicateValue;
108 $pairs[] = $parameter . '=' . $value;
111 // For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
112 // Each name-value pair is separated by an '&' character (ASCII code 38)
113 return implode('&', $pairs);