File: /home/storage/5/78/dd/wicomm2/public_html/blackfriday/lib/PSI.php
<?php
require_once __DIR__.'/Utils.php';
class PSIClient {
private string $apiKey;
public function __construct() {
if (!defined('PSI_API_KEY') || PSI_API_KEY === '') {
throw new Exception('PSI_API_KEY não configurado em config/config.php');
}
$this->apiKey = PSI_API_KEY;
}
private function buildUrl(string $url, string $strategy='mobile'): string {
$base = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=$url";
$params = http_build_query([
'strategy' => $strategy,
'key' => $this->apiKey,
]);
$cats = ['performance','accessibility','best-practices','seo'];
$catsQuery = implode('&', array_map(fn($c) => 'category='.rawurlencode($c), $cats));
return $base.'?'.$params.'&'.$catsQuery;
}
public function run(string $url, string $strategy='mobile'): array {
$endpoint = $this->buildUrl($url, $strategy);
// Preferimos cURL
if (function_exists('curl_init')) {
$ch = curl_init($endpoint);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 120,
CURLOPT_HTTPHEADER => ['User-Agent: FridayUp/1.0 (+https://www.wicomm.com.br)']
]);
$res = curl_exec($ch);
if ($res === false) {
$err = curl_error($ch);
curl_close($ch);
throw new Exception('PSI request failed (cURL): '.$err);
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
$json = json_decode($res, true);
if ($code >= 300 || !$json) {
throw new Exception("PSI error HTTP $code: ".$res);
}
return $json;
}
// Fallback: file_get_contents (requer allow_url_fopen = On)
if (!filter_var(ini_get('allow_url_fopen'), FILTER_VALIDATE_BOOLEAN)) {
throw new Exception('Nenhum método HTTP disponível: cURL ausente e allow_url_fopen=Off');
}
$ctx = stream_context_create([
'http' => [
'method' => 'GET',
'timeout' => 60,
'header' => "User-Agent: FridayUp/1.0 (+https://www.wicomm.com.br)\r\n"
]
]);
$res = @file_get_contents($endpoint, false, $ctx);
if ($res === false) {
$err = error_get_last();
throw new Exception('PSI request failed (fopen): '.($err['message'] ?? 'unknown'));
}
$json = json_decode($res, true);
if (!$json) {
throw new Exception('PSI invalid JSON: '.$res);
}
return $json;
}
}