| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Controllers\GoogleSheets; |
| 4 |
|
| 5 |
use IvyForms\Common\Exceptions\ForbiddenException; |
| 6 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 7 |
use IvyForms\Common\Sanitizer\Sanitizer; |
| 8 |
use IvyForms\Controllers\Controller; |
| 9 |
use IvyForms\Services\GoogleSheets\Helpers\GoogleSheetsOAuthStateHelper; |
| 10 |
use IvyForms\Services\GoogleSheets\GoogleSheetsService; |
| 11 |
use WP_REST_Request; |
| 12 |
use WP_REST_Response; |
| 13 |
|
| 14 |
class GoogleSheetsConnectController extends Controller |
| 15 |
{ |
| 16 |
private GoogleSheetsService $googleSheetsService; |
| 17 |
|
| 18 |
public function __construct(GoogleSheetsService $googleSheetsService) |
| 19 |
{ |
| 20 |
$this->googleSheetsService = $googleSheetsService; |
| 21 |
} |
| 22 |
|
| 23 |
/** |
| 24 |
* @throws ForbiddenException |
| 25 |
* @throws InvalidArgumentException |
| 26 |
*/ |
| 27 |
protected function handle(WP_REST_Request $data): WP_REST_Response |
| 28 |
{ |
| 29 |
Sanitizer::verifyNonce($data->get_header('X-WP-Nonce')); |
| 30 |
|
| 31 |
if (!$this->googleSheetsService->isMiddlewareReachable()) { |
| 32 |
throw new InvalidArgumentException( |
| 33 |
$this->googleSheetsService->getMiddlewareUnreachableMessage() |
| 34 |
); |
| 35 |
} |
| 36 |
|
| 37 |
$authUrl = $this->googleSheetsService->createAuthUrl(GoogleSheetsOAuthStateHelper::createState()); |
| 38 |
|
| 39 |
if ($authUrl === '') { |
| 40 |
throw new InvalidArgumentException( |
| 41 |
$this->googleSheetsService->getOAuthNotConfiguredMessage() |
| 42 |
); |
| 43 |
} |
| 44 |
|
| 45 |
return new WP_REST_Response([ |
| 46 |
'auth_url' => $authUrl, |
| 47 |
], 200); |
| 48 |
} |
| 49 |
} |
| 50 |
|