### Get Script to Localize Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Shows how to get the script handle to which the config data will be localized. ```php echo $config->script_to_localize(); // Output: "my-app" ``` -------------------------------- ### Get Config Data Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Shows how to instantiate a Config object and retrieve its parsed data, checking if the data was successfully retrieved. ```php $config = new MyConfig( $parser ); $data = $config->get_data(); if ( $data ) { // Use the data } ``` -------------------------------- ### Initialize Hooks and Filters Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-provider.md An example of implementing the `init` method to set up WordPress actions and filters. It shows how to retrieve a service from the container and hook its methods to specific WordPress events. ```php public function init( Service_Container $container ) { $my_service = $container->get( 'my_service' ); add_action( 'init', array( $my_service, 'on_init' ) ); add_filter( 'wp_rest_endpoints', array( $my_service, 'register_rest_endpoints' ) ); } ``` -------------------------------- ### Concrete Service Provider Usage Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-provider.md A complete example demonstrating how to create a concrete service provider by extending the abstract `Service_Provider` class. It includes implementing both `register` and `init` methods, and shows how to register the provider with a `Service_Container`. ```php namespace My_App; use Gravity_Forms Gravity_Tools Service_Container; use Gravity_Forms Gravity_Tools Service_Provider; class API_Service_Provider extends Service_Provider { public function register( Service_Container $container ) { $container->add( 'api_client', new API_Client() ); $container->add( 'api_validator', new API_Validator() ); } public function init( Service_Container $container ) { $api_client = $container->get( 'api_client' ); add_action( 'wp_loaded', function() use ( $api_client ) { $api_client->initialize(); } ); } } // Register the provider $container = new Service_Container(); $container->add_provider( new API_Service_Provider() ); ``` -------------------------------- ### Register Services Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-provider.md An example of how to implement the `register` method to add services to the service container. It demonstrates adding multiple services, including one that depends on another service retrieved from the container. ```php public function register( Service_Container $container ) { $container->add( 'my_service_1', new MyService1() ); $container->add( 'my_service_2', new MyService2() ); $cache = $container->get( 'cache' ); $container->add( 'my_service_3', new MyService3( $cache ) ); } ``` -------------------------------- ### Get Config Priority Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Demonstrates retrieving the priority of a config object, which determines its processing order. ```php $priority = $config->priority(); // e.g., 10 ``` -------------------------------- ### Asset Matching Patterns Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/asset-processor.md Shows example URL patterns used to identify and match JavaScript and CSS assets for processing. ```php 'js_match_pattern' => 'dist/js/' // Matches URLs like /dist/js/app.js 'css_match_pattern' => 'dist/css/' // Matches URLs like /dist/css/style.css ``` -------------------------------- ### Install Gravity Tools with Composer Source: https://github.com/gravityforms/gravity-tools/blob/master/README.md Use this command to install the Gravity Tools library via Composer. ```sh composer require gravityforms/gravity-tools ``` -------------------------------- ### Add and Get Service from Container Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Demonstrates how to add a service to the container and then retrieve it. This illustrates the Service Locator pattern. ```php $container->add( 'cache', new Cache() ); $cache = $container->get( 'cache' ); ``` -------------------------------- ### Basic Gravity Tools Service Container Usage Source: https://github.com/gravityforms/gravity-tools/blob/master/README.md This is a basic example demonstrating how to include the autoloader and instantiate the Service Container. ```php validate() ) { wp_send_json_error( array( 'message' => 'Validation failed' ) ); return; } // Process the request } ``` -------------------------------- ### Get Config Name Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Illustrates how to retrieve the unique name of a config object, which is used as the JavaScript object name. ```php echo $config->name(); // Output: "myConfig" ``` -------------------------------- ### Example handle Method Implementation Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/endpoint.md An example implementation of the handle method in a subclass. It calls a processing method and sends a JSON success or error response. ```php public function handle() { $result = $this->process_request(); if ( $result ) { wp_send_json_success( array( 'message' => 'Success' ) ); } else { wp_send_json_error( array( 'message' => 'Failed' ) ); } } ``` -------------------------------- ### Concrete Model Implementation Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/hermes-model.md Extend the abstract Model class to create a concrete model. This example demonstrates setting model properties like type, access capabilities, and defining fields, meta fields, relationships, and transformations. ```php namespace My_App; use Gravity_Forms\Gravity_Tools\Hermes\Models\Model; use Gravity_Forms\Gravity_Tools\Hermes\Utils\Relationship_Collection; class Entry_Model extends Model { protected $type = 'entry'; protected $access_cap_view = 'read_entries'; protected $access_cap_create = 'create_entries'; protected $access_cap_edit = 'edit_entries'; protected $access_cap_delete = 'delete_entries'; protected $supports_ad_hoc_fields = true; protected $searchable_fields = array( 'name', 'email' ); public function fields() { return array( 'id' => 'numeric', 'form_id' => 'numeric', 'user_id' => 'numeric', 'status' => 'text', 'timestamp' => 'text', ); } public function meta_fields() { return array( 'field_value' => 'text', ); } public function relationships() { $relationships = new Relationship_Collection(); $relationships->add( new Relationship( 'form', 'many_to_one', 'has_access' => true ) ); return $relationships; } public function transformations() { return array( 'format_date' => function( $value, $format ) { return date( $format, strtotime( $value ) ); }, ); } } ``` -------------------------------- ### GraphQL-like Query Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md An example of constructing a query string for the Hermes system, which uses a query builder pattern. This query fetches active entries by their ID and name. ```graphql $query = << array( 'version' => 'abc123' ), 'vendor.js' => array( 'version' => 'def456' ), ); $processor = new Asset_Processor( $js_map, $css_map, '/path/to/dist/js', '/path/to/dist/css', 'dist/js/', 'dist/css/', 'GF_SCRIPT_DEBUG' ); ``` -------------------------------- ### Example Config Class Implementation Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Demonstrates how to extend the Config abstract class, setting the 'should_enqueue' property to a callable for conditional enqueuing. ```php class MyConfig extends Config { protected $should_enqueue = true; // Always enqueue // OR use a callable: protected $should_enqueue; public function __construct( Config_Data_Parser $parser ) { parent::__construct( $parser ); $this->should_enqueue = function() { return current_user_can( 'manage_options' ); }; } protected function data() { return array( 'myData' => 'value' ); } } ``` -------------------------------- ### Implement a Service Provider Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Shows how to extend the base Service_Provider class to register and initialize services within the container. This is an example of the Provider pattern. ```php class MyProvider extends Service_Provider { public function register( Service_Container $container ) { // Register services } public function init( Service_Container $container ) { // Initialize hooks/filters } } ``` -------------------------------- ### Example get_nonce_name Method Implementation Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/endpoint.md An example implementation of get_nonce_name to specify a custom nonce name for validation. ```php protected function get_nonce_name() { return 'my_endpoint_nonce'; } ``` -------------------------------- ### Development Mode Constant Definition Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/asset-processor.md Provides an example of how to define a constant in `wp-config.php` to enable development mode for asset processing. ```php // In wp-config.php or theme config if ( $_ENV['WP_ENV'] === 'development' ) { define( 'GF_SCRIPT_DEBUG', true ); } ``` -------------------------------- ### Get Service from Container Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/INDEX.md Demonstrates how to retrieve a service instance from the service container using its identifier. ```php // This is how code is shown $service = $container->get( 'my_service' ); ``` -------------------------------- ### Abstract Data Method Implementation Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Example of implementing the abstract `data()` method in a subclass to define the raw configuration data. ```php protected function data() { return array( 'apiUrl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'my_action' ), 'userRole' => current_user_role(), ); } ``` -------------------------------- ### Check Overwrite Behavior Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Illustrates how to determine if a config should overwrite existing JavaScript data or merge with it. ```php if ( $config->should_overwrite() ) { // This config completely replaces the JavaScript object } else { // This config is merged with existing values } ``` -------------------------------- ### Concrete Endpoint Class Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/endpoint.md An example of a concrete endpoint class extending the base Endpoint class, defining required parameters, minimum capability, and implementing the handle method. ```php class Export_Endpoint extends Endpoint { protected $required_params = array( 'export_type', 'date_range' ); protected $minimum_cap = 'export_data'; protected function get_nonce_name() { return 'export_nonce'; } public function handle() { if ( ! $this->validate() ) { wp_send_json_error( array( 'message' => 'Invalid request or insufficient permissions' ) ); return; } $export_type = sanitize_text_field( $_REQUEST['export_type'] ); $date_range = sanitize_text_field( $_REQUEST['date_range'] ); try { $result = $this->export_data( $export_type, $date_range ); wp_send_json_success( array( 'data' => $result, 'message' => 'Export completed' ) ); } catch ( Exception $e ) { wp_send_json_error( array( 'message' => 'Export failed: ' . $e->getMessage() ) ); } } private function export_data( $type, $range ) { // Implementation } } ``` -------------------------------- ### CSV to Database Import Workflow Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md A complete workflow example demonstrating how to set up a CSV source, a database destination, and execute an import using the Import_Handler. ```php // 1. Create source and destination $csv_source = new CSV_Source(); $csv_source->set_data( file_get_contents( 'data.csv' ) ); $db_destination = new Database_Destination( $wpdb ); // 2. Create handler $handler = new Import_Handler( $csv_source, $db_destination ); // 3. Define mapping $mapping = array( 'First Name' => 'name', 'Email' => 'email', 'Phone' => 'phone', ); // 4. Execute import $handler->handle( $csv_content, $mapping ); ``` -------------------------------- ### Handling Data Imports Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Provides an example of setting up and executing a data import using the Import_Handler. It involves specifying source, destination, and a mapping array. ```php $handler = new Import_Handler( $csv_source, $db_destination ); $mapping = array( 'first_name' => 'name', 'email' => 'email', ); $handler->handle( $csv_content, $mapping ); ``` -------------------------------- ### Service Provider Usage Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/asset-processor.md Demonstrates a typical usage pattern within a WordPress plugin's service provider to load asset maps and initialize the Asset_Processor. ```php class Assets_Service_Provider extends Service_Provider { public function register( Service_Container $container ) { // Load maps from generated manifest files $js_map = require_once( '/path/to/dist/js-manifest.php' ); $css_map = require_once( '/path/to/dist/css-manifest.php' ); $processor = new Asset_Processor( $js_map, $css_map, plugin_dir_path( __FILE__ ) . 'dist/js', plugin_dir_path( __FILE__ ) . 'dist/css', 'dist/js/', 'dist/css/', 'MY_PLUGIN_SCRIPT_DEBUG' ); $container->add( 'asset_processor', $processor ); } public function init( Service_Container $container ) { $processor = $container->get( 'asset_processor' ); add_action( 'wp_enqueue_scripts', function() use ( $processor ) { $processor->process_assets(); }, 99 ); add_action( 'admin_enqueue_scripts', function() use ( $processor ) { $processor->process_assets(); }, 99 ); } } ``` -------------------------------- ### Cache Class Usage Examples Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/cache.md Demonstrates how to instantiate the Cache class and use its methods for temporary and persistent caching, including checking for cached values and flushing the cache. ```php $common = new Common( $manager_url, $support_url, $key ); $cache = new Cache( $common ); // Cache a value temporarily (in-memory, request-scoped) $cache->set( 'temp_data', $data, false ); $retrieved = $cache->get( 'temp_data' ); // Cache a value persistently $cache->set( 'user_settings', $settings, true, DAY_IN_SECONDS ); // Check if found in cache $found = null; $value = $cache->get( 'user_settings', $found ); if ( ! $found ) { // Fetch from elsewhere and cache $value = fetch_user_settings(); $cache->set( 'user_settings', $value, true, DAY_IN_SECONDS ); } // Clear all caches $cache->flush(); ``` -------------------------------- ### Registering an Endpoint Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/endpoint.md Example of how to register a concrete endpoint class with WordPress AJAX actions for both authenticated and non-authenticated users. ```php $endpoint = new Export_Endpoint(); // For both authenticated and non-authenticated users add_action( 'wp_ajax_export', array( $endpoint, 'handle' ) ); add_action( 'wp_ajax_nopriv_export', array( $endpoint, 'handle' ) ); // Note: validate() will block non-authenticated users via capability check ``` -------------------------------- ### Hash Map Format Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/asset-processor.md Illustrates the expected format for JavaScript and CSS manifest maps, including filename, version hash, and optional dependencies. ```php array( 'filename.js' => array( 'version' => 'abc123def456', // Hash or version string 'dependencies' => array(), // Optional ), ) ``` -------------------------------- ### Illustrate Priority Sorting of Configs Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/configuration.md Configs are processed in order of their priority, with lower values being processed first. This example shows how different priority settings affect the processing order. ```php $config1 = new Config1(); // priority = 0 $config2 = new Config2(); // priority = 10 $config3 = new Config3(); // priority = 5 // Processing order: config1 (0), config3 (5), config2 (10) ``` -------------------------------- ### get_plugins_info Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/gravity-api.md Get information about Gravity Forms core and add-on family. This method internally calls `get_version_info()` and extracts the 'offerings' key from the version information. ```APIDOC ## GET /version-info (Internal Call) ### Description Retrieves information about Gravity Forms core and its add-on family by calling `get_version_info()` internally and extracting the 'offerings' data. ### Method GET ### Endpoint /version-info ### Parameters None ### Response #### Success Response (200) - **array** - An array of plugin/offering information. #### Error Response - **false** - If offerings are not available. ``` -------------------------------- ### Retrieving a Service from the Container Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-container.md Shows how to retrieve a registered service by its name using the `get` method. If the service is deferred, it will be invoked and cached on the first retrieval. ```php $logger = $container->get( 'logger' ); if ( $logger ) { $logger->log_info( 'Service retrieved' ); } ``` -------------------------------- ### get Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-container.md Retrieves a service from the container by its registered name. If the service was registered as deferred, it is invoked and cached on first retrieval. ```APIDOC ## get ### Description Retrieves a service from the container by its registered name. If the service was registered as deferred, it is invoked and cached on first retrieval. ### Method `get( string $name ): mixed|null` ### Parameters #### Path Parameters - **name** (string) - Required - The service name. ### Returns `mixed|null` - The service instance, or null if the service does not exist in the container. ### Behavior - If the service was registered as a deferred callable, it is invoked on first retrieval and cached. - Subsequent retrievals return the cached instance. ### Example ```php $logger = $container->get( 'logger' ); if ( $logger ) { $logger->log_info( 'Service retrieved' ); } ``` ``` -------------------------------- ### Cache Methods Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/INDEX.md Methods for interacting with the caching system, including getting, setting, deleting, and flushing cache entries. ```php public function get( string $key, bool &$found = null, bool $is_persistent = true ): mixed|false|null public function set( string $key, mixed $data, bool $is_persistent = false, int $expiration_seconds = 0 ): bool public function delete( string $key ): bool public function flush( bool $flush_persistent = false ): bool ``` -------------------------------- ### Enqueue Scripts Action Example Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/asset-processor.md Shows how to hook the `process_assets` method to the `wp_enqueue_scripts` action to ensure assets are processed during WordPress script enqueuing. ```php add_action( 'wp_enqueue_scripts', function() { $processor->process_assets(); }, 99 ); ``` -------------------------------- ### Usage Pattern: Creating a Concrete Endpoint Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/endpoint.md Example demonstrating how to extend the abstract Endpoint class to create a functional AJAX endpoint with custom validation rules. ```APIDOC ## Usage Pattern Create a concrete endpoint by extending the class: ```php class Export_Endpoint extends Endpoint { protected $required_params = array( 'export_type', 'date_range' ); protected $minimum_cap = 'export_data'; protected function get_nonce_name() { return 'export_nonce'; } public function handle() { if ( ! $this->validate() ) { wp_send_json_error( array( 'message' => 'Invalid request or insufficient permissions' ) ); return; } $export_type = sanitize_text_field( $_REQUEST['export_type'] ); $date_range = sanitize_text_field( $_REQUEST['date_range'] ); try { $result = $this->export_data( $export_type, $date_range ); wp_send_json_success( array( 'data' => $result, 'message' => 'Export completed' ) ); } catch ( Exception $e ) { wp_send_json_error( array( 'message' => 'Export failed: ' . $e->getMessage() ) ); } } private function export_data( $type, $range ) { // Implementation } } ``` ``` -------------------------------- ### Custom API Source Implementation Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Implement a custom data source by extending the Source interface. This example shows how to create an API_Source that parses JSON data. ```php namespace My_App; use Gravity_Forms\Gravity_Tools\Data_Import\Source; use Gravity_Forms\Gravity_Tools\Data_Import\Record; class API_Source implements Source { private $data; private $records; public function set_data( $data ) { $this->data = $data; $this->records = null; // Reset cached records } public function keys( $args = array() ) { $sample = reset( $this->get_parsed_data() ); return $sample ? array_keys( $sample ) : array(); } public function has_key( $key ) { return in_array( $key, $this->keys() ); } public function records( $args = array() ) { $records = array(); foreach ( $this->get_parsed_data() as $data ) { $records[] = new Record( $data ); } return $records; } public function count( $args = array() ) { return count( $this->get_parsed_data() ); } public function slice( $count, $offset, $additional_args = array() ) { $data = array_slice( $this->get_parsed_data(), $offset, $count ); $records = array(); foreach ( $data as $item ) { $records[] = new Record( $item ); } return $records; } private function get_parsed_data() { return json_decode( $this->data, true ); } } ``` -------------------------------- ### Implement should_log Method Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/logger.md Abstract method that subclasses must implement to determine if logging is enabled for a given priority. This example enables logging only if `WP_DEBUG` is defined and true. ```php protected function should_log() { return defined( 'WP_DEBUG' ) && WP_DEBUG; } ``` -------------------------------- ### Get Gravity Forms Plugins Information Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/gravity-api.md Retrieves information about Gravity Forms core and its add-ons. Extracts 'offerings' data from version information. Returns false if offerings are unavailable. ```php $plugins = $api->get_plugins_info(); if ( $plugins ) { foreach ( $plugins as $plugin_slug => $plugin_data ) { echo $plugin_slug . ': ' . $plugin_data['version']; } } ``` -------------------------------- ### Implement delete_log Method Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/logger.md Abstract method that subclasses must implement to handle log deletion or rotation. This example shows deleting a log file using its path. ```php protected function delete_log() { // Delete the log file wp_delete_file( $this->log_file_path ); } ``` -------------------------------- ### Registering a Service Provider Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-container.md Demonstrates how to register a `Service_Provider` instance, which allows for organizing service registration and initialization within modules. The provider's `register` and `init` methods are called automatically. ```php class MyServiceProvider extends Service_Provider { public function register( Service_Container $container ) { $container->add( 'my_service', new MyService() ); } public function init( Service_Container $container ) { add_action( 'init', array( $this, 'on_init' ) ); } public function on_init() { // Initialize hooks } } $provider = new MyServiceProvider(); $container->add_provider( $provider ); ``` -------------------------------- ### Typical Application Bootstrap Usage Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-container.md Shows a common pattern for initializing the `Service_Container` at application bootstrap, registering individual services, and organizing services through providers. ```php $container = new Service_Container(); // Register individual services $container->add( 'cache', new Cache() ); // Or register services via providers $api_provider = new API_Service_Provider(); $container->add_provider( $api_provider ); // Retrieve services later $cache = $container->get( 'cache' ); ``` -------------------------------- ### Registering Services in Service Container Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-container.md Demonstrates how to register different types of services, including simple instances, named services, and deferred (lazy-loaded) services, using the `add` method. ```php $container = new Service_Container(); // Register a simple service $logger = new Logger(); $container->add( 'logger', $logger ); // Register a service with a name $container->add( 'app_cache', $cache_instance, false ); // Register a deferred service (lazy-loaded) $container->add( 'expensive_service', function() { return new ExpensiveService(); }, true ); ``` -------------------------------- ### Basic Service Container Usage Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Demonstrates how to create a service container, register custom service providers, and retrieve services. Requires the autoloader and specific Gravity Tools classes. ```php require 'vendor/autoload.php'; use Gravity_Forms\Gravity_Tools\Service_Container; use Gravity_Forms\Gravity_Tools\Service_Provider; // Create the container $container = new Service_Container(); // Register services via providers class MyServiceProvider extends Service_Provider { public function register( Service_Container $container ) { $container->add( 'my_service', new MyService() ); } public function init( Service_Container $container ) { add_action( 'init', function() use ( $container ) { $container->get( 'my_service' )->initialize(); } ); } } $container->add_provider( new MyServiceProvider() ); // Retrieve services $service = $container->get( 'my_service' ); ``` -------------------------------- ### lock_process Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/background-process.md Locks the process to prevent concurrent execution by setting the start time and creating a process lock. ```APIDOC ## lock_process ### Description Lock the process to prevent concurrent execution. ### Method `protected function lock_process(): void` ### Returns `void` ### Behavior - Sets `start_time` for time limit calculations. - Creates a process lock with current microtime. **Note:** Called automatically by `handle()`. ``` -------------------------------- ### Strategy Pattern for Logging Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Illustrates the Strategy pattern by using a File_Logging_Provider with a File_Logger. This allows for different logging implementations. ```php $provider = new File_Logging_Provider( '/var/log/app.log' ); $logger = new File_Logger( $provider ); ``` -------------------------------- ### Validation Methods Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/types.md Details the specific validation methods available for each field type, including their behavior and usage examples. ```APIDOC ## Validation Methods #### `validate_string( mixed $value ): string|null` Validates a string value. Returns null if not a string. ```php $validated = Field_Type_Validation_Enum::validate_string( 'hello' ); // Returns: "hello" $validated = Field_Type_Validation_Enum::validate_string( 123 ); // Returns: null ``` **Behavior:** - Checks `is_string()` - Adds slashes for database storage --- #### `validate_int( mixed $value ): int|null` Validates an integer value. Returns null if not numeric. ```php $validated = Field_Type_Validation_Enum::validate_int( '42' ); // Returns: 42 $validated = Field_Type_Validation_Enum::validate_int( 'text' ); // Returns: null ``` **Behavior:** - Checks `is_numeric()` - Casts to integer --- #### `validate_float( mixed $value ): float|null` Validates a float value. Returns null if not numeric. ```php $validated = Field_Type_Validation_Enum::validate_float( '3.14' ); // Returns: 3.14 $validated = Field_Type_Validation_Enum::validate_float( 'text' ); // Returns: null ``` **Behavior:** - Checks `is_numeric()` - Casts to float --- #### `validate_bool( mixed $value ): bool|null` Validates a boolean value using the Booliesh utility. ```php $validated = Field_Type_Validation_Enum::validate_bool( true ); // Returns: true $validated = Field_Type_Validation_Enum::validate_bool( 'yes' ); // Returns: true (Booliesh treats 'yes' as true) $validated = Field_Type_Validation_Enum::validate_bool( 'maybe' ); // Returns: null (invalid) ``` **Behavior:** - Uses Booliesh utility for flexible boolean interpretation - Returns true for truthy values: 1, '1', 'true', 'yes', true - Returns false for falsy values: 0, '0', 'false', 'no', false - Returns null for invalid values --- #### `validate_date( mixed $value ): string|null` Validates a date string using strtotime. Returns null if not a valid date. ```php $validated = Field_Type_Validation_Enum::validate_date( '2024-01-15' ); // Returns: "2024-01-15" $validated = Field_Type_Validation_Enum::validate_date( 'invalid' ); // Returns: null ``` **Behavior:** - Checks `is_string()` - Validates with `strtotime()` - Returns original string if valid --- #### `validate_object( mixed $value ): object|null` Validates an object value. Returns null if not an object. ```php $obj = new stdClass(); $validated = Field_Type_Validation_Enum::validate_object( $obj ); // Returns: $obj $validated = Field_Type_Validation_Enum::validate_object( array() ); // Returns: null ``` **Behavior:** - Checks `is_object()` - Returns the object as-is --- #### `validate_array( mixed $value ): array|null` Validates an array value. Returns null if not an array. ```php $validated = Field_Type_Validation_Enum::validate_array( array( 1, 2, 3 ) ); // Returns: [1, 2, 3] $validated = Field_Type_Validation_Enum::validate_array( 'not_array' ); // Returns: null ``` **Behavior:** - Checks `is_array()` - Returns the array as-is --- #### `validate_email( mixed $value ): string|null` Validates an email address. Returns null if invalid. ```php $validated = Field_Type_Validation_Enum::validate_email( 'user@example.com' ); // Returns: "user@example.com" $validated = Field_Type_Validation_Enum::validate_email( 'invalid-email' ); // Returns: null ``` **Behavior:** - Uses PHP `filter_var()` with `FILTER_VALIDATE_EMAIL` - Returns the email string if valid, null if invalid --- ### Generic Validation #### `validate( string|callable $type, mixed $value ): mixed` Generic validation method that dispatches to type-specific validators. ```php $validated = Field_Type_Validation_Enum::validate( Field_Type_Validation_Enum::STRING, 'hello' ); // Returns: "hello" ``` **Parameters:** - `$type` — Field type constant or callable - `$value` — Value to validate **Returns:** The validated value, or null if validation fails **Throws:** `InvalidArgumentException` if type is not recognized **Custom Type Validation:** You can use a callable as the type for custom validation: ```php $custom_validator = function( $value ) { return is_numeric( $value ) && $value > 0 ? (int) $value : null; }; $validated = Field_Type_Validation_Enum::validate( $custom_validator, '42' ); // Returns: 42 ``` ``` -------------------------------- ### Deferred Services for Testing Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Demonstrates how to add a service to the container with deferred loading enabled, which is useful for lazy initialization in testing scenarios. ```php // Use deferred services for lazy loading in tests $container->add( 'my_service', function() { return new My_Service(); }, true ); ``` -------------------------------- ### Get Destination Keys Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Retrieve the valid field names (keys) that a destination can accept. This is crucial for mapping data correctly. ```php $db_keys = $destination->keys(); // Returns: ['id', 'user_id', 'email', 'name'] ``` -------------------------------- ### Get License Status Message Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/types.md Retrieve a user-friendly message for a given license status code using License_Statuses::get_message_for_code(). ```php $message = License_Statuses::get_message_for_code( License_Statuses::VALID_KEY ); // Returns: "Your license key has been successfully validated." ``` -------------------------------- ### script_to_localize Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Get the ID of the script to localize the data to. This method returns the registered script handle to which the configuration data will be localized. ```APIDOC ## script_to_localize ### Description Get the ID of the script to localize the data to. This method returns the registered script handle to which the configuration data will be localized. ### Method ```php public function script_to_localize(): string ``` ### Returns `string` — The registered script handle. ### Example ```php echo $config->script_to_localize(); // Output: "my-app" ``` ``` -------------------------------- ### Register Current Site with License Key Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/gravity-api.md Registers the current site using a license key. Optionally specify if the key is already MD5 hashed. Stores site key and secret upon success. ```php $api = new Gravity_Api( $common, $model, 'gravityapi' ); $result = $api->register_current_site( 'my_license_key' ); if ( is_wp_error( $result ) ) { echo 'Registration failed: ' . $result->get_error_message(); } else { echo 'Site registered successfully'; } ``` -------------------------------- ### Background Processing Tasks Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Illustrates how to queue and dispatch background tasks using the Import_Background_Process class. Requires utility, logger, and cache instances. ```php $process = new Import_Background_Process( $utils, $logger, $cache ); foreach ( $tasks as $task ) { $process->push_to_queue( $task ); } $process->save()->dispatch(); ``` -------------------------------- ### Get a Slice of Records from CSV Source Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Retrieve a specific subset of records from the CSV source, useful for pagination or batch processing. ```php // Get records 10-20 $batch = $source->slice( 10, 10 ); ``` -------------------------------- ### Caching with Gravity Tools Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Shows how to use the Cache utility for both request-scoped in-memory caching and persistent cross-request caching. Requires a Common utility instance. ```php $cache = new Cache( $common ); // In-memory cache (request-scoped) $cache->set( 'temp_data', $data, false ); $cached = $cache->get( 'temp_data' ); // Persistent cache (cross-request) $cache->set( 'user_prefs', $prefs, true, DAY_IN_SECONDS ); ``` -------------------------------- ### Get CSV Source Keys Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Retrieve the available field names (keys) from a CSV source. This helps in understanding the structure of the data. ```php $csv_keys = $source->keys(); // Returns: ['name', 'email', 'phone'] ``` -------------------------------- ### Logging with Gravity Tools Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Illustrates basic logging operations using the Logger utility. Different levels like info, error, and debug can be used. ```php $logger->log_info( 'User login attempt' ); $logger->log_error( 'Database connection failed' ); $logger->log_debug( 'Debug information' ); ``` -------------------------------- ### Get Model Type Identifier Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/hermes-model.md Returns the string identifier for the model type, typically a lowercase version of the object type name. ```php echo $model->type(); // Output: "entry" ``` -------------------------------- ### name Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Get the object name for this config. This method returns the name of the configuration object, which is used as the JavaScript object name when localizing data. ```APIDOC ## name ### Description Get the object name for this config. This method returns the name of the configuration object, which is used as the JavaScript object name when localizing data. ### Method ```php public function name(): string ``` ### Returns `string` — The config's object name, used as the JavaScript object name when localizing. ### Example ```php echo $config->name(); // Output: "myConfig" ``` ``` -------------------------------- ### Execute Import with Mapping Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Run the import process using the Import_Handler. This method takes the data, a mapping array, and optional arguments for batching or specific record counts. ```php $handler = new Import_Handler( $csv_source, $db_destination ); $mapping = array( 'first_name' => 'name', 'email' => 'email', 'phone' => 'phone', ); // Import all records $handler->handle( $csv_content, $mapping ); // Import 100 records starting from position 0 (batch 1) $handler->handle( $csv_content, $mapping, array(), 100, 0 ); // Import 100 records starting from position 100 (batch 2) $handler->handle( $csv_content, $mapping, array(), 100, 100 ); ``` -------------------------------- ### Get Gravity API URL Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/gravity-api.md Returns the base Gravity API URL, ensuring it includes a trailing slash. This is the base endpoint for all API communications. ```php public function get_gravity_api_url(): string ``` ```php $url = $api->get_gravity_api_url(); // Output: "https://gravityapi.com/wp-json/gravityapi/v1/" ``` -------------------------------- ### Configure File Logging Provider Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/configuration.md Instantiate a File_Logging_Provider with a specified log file path and then create a File_Logger instance using this provider. This allows for logging application events to a dedicated file. ```php $file_provider = new File_Logging_Provider( '/var/log/gravityforms.log' ); $logger = new File_Logger( $file_provider ); $logger->log_info( 'Application started' ); ``` -------------------------------- ### check_license Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/gravity-api.md Check a license key and retrieve its information from the API. This method sends a GET request to the 'licenses/{key}/check' endpoint and caches the result. ```APIDOC ## GET /licenses/{key}/check ### Description Checks a given license key and retrieves its associated information from the Gravity API. This operation includes site URL and multisite status in the request and caches the result for 24 hours. ### Method GET ### Endpoint /licenses/{key}/check ### Parameters #### Path Parameters - **key** (string) - Required - The license key to check. ### Response #### Success Response (200) - **array** - An array containing license information. #### Error Response - **false** - If the license is invalid. - **WP_Error** - On other API errors. ``` -------------------------------- ### Get Record Value by Key Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Retrieve the value associated with a specific key from a single record object. Used for accessing individual data points. ```php $record = $records[0]; $email = $record->value_for_key( 'email' ); ``` -------------------------------- ### Count Records in CSV Source Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Get the total number of records available in the CSV source. Useful for progress tracking or determining if data exists. ```php $total = $source->count(); ``` -------------------------------- ### Set CSV Source Data Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/data-import-system.md Instantiate a CSV source and set its data from a file. This is the initial step to prepare data for import. ```php $source = new CSV_Source(); $source->set_data( file_get_contents( 'data.csv' ) ); ``` -------------------------------- ### Get Custom Table Name Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/hermes-model.md Returns a custom table name for the model, overriding the default naming convention. If false, standard naming is used. ```php public function forced_table_name() { return 'custom_entries_table'; // Or false for standard naming } ``` -------------------------------- ### Create a Custom Background Process Class Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/background-process.md Define a new class extending `Background_Process` to handle specific background tasks. Implement the `task` method for individual item processing and `complete` for post-process actions. Usage involves instantiating the class, queuing items, and dispatching the process. ```php class Import_Background_Process extends Background_Process { protected $action = 'gf_import_process'; public function __construct( Common $utils, Logger $logger, Cache $cache ) { parent::__construct( $utils, $logger, $cache ); } protected function task( $item ) { $this->logger->log_debug( 'Importing entry: ' . $item['entry_id'] ); try { $entry_data = $this->import_entry( $item['entry_id'] ); $this->logger->log_info( 'Entry imported successfully' ); return false; // Task complete } catch ( Exception $e ) { $this->logger->log_error( 'Import failed: ' . $e->getMessage() ); return $item; // Retry later } } protected function complete() { parent::complete(); $this->logger->log_info( 'Import process complete' ); } } // Usage: $process = new Import_Background_Process( $utils, $logger, $cache ); // Queue tasks foreach ( $entries as $entry ) { $process->push_to_queue( array( 'entry_id' => $entry['id'] ) ); } // Start processing $process->save()->dispatch(); ``` -------------------------------- ### priority Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Get the priority of this config. This method returns the priority value, which determines the order in which configurations are processed. Lower values indicate higher priority. ```APIDOC ## priority ### Description Get the priority of this config. This method returns the priority value, which determines the order in which configurations are processed. Lower values indicate higher priority. ### Method ```php public function priority(): int ``` ### Returns `int` — The priority value. Configs are sorted by priority in ascending order. ### Example ```php $priority = $config->priority(); // e.g., 10 ``` ``` -------------------------------- ### Mocking Providers for Testing Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Shows how to add a mock provider to the service container for testing purposes. This allows isolating components and controlling their behavior during tests. ```php // Mock providers for testing $mock_provider = new Mock_Provider(); $container->add_provider( $mock_provider ); ``` -------------------------------- ### Executing Hermes GraphQL-like Queries Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/README.md Demonstrates how to define and execute a query using the Hermes system's query handler. The query is defined using a HEREDOC syntax. ```php $query = <<handle_query( $query, true ); ``` -------------------------------- ### JavaScript AJAX Request with Nonce Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/endpoint.md Example of making an AJAX POST request from JavaScript, including the nonce value obtained from a hidden input field. ```javascript // In JavaScript const nonce = document.querySelector('input[name="_wpnonce"]').value; fetch(ajaxurl, { method: 'POST', body: new FormData({ action: 'export', security: nonce, export_type: 'csv', date_range: 'month' }) }) .then(response => response.json()) .then(data => { if ( data.success ) { console.log('Export successful:', data.data); } else { console.error('Export failed:', data.data.message); } }); ``` -------------------------------- ### Get Site Secret Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/gravity-api.md Retrieves the stored site secret, checking the GRAVITY_API_SITE_SECRET constant first, then the 'gf_site_secret' option. Returns the secret as a string or false if not set. ```php public function get_site_secret(): string|false ``` ```php $secret = $api->get_site_secret(); ``` -------------------------------- ### add Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/service-container.md Registers a service in the container. Services can be registered directly or deferred for lazy initialization. ```APIDOC ## add ### Description Registers a service in the container. Services can be registered directly or deferred for lazy initialization. ### Method `add( string $name, mixed $service, bool $defer = false ): void` ### Parameters #### Path Parameters - **name** (string) - Required - The service name. If empty, the class name of the service is used as the name. - **service** (mixed) - Required - The service instance or callable that returns the service. - **defer** (bool) - Optional - If true, the service is stored as-is. If false and the service is callable, it is invoked immediately and the result is stored. Defaults to `false`. ### Returns `void` ### Behavior - If `$defer` is false and `$service` is callable, the service is invoked immediately and the result replaces the callable. - If `$defer` is true, a callable service is stored as-is and will be invoked on first retrieval via `get()`. - If no `$name` is provided, the fully qualified class name of the service object is used. ### Example ```php $container = new Service_Container(); // Register a simple service $logger = new Logger(); $container->add( 'logger', $logger ); // Register a service with a name $container->add( 'app_cache', $cache_instance, false ); // Register a deferred service (lazy-loaded) $container->add( 'expensive_service', function() { return new ExpensiveService(); }, true ); ``` ``` -------------------------------- ### Get Site Key Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/gravity-api.md Retrieves the stored site key, checking the GRAVITY_API_SITE_KEY constant first, then the 'gf_site_key' option. Returns the key as a string or false if not set. ```php public function get_site_key(): string|false ``` ```php $key = $api->get_site_key(); ``` -------------------------------- ### get_data Source: https://github.com/gravityforms/gravity-tools/blob/master/_autodocs/api-reference/config.md Get the parsed data for this config, applying filters. This method retrieves and processes the configuration data, returning it in an array format or false if the config should not be enqueued. ```APIDOC ## get_data ### Description Get the parsed data for this config, applying filters. This method retrieves and processes the configuration data, returning it in an array format or false if the config should not be enqueued. ### Method ```php public function get_data(): array|false ``` ### Returns `array|false` — The parsed data, or false if the config should not be enqueued. ### Behavior - Returns false immediately if `should_enqueue()` returns false (unless in mock mode). - Applies the `gform_config_data_{$name}` filter to allow modification of raw data before parsing. - Passes the filtered data through the Config_Data_Parser. - Returns the parsed result. ### Filter `gform_config_data_{$name}` — Allows modification of raw config data before parsing. Receives the data array and script ID. ### Example ```php $config = new MyConfig( $parser ); $data = $config->get_data(); if ( $data ) { // Use the data } ``` ```