Curl\Curl::buildPostData PHP Méthode

buildPostData() public méthode

Build Post Data
public buildPostData ( $data ) : array | string
$data
Résultat array | string
    public function buildPostData($data)
    {
        $binary_data = false;
        if (is_array($data)) {
            // Return JSON-encoded string when the request's content-type is JSON.
            if (isset($this->headers['Content-Type']) && preg_match($this->jsonPattern, $this->headers['Content-Type'])) {
                $json_str = json_encode($data);
                if (!($json_str === false)) {
                    $data = $json_str;
                }
            } else {
                // Manually build a single-dimensional array from a multi-dimensional array as using curl_setopt($ch,
                // CURLOPT_POSTFIELDS, $data) doesn't correctly handle multi-dimensional arrays when files are
                // referenced.
                if (self::is_array_multidim($data)) {
                    $data = self::array_flatten_multidim($data);
                }
                // Modify array values to ensure any referenced files are properly handled depending on the support of
                // the @filename API or CURLFile usage. This also fixes the warning "curl_setopt(): The usage of the
                // @filename API for file uploading is deprecated. Please use the CURLFile class instead". Ignore
                // non-file values prefixed with the @ character.
                foreach ($data as $key => $value) {
                    if (is_string($value) && strpos($value, '@') === 0 && is_file(substr($value, 1))) {
                        $binary_data = true;
                        if (class_exists('CURLFile')) {
                            $data[$key] = new \CURLFile(substr($value, 1));
                        }
                    } elseif ($value instanceof \CURLFile) {
                        $binary_data = true;
                    }
                }
            }
        }
        if (!$binary_data && (is_array($data) || is_object($data))) {
            $data = http_build_query($data, '', '&');
        }
        return $data;
    }

Usage Example

 public function testBuildPostDataArgSeparator()
 {
     $data = array('foo' => 'Hello', 'bar' => 'World');
     foreach (array(false, '&', '&') as $arg_separator) {
         if ($arg_separator) {
             ini_set('arg_separator.output', $arg_separator);
         }
         $curl = new Curl();
         $this->assertEquals('foo=Hello&bar=World', $curl->buildPostData($data));
     }
 }