FormatsPagarmeData.php 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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' => $streetSegment,
  21. 'street_number' => (string) ($data['number'] ?? $matches[1] ?? 'S/N'),
  22. 'neighborhood' => (string) ($data['district'] ?? $segments[1] ?? 'N/A'),
  23. 'reference_point' => (string) ($data['reference_point'] ?? 'N/A'),
  24. 'complementary' => (string) ($data['complement'] ?? 'N/A'),
  25. ];
  26. }
  27. protected function formatBirthdate(mixed $birthdate): ?string
  28. {
  29. if ($birthdate === null || $birthdate === '') {
  30. return null;
  31. }
  32. if ($birthdate instanceof \DateTimeInterface) {
  33. return Carbon::instance($birthdate)->format('d/m/Y');
  34. }
  35. $birthdate = trim((string) $birthdate);
  36. if (preg_match('/^\d{2}\/\d{2}\/\d{4}$/', $birthdate) === 1) {
  37. return $birthdate;
  38. }
  39. if (preg_match('/^\d{4}-\d{2}-\d{2}$/', $birthdate) === 1) {
  40. return Carbon::createFromFormat('Y-m-d', $birthdate)->format('d/m/Y');
  41. }
  42. return Carbon::parse($birthdate)->format('d/m/Y');
  43. }
  44. protected function normalizeHolderName(string $holderName): string
  45. {
  46. $holderName = trim(preg_replace('/\s+/', ' ', $holderName) ?? '');
  47. if (Str::length($holderName) < 30) {
  48. return $holderName;
  49. }
  50. $parts = explode(' ', $holderName);
  51. if (count($parts) >= 3) {
  52. $firstName = array_shift($parts);
  53. $lastName = array_pop($parts);
  54. $initials = array_map(
  55. static fn (string $part): string => Str::upper(Str::substr($part, 0, 1)),
  56. $parts
  57. );
  58. $abbreviated = trim($firstName.' '.implode(' ', $initials).' '.$lastName);
  59. if (Str::length($abbreviated) < 30) {
  60. return $abbreviated;
  61. }
  62. $firstAndLast = trim($firstName.' '.$lastName);
  63. if (Str::length($firstAndLast) < 30) {
  64. return $firstAndLast;
  65. }
  66. }
  67. return Str::limit($holderName, 29, '');
  68. }
  69. }