give
/
src
/
API
/
REST
/
V3
/
Routes
/
Subscriptions
/
DataTransferObjects
/
SubscriptionCreateData.php
SubscriptionCreateData.php
97 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\API\REST\V3\Routes\Subscriptions\DataTransferObjects; |
| 4 | |
| 5 | use Exception; |
| 6 | use Give\API\REST\V3\Routes\Subscriptions\Fields\SubscriptionFields; |
| 7 | use Give\Subscriptions\Models\Subscription; |
| 8 | use WP_REST_Request; |
| 9 | |
| 10 | /** |
| 11 | * @since 4.8.0 |
| 12 | */ |
| 13 | class SubscriptionCreateData |
| 14 | { |
| 15 | /** |
| 16 | * @var array |
| 17 | */ |
| 18 | private $attributes; |
| 19 | |
| 20 | /** |
| 21 | * @since 3.0.0 |
| 22 | */ |
| 23 | public function __construct(array $attributes) |
| 24 | { |
| 25 | $this->attributes = $this->processAttributes($attributes); |
| 26 | } |
| 27 | |
| 28 | /** |
| 29 | * Create SubscriptionCreateData from REST request |
| 30 | * |
| 31 | * @since 4.8.0 |
| 32 | * |
| 33 | * @param WP_REST_Request $request |
| 34 | * @return SubscriptionCreateData |
| 35 | */ |
| 36 | public static function fromRequest(WP_REST_Request $request): SubscriptionCreateData |
| 37 | { |
| 38 | return new self($request->get_params()); |
| 39 | } |
| 40 | |
| 41 | |
| 42 | |
| 43 | /** |
| 44 | * Convert to Subscription model |
| 45 | * |
| 46 | * @since 4.8.0 |
| 47 | * |
| 48 | * @return Subscription |
| 49 | * @throws Exception |
| 50 | */ |
| 51 | public function createSubscription(): Subscription |
| 52 | { |
| 53 | // Filter out auto-generated fields |
| 54 | $subscriptionAttributes = array_filter($this->attributes, function ($key) { |
| 55 | return !in_array($key, ['id', 'createdAt', 'updatedAt'], true); |
| 56 | }, ARRAY_FILTER_USE_KEY); |
| 57 | |
| 58 | return Subscription::create($subscriptionAttributes); |
| 59 | } |
| 60 | |
| 61 | /** |
| 62 | * Get the processed attributes |
| 63 | * |
| 64 | * @since 4.8.0 |
| 65 | * |
| 66 | * @return array |
| 67 | */ |
| 68 | public function getAttributes(): array |
| 69 | { |
| 70 | return $this->attributes; |
| 71 | } |
| 72 | |
| 73 | /** |
| 74 | * Process attributes for special data types |
| 75 | * |
| 76 | * @since 4.8.0 |
| 77 | * |
| 78 | * @param array $attributes |
| 79 | * @return array |
| 80 | */ |
| 81 | private function processAttributes(array $attributes): array |
| 82 | { |
| 83 | $processedAttributes = []; |
| 84 | |
| 85 | foreach ($attributes as $key => $value) { |
| 86 | if ($key === 'id' || $key === 'createdAt' || $key === 'updatedAt') { |
| 87 | // Skip these fields as they are auto-generated |
| 88 | continue; |
| 89 | } |
| 90 | |
| 91 | $processedAttributes[$key] = SubscriptionFields::processValue($key, $value); |
| 92 | } |
| 93 | |
| 94 | return $processedAttributes; |
| 95 | } |
| 96 | } |
| 97 |