friendship ended with social-app. php is my new best friend
1<?php
2/**
3 * Class EchoClient
4 *
5 * @created 15.03.2024
6 * @author smiley <smiley@chillerlan.net>
7 * @copyright 2024 smiley
8 * @license MIT
9 */
10declare(strict_types=1);
11
12namespace chillerlan\HTTP\Utils\Client;
13
14use chillerlan\HTTP\Utils\MessageUtil;
15use Psr\Http\Client\ClientInterface;
16use Psr\Http\Message\{RequestInterface, ResponseFactoryInterface, ResponseInterface};
17use Throwable;
18use function json_encode, strlen;
19
20/**
21 * Echoes the http request back (as a JSON object)
22 */
23class EchoClient implements ClientInterface{
24
25 protected ResponseFactoryInterface $responseFactory;
26
27 /**
28 * EchoClient constructor.
29 */
30 public function __construct(ResponseFactoryInterface $responseFactory){
31 $this->responseFactory = $responseFactory;
32 }
33
34 public function sendRequest(RequestInterface $request):ResponseInterface{
35 $response = $this->responseFactory->createResponse();
36
37 try{
38 $content = MessageUtil::toJSON($request);
39 }
40 catch(Throwable $e){
41 $response = $response->withStatus(500);
42 $content = json_encode(['error' => $e->getMessage()]);
43 }
44 /** @var string $content */
45 $response = $response
46 ->withHeader('Content-Type', 'application/json')
47 ->withHeader('Content-Length', (string)strlen($content))
48 ;
49
50 $response->getBody()->write($content);
51
52 return $response;
53 }
54
55}