api de gestion de ticket, basé sur php-crud-api. Le but est de décorrélé les outils de gestion des données, afin
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ResponseFactory.php 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. <?php
  2. namespace Tqdev\PhpCrudApi;
  3. use Nyholm\Psr7\Factory\Psr17Factory;
  4. use Psr\Http\Message\ResponseInterface;
  5. class ResponseFactory
  6. {
  7. public const OK = 200;
  8. public const UNAUTHORIZED = 401;
  9. public const FORBIDDEN = 403;
  10. public const NOT_FOUND = 404;
  11. public const METHOD_NOT_ALLOWED = 405;
  12. public const CONFLICT = 409;
  13. public const UNPROCESSABLE_ENTITY = 422;
  14. public const INTERNAL_SERVER_ERROR = 500;
  15. public static function fromHtml(int $status, string $html): ResponseInterface
  16. {
  17. return self::from($status, 'text/html', $html);
  18. }
  19. public static function fromObject(int $status, $body): ResponseInterface
  20. {
  21. $content = json_encode($body, JSON_UNESCAPED_UNICODE);
  22. return self::from($status, 'application/json', $content);
  23. }
  24. private static function from(int $status, string $contentType, string $content): ResponseInterface
  25. {
  26. $psr17Factory = new Psr17Factory();
  27. $response = $psr17Factory->createResponse($status);
  28. $stream = $psr17Factory->createStream($content);
  29. $stream->rewind();
  30. $response = $response->withBody($stream);
  31. $response = $response->withHeader('Content-Type', $contentType);
  32. $response = $response->withHeader('Content-Length', strlen($content));
  33. return $response;
  34. }
  35. public static function fromStatus(int $status): ResponseInterface
  36. {
  37. $psr17Factory = new Psr17Factory();
  38. return $psr17Factory->createResponse($status);
  39. }
  40. }