1
0

BirthdateParserService.php 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. <?php
  2. /**
  3. * SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
  4. * SPDX-License-Identifier: AGPL-3.0-or-later
  5. */
  6. namespace OCA\User_LDAP\Service;
  7. use DateTimeImmutable;
  8. use Exception;
  9. use InvalidArgumentException;
  10. class BirthdateParserService {
  11. /**
  12. * Try to parse the birthdate from LDAP.
  13. * Supports LDAP's generalized time syntax, YYYYMMDD and YYYY-MM-DD.
  14. *
  15. * @throws InvalidArgumentException If the format of then given date is unknown
  16. */
  17. public function parseBirthdate(string $value): DateTimeImmutable {
  18. // Minimum LDAP generalized date is "1994121610Z" with 11 chars
  19. // While maximum other format is "1994-12-16" with 10 chars
  20. if (strlen($value) > strlen('YYYY-MM-DD')) {
  21. // Probably LDAP generalized time syntax
  22. $value = substr($value, 0, 8);
  23. }
  24. // Should be either YYYYMMDD or YYYY-MM-DD
  25. if (!preg_match('/^(\d{8}|\d{4}-\d{2}-\d{2})$/', $value)) {
  26. throw new InvalidArgumentException("Unknown date format: $value");
  27. }
  28. try {
  29. return new DateTimeImmutable($value);
  30. } catch (Exception $e) {
  31. throw new InvalidArgumentException(
  32. "Unknown date format: $value",
  33. 0,
  34. $e,
  35. );
  36. }
  37. }
  38. }