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.

ErrorDocument.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace Tqdev\PhpCrudApi\Record\Document;
  3. use Tqdev\PhpCrudApi\Record\ErrorCode;
  4. class ErrorDocument implements \JsonSerializable
  5. {
  6. public $errorCode;
  7. public $argument;
  8. public $details;
  9. public function __construct(ErrorCode $errorCode, string $argument, $details)
  10. {
  11. $this->errorCode = $errorCode;
  12. $this->argument = $argument;
  13. $this->details = $details;
  14. }
  15. public function getStatus(): int
  16. {
  17. return $this->errorCode->getStatus();
  18. }
  19. public function getCode(): int
  20. {
  21. return $this->errorCode->getCode();
  22. }
  23. public function getMessage(): string
  24. {
  25. return $this->errorCode->getMessage($this->argument);
  26. }
  27. public function serialize()
  28. {
  29. return [
  30. 'code' => $this->getCode(),
  31. 'message' => $this->getMessage(),
  32. 'details' => $this->details,
  33. ];
  34. }
  35. public function jsonSerialize()
  36. {
  37. return array_filter($this->serialize(), function($v) {return $v!==null;});
  38. }
  39. public static function fromException(\Throwable $exception)
  40. {
  41. $document = new ErrorDocument(new ErrorCode(ErrorCode::ERROR_NOT_FOUND), $exception->getMessage(), null);
  42. if ($exception instanceof \PDOException) {
  43. if (strpos(strtolower($exception->getMessage()), 'duplicate') !== false) {
  44. $document = new ErrorDocument(new ErrorCode(ErrorCode::DUPLICATE_KEY_EXCEPTION), '', null);
  45. } elseif (strpos(strtolower($exception->getMessage()), 'unique constraint') !== false) {
  46. $document = new ErrorDocument(new ErrorCode(ErrorCode::DUPLICATE_KEY_EXCEPTION), '', null);
  47. } elseif (strpos(strtolower($exception->getMessage()), 'default value') !== false) {
  48. $document = new ErrorDocument(new ErrorCode(ErrorCode::DATA_INTEGRITY_VIOLATION), '', null);
  49. } elseif (strpos(strtolower($exception->getMessage()), 'allow nulls') !== false) {
  50. $document = new ErrorDocument(new ErrorCode(ErrorCode::DATA_INTEGRITY_VIOLATION), '', null);
  51. } elseif (strpos(strtolower($exception->getMessage()), 'constraint') !== false) {
  52. $document = new ErrorDocument(new ErrorCode(ErrorCode::DATA_INTEGRITY_VIOLATION), '', null);
  53. } else {
  54. $document = new ErrorDocument(new ErrorCode(ErrorCode::ERROR_NOT_FOUND), '', null);
  55. }
  56. }
  57. return $document;
  58. }
  59. }