46 lines
1.1 KiB
PHP
46 lines
1.1 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Builder\Traits;
|
|
use Hyperf\HttpServer\Response;
|
|
use JsonSerializable;
|
|
use Hyperf\Contract\Jsonable;
|
|
class JsonBuilder implements JsonSerializable, Jsonable
|
|
{
|
|
protected $hideAttrs = [];
|
|
|
|
public function jsonSerialize(): array
|
|
{
|
|
$data = [];
|
|
$hide = collect($this->hideAttrs)->push("hideAttrs")->toArray();
|
|
foreach ($this as $key => $val) {
|
|
if (!in_array($key, $hide) && $val !== null) {
|
|
$data[$key] = $val;
|
|
}
|
|
}
|
|
return $data;
|
|
}
|
|
|
|
/***
|
|
* 输出JSON
|
|
* @return \Psr\Http\Message\ResponseInterface
|
|
*/
|
|
public function toJson()
|
|
{
|
|
$response = new Response();
|
|
return $response
|
|
->json($this->jsonSerialize());
|
|
}
|
|
/***
|
|
* 自动执行
|
|
* @return mixed
|
|
*/
|
|
public function __toString(): string
|
|
{
|
|
// TODO: Implement __toString() method.
|
|
$response = new Response();
|
|
return $response
|
|
->json($this->jsonSerialize())
|
|
->__toString();
|
|
}
|
|
} |