85 lines
2.2 KiB
PHP
85 lines
2.2 KiB
PHP
<?php
|
|
/**
|
|
* @package ogre-consent
|
|
* @author cleverogre
|
|
* @copyright 2026 CleverOgre
|
|
* @license GLP-3.0-or-later
|
|
* @version 0.0.0
|
|
* @since 0.0.0
|
|
*/
|
|
|
|
namespace Ogre\Consent;
|
|
|
|
use Ogre\Consent as Plugin;
|
|
use Ogre\Singleton;
|
|
use WP_HTML_Tag_Processor;
|
|
|
|
defined('ABSPATH') || exit;
|
|
|
|
final class Script {
|
|
use Singleton;
|
|
|
|
private const HANDLE = 'klaro';
|
|
private const CONFIG = 'klaroConfig';
|
|
|
|
protected function __construct() {
|
|
add_action('wp_enqueue_scripts', [$this, 'wp_enqueue_scripts']);
|
|
add_filter('script_loader_tag', [$this, 'script_loader_tag'], 99, 3);
|
|
}
|
|
|
|
public function wp_enqueue_scripts(): void
|
|
{
|
|
// Check user role
|
|
if (is_user_logged_in() && empty(array_intersect((array) wp_get_current_user()->roles, Settings::instance()->get_enabled_user_roles()))) return;
|
|
|
|
wp_enqueue_script(
|
|
self::HANDLE,
|
|
Plugin::get_url('assets/klaro.js'),
|
|
ver: Plugin::get_version()
|
|
);
|
|
|
|
wp_enqueue_style(
|
|
self::HANDLE,
|
|
Plugin::get_url('assets/klaro.min.css'),
|
|
ver: Plugin::get_version()
|
|
);
|
|
|
|
wp_enqueue_style(
|
|
Plugin::get_id(),
|
|
Plugin::get_url('assets/style.css'),
|
|
deps: [
|
|
self::HANDLE
|
|
],
|
|
ver: Plugin::get_version()
|
|
);
|
|
}
|
|
|
|
private function get_config_tag(): string
|
|
{
|
|
return sprintf(
|
|
'<script id="%s-config" type="application/javascript">window.%s = %s;</script>',
|
|
esc_attr(self::HANDLE),
|
|
esc_js(self::CONFIG),
|
|
wp_json_encode(Config::instance()->get_config())
|
|
);
|
|
}
|
|
|
|
public function script_loader_tag(string $tag, string $handle, string $src): string
|
|
{
|
|
if ($handle !== self::HANDLE) return $tag;
|
|
$tags = new WP_HTML_Tag_Processor($tag);
|
|
if ($tags->next_tag('script')) {
|
|
$tags->set_attribute('data-config', self::CONFIG);
|
|
if ((bool) apply_filters('ogre_consent_async', true)) {
|
|
$tags->set_attribute('async', true);
|
|
}
|
|
}
|
|
$tag = $tags->get_updated_html();
|
|
$tag = $this->get_config_tag() . $tag;
|
|
return $tag;
|
|
}
|
|
|
|
}
|
|
|
|
Script::instance();
|