| 1 |
<?php |
| 2 |
|
| 3 |
namespace IvyForms\Services\API; |
| 4 |
|
| 5 |
use WP_Error; |
| 6 |
use IvyForms\Common\Exceptions\InvalidArgumentException; |
| 7 |
use IvyForms\Common\Exceptions\NotFoundException; |
| 8 |
use IvyForms\Common\Exceptions\QueryExecutionException; |
| 9 |
use IvyForms\Common\Exceptions\ValidationException; |
| 10 |
use Exception; |
| 11 |
|
| 12 |
/** |
| 13 |
* Trait IvyFormsAPIHelpers |
| 14 |
* |
| 15 |
* Contains helper methods for IvyFormsAPI to reduce complexity. |
| 16 |
*/ |
| 17 |
trait IvyFormsAPIHelpers |
| 18 |
{ |
| 19 |
/** |
| 20 |
* Handle errors uniformly across all API methods |
| 21 |
* |
| 22 |
* @param callable $callback The function to execute |
| 23 |
* @return mixed The result of the callback or WP_Error on failure |
| 24 |
*/ |
| 25 |
protected static function handleErrors(callable $callback) |
| 26 |
{ |
| 27 |
try { |
| 28 |
return $callback(); |
| 29 |
} catch (InvalidArgumentException $e) { |
| 30 |
return new WP_Error('invalid_argument', $e->getMessage(), ['status' => 400]); |
| 31 |
} catch (NotFoundException $e) { |
| 32 |
return new WP_Error('not_found', $e->getMessage(), ['status' => 404]); |
| 33 |
} catch (QueryExecutionException $e) { |
| 34 |
return new WP_Error('query_execution_error', $e->getMessage(), ['status' => 500]); |
| 35 |
} catch (ValidationException $e) { |
| 36 |
return new WP_Error('validation_error', $e->getMessage(), ['status' => 422]); |
| 37 |
} catch (Exception $e) { |
| 38 |
return new WP_Error('unknown_error', $e->getMessage(), ['status' => 500]); |
| 39 |
} |
| 40 |
} |
| 41 |
|
| 42 |
/** |
| 43 |
* Filter forms that have an integration enabled |
| 44 |
* |
| 45 |
* @param array<int, mixed> $forms |
| 46 |
* @return array<int, mixed> |
| 47 |
*/ |
| 48 |
private static function filterFormsWithIntegration(array $forms, string $integration): array |
| 49 |
{ |
| 50 |
return array_filter($forms, function ($form) use ($integration) { |
| 51 |
if (method_exists($form, 'getIntegrationSettings')) { |
| 52 |
$integrationSettings = $form->getIntegrationSettings(); |
| 53 |
return $integrationSettings->isIntegrationEnabled($integration) |
| 54 |
|| empty($integrationSettings->toArray()); |
| 55 |
} |
| 56 |
return false; |
| 57 |
}); |
| 58 |
} |
| 59 |
|
| 60 |
/** |
| 61 |
* Check if a specific integration is enabled in settings |
| 62 |
* |
| 63 |
* @param self $instance |
| 64 |
* @param string $integration |
| 65 |
* @return bool |
| 66 |
*/ |
| 67 |
private static function checkIntegrationEnabled(self $instance, string $integration): bool |
| 68 |
{ |
| 69 |
$integrations = $instance->settingsService->getCategorySettings('integrations'); |
| 70 |
return !empty($integrations[$integration]['enabled']) && $integrations[$integration]['enabled'] === true; |
| 71 |
} |
| 72 |
} |
| 73 |
|