CustomerResponseData.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. namespace App\Data\Pagarme\Customer;
  3. use App\Data\Pagarme\Customer\Parts\Response\AddressData;
  4. use App\Data\Pagarme\Customer\Parts\Response\PhonesData;
  5. use App\Data\Pagarme\PagarmeResponseData;
  6. final readonly class CustomerResponseData extends PagarmeResponseData
  7. {
  8. public function __construct(
  9. public ?string $id,
  10. public ?string $name,
  11. public ?string $email,
  12. public ?string $code,
  13. public ?string $document,
  14. public ?string $documentType,
  15. public ?string $type,
  16. public ?bool $delinquent,
  17. public ?AddressData $address, public PhonesData $phones,
  18. public ?string $createdAt = null,
  19. public ?string $updatedAt = null,
  20. ) {}
  21. public function requireId(): string
  22. {
  23. if (! $this->id) {
  24. throw new \RuntimeException('Customer creation returned an empty id.');
  25. }
  26. return $this->id;
  27. }
  28. //
  29. public static function fromArray(array $payload): static
  30. {
  31. $address = static::arrArray($payload, 'address');
  32. $phones = static::arrArray($payload, 'phones');
  33. return new self(
  34. id: static::arrString($payload, 'id'),
  35. name: static::arrString($payload, 'name'),
  36. email: static::arrString($payload, 'email'),
  37. code: static::arrString($payload, 'code'),
  38. document: static::arrString($payload, 'document'),
  39. documentType: static::arrString($payload, 'document_type'),
  40. type: static::arrString($payload, 'type'),
  41. delinquent: static::arrBool($payload, 'delinquent'),
  42. address: ! empty($address) ? AddressData::fromArray($address) : null,
  43. phones: PhonesData::fromArray($phones),
  44. createdAt: static::arrString($payload, 'created_at'),
  45. updatedAt: static::arrString($payload, 'updated_at'),
  46. );
  47. }
  48. public function toArray(): array
  49. {
  50. return [
  51. 'id' => $this->id,
  52. 'name' => $this->name,
  53. 'email' => $this->email,
  54. 'code' => $this->code,
  55. 'document' => $this->document,
  56. 'document_type' => $this->documentType,
  57. 'type' => $this->type,
  58. 'delinquent' => $this->delinquent,
  59. 'address' => $this->address?->toArray(),
  60. 'phones' => $this->phones->toArray(),
  61. 'created_at' => $this->createdAt,
  62. 'updated_at' => $this->updatedAt,
  63. ];
  64. }
  65. }