# ivyforms/0.3.1/backend/src/Services/API/IvyFormsAPI.php

The Innovative Form Builder – IvyForms, version 0.3.1. 289 lines.

- Page: https://pluginprobe.com/plugins/ivyforms/0.3.1/code/backend/src/Services/API/IvyFormsAPI.php
- Raw: https://pluginprobe.com/plugins/ivyforms/0.3.1/raw/backend/src/Services/API/IvyFormsAPI.php
- Modified: 2025-09-04T07:37:14+00:00

Line numbers below start at 1. Link to a line or a range by appending a fragment to the
page URL, for example `https://pluginprobe.com/plugins/ivyforms/0.3.1/code/backend/src/Services/API/IvyFormsAPI.php#L10-L20`.

```php
<?php

namespace IvyForms\Services\API;

// phpcs:disable PSR1.Files.SideEffects
if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

use Exception;
use IvyForms\Factory\Form\FormFactory;
use IvyForms\Services\Confirmation\ConfirmationService;
use IvyForms\Services\Form\FormService;
use IvyForms\Services\Field\FieldService;
use IvyForms\Common\Exceptions\NotFoundException;
use IvyForms\Common\Exceptions\InvalidArgumentException;
use IvyForms\Common\Exceptions\QueryExecutionException;
use IvyForms\Common\Exceptions\ValidationException;
use IvyForms\Services\Translations\BackendStrings;
use WP_Error;

/**
 * Class IvyFormsAPI
 *
 * @package IvyForms\Services\API
 *
 * This class provides a singleton instance to interact with the IvyForms plugin.
 * It includes methods to manage forms and fields, including creating, updating,
 * deleting, and retrieving forms and fields.
 */
class IvyFormsAPI
{
    private static ?self $instance = null;
    private FormService $formService;
    private FieldService $fieldService;
    private ConfirmationService $confirmationService;

    private function __construct(
        FormService $formService,
        FieldService $fieldService,
        ConfirmationService $confirmationService
    ) {
        $this->formService = $formService;
        $this->fieldService = $fieldService;
        $this->confirmationService = $confirmationService;
    }

    /**
     * Protected method to handle errors uniformly across all API methods
     *
     * @param callable $callback The function to execute
     * @return mixed The result of the callback or WP_Error on failure
     */
    protected static function handleErrors(callable $callback)
    {
        try {
            return $callback();
        } catch (InvalidArgumentException $e) {
            return new WP_Error('invalid_argument', $e->getMessage(), ['status' => 400]);
        } catch (NotFoundException $e) {
            return new WP_Error('not_found', $e->getMessage(), ['status' => 404]);
        } catch (QueryExecutionException $e) {
            return new WP_Error('query_execution_error', $e->getMessage(), ['status' => 500]);
        } catch (ValidationException $e) {
            return new WP_Error('validation_error', $e->getMessage(), ['status' => 422]);
        } catch (Exception $e) {
            return new WP_Error('unknown_error', $e->getMessage(), ['status' => 500]);
        }
    }

    /**
     * Check if IvyForms plugin is installed and activated
     *
     * @return bool
     */
    public static function isPluginActive(): bool
    {
        if (!function_exists('is_plugin_active')) {
            require_once ABSPATH . 'wp-admin/includes/plugin.php';
        }
        return is_plugin_active('ivyforms/ivyforms.php');
    }

    /**
     * Get instance with error handling
     *
     * @return self|WP_Error Returns an instance of IvyFormsAPI or WP_Error on failure
     */
    public static function getInstance()
    {
        if (self::$instance === null) {
            return self::handleErrors(function () {
                if (!self::isPluginActive()) {
                    throw new Exception(
                        BackendStrings::getExceptionStrings()['ivyforms_not_installed']
                    );
                }
                if (!file_exists(IVYFORMS_PATH . '/backend/vendor/autoload.php')) {
                    throw new Exception(
                        BackendStrings::getExceptionStrings()['autoload_not_found']
                    );
                }
                if (!file_exists(IVYFORMS_PATH . '/backend/src/Config/container.php')) {
                    throw new Exception(
                        BackendStrings::getExceptionStrings()['container_not_found']
                    );
                }

                require_once IVYFORMS_PATH . '/backend/vendor/autoload.php';
                $container = require IVYFORMS_PATH . '/backend/src/Config/container.php';

                $formService = $container->get(FormService::class);
                $fieldService = $container->get(FieldService::class);
                $confirmationService = $container->get(ConfirmationService::class);

                self::$instance = new self($formService, $fieldService, $confirmationService);
                return self::$instance;
            });
        }
        return self::$instance;
    }

    /**
     * Get a single form by ID
     *
     * @param int $formId
     * @return object|WP_Error
     */
    public static function getForm(int $formId)
    {
        return self::handleErrors(function () use ($formId) {
            if ($formId <= 0) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_id']
                );
            }
            return self::getInstance()->formService->getFormById($formId);
        });
    }

    /**
     * Get all forms
     *
     * @return mixed[] | WP_Error
     */
    public static function getForms()
    {
        return self::handleErrors(function () {
            return self::getInstance()->formService->getAllForms();
        });
    }

    /**
     * Create a new form
     *
     * @param mixed[] $formData
     * @return int|WP_Error
     */
    public static function createForm(array $formData)
    {
        return self::handleErrors(function () use ($formData) {
            if (empty($formData)) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_data']
                );
            }
            $formData = FormFactory::create($formData);
            return self::getInstance()->formService->createForm($formData);
        });
    }

    /**
     * Update an existing form
     *
     * @param int $formId
     * @param mixed[] $formData
     * @return bool|WP_Error
     */
    public static function updateForm(int $formId, array $formData)
    {
        return self::handleErrors(function () use ($formId, $formData) {
            if ($formId <= 0) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_id']
                );
            }
            if (empty($formData)) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_data']
                );
            }
            $formData = FormFactory::create($formData);
            return self::getInstance()->formService->updateForm($formId, $formData);
        });
    }

    /**
     * Delete a form
     *
     * @param int $formId
     * @return bool | WP_Error
     */
    public static function deleteForm(int $formId)
    {
        return self::handleErrors(function () use ($formId) {
            if ($formId <= 0) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_id']
                );
            }
            self::getInstance()->formService->deleteForm($formId);
            self::getInstance()->fieldService->deleteFieldsByFormId($formId);
            return true;
        });
    }

    /**
     * Check if a form exists
     *
     * @param int $formId
     * @return bool | WP_Error
     */
    public static function formExists(int $formId)
    {
        return self::handleErrors(function () use ($formId) {
            if ($formId <= 0) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_id']
                );
            }
            return self::getInstance()->formService->formExists($formId);
        });
    }

    /**
     * Get all fields for a form
     *
     * @param int $formId
     * @return mixed[] | WP_Error
     */
    public static function getFields(int $formId)
    {
        return self::handleErrors(function () use ($formId) {
            if ($formId <= 0) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_id']
                );
            }
            return self::getInstance()->fieldService->getAllFields($formId);
        });
    }

    /**
     * Delete fields by form ID
     *
     * @param int $formId
     * @return bool | WP_Error
     */
    public static function deleteFields(int $formId)
    {
        return self::handleErrors(function () use ($formId) {
            if ($formId <= 0) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_id']
                );
            }
            self::getInstance()->fieldService->deleteFieldsByFormId($formId);
            return true;
        });
    }
    /**
     * Get all fields for a form
     *
     * @param int $formId
     * @return mixed[] | WP_Error
     */
    public static function getConfirmations(int $formId)
    {
        return self::handleErrors(function () use ($formId) {
            if ($formId <= 0) {
                throw new InvalidArgumentException(
                    BackendStrings::getExceptionStrings()['invalid_form_id']
                );
            }
            return self::getInstance()->confirmationService->getConfirmationsById($formId);
        });
    }
}

```
