SubscriptionFields.php
80 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\API\REST\V3\Routes\Subscriptions\Fields; |
| 4 | |
| 5 | use DateTime; |
| 6 | use Give\Framework\Exceptions\Primitives\InvalidArgumentException; |
| 7 | use Give\Framework\Support\ValueObjects\Money; |
| 8 | use Give\Subscriptions\ValueObjects\SubscriptionMode; |
| 9 | use Give\Subscriptions\ValueObjects\SubscriptionPeriod; |
| 10 | use Give\Subscriptions\ValueObjects\SubscriptionStatus; |
| 11 | |
| 12 | /** |
| 13 | * @since 4.8.0 |
| 14 | */ |
| 15 | class SubscriptionFields |
| 16 | { |
| 17 | /** |
| 18 | * Process field values for special data types before setting them on the subscription model. |
| 19 | * |
| 20 | * @since 4.8.0 |
| 21 | */ |
| 22 | public static function processValue(string $key, $value) |
| 23 | { |
| 24 | switch ($key) { |
| 25 | case 'amount': |
| 26 | case 'feeAmountRecovered': |
| 27 | if (is_array($value)) { |
| 28 | // Handle Money object array format: ['value' => 100.00, 'currency' => 'USD'] |
| 29 | if (isset($value['value']) && isset($value['currency'])) { |
| 30 | return Money::fromDecimal($value['value'], $value['currency']); |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | return $value; |
| 35 | |
| 36 | case 'status': |
| 37 | if (is_string($value) && SubscriptionStatus::isValid($value)) { |
| 38 | return new SubscriptionStatus($value); |
| 39 | } |
| 40 | |
| 41 | return $value; |
| 42 | |
| 43 | case 'period': |
| 44 | if (is_string($value)) { |
| 45 | return new SubscriptionPeriod($value); |
| 46 | } |
| 47 | |
| 48 | return $value; |
| 49 | |
| 50 | case 'mode': |
| 51 | if (is_string($value) && SubscriptionMode::isValid($value)) { |
| 52 | return new SubscriptionMode($value); |
| 53 | } |
| 54 | |
| 55 | return $value; |
| 56 | |
| 57 | case 'gatewayId': |
| 58 | // Gateway ID is a simple string, no special processing needed |
| 59 | return $value; |
| 60 | |
| 61 | case 'createdAt': |
| 62 | case 'renewsAt': |
| 63 | try { |
| 64 | if (is_string($value)) { |
| 65 | return new DateTime($value, wp_timezone()); |
| 66 | } elseif (is_array($value)) { |
| 67 | return new DateTime($value['date'], new \DateTimeZone($value['timezone'])); |
| 68 | } |
| 69 | } catch (\Exception $e) { |
| 70 | throw new InvalidArgumentException("Invalid date format for {$key}: {$value}."); |
| 71 | } |
| 72 | |
| 73 | return $value; |
| 74 | |
| 75 | default: |
| 76 | return $value; |
| 77 | } |
| 78 | } |
| 79 | } |
| 80 |