Subscriber.php
2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
<?php
namespace WP_Rocket\Engine\Optimization\GoogleFonts;
use WP_Rocket\Admin\Options_Data;
use WP_Rocket\Event_Management\Subscriber_Interface;
/**
* Combine Google Fonts subscriber
*
* @since 3.1
*/
class Subscriber implements Subscriber_Interface {
/**
* Plugin options.
*
* @var Options_Data
*/
private $options;
/**
* Combine instance.
*
* @var AbstractGFOptimization
*/
private $combine;
/**
* CombineV2 instance.
*
* @var AbstractGFOptimization
*/
private $combine_v2;
/**
* Instantiate the subscriber.
*
* @param AbstractGFOptimization $combine Combine instance.
* @param AbstractGFOptimization $combine_v2 Combine V2 instance.
* @param Options_Data $options Options_Data instance.
*/
public function __construct( AbstractGFOptimization $combine, AbstractGFOptimization $combine_v2, Options_Data $options ) {
$this->combine = $combine;
$this->combine_v2 = $combine_v2;
$this->options = $options;
}
/**
* Return an array of events that this subscriber wants to listen to.
*
* @since 3.1
*
* @return array
*/
public static function get_subscribed_events() {
return [
'wp_resource_hints' => [ 'preconnect', 10, 2 ],
'rocket_buffer' => [ 'process', 1001 ],
];
}
/**
* Adds google fonts URL to preconnect
*
* @since 3.5.3
*
* @param array $urls URLs to print for resource hints.
* @param string $relation_type The relation type the URLs are printed for, e.g. 'preconnect' or 'prerender'.
* @return array
*/
public function preconnect( array $urls, $relation_type ) {
if ( ! $this->is_allowed() ) {
return $urls;
}
if ( 'preconnect' !== $relation_type ) {
return $urls;
}
$urls[] = [
'href' => 'https://fonts.gstatic.com',
1 => 'crossorigin',
];
return $urls;
}
/**
* Processes the HTML to combine found Google fonts.
* Handles both Google Fonts API v2 and v1.
*
* @since 3.1
*
* @param string $html HTML content.
* @return string
*/
public function process( $html ) {
if ( ! $this->is_allowed() ) {
return $html;
}
// Combine Google Font API V2.
$html = $this->combine_v2->optimize( $html );
// Combine Google Font API V1.
$html = $this->combine->optimize( $html );
if ( ! $this->combine->has_google_fonts() && ! $this->combine_v2->has_google_fonts() ) {
$html = preg_replace( '/<link\s+(?:[^>]+[\s"\'])?href\s*=\s*[\'"]https:\/\/fonts\.gstatic\.com[\'"](?:[^>]+[\s"\'])?\s?\/?>/', '', $html );
}
return $html;
}
/**
* Checks if files can combine found Google fonts.
*
* @since 3.1
*/
protected function is_allowed() {
if ( rocket_bypass() ) {
return false;
}
return (bool) $this->options->get( 'minify_google_fonts', 0 );
}
}