| @@ -1,0 +1,57 @@ | ||
| 1 | +<?php | |
| 2 | + | |
| 3 | +declare(strict_types=1); | |
| 4 | + | |
| 5 | +namespace Metricool\Controllers; | |
| 6 | + | |
| 7 | +if (!defined('ABSPATH')) { | |
| 8 | + exit; | |
| 9 | +} | |
| 10 | + | |
| 11 | +use Metricool\Traits\HasViews; | |
| 12 | +use Metricool\Services\TrackingScriptService; | |
| 13 | +use Metricool\Interfaces\ControllerInterface; | |
| 14 | +use Metricool\Support\Helpers\Storages\EnvironmentConfig; | |
| 15 | + | |
| 16 | +class TrackingScriptController implements ControllerInterface | |
| 17 | +{ | |
| 18 | + use HasViews; | |
| 19 | + | |
| 20 | + private EnvironmentConfig $env; | |
| 21 | + private TrackingScriptService $service; | |
| 22 | + | |
| 23 | + public function __construct(EnvironmentConfig $env, TrackingScriptService $service) | |
| 24 | + { | |
| 25 | + $this->env = $env; | |
| 26 | + $this->service = $service; | |
| 27 | + } | |
| 28 | + | |
| 29 | + public function register(): void | |
| 30 | + { | |
| 31 | + add_action('wp_footer', [$this, 'renderTrackingWidget']); | |
| 32 | + } | |
| 33 | + | |
| 34 | + public function renderTrackingWidget(): void | |
| 35 | + { | |
| 36 | + if ($this->canRenderTrackingScript() === false) { | |
| 37 | + return; | |
| 38 | + } | |
| 39 | + | |
| 40 | + $this->render('public/tracking-script', [ | |
| 41 | + 'script_url' => $this->env->getUrl('metricool.tracking_script_url'), | |
| 42 | + 'hash' => $this->service->getTrackingHash(), | |
| 43 | + ]); | |
| 44 | + } | |
| 45 | + | |
| 46 | + /** | |
| 47 | + * Checks if the tracking script can be rendered. Only if the tracking hash | |
| 48 | + * is set and the user has enabled the widget. | |
| 49 | + */ | |
| 50 | + private function canRenderTrackingScript(): bool | |
| 51 | + { | |
| 52 | + $outOfScope = (is_admin() || is_feed() || is_robots() || is_trackback()); | |
| 53 | + $trackingHashIsNotEmpty = (strlen($this->service->getTrackingHash()) > 0); | |
| 54 | + | |
| 55 | + return $trackingHashIsNotEmpty && $this->service->isTrackingWidgetActive() && ($outOfScope === false); | |
| 56 | + } | |
| 57 | +} | |