FormatsPagarmeData.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Services\Pagarme\Concerns;
  3. use Carbon\Carbon;
  4. use Illuminate\Support\Str;
  5. trait FormatsPagarmeData
  6. {
  7. protected function digits(?string $value): string
  8. {
  9. return preg_replace('/\D+/', '', (string) $value) ?? '';
  10. }
  11. protected function extractAddressParts(array $data): array
  12. {
  13. $addressLine = trim((string) ($data['address'] ?? ''));
  14. $segments = array_map('trim', explode(',', $addressLine));
  15. $streetSegment = $segments[0] ?? '';
  16. if (($data['number'] ?? null) === null) {
  17. preg_match('/^(\d+)/', $streetSegment, $matches);
  18. }
  19. return [
  20. 'street_number' => (string) ($data['number'] ?? $matches[1] ?? 'S/N'),
  21. 'neighborhood' => (string) ($data['district'] ?? $segments[1] ?? 'N/A'),
  22. 'reference_point' => (string) ($data['reference_point'] ?? 'N/A'),
  23. 'complementary' => (string) ($data['complement'] ?? 'N/A'),
  24. ];
  25. }
  26. protected function formatBirthdate(mixed $birthdate): ?string
  27. {
  28. if ($birthdate === null || $birthdate === '') {
  29. return null;
  30. }
  31. if ($birthdate instanceof \DateTimeInterface) {
  32. return Carbon::instance($birthdate)->format('d/m/Y');
  33. }
  34. $birthdate = trim((string) $birthdate);
  35. if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $birthdate) === 1) {
  36. return $birthdate;
  37. }
  38. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $birthdate) === 1) {
  39. return Carbon::createFromFormat('Y-m-d', $birthdate)->format('d/m/Y');
  40. }
  41. return Carbon::parse($birthdate)->format('d/m/Y');
  42. }
  43. protected function normalizeHolderName(string $holderName): string
  44. {
  45. $holderName = trim(preg_replace('/\s+/', ' ', $holderName) ?? '');
  46. if (Str::length($holderName) < 30) {
  47. return $holderName;
  48. }
  49. $parts = explode(' ', $holderName);
  50. if (count($parts) >= 3) {
  51. $firstName = array_shift($parts);
  52. $lastName = array_pop($parts);
  53. $initials = array_map(
  54. static fn (string $part): string => Str::upper(Str::substr($part, 0, 1)),
  55. $parts
  56. );
  57. $abbreviated = trim($firstName.' '.implode(' ', $initials).' '.$lastName);
  58. if (Str::length($abbreviated) < 30) {
  59. return $abbreviated;
  60. }
  61. $firstAndLast = trim($firstName.' '.$lastName);
  62. if (Str::length($firstAndLast) < 30) {
  63. return $firstAndLast;
  64. }
  65. }
  66. return Str::limit($holderName, 29, '');
  67. }
  68. }