Body.php
70 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Unirest\Request; |
| 4 | |
| 5 | use CURLFile; |
| 6 | use Exception; |
| 7 | |
| 8 | class Body |
| 9 | { |
| 10 | /** |
| 11 | * Prepares a file for upload. To be used inside the parameters declaration for a request. |
| 12 | * @param string $filename The file path |
| 13 | * @param string $mimetype MIME type |
| 14 | * @param string $postName the file name |
| 15 | * @return string|CURLFile |
| 16 | */ |
| 17 | public static function file(string $filename, string $mimetype = '', string $postName = '') |
| 18 | { |
| 19 | if (class_exists('CURLFile')) { |
| 20 | return new CURLFile($filename, $mimetype, $postName); |
| 21 | } |
| 22 | |
| 23 | if (function_exists('curl_file_create')) { |
| 24 | return curl_file_create($filename, $mimetype, $postName); |
| 25 | } |
| 26 | |
| 27 | return sprintf('@%s;filename=%s;type=%s', $filename, $postName ?: basename($filename), $mimetype); |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * @throws Exception |
| 32 | */ |
| 33 | public static function json($data) |
| 34 | { |
| 35 | if (!function_exists('json_encode')) { |
| 36 | throw new Exception('JSON Extension not available'); |
| 37 | } |
| 38 | |
| 39 | return json_encode($data); |
| 40 | } |
| 41 | |
| 42 | public static function form($data) |
| 43 | { |
| 44 | if (is_array($data) || is_object($data) || $data instanceof \Traversable) { |
| 45 | return http_build_query(Request::buildHTTPCurlQuery($data)); |
| 46 | } |
| 47 | |
| 48 | return $data; |
| 49 | } |
| 50 | |
| 51 | public static function multipart($data, $files = false): array |
| 52 | { |
| 53 | if (is_object($data)) { |
| 54 | return get_object_vars($data); |
| 55 | } |
| 56 | |
| 57 | if (!is_array($data)) { |
| 58 | return [$data]; |
| 59 | } |
| 60 | |
| 61 | if ($files !== false) { |
| 62 | foreach ($files as $name => $file) { |
| 63 | $data[$name] = call_user_func([__CLASS__, 'File'], $file); |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | return $data; |
| 68 | } |
| 69 | } |
| 70 |