PluginProbe
WooCommerce / 11.1.0-rc.2
WooCommerce v11.1.0-rc.2
11.1.0 11.1.0-rc.2 11.1.0-rc.1 11.1.0-beta.2 11.1.0-beta.1 11.0.1 11.0.0 11.0.0-rc.3 11.0.0-rc.2 11.0.0-rc.1 11.0.0-beta.2 11.0.0-beta.1 10.9.4 10.9.3 10.9.2 10.9.1 10.9.0 10.9.0-rc.1 10.9.0-beta.2 10.9.0-beta.1 10.8.1 10.8.0 10.8.0-rc.1 10.8.0-beta.2 10.8.0-beta.1 All 648 releases
woocommerce / src / Blocks / BlockPatterns.php
BlockPatterns.php
281 lines 8.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 declare(strict_types=1);
3
4 namespace Automattic\WooCommerce\Blocks;
5
6 use Automattic\WooCommerce\Blocks\Domain\Package;
7 use Automattic\WooCommerce\Blocks\Patterns\PatternRegistry;
8 use Automattic\WooCommerce\Blocks\Patterns\PTKPatternsStore;
9
10 /**
11 * Registers patterns under the `./patterns/` directory and from the PTK API and updates their content.
12 * Each pattern from core is defined as a PHP file and defines its metadata using plugin-style headers.
13 * The minimum required definition is:
14 *
15 * /**
16 * * Title: My Pattern
17 * * Slug: my-theme/my-pattern
18 * *
19 *
20 * The output of the PHP source corresponds to the content of the pattern, e.g.:
21 *
22 * <main><p><?php echo "Hello"; ?></p></main>
23 *
24 * Other settable fields include:
25 *
26 * - Description
27 * - Viewport Width
28 * - Categories (comma-separated values)
29 * - Keywords (comma-separated values)
30 * - Block Types (comma-separated values)
31 * - Inserter (yes/no)
32 *
33 * @internal
34 */
35 class BlockPatterns {
36 const CATEGORIES_PREFIXES = [ '_woo_', '_dotcom_imported_' ];
37
38 /**
39 * Path to the patterns' directory.
40 *
41 * @var string $patterns_path
42 */
43 private string $patterns_path;
44
45 /**
46 * PatternRegistry instance.
47 *
48 * @var PatternRegistry $pattern_registry
49 */
50 private PatternRegistry $pattern_registry;
51
52 /**
53 * PTKPatternsStore instance.
54 *
55 * @var PTKPatternsStore $ptk_patterns_store
56 */
57 private PTKPatternsStore $ptk_patterns_store;
58
59 /**
60 * Constructor for class
61 *
62 * @param Package $package An instance of Package.
63 * @param PatternRegistry $pattern_registry An instance of PatternRegistry.
64 * @param PTKPatternsStore $ptk_patterns_store An instance of PTKPatternsStore.
65 */
66 public function __construct(
67 Package $package,
68 PatternRegistry $pattern_registry,
69 PTKPatternsStore $ptk_patterns_store
70 ) {
71 $this->patterns_path = $package->get_path( 'patterns' );
72 $this->pattern_registry = $pattern_registry;
73 $this->ptk_patterns_store = $ptk_patterns_store;
74
75 add_action( 'init', array( $this, 'register_block_patterns' ) );
76 add_action( 'init', array( $this, 'register_ptk_patterns' ) );
77 }
78
79 /**
80 * Register block patterns from core.
81 *
82 * The pattern content is not loaded here. Instead, each pattern is registered
83 * with the absolute path to its source file (via the `filePath` property), so
84 * that core's `WP_Block_Patterns_Registry` loads (and caches) the content
85 * lazily, only when a pattern is actually requested. This avoids the cost of
86 * `include`-ing all pattern files on every request (e.g. front-end, REST,
87 * cron), where patterns are never consumed.
88 *
89 * @return void
90 */
91 public function register_block_patterns() {
92 if ( ! class_exists( 'WP_Block_Patterns_Registry' ) ) {
93 return;
94 }
95
96 $patterns = $this->get_block_patterns();
97 foreach ( $patterns as $pattern ) {
98 // The pattern list can come from a stale or malformed site transient, so make sure the source is a
99 // usable string before dereferencing it, to avoid a PHP warning when building the path.
100 if ( empty( $pattern['source'] ) || ! is_string( $pattern['source'] ) ) {
101 continue;
102 }
103
104 $pattern_path = $this->patterns_path . '/' . $pattern['source'];
105
106 // The pattern list can come from a stale cache, so confirm the file
107 // still exists before registering it with a `filePath`. Without
108 // inline content, core would otherwise emit an undefined-content
109 // warning when it tries to load a missing file on demand. This
110 // mirrors core's own `_register_theme_block_patterns()` guard.
111 if ( ! file_exists( $pattern_path ) ) {
112 continue;
113 }
114
115 $pattern['source'] = $pattern_path;
116 $pattern['filePath'] = $pattern_path;
117
118 $this->pattern_registry->register_block_pattern( $pattern_path, $pattern );
119 }
120 }
121
122 /**
123 * Gets block pattern data from the cache if available
124 *
125 * @return array Block pattern data.
126 */
127 private function get_block_patterns() {
128 $pattern_data = $this->get_pattern_cache();
129
130 if ( is_array( $pattern_data ) ) {
131 return $pattern_data;
132 }
133
134 $default_headers = array(
135 'title' => 'Title',
136 'slug' => 'Slug',
137 'description' => 'Description',
138 'viewportWidth' => 'Viewport Width',
139 'categories' => 'Categories',
140 'keywords' => 'Keywords',
141 'blockTypes' => 'Block Types',
142 'inserter' => 'Inserter',
143 'templateTypes' => 'Template Types',
144 );
145
146 if ( ! file_exists( $this->patterns_path ) ) {
147 return array();
148 }
149
150 $files = glob( $this->patterns_path . '/*.php' );
151 if ( ! $files ) {
152 return array();
153 }
154
155 $patterns = array();
156
157 foreach ( $files as $file ) {
158 $data = get_file_data( $file, $default_headers );
159 // We want to store the relative path in the cache, so we can use it later to register the pattern.
160 $data['source'] = str_replace( $this->patterns_path . '/', '', $file );
161 $patterns[] = $data;
162 }
163
164 $this->set_pattern_cache( $patterns );
165 return $patterns;
166 }
167
168 /**
169 * Gets block pattern cache.
170 *
171 * @return array|false Returns an array of patterns if cache is found, otherwise false.
172 */
173 private function get_pattern_cache() {
174 $pattern_data = get_site_transient( 'woocommerce_blocks_patterns' );
175
176 if ( is_array( $pattern_data ) && WOOCOMMERCE_VERSION === $pattern_data['version'] ) {
177 return $pattern_data['patterns'];
178 }
179
180 return false;
181 }
182
183 /**
184 * Sets block pattern cache.
185 *
186 * @param array $patterns Block patterns data to set in cache.
187 */
188 private function set_pattern_cache( array $patterns ) {
189 $pattern_data = array(
190 'version' => WOOCOMMERCE_VERSION,
191 'patterns' => $patterns,
192 );
193
194 set_site_transient( 'woocommerce_blocks_patterns', $pattern_data, MONTH_IN_SECONDS );
195 }
196
197 /**
198 * Register patterns from the Patterns Toolkit.
199 *
200 * @return void
201 */
202 public function register_ptk_patterns() {
203 // Only if the user has allowed tracking, we register the patterns from the PTK.
204 $allow_tracking = 'yes' === get_option( 'woocommerce_allow_tracking' );
205 if ( ! $allow_tracking ) {
206 return;
207 }
208
209 // The most efficient way to check for an existing action is to use `as_has_scheduled_action`, but in unusual
210 // cases where another plugin has loaded a very old version of Action Scheduler, it may not be available to us.
211 $has_scheduled_action = function_exists( 'as_has_scheduled_action' ) ? 'as_has_scheduled_action' : 'as_next_scheduled_action';
212
213 $patterns = $this->ptk_patterns_store->get_patterns();
214 if ( empty( $patterns ) || ! is_array( $patterns ) ) {
215 // Only log once per day by using a transient.
216 $transient_key = 'wc_ptk_pattern_store_warning';
217 // By only logging when patterns are empty and no fetch is scheduled,
218 // we ensure that warnings are only generated in genuinely problematic situations,
219 // such as when the pattern fetching mechanism has failed entirely.
220 if ( ! get_transient( $transient_key ) && ! call_user_func( $has_scheduled_action, 'fetch_patterns' ) ) {
221 wc_get_logger()->warning(
222 __( 'Empty patterns received from the PTK Pattern Store', 'woocommerce' ),
223 );
224 // Set the transient to true to indicate that the warning has been logged in the current day.
225 set_transient( $transient_key, true, DAY_IN_SECONDS );
226 }
227 return;
228 }
229
230 $patterns = $this->parse_categories( $patterns );
231
232 foreach ( $patterns as $pattern ) {
233 $pattern['slug'] = $pattern['name'];
234 $pattern['content'] = $pattern['html'];
235
236 $this->pattern_registry->register_block_pattern( $pattern['ID'], $pattern );
237 }
238 }
239
240 /**
241 * Parse prefixed categories from the PTK patterns into the actual WooCommerce categories.
242 *
243 * @param array $patterns The patterns to parse.
244 * @return array The parsed patterns.
245 */
246 private function parse_categories( array $patterns ) {
247 return array_map(
248 function ( $pattern ) {
249 if ( ! isset( $pattern['categories'] ) ) {
250 $pattern['categories'] = array();
251 }
252
253 $values = array_values( $pattern['categories'] );
254
255 foreach ( $values as $value ) {
256 if ( ! isset( $value['title'] ) || ! isset( $value['slug'] ) ) {
257 $pattern['categories'] = array();
258 }
259 }
260
261 $pattern['categories'] = array_map(
262 function ( $category ) {
263 foreach ( self::CATEGORIES_PREFIXES as $prefix ) {
264 if ( strpos( $category['title'], $prefix ) !== false ) {
265 $parsed_category = str_replace( $prefix, '', $category['title'] );
266 $parsed_category = str_replace( '_', ' ', $parsed_category );
267 $category['title'] = ucfirst( $parsed_category );
268 }
269 }
270
271 return $category;
272 },
273 $pattern['categories']
274 );
275 return $pattern;
276 },
277 $patterns
278 );
279 }
280 }
281