PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.6.1
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.6.1
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
wp-optimize / webp / class-wpo-webp-self-test.php

class-wpo-webp-self-test.php in WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance 4.6.1, at webp/class-wpo-webp-self-test.php

91 lines 2.0 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 if (!defined('ABSPATH')) die('No direct access allowed');
4
5 if (!class_exists('WPO_WebP_Self_Test')) :
6
7 class WPO_WebP_Self_Test {
8
9 /**
10 * Relative path to the test image used for WebP serving verification.
11 *
12 * @var string
13 */
14 const TEST_IMAGE_PATH = '/wpo/images/wpo_logo_small.png';
15
16 /**
17 * The MIME type for WebP images, used as the Accept header value
18 * and for content-type verification.
19 *
20 * @var string
21 */
22 const WEBP_MIME_TYPE = 'image/webp';
23
24 /**
25 * Determines whether the content-type header indicates a WebP image.
26 *
27 * @param array<string, string> $headers An array of response headers
28 *
29 * @return bool
30 */
31 private function has_webp_mime($headers): bool {
32 return isset($headers['content-type']) && 0 === strcasecmp(self::WEBP_MIME_TYPE, $headers['content-type']);
33 }
34
35 /**
36 * Determines whether the Vary header includes Accept.
37 *
38 * @param array<string, string> $headers An array of response headers
39 *
40 * @return bool
41 */
42 private function has_vary($headers): bool {
43 return isset($headers['vary']) && preg_match('/accept/i', $headers['vary']);
44 }
45
46 /**
47 * Determines whether a WebP version is served when requested with
48 * an appropriate Accept header.
49 *
50 * @return bool
51 */
52 public function is_webp_served(): bool {
53 $args = array(
54 'headers' => array(
55 'accept' => self::WEBP_MIME_TYPE
56 )
57 );
58
59 $upload_dir = wp_upload_dir();
60 $url = $upload_dir['baseurl'] . self::TEST_IMAGE_PATH;
61
62 $response = wp_remote_head($url, $args);
63
64 if (is_wp_error($response) || 200 !== $response['response']['code']) {
65 return false;
66 }
67
68 $headers = wp_remote_retrieve_headers($response);
69 if (is_object($headers) && method_exists($headers, 'getAll')) {
70 $headers = $headers->getAll();
71 return $this->has_webp_mime($headers) && $this->has_vary($headers);
72 }
73 return false;
74 }
75
76 /**
77 * Returns singleton instance
78 *
79 * @return WPO_WebP_Self_Test
80 */
81 public static function get_instance(): self {
82 static $_instance = null;
83 if (null === $_instance) {
84 $_instance = new self();
85 }
86 return $_instance;
87 }
88 }
89
90 endif;
91