Files
kiri-client/HttpParse.php
T

109 lines
2.5 KiB
PHP
Raw Normal View History

2022-01-09 13:54:34 +08:00
<?php
declare(strict_types=1);
2022-01-10 11:39:56 +08:00
namespace Kiri;
2022-01-09 13:54:34 +08:00
use Exception;
/**
* Class HttpParse
* @package BeReborn\Http
*/
class HttpParse
{
2023-12-12 15:35:36 +08:00
/**
* @param mixed ...$object
* @return string
*/
private static function getKey(...$object): string
{
$first = '';
$tp = [];
foreach ($object as $value) {
if ($value === null) {
continue;
}
if (is_array($value)) {
$value = key($value);
}
if ($first === '') {
$first = $value;
} else {
$tp[] = $value;
}
}
$key = $first . '[' . implode('][', $tp) . ']';
if (count($tp) < 1) {
$key = $first;
}
return $key;
}
2022-01-09 13:54:34 +08:00
2023-12-12 15:35:36 +08:00
/**
2023-12-18 18:21:09 +08:00
* @param array|string $data
2023-12-12 15:35:36 +08:00
* @return string
*/
2023-12-18 18:21:09 +08:00
public static function parse(array|string $data): string
2023-12-12 15:35:36 +08:00
{
$tmp = [];
if (is_string($data)) {
return $data;
}
foreach ($data as $key => $datum) {
if ($datum === null) {
continue;
}
$tmp[] = static::ifElse($key, $datum);
}
return implode('&', $tmp);
}
2022-01-09 13:54:34 +08:00
2023-12-12 15:35:36 +08:00
/**
* @param $t
* @param $qt
* @return string
* @throws
*/
2023-12-18 18:21:09 +08:00
private static function ifElse(string $t, mixed $qt): string
2023-12-12 15:35:36 +08:00
{
if (is_numeric($qt)) {
return $t . '=' . $qt;
}
if (is_string($qt)) {
$string = $t . '=' . urlencode($qt);
} else {
$string = static::encode($t, $qt);
}
return $string;
}
2022-01-09 13:54:34 +08:00
2023-12-12 15:35:36 +08:00
/**
* @param mixed ...$object
* @return string
* @throws
*/
private static function encode(...$object): string
{
$ret = [];
2022-01-09 13:54:34 +08:00
2023-12-12 15:35:36 +08:00
$data = $object[count($object) - 1];
$key = static::getKey(...$object);
foreach ($data as $s => $datum) {
if (is_array($datum)) {
$object[count($object) - 1] = $s;
$object[] = $datum;
$string = static::encode(...$object);
} else {
if (is_object($datum)) {
throw new Exception('Http body con\'t object.');
}
$string = $key . '=' . urlencode($datum);
}
$ret[] = $string;
}
return implode('&', $ret);
}
2022-01-09 13:54:34 +08:00
}