HEX
Server: Apache/2.4.65 (Debian)
System: Linux 88f31f35b0b8 6.1.0-38-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.147-1 (2025-08-02) x86_64
User: www-data (33)
PHP: 8.2.29
Disabled: NONE
Upload Files
File: /var/www/html/wp-content/plugins/adnkronos/src/Stats/StatsReporter.php
<?php

namespace AdnKronos\Stats;

use AdnKronos\Api\AdnkApiClient;
use AdnKronos\Options\AccountOptions;
use AdnKronos\Psr\Log\LoggerInterface;

/**
 * Sends yesterday's per-category statistics to the AdnKronos API.
 * Hooked to the daily cron event (adki_add_cron_onceaday).
 */
class StatsReporter {

    /** @var AdnkApiClient */
    private $apiClient;

    /** @var StatsCollector */
    private $collector;

    /** @var AccountOptions */
    private $accountOptions;

    /** @var LoggerInterface */
    private $logger;

    public function __construct(
        AdnkApiClient $apiClient,
        StatsCollector $collector,
        AccountOptions $accountOptions,
        LoggerInterface $logger
    ) {
        $this->apiClient      = $apiClient;
        $this->collector      = $collector;
        $this->accountOptions = $accountOptions;
        $this->logger         = $logger;
    }

    /**
     * Checks user consent and site verification, then sends stats.
     * Safe to call from cron or from admin action.
     */
    public function report() {
        if ($this->accountOptions->get('consent_send_statistical_data') !== 'on') {
            $this->logger->info('Stats reporting skipped: user has not consented');
            return;
        }

        $domain = get_home_url();

        if (!$this->apiClient->verifySite($domain)) {
            $this->logger->warning('Stats reporting skipped: site not verified');
            return;
        }

        $stats = $this->collector->collectYesterday();
        $date  = $this->collector->yesterdayString();

        foreach ($stats as $category => $counts) {
            $published = $counts['publish'];
            $imported  = $counts['publish'] + $counts['draft'];
            $this->apiClient->sendStats($domain, $category, $date, $published, $imported);
        }

        $this->logger->info('Stats reported for ' . $date . ' (' . count($stats) . ' categories)');
    }

}