PluginProbe
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO / 1.10.0
ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO v1.10.0
2.7.0 2.6.0 2.5.0 2.4.0 2.3.0 2.2.0 2.1.1 2.1.0 2.0.2 2.0.1 2.0.0 1.32.0 1.31.0 1.30.0 1.29.0 1.28.0 1.27.0 1.26.0 1.25.0 trunk 1.0.0 1.0.1 1.0.2 1.1.0 1.10.0 All 48 releases
thinkrank / includes / integrations / class-google-pagespeed-client.php

class-google-pagespeed-client.php in ThinkRank AI SEO – AI SEO Plugin for WordPress: Schema, XML Sitemaps, Meta Tags, Search Console & Local SEO 1.10.0, at includes/integrations/class-google-pagespeed-client.php

360 lines 14.1 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Google PageSpeed Insights Client Class
4 *
5 * Handles communication with Google PageSpeed Insights API for Core Web Vitals
6 * and performance data retrieval. Extends the base Google API client with
7 * PageSpeed-specific functionality and rate limiting.
8 *
9 * @package ThinkRank\Integrations
10 * @since 1.0.0
11 */
12
13 declare(strict_types=1);
14
15 namespace ThinkRank\Integrations;
16
17 // Prevent direct access
18 if (!defined('ABSPATH')) {
19 exit;
20 }
21
22 /**
23 * Google PageSpeed Insights Client Class
24 *
25 * Single Responsibility: Handle PageSpeed Insights API communication
26 * Following ThinkRank HTTP client patterns from Claude_Client and OpenAI_Client
27 *
28 * @since 1.0.0
29 */
30 class Google_PageSpeed_Client extends Google_API_Base_Client {
31
32 /**
33 * PageSpeed Insights API base URL
34 */
35 private const API_BASE_URL = 'https://www.googleapis.com/pagespeedonline/v5';
36
37 /**
38 * Rate limit transient key prefix
39 * Following ThinkRank option naming patterns
40 */
41 private const RATE_LIMIT_KEY = 'thinkrank_pagespeed_rate_limit';
42
43 /**
44 * Maximum requests per day (Google free tier limit)
45 */
46 private const MAX_REQUESTS_PER_DAY = 25000;
47
48 /**
49 * Run PageSpeed test for a URL
50 *
51 * @param string $url URL to test
52 * @param string $strategy Device strategy ('mobile' or 'desktop')
53 * @param array $categories Categories to test (default: ['performance'])
54 * @return array PageSpeed test results
55 * @throws \Exception If API request fails
56 */
57 public function run_pagespeed_test(string $url, string $strategy = 'mobile', array $categories = ['performance']): array {
58 $endpoint = '/runPagespeed';
59 $params = [
60 'url' => $url,
61 'strategy' => $strategy,
62 'category' => $categories,
63 ];
64
65 $full_url = self::API_BASE_URL . $endpoint;
66 return $this->make_request($full_url, $params, 'GET');
67 }
68
69 /**
70 * Test API connection
71 * Following ThinkRank test_connection patterns from AI clients
72 *
73 * @return array Connection test results
74 */
75 public function test_connection(): array {
76 try {
77 $test_url = home_url();
78 $result = $this->run_pagespeed_test($test_url, 'mobile', ['performance']);
79
80 $performance_score = 0;
81 if (isset($result['lighthouseResult']['categories']['performance']['score'])) {
82 $performance_score = $result['lighthouseResult']['categories']['performance']['score'] * 100;
83 }
84
85 return [
86 'success' => true,
87 'message' => 'PageSpeed Insights API connection successful',
88 'test_url' => $test_url,
89 'performance_score' => $performance_score
90 ];
91 } catch (\Exception $e) {
92 return [
93 'success' => false,
94 'error' => $e->getMessage()
95 ];
96 }
97 }
98
99 /**
100 * Get Core Web Vitals data for a URL
101 *
102 * @param string $url URL to analyze
103 * @param string $strategy Device strategy ('mobile' or 'desktop')
104 * @return array Core Web Vitals data
105 * @throws \Exception If API request fails
106 */
107 public function get_core_web_vitals(string $url, string $strategy = 'mobile'): array {
108 $result = $this->run_pagespeed_test($url, $strategy, ['performance']);
109 return $this->parse_core_web_vitals($result);
110 }
111
112 /**
113 * Get performance opportunities for a URL
114 *
115 * @param string $url URL to test
116 * @param string $strategy Testing strategy (mobile/desktop)
117 * @return array Performance opportunities
118 * @throws \Exception If API request fails
119 */
120 public function get_opportunities(string $url, string $strategy = 'mobile'): array {
121 $result = $this->run_pagespeed_test($url, $strategy, ['performance']);
122 return $this->parse_opportunities($result);
123 }
124
125 /**
126 * Get diagnostic information for a URL
127 *
128 * @param string $url URL to test
129 * @param string $strategy Testing strategy (mobile/desktop)
130 * @return array Diagnostic information
131 * @throws \Exception If API request fails
132 */
133 public function get_diagnostics(string $url, string $strategy = 'mobile'): array {
134 $result = $this->run_pagespeed_test($url, $strategy, ['performance']);
135 return $this->parse_diagnostics($result);
136 }
137
138 /**
139 * Parse Core Web Vitals from PageSpeed response
140 *
141 * @param array $pagespeed_data Raw PageSpeed API response
142 * @return array Parsed Core Web Vitals data
143 */
144 private function parse_core_web_vitals(array $pagespeed_data): array {
145 $audits = $pagespeed_data['lighthouseResult']['audits'] ?? [];
146
147 return [
148 'lcp' => [
149 'name' => 'Largest Contentful Paint',
150 'value' => round((($audits['largest-contentful-paint']['numericValue'] ?? 0) / 1000), 4),
151 'score' => ($audits['largest-contentful-paint']['score'] ?? 0) * 100,
152 'unit' => 's',
153 'good_threshold' => 2.5,
154 'needs_improvement_threshold' => 4.0,
155 'description' => 'Time until the largest content element is rendered'
156 ],
157 'fid' => [
158 'name' => 'First Input Delay',
159 'value' => round(($audits['max-potential-fid']['numericValue'] ?? 0), 4),
160 'score' => ($audits['max-potential-fid']['score'] ?? 0) * 100,
161 'unit' => 'ms',
162 'good_threshold' => 100,
163 'needs_improvement_threshold' => 300,
164 'description' => 'Time from first user interaction to browser response'
165 ],
166 'cls' => [
167 'name' => 'Cumulative Layout Shift',
168 'value' => round(($audits['cumulative-layout-shift']['numericValue'] ?? 0), 4),
169 'score' => ($audits['cumulative-layout-shift']['score'] ?? 0) * 100,
170 'unit' => '',
171 'good_threshold' => 0.1,
172 'needs_improvement_threshold' => 0.25,
173 'description' => 'Measure of visual stability during page load'
174 ],
175 'fcp' => [
176 'name' => 'First Contentful Paint',
177 'value' => round((($audits['first-contentful-paint']['numericValue'] ?? 0) / 1000), 4),
178 'score' => ($audits['first-contentful-paint']['score'] ?? 0) * 100,
179 'unit' => 's',
180 'good_threshold' => 1.8,
181 'needs_improvement_threshold' => 3.0,
182 'description' => 'Time until the first content is painted on screen'
183 ]
184 ];
185 }
186
187 /**
188 * Parse performance opportunities from PageSpeed data
189 *
190 * @param array $pagespeed_data Raw PageSpeed API response
191 * @return array Parsed opportunities data
192 */
193 private function parse_opportunities(array $pagespeed_data): array {
194 $audits = $pagespeed_data['lighthouseResult']['audits'] ?? [];
195 $opportunities = [];
196
197 // Define opportunity audits that provide savings estimates
198 $opportunity_audits = [
199 'render-blocking-resources' => 'Eliminate render-blocking resources',
200 'unused-css-rules' => 'Remove unused CSS',
201 'unused-javascript' => 'Remove unused JavaScript',
202 'modern-image-formats' => 'Serve images in next-gen formats',
203 'offscreen-images' => 'Defer offscreen images',
204 'unminified-css' => 'Minify CSS',
205 'unminified-javascript' => 'Minify JavaScript',
206 'efficient-animated-content' => 'Use video formats for animated content',
207 'duplicated-javascript' => 'Remove duplicate modules in JavaScript bundles',
208 'legacy-javascript' => 'Avoid serving legacy JavaScript to modern browsers'
209 ];
210
211 foreach ($opportunity_audits as $audit_id => $title) {
212 if (isset($audits[$audit_id]) && isset($audits[$audit_id]['details'])) {
213 $audit = $audits[$audit_id];
214 $savings = $audit['details']['overallSavingsMs'] ?? 0;
215
216 if ($savings > 0) {
217 $opportunities[] = [
218 'id' => $audit_id,
219 'title' => $title,
220 'description' => $audit['description'] ?? '',
221 'estimated_savings' => $savings,
222 'score' => ($audit['score'] ?? 0) * 100,
223 'details' => $audit['details'] ?? [],
224 'difficulty' => $this->get_difficulty_level($audit_id)
225 ];
226 }
227 }
228 }
229
230 // Sort by estimated savings (highest first)
231 usort($opportunities, function($a, $b) {
232 return $b['estimated_savings'] - $a['estimated_savings'];
233 });
234
235 return $opportunities;
236 }
237
238 /**
239 * Parse diagnostic information from PageSpeed data
240 *
241 * @param array $pagespeed_data Raw PageSpeed API response
242 * @return array Parsed diagnostics data
243 */
244 private function parse_diagnostics(array $pagespeed_data): array {
245 $audits = $pagespeed_data['lighthouseResult']['audits'] ?? [];
246 $diagnostics = [];
247
248 // Define diagnostic audits
249 $diagnostic_audits = [
250 'first-contentful-paint' => ['title' => 'First Contentful Paint', 'impact' => 'Performance'],
251 'largest-contentful-paint' => ['title' => 'Largest Contentful Paint', 'impact' => 'LCP'],
252 'first-meaningful-paint' => ['title' => 'First Meaningful Paint', 'impact' => 'Performance'],
253 'speed-index' => ['title' => 'Speed Index', 'impact' => 'Performance'],
254 'total-blocking-time' => ['title' => 'Total Blocking Time', 'impact' => 'Performance'],
255 'max-potential-fid' => ['title' => 'Max Potential First Input Delay', 'impact' => 'FID'],
256 'cumulative-layout-shift' => ['title' => 'Cumulative Layout Shift', 'impact' => 'CLS'],
257 'server-response-time' => ['title' => 'Initial server response time was short', 'impact' => 'Performance'],
258 'interactive' => ['title' => 'Time to Interactive', 'impact' => 'Performance'],
259 'user-timings' => ['title' => 'User Timing marks and measures', 'impact' => 'Performance'],
260 'critical-request-chains' => ['title' => 'Avoid chaining critical requests', 'impact' => 'Performance'],
261 'redirects' => ['title' => 'Avoid multiple page redirects', 'impact' => 'Performance'],
262 'installable-manifest' => ['title' => 'Web app manifest meets the installability requirements', 'impact' => 'PWA'],
263 'apple-touch-icon' => ['title' => 'Provides a valid apple-touch-icon', 'impact' => 'PWA'],
264 'splash-screen' => ['title' => 'Configured for a custom splash screen', 'impact' => 'PWA'],
265 'themed-omnibox' => ['title' => 'Sets a theme color for the address bar', 'impact' => 'PWA'],
266 'content-width' => ['title' => 'Content is sized correctly for the viewport', 'impact' => 'Mobile'],
267 'image-aspect-ratio' => ['title' => 'Displays images with correct aspect ratio', 'impact' => 'Layout'],
268 'image-size-responsive' => ['title' => 'Serves images with appropriate resolution', 'impact' => 'Performance'],
269 'preload-fonts' => ['title' => 'Fonts with font-display: optional are preloaded', 'impact' => 'Performance'],
270 'font-display' => ['title' => 'All text remains visible during webfont loads', 'impact' => 'Performance']
271 ];
272
273 foreach ($diagnostic_audits as $audit_id => $config) {
274 if (isset($audits[$audit_id])) {
275 $audit = $audits[$audit_id];
276 $score = $audit['score'] ?? null;
277
278 $status = 'info';
279 if ($score !== null) {
280 if ($score >= 0.9) {
281 $status = 'passed';
282 } elseif ($score >= 0.5) {
283 $status = 'warning';
284 } else {
285 $status = 'failed';
286 }
287 }
288
289 $diagnostics[] = [
290 'id' => $audit_id,
291 'title' => $config['title'],
292 'description' => $audit['description'] ?? '',
293 'status' => $status,
294 'score' => $score ? ($score * 100) : null,
295 'impact' => $config['impact'],
296 'details' => $audit['details'] ?? [],
297 'display_value' => $audit['displayValue'] ?? null
298 ];
299 }
300 }
301
302 return $diagnostics;
303 }
304
305 /**
306 * Get difficulty level for optimization opportunities
307 *
308 * @param string $audit_id Audit identifier
309 * @return string Difficulty level
310 */
311 private function get_difficulty_level(string $audit_id): string {
312 $difficulty_map = [
313 'unminified-css' => 'Easy',
314 'unminified-javascript' => 'Easy',
315 'modern-image-formats' => 'Easy',
316 'offscreen-images' => 'Medium',
317 'unused-css-rules' => 'Hard',
318 'unused-javascript' => 'Hard',
319 'render-blocking-resources' => 'Medium',
320 'efficient-animated-content' => 'Medium',
321 'duplicated-javascript' => 'Hard',
322 'legacy-javascript' => 'Medium'
323 ];
324
325 return $difficulty_map[$audit_id] ?? 'Medium';
326 }
327
328 /**
329 * Get rate limit configuration
330 * Following ThinkRank rate limiting patterns
331 *
332 * @return array Rate limit configuration
333 */
334 protected function get_rate_limits(): array {
335 return [
336 'max_requests_per_day' => self::MAX_REQUESTS_PER_DAY,
337 'reset_time' => get_transient(self::RATE_LIMIT_KEY . '_reset') ?: strtotime('tomorrow')
338 ];
339 }
340
341 /**
342 * Get rate limit transient key
343 * Following ThinkRank option naming patterns
344 *
345 * @return string Rate limit key
346 */
347 protected function get_rate_limit_key(): string {
348 return self::RATE_LIMIT_KEY;
349 }
350
351 /**
352 * Get rate limit error message
353 *
354 * @return string Error message
355 */
356 protected function get_rate_limit_error_message(): string {
357 return 'PageSpeed Insights API rate limit exceeded. Try again tomorrow.';
358 }
359 }
360