DateTime.php
51 lines
| 1 | <?php |
| 2 | |
| 3 | declare(strict_types=1); |
| 4 | |
| 5 | namespace Automattic\WooCommerce\Api\Scalars; |
| 6 | |
| 7 | use Automattic\WooCommerce\Api\Attributes\Description; |
| 8 | |
| 9 | /** |
| 10 | * Custom scalar for ISO 8601 date/time values. |
| 11 | */ |
| 12 | #[Description( 'An ISO 8601 encoded date and time string.' )] |
| 13 | class DateTime { |
| 14 | /** |
| 15 | * Serialize a PHP value to the scalar's transport format. |
| 16 | * |
| 17 | * @param mixed $value The value to serialize. |
| 18 | * @return string |
| 19 | */ |
| 20 | public static function serialize( mixed $value ): string { |
| 21 | if ( $value instanceof \DateTimeInterface ) { |
| 22 | return $value->format( \DateTimeInterface::ATOM ); |
| 23 | } |
| 24 | return (string) $value; |
| 25 | } |
| 26 | |
| 27 | /** |
| 28 | * Parse a value received from a client (variable or literal). |
| 29 | * |
| 30 | * @param string $value The raw string value from the client. |
| 31 | * @return \DateTimeImmutable |
| 32 | * @throws \InvalidArgumentException When the value cannot be parsed as an ISO 8601 date/time string. |
| 33 | */ |
| 34 | public static function parse( string $value ): \DateTimeImmutable { |
| 35 | try { |
| 36 | return new \DateTimeImmutable( $value ); |
| 37 | } catch ( \Exception $e ) { |
| 38 | // PHP 8.3+ throws \DateMalformedStringException; earlier versions |
| 39 | // throw a plain \Exception. Both extend \Exception, so a single |
| 40 | // catch captures them. |
| 41 | // phpcs:disable WordPress.Security.EscapeOutput.ExceptionNotEscaped -- Not HTML output; serialized as JSON in the GraphQL error response. |
| 42 | throw new \InvalidArgumentException( |
| 43 | sprintf( 'Invalid ISO 8601 date/time: %s', $e->getMessage() ), |
| 44 | 0, |
| 45 | $e |
| 46 | ); |
| 47 | // phpcs:enable WordPress.Security.EscapeOutput.ExceptionNotEscaped |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 |