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.8KB

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