TransferController.php
79 lines
| 1 | <?php |
| 2 | |
| 3 | namespace Give\FormMigration\Controllers; |
| 4 | |
| 5 | use Give\Campaigns\Repositories\CampaignRepository; |
| 6 | use Give\Campaigns\ValueObjects\CampaignType; |
| 7 | use Give\DonationForms\V2\Models\DonationForm; |
| 8 | use Give\FormMigration\Actions\GetMigratedFormId; |
| 9 | use Give\FormMigration\Actions\TransferDonations; |
| 10 | use Give\FormMigration\Actions\TransferFormUrl; |
| 11 | use Give\FormMigration\DataTransferObjects\TransferOptions; |
| 12 | use Give\Framework\Database\DB; |
| 13 | use WP_REST_Request; |
| 14 | use WP_REST_Response; |
| 15 | |
| 16 | class TransferController |
| 17 | { |
| 18 | protected $debugContext; |
| 19 | |
| 20 | /** |
| 21 | * @var WP_REST_Request |
| 22 | */ |
| 23 | protected $request; |
| 24 | |
| 25 | public function __construct(WP_REST_Request $request) |
| 26 | { |
| 27 | $this->request = $request; |
| 28 | } |
| 29 | |
| 30 | /** |
| 31 | * @since 4.14.2 updated logic to search for non-core campaigns (e.g., P2P) |
| 32 | * @since 3.0.0 |
| 33 | */ |
| 34 | public function __invoke(DonationForm $formV2, TransferOptions $options) |
| 35 | { |
| 36 | DB::transaction(function() use ($formV2, $options) { |
| 37 | |
| 38 | $v3FormId = (new GetMigratedFormId)($formV2->id); |
| 39 | TransferFormUrl::from($formV2->id)->to($v3FormId); |
| 40 | TransferDonations::from($formV2->id)->to($v3FormId); |
| 41 | |
| 42 | // Promote upgraded form to default form |
| 43 | $campaignRepository = give(CampaignRepository::class); |
| 44 | if ($campaign = $campaignRepository->getByFormId($formV2->id)) { |
| 45 | $defaultForm = $campaign->defaultForm(); |
| 46 | |
| 47 | if ($defaultForm->id === $formV2->id) { |
| 48 | $campaignRepository->updateDefaultCampaignForm($campaign, $v3FormId); |
| 49 | } |
| 50 | } else { |
| 51 | // Fallback: Check for non-core campaigns (e.g., P2P) linked via give_campaigns.form_id |
| 52 | $campaignData = DB::table('give_campaigns') |
| 53 | ->where('form_id', $formV2->id) |
| 54 | ->where('campaign_type', CampaignType::CORE, '!=') |
| 55 | ->get(); |
| 56 | |
| 57 | if ($campaignData) { |
| 58 | DB::table('give_campaigns') |
| 59 | ->where('id', $campaignData->id) |
| 60 | ->update([ |
| 61 | 'form_id' => $v3FormId, |
| 62 | ]); |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | if($options->shouldDelete()) { |
| 67 | wp_trash_post($formV2->id); |
| 68 | } |
| 69 | |
| 70 | wp_update_post(['ID' => $v3FormId, 'post_status' => $formV2->status->getValue()]); |
| 71 | give_update_meta($v3FormId, 'transferredFormId', true); |
| 72 | }); |
| 73 | |
| 74 | return new WP_REST_Response(array('errors' => [], 'successes' => [ |
| 75 | $formV2->id |
| 76 | ])); |
| 77 | } |
| 78 | } |
| 79 |