|null Null when the form is missing, not published or has no schema. */ public static function payload( int $formId ): ?array { if ( array_key_exists( $formId, self::$payloads ) ) { return self::$payloads[ $formId ]; } self::$payloads[ $formId ] = self::build( $formId ); return self::$payloads[ $formId ]; } /** * Whether the tag for a form was printed during this request. * * @param int $formId Form ID. * @return bool */ public static function printed( int $formId ): bool { return isset( self::$printed[ $formId ] ); } /** * @param int $formId Form ID. * @return array|null */ private static function build( int $formId ): ?array { try { $container = \SubtleForms\Plugin::instance()->container(); $repo = $container->get( \SubtleForms\Repositories\FormsRepository::class ); $form = $repo->find( $formId ); if ( ! is_array( $form ) || 'published' !== ( $form['status'] ?? '' ) ) { return null; } $api = new \SubtleForms\Api\FormsApi( $repo, $container->get( \SubtleForms\Repositories\SubmissionsRepository::class ), $container->get( \SubtleForms\Support\FeatureGate::class ), $container->has( \SubtleForms\Support\Settings::class ) ? $container->get( \SubtleForms\Support\Settings::class ) : null, $container->has( \SubtleForms\Support\Captcha\CaptchaManager::class ) ? $container->get( \SubtleForms\Support\Captcha\CaptchaManager::class ) : null ); return $api->publicPayload( $form ); } catch ( \Throwable $e ) { return null; } } /** * The script tag to print next to a form's container. * * Printed once per form per page: a second container for the same form * reads the first one's tag. * * @param int $formId Form ID. * @param array|null $payload Payload from payload(), when the caller has it. * @return string The tag, or '' when the data is not printed here. */ public static function tag( int $formId, ?array $payload = null ): string { if ( $formId <= 0 || ! self::enabled() || isset( self::$printed[ $formId ] ) ) { return ''; } $payload = $payload ?? self::payload( $formId ); if ( null === $payload ) { return ''; } // Escaped for a script element: no "<", "&", quote or apostrophe survives, // so no value can close the tag or start another one. $json = wp_json_encode( $payload, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT ); if ( ! is_string( $json ) || '' === $json ) { return ''; } self::$printed[ $formId ] = true; return sprintf( '', esc_attr( self::tagId( $formId ) ), $json ); } /** Test helper: forget what was printed. */ public static function resetForTests(): void { self::$printed = array(); self::$payloads = array(); } }