Completed
Pull Request — develop (#1679)
by Naveen
01:12
created
src/includes/cache/class-wordlift-cached-post-converter.php 2 patches
Indentation   +360 added lines, -360 removed lines patch added patch discarded remove patch
@@ -21,365 +21,365 @@
 block discarded – undo
21 21
  */
22 22
 class Wordlift_Cached_Post_Converter implements Wordlift_Post_Converter {
23 23
 
24
-	/**
25
-	 * A {@link Wordlift_Post_Converter} instance.
26
-	 *
27
-	 * @since 3.16.0
28
-	 *
29
-	 * @var \Wordlift_Post_Converter $converter A {@link Wordlift_Post_Converter} instance.
30
-	 */
31
-	private $converter;
32
-
33
-	/**
34
-	 * A {@link Wordlift_Log_Service} instance.
35
-	 *
36
-	 * @since 3.16.0
37
-	 *
38
-	 * @var Wordlift_Log_Service \$log A {@link Wordlift_Log_Service} instance.
39
-	 */
40
-	private $log;
41
-
42
-	/**
43
-	 * A list of meta keys that do not cause the cache to update.
44
-	 *
45
-	 * @since 3.17.3
46
-	 * @var array An array of ignored meta keys.
47
-	 */
48
-	private static $ignored_meta_keys = array(
49
-		'_edit_lock',
50
-		'_edit_last',
51
-		'_wp_page_template',
52
-		'_wp_attachment_is_custom_background',
53
-		'_wp_attachment_backup_sizes',
54
-		'_wp_attachment_is_custom_header',
55
-	);
56
-	/**
57
-	 * @var Ttl_Cache
58
-	 */
59
-	private $cache;
60
-
61
-	/**
62
-	 * Wordlift_Cached_Post_Converter constructor.
63
-	 *
64
-	 * @param \Wordlift_Post_Converter $converter The {@link Wordlift_Post_Converter} implementation.
65
-	 * @param Ttl_Cache                $cache The {@link Ttl_Cache} cache instance.
66
-	 */
67
-	public function __construct( $converter, $cache ) {
68
-
69
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
70
-
71
-		$this->cache     = $cache;
72
-		$this->converter = $converter;
73
-		$this->init_hooks();
74
-
75
-	}
76
-
77
-	/**
78
-	 * Hooks to catch post/post meta changes in order to invalidate the cache.
79
-	 *
80
-	 * @since 3.16.0
81
-	 */
82
-	private function init_hooks() {
83
-
84
-		// Hook on post save to flush relevant cache.
85
-		add_action( 'save_post', array( $this, 'save_post' ) );
86
-
87
-		add_action(
88
-			'added_post_meta',
89
-			array(
90
-				$this,
91
-				'changed_post_meta',
92
-			),
93
-			10,
94
-			3
95
-		);
96
-		add_action(
97
-			'updated_post_meta',
98
-			array(
99
-				$this,
100
-				'changed_post_meta',
101
-			),
102
-			10,
103
-			3
104
-		);
105
-		add_action(
106
-			'deleted_post_meta',
107
-			array(
108
-				$this,
109
-				'changed_post_meta',
110
-			),
111
-			10,
112
-			3
113
-		);
114
-
115
-		// Flush cache when wordlift settings were updated.
116
-		add_action(
117
-			'update_option_wl_general_settings',
118
-			array(
119
-				$this,
120
-				'update_option_wl_general_settings',
121
-			)
122
-		);
123
-
124
-		// Flushes the cache when permalink structure is changed.
125
-		add_action(
126
-			'update_option_permalink_structure',
127
-			array(
128
-				$this,
129
-				'permalinks_structure_changed',
130
-			)
131
-		);
132
-
133
-		// Invalid cache on relationship change.
134
-		add_action( 'wl_relation_added', array( $this, 'relation_changed' ) );
135
-		add_action( 'wl_relation_deleted', array( $this, 'relation_changed' ) );
136
-
137
-	}
138
-
139
-	/**
140
-	 * Note that the `&$cache` parameter here is used only to report whether the response comes from the cache. It
141
-	 * used by `test-issue-626.php` and nowhere else in code.
142
-	 *
143
-	 * @inheritdoc
144
-	 */
145
-	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
146
-	public function convert( $post_id, &$references = array(), &$references_infos = array(), $relations = null, &$cache = false ) {
147
-
148
-		// Ensure post ID is `int`. Otherwise we may have issues with caching, since caching is strict about
149
-		// key var types.
150
-		$post_id = (int) $post_id;
151
-
152
-		$this->log->trace( "Converting post $post_id..." );
153
-
154
-		// Try to get a cached result.
155
-		$arr = $this->get_cache( $post_id );
156
-
157
-		// Return the cached contents if any.
158
-		if ( false !== $arr ) {
159
-			$contents = $arr['jsonld'];
160
-
161
-			// Add the cached relations if any.
162
-			if ( is_a( $arr['relations'], 'Wordlift\Relation\Relations' ) ) {
163
-				$relations->add( ...$arr['relations']->toArray() );
164
-			}
165
-
166
-			if ( is_array( $arr['references'] ) ) {
167
-				$references = $arr['references'];
168
-			}
169
-
170
-			$this->log->debug( "Cached contents found for post $post_id." );
171
-
172
-			// Inform the caller that this is cached result.
173
-			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
174
-			$cache = true;
175
-			$this->add_http_header( $post_id, true );
176
-
177
-			// Return the contents.
178
-			return $contents;
179
-		}
180
-
181
-		// Set cached to false.
182
-		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
183
-		$cache = false;
184
-		$this->add_http_header( $post_id, false );
185
-
186
-		// Convert the post.
187
-		$jsonld = $this->converter->convert( $post_id, $references, $references_infos, $relations );
188
-
189
-		/**
190
-		 * @since 3.32.0
191
-		 * We cant apply json_encode on the objects {@link \Wordlift\Jsonld\Reference}, so we decode
192
-		 * it here before saving it on cache.
193
-		 */
194
-		// Cache the results.
195
-		$this->set_cache( $post_id, $references, $jsonld, $relations );
196
-
197
-		// Finally return the JSON-LD.
198
-		return $jsonld;
199
-	}
200
-
201
-	/**
202
-	 * Try to get the cached contents.
203
-	 *
204
-	 * @param int $post_id The {@link WP_Post} id.
205
-	 * @param array $references The referenced posts.
206
-	 *
207
-	 * @return mixed|bool The cached contents or false if the cached isn't found.
208
-	 * @since 3.16.0
209
-	 */
210
-	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
211
-	private function get_cache( $post_id ) {
212
-
213
-		// Ensure post ID is int, because cache is strict about var types.
214
-		$post_id = (int) $post_id;
215
-
216
-		$this->log->trace( "Getting cached contents for post $post_id..." );
217
-
218
-		// Get the cache.
219
-		$modified_date_time = get_post_datetime( $post_id, 'modified', 'gmt' );
220
-		$contents           = $this->cache->get( $post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0 );
221
-
222
-		// Bail out if we don't have cached contents or the cached contents are
223
-		// invalid.
224
-		if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) || ! isset( $contents['relations'] ) ) {
225
-			$this->log->debug( "Cached contents for post $post_id not found." );
226
-
227
-			return false;
228
-		}
229
-
230
-		return $contents['jsonld']
231
-			? array(
232
-				'jsonld'     => $contents['jsonld'],
233
-				'relations'  => Relations::from_json( $contents['relations'] ),
234
-				'references' => $contents['references'],
235
-			)
236
-			: false;
237
-	}
238
-
239
-	/**
240
-	 * Set the cache with the provided results.
241
-	 *
242
-	 * The function will prepare the provided results and will ask the {@link Ttl_Cache} to cache them.
243
-	 *
244
-	 * @param int   $post_id The {@link WP_Post} id.
245
-	 * @param array $references An array of references.
246
-	 * @param array $jsonld A JSON-LD structure.
247
-	 *
248
-	 * @since 3.16.0
249
-	 */
250
-	private function set_cache( $post_id, $references, $jsonld, $relations ) {
251
-
252
-		$this->log->trace( "Caching result for post $post_id..." );
253
-
254
-		$this->cache->put(
255
-			$post_id,
256
-			array(
257
-				// @@todo check the `references`.
258
-				'references' => $references,
259
-				'jsonld'     => $jsonld,
260
-				'relations'  => $relations,
261
-			)
262
-		);
263
-
264
-	}
265
-
266
-	/**
267
-	 * Hook to 'save_post', will invalidate the cache for that post.
268
-	 *
269
-	 * @param int $post_id The {@link WP_Post} id.
270
-	 *
271
-	 * @since 3.16.0
272
-	 */
273
-	public function save_post( $post_id ) {
274
-
275
-		$this->log->trace( "Post $post_id saved, invalidating cache..." );
276
-
277
-		$this->cache->delete( $post_id );
278
-
279
-		$this->flush_cache_if_publisher( $post_id );
280
-
281
-	}
282
-
283
-	/**
284
-	 * Hook to meta changed for a {@link WP_Post}, will cause the cause to
285
-	 * invalidate.
286
-	 *
287
-	 * @param int    $id The {@link WP_Post} meta id.
288
-	 * @param int    $post_id The {@link WP_Post} id.
289
-	 * @param string $meta_key The meta key.
290
-	 *
291
-	 * @since 3.16.0
292
-	 */
293
-	public function changed_post_meta( $id, $post_id, $meta_key ) {
294
-
295
-		if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
296
-			$this->log->trace( "Post $post_id meta $meta_key ignored." );
297
-
298
-			return;
299
-		}
300
-
301
-		$this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
302
-
303
-		// Delete the single cache file.
304
-		$this->cache->delete( $post_id );
305
-
306
-		// Flush the cache if it's the publisher.
307
-		$this->flush_cache_if_publisher( $post_id );
308
-
309
-	}
310
-
311
-	/**
312
-	 * Hook to WordLift's options changes, will flush the cache.
313
-	 *
314
-	 * @since 3.16.0
315
-	 */
316
-	public function update_option_wl_general_settings() {
317
-		$this->log->trace( 'WordLift options changed, flushing cache...' );
318
-
319
-		$this->cache->flush();
320
-	}
321
-
322
-	/**
323
-	 * Hook when permalinks are changed, will flush the cache.
324
-	 *
325
-	 * @since 3.17.0
326
-	 */
327
-	public function permalinks_structure_changed() {
328
-		$this->log->trace( 'Permalinks structure changed, flushing cache...' );
329
-
330
-		$this->cache->flush();
331
-	}
332
-
333
-	/**
334
-	 * Hook to WordLift's post/entity relation changes, will invalidate the cache.
335
-	 *
336
-	 * @param int $post_id The {@link WP_Post} id.
337
-	 *
338
-	 * @since 3.16.0
339
-	 */
340
-	public function relation_changed( $post_id ) {
341
-		$this->log->trace( "Post $post_id relations changed, invalidating cache..." );
342
-
343
-		$this->cache->delete( $post_id );
344
-	}
345
-
346
-	/**
347
-	 * When in Ajax, prints an http header with the information whether the
348
-	 * response is cached or not.
349
-	 *
350
-	 * @param int  $post_id The {@link WP_Post} id.
351
-	 * @param bool $cache Whether the response fragment is cached.
352
-	 *
353
-	 * @since 3.16.0
354
-	 */
355
-	private function add_http_header( $post_id, $cache ) {
356
-
357
-		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
358
-			return;
359
-		}
360
-
361
-		header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
362
-
363
-	}
364
-
365
-	/**
366
-	 * Call the `flush` operation on the {@link Ttl_Cache} if
367
-	 * the publisher has changed.
368
-	 *
369
-	 * @param int $post_id The changed {@link WP_Post}'s id.
370
-	 *
371
-	 * @since 3.16.0
372
-	 */
373
-	private function flush_cache_if_publisher( $post_id ) {
374
-
375
-		// Bail out if it's not the publisher.
376
-		if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
377
-			return;
378
-		}
379
-
380
-		// Flush the cache, since the publisher has changed.
381
-		$this->cache->flush();
382
-
383
-	}
24
+    /**
25
+     * A {@link Wordlift_Post_Converter} instance.
26
+     *
27
+     * @since 3.16.0
28
+     *
29
+     * @var \Wordlift_Post_Converter $converter A {@link Wordlift_Post_Converter} instance.
30
+     */
31
+    private $converter;
32
+
33
+    /**
34
+     * A {@link Wordlift_Log_Service} instance.
35
+     *
36
+     * @since 3.16.0
37
+     *
38
+     * @var Wordlift_Log_Service \$log A {@link Wordlift_Log_Service} instance.
39
+     */
40
+    private $log;
41
+
42
+    /**
43
+     * A list of meta keys that do not cause the cache to update.
44
+     *
45
+     * @since 3.17.3
46
+     * @var array An array of ignored meta keys.
47
+     */
48
+    private static $ignored_meta_keys = array(
49
+        '_edit_lock',
50
+        '_edit_last',
51
+        '_wp_page_template',
52
+        '_wp_attachment_is_custom_background',
53
+        '_wp_attachment_backup_sizes',
54
+        '_wp_attachment_is_custom_header',
55
+    );
56
+    /**
57
+     * @var Ttl_Cache
58
+     */
59
+    private $cache;
60
+
61
+    /**
62
+     * Wordlift_Cached_Post_Converter constructor.
63
+     *
64
+     * @param \Wordlift_Post_Converter $converter The {@link Wordlift_Post_Converter} implementation.
65
+     * @param Ttl_Cache                $cache The {@link Ttl_Cache} cache instance.
66
+     */
67
+    public function __construct( $converter, $cache ) {
68
+
69
+        $this->log = Wordlift_Log_Service::get_logger( get_class() );
70
+
71
+        $this->cache     = $cache;
72
+        $this->converter = $converter;
73
+        $this->init_hooks();
74
+
75
+    }
76
+
77
+    /**
78
+     * Hooks to catch post/post meta changes in order to invalidate the cache.
79
+     *
80
+     * @since 3.16.0
81
+     */
82
+    private function init_hooks() {
83
+
84
+        // Hook on post save to flush relevant cache.
85
+        add_action( 'save_post', array( $this, 'save_post' ) );
86
+
87
+        add_action(
88
+            'added_post_meta',
89
+            array(
90
+                $this,
91
+                'changed_post_meta',
92
+            ),
93
+            10,
94
+            3
95
+        );
96
+        add_action(
97
+            'updated_post_meta',
98
+            array(
99
+                $this,
100
+                'changed_post_meta',
101
+            ),
102
+            10,
103
+            3
104
+        );
105
+        add_action(
106
+            'deleted_post_meta',
107
+            array(
108
+                $this,
109
+                'changed_post_meta',
110
+            ),
111
+            10,
112
+            3
113
+        );
114
+
115
+        // Flush cache when wordlift settings were updated.
116
+        add_action(
117
+            'update_option_wl_general_settings',
118
+            array(
119
+                $this,
120
+                'update_option_wl_general_settings',
121
+            )
122
+        );
123
+
124
+        // Flushes the cache when permalink structure is changed.
125
+        add_action(
126
+            'update_option_permalink_structure',
127
+            array(
128
+                $this,
129
+                'permalinks_structure_changed',
130
+            )
131
+        );
132
+
133
+        // Invalid cache on relationship change.
134
+        add_action( 'wl_relation_added', array( $this, 'relation_changed' ) );
135
+        add_action( 'wl_relation_deleted', array( $this, 'relation_changed' ) );
136
+
137
+    }
138
+
139
+    /**
140
+     * Note that the `&$cache` parameter here is used only to report whether the response comes from the cache. It
141
+     * used by `test-issue-626.php` and nowhere else in code.
142
+     *
143
+     * @inheritdoc
144
+     */
145
+    // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
146
+    public function convert( $post_id, &$references = array(), &$references_infos = array(), $relations = null, &$cache = false ) {
147
+
148
+        // Ensure post ID is `int`. Otherwise we may have issues with caching, since caching is strict about
149
+        // key var types.
150
+        $post_id = (int) $post_id;
151
+
152
+        $this->log->trace( "Converting post $post_id..." );
153
+
154
+        // Try to get a cached result.
155
+        $arr = $this->get_cache( $post_id );
156
+
157
+        // Return the cached contents if any.
158
+        if ( false !== $arr ) {
159
+            $contents = $arr['jsonld'];
160
+
161
+            // Add the cached relations if any.
162
+            if ( is_a( $arr['relations'], 'Wordlift\Relation\Relations' ) ) {
163
+                $relations->add( ...$arr['relations']->toArray() );
164
+            }
165
+
166
+            if ( is_array( $arr['references'] ) ) {
167
+                $references = $arr['references'];
168
+            }
169
+
170
+            $this->log->debug( "Cached contents found for post $post_id." );
171
+
172
+            // Inform the caller that this is cached result.
173
+            // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
174
+            $cache = true;
175
+            $this->add_http_header( $post_id, true );
176
+
177
+            // Return the contents.
178
+            return $contents;
179
+        }
180
+
181
+        // Set cached to false.
182
+        // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
183
+        $cache = false;
184
+        $this->add_http_header( $post_id, false );
185
+
186
+        // Convert the post.
187
+        $jsonld = $this->converter->convert( $post_id, $references, $references_infos, $relations );
188
+
189
+        /**
190
+         * @since 3.32.0
191
+         * We cant apply json_encode on the objects {@link \Wordlift\Jsonld\Reference}, so we decode
192
+         * it here before saving it on cache.
193
+         */
194
+        // Cache the results.
195
+        $this->set_cache( $post_id, $references, $jsonld, $relations );
196
+
197
+        // Finally return the JSON-LD.
198
+        return $jsonld;
199
+    }
200
+
201
+    /**
202
+     * Try to get the cached contents.
203
+     *
204
+     * @param int $post_id The {@link WP_Post} id.
205
+     * @param array $references The referenced posts.
206
+     *
207
+     * @return mixed|bool The cached contents or false if the cached isn't found.
208
+     * @since 3.16.0
209
+     */
210
+    // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
211
+    private function get_cache( $post_id ) {
212
+
213
+        // Ensure post ID is int, because cache is strict about var types.
214
+        $post_id = (int) $post_id;
215
+
216
+        $this->log->trace( "Getting cached contents for post $post_id..." );
217
+
218
+        // Get the cache.
219
+        $modified_date_time = get_post_datetime( $post_id, 'modified', 'gmt' );
220
+        $contents           = $this->cache->get( $post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0 );
221
+
222
+        // Bail out if we don't have cached contents or the cached contents are
223
+        // invalid.
224
+        if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) || ! isset( $contents['relations'] ) ) {
225
+            $this->log->debug( "Cached contents for post $post_id not found." );
226
+
227
+            return false;
228
+        }
229
+
230
+        return $contents['jsonld']
231
+            ? array(
232
+                'jsonld'     => $contents['jsonld'],
233
+                'relations'  => Relations::from_json( $contents['relations'] ),
234
+                'references' => $contents['references'],
235
+            )
236
+            : false;
237
+    }
238
+
239
+    /**
240
+     * Set the cache with the provided results.
241
+     *
242
+     * The function will prepare the provided results and will ask the {@link Ttl_Cache} to cache them.
243
+     *
244
+     * @param int   $post_id The {@link WP_Post} id.
245
+     * @param array $references An array of references.
246
+     * @param array $jsonld A JSON-LD structure.
247
+     *
248
+     * @since 3.16.0
249
+     */
250
+    private function set_cache( $post_id, $references, $jsonld, $relations ) {
251
+
252
+        $this->log->trace( "Caching result for post $post_id..." );
253
+
254
+        $this->cache->put(
255
+            $post_id,
256
+            array(
257
+                // @@todo check the `references`.
258
+                'references' => $references,
259
+                'jsonld'     => $jsonld,
260
+                'relations'  => $relations,
261
+            )
262
+        );
263
+
264
+    }
265
+
266
+    /**
267
+     * Hook to 'save_post', will invalidate the cache for that post.
268
+     *
269
+     * @param int $post_id The {@link WP_Post} id.
270
+     *
271
+     * @since 3.16.0
272
+     */
273
+    public function save_post( $post_id ) {
274
+
275
+        $this->log->trace( "Post $post_id saved, invalidating cache..." );
276
+
277
+        $this->cache->delete( $post_id );
278
+
279
+        $this->flush_cache_if_publisher( $post_id );
280
+
281
+    }
282
+
283
+    /**
284
+     * Hook to meta changed for a {@link WP_Post}, will cause the cause to
285
+     * invalidate.
286
+     *
287
+     * @param int    $id The {@link WP_Post} meta id.
288
+     * @param int    $post_id The {@link WP_Post} id.
289
+     * @param string $meta_key The meta key.
290
+     *
291
+     * @since 3.16.0
292
+     */
293
+    public function changed_post_meta( $id, $post_id, $meta_key ) {
294
+
295
+        if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
296
+            $this->log->trace( "Post $post_id meta $meta_key ignored." );
297
+
298
+            return;
299
+        }
300
+
301
+        $this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
302
+
303
+        // Delete the single cache file.
304
+        $this->cache->delete( $post_id );
305
+
306
+        // Flush the cache if it's the publisher.
307
+        $this->flush_cache_if_publisher( $post_id );
308
+
309
+    }
310
+
311
+    /**
312
+     * Hook to WordLift's options changes, will flush the cache.
313
+     *
314
+     * @since 3.16.0
315
+     */
316
+    public function update_option_wl_general_settings() {
317
+        $this->log->trace( 'WordLift options changed, flushing cache...' );
318
+
319
+        $this->cache->flush();
320
+    }
321
+
322
+    /**
323
+     * Hook when permalinks are changed, will flush the cache.
324
+     *
325
+     * @since 3.17.0
326
+     */
327
+    public function permalinks_structure_changed() {
328
+        $this->log->trace( 'Permalinks structure changed, flushing cache...' );
329
+
330
+        $this->cache->flush();
331
+    }
332
+
333
+    /**
334
+     * Hook to WordLift's post/entity relation changes, will invalidate the cache.
335
+     *
336
+     * @param int $post_id The {@link WP_Post} id.
337
+     *
338
+     * @since 3.16.0
339
+     */
340
+    public function relation_changed( $post_id ) {
341
+        $this->log->trace( "Post $post_id relations changed, invalidating cache..." );
342
+
343
+        $this->cache->delete( $post_id );
344
+    }
345
+
346
+    /**
347
+     * When in Ajax, prints an http header with the information whether the
348
+     * response is cached or not.
349
+     *
350
+     * @param int  $post_id The {@link WP_Post} id.
351
+     * @param bool $cache Whether the response fragment is cached.
352
+     *
353
+     * @since 3.16.0
354
+     */
355
+    private function add_http_header( $post_id, $cache ) {
356
+
357
+        if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
358
+            return;
359
+        }
360
+
361
+        header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
362
+
363
+    }
364
+
365
+    /**
366
+     * Call the `flush` operation on the {@link Ttl_Cache} if
367
+     * the publisher has changed.
368
+     *
369
+     * @param int $post_id The changed {@link WP_Post}'s id.
370
+     *
371
+     * @since 3.16.0
372
+     */
373
+    private function flush_cache_if_publisher( $post_id ) {
374
+
375
+        // Bail out if it's not the publisher.
376
+        if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
377
+            return;
378
+        }
379
+
380
+        // Flush the cache, since the publisher has changed.
381
+        $this->cache->flush();
382
+
383
+    }
384 384
 
385 385
 }
Please login to merge, or discard this patch.
Spacing   +46 added lines, -46 removed lines patch added patch discarded remove patch
@@ -64,9 +64,9 @@  discard block
 block discarded – undo
64 64
 	 * @param \Wordlift_Post_Converter $converter The {@link Wordlift_Post_Converter} implementation.
65 65
 	 * @param Ttl_Cache                $cache The {@link Ttl_Cache} cache instance.
66 66
 	 */
67
-	public function __construct( $converter, $cache ) {
67
+	public function __construct($converter, $cache) {
68 68
 
69
-		$this->log = Wordlift_Log_Service::get_logger( get_class() );
69
+		$this->log = Wordlift_Log_Service::get_logger(get_class());
70 70
 
71 71
 		$this->cache     = $cache;
72 72
 		$this->converter = $converter;
@@ -82,7 +82,7 @@  discard block
 block discarded – undo
82 82
 	private function init_hooks() {
83 83
 
84 84
 		// Hook on post save to flush relevant cache.
85
-		add_action( 'save_post', array( $this, 'save_post' ) );
85
+		add_action('save_post', array($this, 'save_post'));
86 86
 
87 87
 		add_action(
88 88
 			'added_post_meta',
@@ -131,8 +131,8 @@  discard block
 block discarded – undo
131 131
 		);
132 132
 
133 133
 		// Invalid cache on relationship change.
134
-		add_action( 'wl_relation_added', array( $this, 'relation_changed' ) );
135
-		add_action( 'wl_relation_deleted', array( $this, 'relation_changed' ) );
134
+		add_action('wl_relation_added', array($this, 'relation_changed'));
135
+		add_action('wl_relation_deleted', array($this, 'relation_changed'));
136 136
 
137 137
 	}
138 138
 
@@ -143,36 +143,36 @@  discard block
 block discarded – undo
143 143
 	 * @inheritdoc
144 144
 	 */
145 145
 	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
146
-	public function convert( $post_id, &$references = array(), &$references_infos = array(), $relations = null, &$cache = false ) {
146
+	public function convert($post_id, &$references = array(), &$references_infos = array(), $relations = null, &$cache = false) {
147 147
 
148 148
 		// Ensure post ID is `int`. Otherwise we may have issues with caching, since caching is strict about
149 149
 		// key var types.
150 150
 		$post_id = (int) $post_id;
151 151
 
152
-		$this->log->trace( "Converting post $post_id..." );
152
+		$this->log->trace("Converting post $post_id...");
153 153
 
154 154
 		// Try to get a cached result.
155
-		$arr = $this->get_cache( $post_id );
155
+		$arr = $this->get_cache($post_id);
156 156
 
157 157
 		// Return the cached contents if any.
158
-		if ( false !== $arr ) {
158
+		if (false !== $arr) {
159 159
 			$contents = $arr['jsonld'];
160 160
 
161 161
 			// Add the cached relations if any.
162
-			if ( is_a( $arr['relations'], 'Wordlift\Relation\Relations' ) ) {
163
-				$relations->add( ...$arr['relations']->toArray() );
162
+			if (is_a($arr['relations'], 'Wordlift\Relation\Relations')) {
163
+				$relations->add(...$arr['relations']->toArray());
164 164
 			}
165 165
 
166
-			if ( is_array( $arr['references'] ) ) {
166
+			if (is_array($arr['references'])) {
167 167
 				$references = $arr['references'];
168 168
 			}
169 169
 
170
-			$this->log->debug( "Cached contents found for post $post_id." );
170
+			$this->log->debug("Cached contents found for post $post_id.");
171 171
 
172 172
 			// Inform the caller that this is cached result.
173 173
 			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
174 174
 			$cache = true;
175
-			$this->add_http_header( $post_id, true );
175
+			$this->add_http_header($post_id, true);
176 176
 
177 177
 			// Return the contents.
178 178
 			return $contents;
@@ -181,10 +181,10 @@  discard block
 block discarded – undo
181 181
 		// Set cached to false.
182 182
 		// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
183 183
 		$cache = false;
184
-		$this->add_http_header( $post_id, false );
184
+		$this->add_http_header($post_id, false);
185 185
 
186 186
 		// Convert the post.
187
-		$jsonld = $this->converter->convert( $post_id, $references, $references_infos, $relations );
187
+		$jsonld = $this->converter->convert($post_id, $references, $references_infos, $relations);
188 188
 
189 189
 		/**
190 190
 		 * @since 3.32.0
@@ -192,7 +192,7 @@  discard block
 block discarded – undo
192 192
 		 * it here before saving it on cache.
193 193
 		 */
194 194
 		// Cache the results.
195
-		$this->set_cache( $post_id, $references, $jsonld, $relations );
195
+		$this->set_cache($post_id, $references, $jsonld, $relations);
196 196
 
197 197
 		// Finally return the JSON-LD.
198 198
 		return $jsonld;
@@ -208,21 +208,21 @@  discard block
 block discarded – undo
208 208
 	 * @since 3.16.0
209 209
 	 */
210 210
 	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
211
-	private function get_cache( $post_id ) {
211
+	private function get_cache($post_id) {
212 212
 
213 213
 		// Ensure post ID is int, because cache is strict about var types.
214 214
 		$post_id = (int) $post_id;
215 215
 
216
-		$this->log->trace( "Getting cached contents for post $post_id..." );
216
+		$this->log->trace("Getting cached contents for post $post_id...");
217 217
 
218 218
 		// Get the cache.
219
-		$modified_date_time = get_post_datetime( $post_id, 'modified', 'gmt' );
220
-		$contents           = $this->cache->get( $post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0 );
219
+		$modified_date_time = get_post_datetime($post_id, 'modified', 'gmt');
220
+		$contents           = $this->cache->get($post_id, $modified_date_time ? $modified_date_time->getTimestamp() : 0);
221 221
 
222 222
 		// Bail out if we don't have cached contents or the cached contents are
223 223
 		// invalid.
224
-		if ( null === $contents || ! isset( $contents['jsonld'] ) || ! isset( $contents['references'] ) || ! isset( $contents['relations'] ) ) {
225
-			$this->log->debug( "Cached contents for post $post_id not found." );
224
+		if (null === $contents || ! isset($contents['jsonld']) || ! isset($contents['references']) || ! isset($contents['relations'])) {
225
+			$this->log->debug("Cached contents for post $post_id not found.");
226 226
 
227 227
 			return false;
228 228
 		}
@@ -230,7 +230,7 @@  discard block
 block discarded – undo
230 230
 		return $contents['jsonld']
231 231
 			? array(
232 232
 				'jsonld'     => $contents['jsonld'],
233
-				'relations'  => Relations::from_json( $contents['relations'] ),
233
+				'relations'  => Relations::from_json($contents['relations']),
234 234
 				'references' => $contents['references'],
235 235
 			)
236 236
 			: false;
@@ -247,9 +247,9 @@  discard block
 block discarded – undo
247 247
 	 *
248 248
 	 * @since 3.16.0
249 249
 	 */
250
-	private function set_cache( $post_id, $references, $jsonld, $relations ) {
250
+	private function set_cache($post_id, $references, $jsonld, $relations) {
251 251
 
252
-		$this->log->trace( "Caching result for post $post_id..." );
252
+		$this->log->trace("Caching result for post $post_id...");
253 253
 
254 254
 		$this->cache->put(
255 255
 			$post_id,
@@ -270,13 +270,13 @@  discard block
 block discarded – undo
270 270
 	 *
271 271
 	 * @since 3.16.0
272 272
 	 */
273
-	public function save_post( $post_id ) {
273
+	public function save_post($post_id) {
274 274
 
275
-		$this->log->trace( "Post $post_id saved, invalidating cache..." );
275
+		$this->log->trace("Post $post_id saved, invalidating cache...");
276 276
 
277
-		$this->cache->delete( $post_id );
277
+		$this->cache->delete($post_id);
278 278
 
279
-		$this->flush_cache_if_publisher( $post_id );
279
+		$this->flush_cache_if_publisher($post_id);
280 280
 
281 281
 	}
282 282
 
@@ -290,21 +290,21 @@  discard block
 block discarded – undo
290 290
 	 *
291 291
 	 * @since 3.16.0
292 292
 	 */
293
-	public function changed_post_meta( $id, $post_id, $meta_key ) {
293
+	public function changed_post_meta($id, $post_id, $meta_key) {
294 294
 
295
-		if ( in_array( $meta_key, self::$ignored_meta_keys, true ) ) {
296
-			$this->log->trace( "Post $post_id meta $meta_key ignored." );
295
+		if (in_array($meta_key, self::$ignored_meta_keys, true)) {
296
+			$this->log->trace("Post $post_id meta $meta_key ignored.");
297 297
 
298 298
 			return;
299 299
 		}
300 300
 
301
-		$this->log->trace( "Post $post_id meta $meta_key changed, invalidating cache..." );
301
+		$this->log->trace("Post $post_id meta $meta_key changed, invalidating cache...");
302 302
 
303 303
 		// Delete the single cache file.
304
-		$this->cache->delete( $post_id );
304
+		$this->cache->delete($post_id);
305 305
 
306 306
 		// Flush the cache if it's the publisher.
307
-		$this->flush_cache_if_publisher( $post_id );
307
+		$this->flush_cache_if_publisher($post_id);
308 308
 
309 309
 	}
310 310
 
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 	 * @since 3.16.0
315 315
 	 */
316 316
 	public function update_option_wl_general_settings() {
317
-		$this->log->trace( 'WordLift options changed, flushing cache...' );
317
+		$this->log->trace('WordLift options changed, flushing cache...');
318 318
 
319 319
 		$this->cache->flush();
320 320
 	}
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 	 * @since 3.17.0
326 326
 	 */
327 327
 	public function permalinks_structure_changed() {
328
-		$this->log->trace( 'Permalinks structure changed, flushing cache...' );
328
+		$this->log->trace('Permalinks structure changed, flushing cache...');
329 329
 
330 330
 		$this->cache->flush();
331 331
 	}
@@ -337,10 +337,10 @@  discard block
 block discarded – undo
337 337
 	 *
338 338
 	 * @since 3.16.0
339 339
 	 */
340
-	public function relation_changed( $post_id ) {
341
-		$this->log->trace( "Post $post_id relations changed, invalidating cache..." );
340
+	public function relation_changed($post_id) {
341
+		$this->log->trace("Post $post_id relations changed, invalidating cache...");
342 342
 
343
-		$this->cache->delete( $post_id );
343
+		$this->cache->delete($post_id);
344 344
 	}
345 345
 
346 346
 	/**
@@ -352,13 +352,13 @@  discard block
 block discarded – undo
352 352
 	 *
353 353
 	 * @since 3.16.0
354 354
 	 */
355
-	private function add_http_header( $post_id, $cache ) {
355
+	private function add_http_header($post_id, $cache) {
356 356
 
357
-		if ( ! defined( 'DOING_AJAX' ) || ! DOING_AJAX || headers_sent() ) {
357
+		if ( ! defined('DOING_AJAX') || ! DOING_AJAX || headers_sent()) {
358 358
 			return;
359 359
 		}
360 360
 
361
-		header( "X-WordLift-JsonLd-Cache-$post_id: " . ( $cache ? 'HIT' : 'MISS' ) );
361
+		header("X-WordLift-JsonLd-Cache-$post_id: ".($cache ? 'HIT' : 'MISS'));
362 362
 
363 363
 	}
364 364
 
@@ -370,10 +370,10 @@  discard block
 block discarded – undo
370 370
 	 *
371 371
 	 * @since 3.16.0
372 372
 	 */
373
-	private function flush_cache_if_publisher( $post_id ) {
373
+	private function flush_cache_if_publisher($post_id) {
374 374
 
375 375
 		// Bail out if it's not the publisher.
376
-		if ( Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id ) {
376
+		if (Wordlift_Configuration_Service::get_instance()->get_publisher_id() !== $post_id) {
377 377
 			return;
378 378
 		}
379 379
 
Please login to merge, or discard this patch.
src/includes/class-wordlift-post-adapter.php 2 patches
Indentation   +219 added lines, -219 removed lines patch added patch discarded remove patch
@@ -19,229 +19,229 @@
 block discarded – undo
19 19
  */
20 20
 class Wordlift_Post_Adapter {
21 21
 
22
-	/**
23
-	 * The post id to which the adopter relates.
24
-	 *
25
-	 * @since 3.14.0
26
-	 *
27
-	 * @var integer $post_id .
28
-	 */
29
-	private $post_id;
30
-
31
-	const TYPE_ENTITY_LINK = 0;
32
-	const TYPE_TERM_LINK   = 1;
33
-
34
-	/**
35
-	 * Create the {@link Wordlift_Post_Adatpter} instance.
36
-	 *
37
-	 * @param integer $post_id the post ID of the post the adopter relates to.
38
-	 *
39
-	 * @since 3.14.0
40
-	 */
41
-	public function __construct( $post_id ) {
42
-
43
-		$this->post_id = $post_id;
44
-
45
-	}
46
-
47
-	/**
48
-	 * Get the word count of the post content.
49
-	 *
50
-	 * The count is calculated over the post content after stripping shortcodes and html tags.
51
-	 *
52
-	 * @return integer the number of words in the content after stripping shortcodes and html tags..
53
-	 * @since 3.14.0
54
-	 */
55
-	public function word_count() {
56
-
57
-		$post = get_post( $this->post_id );
58
-
59
-		/*
22
+    /**
23
+     * The post id to which the adopter relates.
24
+     *
25
+     * @since 3.14.0
26
+     *
27
+     * @var integer $post_id .
28
+     */
29
+    private $post_id;
30
+
31
+    const TYPE_ENTITY_LINK = 0;
32
+    const TYPE_TERM_LINK   = 1;
33
+
34
+    /**
35
+     * Create the {@link Wordlift_Post_Adatpter} instance.
36
+     *
37
+     * @param integer $post_id the post ID of the post the adopter relates to.
38
+     *
39
+     * @since 3.14.0
40
+     */
41
+    public function __construct( $post_id ) {
42
+
43
+        $this->post_id = $post_id;
44
+
45
+    }
46
+
47
+    /**
48
+     * Get the word count of the post content.
49
+     *
50
+     * The count is calculated over the post content after stripping shortcodes and html tags.
51
+     *
52
+     * @return integer the number of words in the content after stripping shortcodes and html tags..
53
+     * @since 3.14.0
54
+     */
55
+    public function word_count() {
56
+
57
+        $post = get_post( $this->post_id );
58
+
59
+        /*
60 60
 		 * Apply the `wl_post_content` filter, in case 3rd parties want to change the post content, e.g.
61 61
 		 * because the content is written elsewhere.
62 62
 		 *
63 63
 		 * @since 3.20.0
64 64
 		 */
65
-		$post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
66
-
67
-		return self::str_word_count_utf8( wp_strip_all_tags( strip_shortcodes( $post_content ) ) );
68
-	}
69
-
70
-	/**
71
-	 * Count words in the string, taking into account UTF-8 characters.
72
-	 *
73
-	 * @see https://github.com/insideout10/wordlift-plugin/issues/884
74
-	 *
75
-	 * @since 3.20.0
76
-	 *
77
-	 * @param string $str The target string.
78
-	 *
79
-	 * @return int The number of words.
80
-	 */
81
-	private static function str_word_count_utf8( $str ) {
82
-
83
-		$words = preg_split( '~[^\p{L}\p{N}\']+~u', $str );
84
-
85
-		return $words ? count( $words ) : 0;
86
-	}
87
-
88
-	/**
89
-	 * Get the {@link WP_Post} permalink allowing 3rd parties to alter the URL.
90
-	 *
91
-	 * @param int $post_id Post ID.
92
-	 *
93
-	 * @return string The post permalink.
94
-	 * @since 3.20.0
95
-	 */
96
-	public static function get_production_permalink( $post_id, $object_type = Object_Type_Enum::POST ) {
97
-
98
-		$object_link_service = Object_Link_Provider::get_instance();
99
-		$permalink           = $object_link_service->get_permalink( $post_id, $object_type );
100
-
101
-		/**
102
-		 * WordPress 4.4 doesn't support meta queries for terms, therefore we only support post permalinks here.
103
-		 *
104
-		 * Later on for WordPress 4.5+ we look for terms bound to the entity and we use the term link instead of the
105
-		 * post permalink if we find them.
106
-		 */
107
-		global $wp_version;
108
-		if ( version_compare( $wp_version, '4.5', '<' ) ) {
109
-			return apply_filters( 'wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null );
110
-		}
111
-
112
-		/**
113
-		 * The `wl_production_permalink` filter allows to change the permalink, this is useful in contexts
114
-		 * when the production environment is copied over from a staging environment with staging
115
-		 * URLs.
116
-		 *
117
-		 * @param string $permalink_url The default permalink.
118
-		 * @param int $post_id The post id.
119
-		 *
120
-		 * @since 3.23.0 we check whether the entity is bound to a term and, in that case, we link to the term.
121
-		 * @since 3.20.0
122
-		 *
123
-		 * @see https://github.com/insideout10/wordlift-plugin/issues/850
124
-		 */
125
-
126
-		$uris = $object_link_service->get_same_as_uris(
127
-			$post_id,
128
-			$object_type
129
-		);
130
-
131
-		// Only try to link a term if `WL_ENABLE_TERM_LINKING` is enabled.
132
-		$terms = array();
133
-		if ( defined( 'WL_ENABLE_TERM_LINKING' ) && WL_ENABLE_TERM_LINKING ) {
134
-			// Try to find one term matching the entity.
135
-			$terms = get_terms(
136
-				array(
137
-					'number'                 => 1,
138
-					'hide_empty'             => false,
139
-					'update_term_meta_cache' => false,
140
-					'meta_key'               => '_wl_entity_id',
141
-					'meta_value'             => $uris,
142
-					'meta_compare'           => 'IN',
143
-				)
144
-			);
145
-		}
146
-
147
-		$type = self::TYPE_ENTITY_LINK;
148
-		$term = null;
149
-		// If found use the term link, otherwise the permalink.
150
-		if ( 1 === count( $terms ) ) {
151
-			$term      = current( $terms );
152
-			$permalink = get_term_link( $term );
153
-			$type      = self::TYPE_TERM_LINK;
154
-		}
155
-
156
-		/**
157
-		 * Apply the `wl_production_permalink` filter.
158
-		 *
159
-		 * @param string $permalink The permalink.
160
-		 * @param int $post_id The post id.
161
-		 * @param int $type The permalink type: 0 = entity permalink, 1 = term link.
162
-		 * @param WP_Term $term The term if type is term link, otherwise null.
163
-		 *
164
-		 * @since 3.23.0 add the permalink type and term parameters.
165
-		 */
166
-		return apply_filters( 'wl_production_permalink', $permalink, $post_id, $type, $term );
167
-	}
168
-
169
-	/**
170
-	 * Get comma separated tags to be used as keywords
171
-	 *
172
-	 * @return string|void Comma separated tags
173
-	 *
174
-	 * @since 3.27.2
175
-	 */
176
-	public function keywords() {
177
-		$tags = get_the_tags( $this->post_id );
178
-
179
-		if ( empty( $tags ) ) {
180
-			return;
181
-		}
182
-
183
-		return implode(
184
-			',',
185
-			array_map(
186
-				function ( $tag ) {
187
-					return $tag->name;
188
-				},
189
-				$tags
190
-			)
191
-		);
192
-	}
193
-
194
-	/**
195
-	 * Get comma separated categories to be used as article section
196
-	 *
197
-	 * @return string[] Comma separated categories
198
-	 *
199
-	 * @since 3.27.2
200
-	 */
201
-	public function article_section() {
202
-		$categories = get_the_category( $this->post_id );
203
-
204
-		return wp_list_pluck( $categories, 'cat_name' );
205
-	}
206
-
207
-	/**
208
-	 * Get comment count
209
-	 *
210
-	 * @return string|void Comment count
211
-	 *
212
-	 * @since 3.27.2
213
-	 */
214
-	public function comment_count() {
215
-		return get_comments_number( $this->post_id );
216
-	}
217
-
218
-	/**
219
-	 * Get Language
220
-	 * Try WPML, Polylang for post specific languages, else fallback on get_locale()
221
-	 *
222
-	 * @return string|void Language code (locale)
223
-	 *
224
-	 * @since 3.27.2
225
-	 */
226
-	public function locale() {
227
-		$language = 'en-US';
228
-
229
-		if ( function_exists( 'wpml_get_language_information' ) ) {
230
-			// WPML handling
231
-			// WPML: Updated function signature.
232
-			// function wpml_get_language_information( $empty_value = null, $post_id = null )
233
-			$post_language = wpml_get_language_information( null, $this->post_id );
234
-			if ( ! $post_language instanceof WP_Error ) {
235
-				$language = $post_language['locale'];
236
-			}
237
-		} elseif ( function_exists( 'pll_get_post_language' ) ) {
238
-			// Polylang handling
239
-			$language = pll_get_post_language( $this->post_id, 'locale' );
240
-		} else {
241
-			$language = get_locale();
242
-		}
243
-
244
-		return str_replace( '_', '-', $language );
245
-	}
65
+        $post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
66
+
67
+        return self::str_word_count_utf8( wp_strip_all_tags( strip_shortcodes( $post_content ) ) );
68
+    }
69
+
70
+    /**
71
+     * Count words in the string, taking into account UTF-8 characters.
72
+     *
73
+     * @see https://github.com/insideout10/wordlift-plugin/issues/884
74
+     *
75
+     * @since 3.20.0
76
+     *
77
+     * @param string $str The target string.
78
+     *
79
+     * @return int The number of words.
80
+     */
81
+    private static function str_word_count_utf8( $str ) {
82
+
83
+        $words = preg_split( '~[^\p{L}\p{N}\']+~u', $str );
84
+
85
+        return $words ? count( $words ) : 0;
86
+    }
87
+
88
+    /**
89
+     * Get the {@link WP_Post} permalink allowing 3rd parties to alter the URL.
90
+     *
91
+     * @param int $post_id Post ID.
92
+     *
93
+     * @return string The post permalink.
94
+     * @since 3.20.0
95
+     */
96
+    public static function get_production_permalink( $post_id, $object_type = Object_Type_Enum::POST ) {
97
+
98
+        $object_link_service = Object_Link_Provider::get_instance();
99
+        $permalink           = $object_link_service->get_permalink( $post_id, $object_type );
100
+
101
+        /**
102
+         * WordPress 4.4 doesn't support meta queries for terms, therefore we only support post permalinks here.
103
+         *
104
+         * Later on for WordPress 4.5+ we look for terms bound to the entity and we use the term link instead of the
105
+         * post permalink if we find them.
106
+         */
107
+        global $wp_version;
108
+        if ( version_compare( $wp_version, '4.5', '<' ) ) {
109
+            return apply_filters( 'wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null );
110
+        }
111
+
112
+        /**
113
+         * The `wl_production_permalink` filter allows to change the permalink, this is useful in contexts
114
+         * when the production environment is copied over from a staging environment with staging
115
+         * URLs.
116
+         *
117
+         * @param string $permalink_url The default permalink.
118
+         * @param int $post_id The post id.
119
+         *
120
+         * @since 3.23.0 we check whether the entity is bound to a term and, in that case, we link to the term.
121
+         * @since 3.20.0
122
+         *
123
+         * @see https://github.com/insideout10/wordlift-plugin/issues/850
124
+         */
125
+
126
+        $uris = $object_link_service->get_same_as_uris(
127
+            $post_id,
128
+            $object_type
129
+        );
130
+
131
+        // Only try to link a term if `WL_ENABLE_TERM_LINKING` is enabled.
132
+        $terms = array();
133
+        if ( defined( 'WL_ENABLE_TERM_LINKING' ) && WL_ENABLE_TERM_LINKING ) {
134
+            // Try to find one term matching the entity.
135
+            $terms = get_terms(
136
+                array(
137
+                    'number'                 => 1,
138
+                    'hide_empty'             => false,
139
+                    'update_term_meta_cache' => false,
140
+                    'meta_key'               => '_wl_entity_id',
141
+                    'meta_value'             => $uris,
142
+                    'meta_compare'           => 'IN',
143
+                )
144
+            );
145
+        }
146
+
147
+        $type = self::TYPE_ENTITY_LINK;
148
+        $term = null;
149
+        // If found use the term link, otherwise the permalink.
150
+        if ( 1 === count( $terms ) ) {
151
+            $term      = current( $terms );
152
+            $permalink = get_term_link( $term );
153
+            $type      = self::TYPE_TERM_LINK;
154
+        }
155
+
156
+        /**
157
+         * Apply the `wl_production_permalink` filter.
158
+         *
159
+         * @param string $permalink The permalink.
160
+         * @param int $post_id The post id.
161
+         * @param int $type The permalink type: 0 = entity permalink, 1 = term link.
162
+         * @param WP_Term $term The term if type is term link, otherwise null.
163
+         *
164
+         * @since 3.23.0 add the permalink type and term parameters.
165
+         */
166
+        return apply_filters( 'wl_production_permalink', $permalink, $post_id, $type, $term );
167
+    }
168
+
169
+    /**
170
+     * Get comma separated tags to be used as keywords
171
+     *
172
+     * @return string|void Comma separated tags
173
+     *
174
+     * @since 3.27.2
175
+     */
176
+    public function keywords() {
177
+        $tags = get_the_tags( $this->post_id );
178
+
179
+        if ( empty( $tags ) ) {
180
+            return;
181
+        }
182
+
183
+        return implode(
184
+            ',',
185
+            array_map(
186
+                function ( $tag ) {
187
+                    return $tag->name;
188
+                },
189
+                $tags
190
+            )
191
+        );
192
+    }
193
+
194
+    /**
195
+     * Get comma separated categories to be used as article section
196
+     *
197
+     * @return string[] Comma separated categories
198
+     *
199
+     * @since 3.27.2
200
+     */
201
+    public function article_section() {
202
+        $categories = get_the_category( $this->post_id );
203
+
204
+        return wp_list_pluck( $categories, 'cat_name' );
205
+    }
206
+
207
+    /**
208
+     * Get comment count
209
+     *
210
+     * @return string|void Comment count
211
+     *
212
+     * @since 3.27.2
213
+     */
214
+    public function comment_count() {
215
+        return get_comments_number( $this->post_id );
216
+    }
217
+
218
+    /**
219
+     * Get Language
220
+     * Try WPML, Polylang for post specific languages, else fallback on get_locale()
221
+     *
222
+     * @return string|void Language code (locale)
223
+     *
224
+     * @since 3.27.2
225
+     */
226
+    public function locale() {
227
+        $language = 'en-US';
228
+
229
+        if ( function_exists( 'wpml_get_language_information' ) ) {
230
+            // WPML handling
231
+            // WPML: Updated function signature.
232
+            // function wpml_get_language_information( $empty_value = null, $post_id = null )
233
+            $post_language = wpml_get_language_information( null, $this->post_id );
234
+            if ( ! $post_language instanceof WP_Error ) {
235
+                $language = $post_language['locale'];
236
+            }
237
+        } elseif ( function_exists( 'pll_get_post_language' ) ) {
238
+            // Polylang handling
239
+            $language = pll_get_post_language( $this->post_id, 'locale' );
240
+        } else {
241
+            $language = get_locale();
242
+        }
243
+
244
+        return str_replace( '_', '-', $language );
245
+    }
246 246
 
247 247
 }
Please login to merge, or discard this patch.
Spacing   +28 added lines, -28 removed lines patch added patch discarded remove patch
@@ -38,7 +38,7 @@  discard block
 block discarded – undo
38 38
 	 *
39 39
 	 * @since 3.14.0
40 40
 	 */
41
-	public function __construct( $post_id ) {
41
+	public function __construct($post_id) {
42 42
 
43 43
 		$this->post_id = $post_id;
44 44
 
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 	 */
55 55
 	public function word_count() {
56 56
 
57
-		$post = get_post( $this->post_id );
57
+		$post = get_post($this->post_id);
58 58
 
59 59
 		/*
60 60
 		 * Apply the `wl_post_content` filter, in case 3rd parties want to change the post content, e.g.
@@ -62,9 +62,9 @@  discard block
 block discarded – undo
62 62
 		 *
63 63
 		 * @since 3.20.0
64 64
 		 */
65
-		$post_content = apply_filters( 'wl_post_content', $post->post_content, $post );
65
+		$post_content = apply_filters('wl_post_content', $post->post_content, $post);
66 66
 
67
-		return self::str_word_count_utf8( wp_strip_all_tags( strip_shortcodes( $post_content ) ) );
67
+		return self::str_word_count_utf8(wp_strip_all_tags(strip_shortcodes($post_content)));
68 68
 	}
69 69
 
70 70
 	/**
@@ -78,11 +78,11 @@  discard block
 block discarded – undo
78 78
 	 *
79 79
 	 * @return int The number of words.
80 80
 	 */
81
-	private static function str_word_count_utf8( $str ) {
81
+	private static function str_word_count_utf8($str) {
82 82
 
83
-		$words = preg_split( '~[^\p{L}\p{N}\']+~u', $str );
83
+		$words = preg_split('~[^\p{L}\p{N}\']+~u', $str);
84 84
 
85
-		return $words ? count( $words ) : 0;
85
+		return $words ? count($words) : 0;
86 86
 	}
87 87
 
88 88
 	/**
@@ -93,10 +93,10 @@  discard block
 block discarded – undo
93 93
 	 * @return string The post permalink.
94 94
 	 * @since 3.20.0
95 95
 	 */
96
-	public static function get_production_permalink( $post_id, $object_type = Object_Type_Enum::POST ) {
96
+	public static function get_production_permalink($post_id, $object_type = Object_Type_Enum::POST) {
97 97
 
98 98
 		$object_link_service = Object_Link_Provider::get_instance();
99
-		$permalink           = $object_link_service->get_permalink( $post_id, $object_type );
99
+		$permalink           = $object_link_service->get_permalink($post_id, $object_type);
100 100
 
101 101
 		/**
102 102
 		 * WordPress 4.4 doesn't support meta queries for terms, therefore we only support post permalinks here.
@@ -105,8 +105,8 @@  discard block
 block discarded – undo
105 105
 		 * post permalink if we find them.
106 106
 		 */
107 107
 		global $wp_version;
108
-		if ( version_compare( $wp_version, '4.5', '<' ) ) {
109
-			return apply_filters( 'wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null );
108
+		if (version_compare($wp_version, '4.5', '<')) {
109
+			return apply_filters('wl_production_permalink', $permalink, $post_id, self::TYPE_ENTITY_LINK, null);
110 110
 		}
111 111
 
112 112
 		/**
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 
131 131
 		// Only try to link a term if `WL_ENABLE_TERM_LINKING` is enabled.
132 132
 		$terms = array();
133
-		if ( defined( 'WL_ENABLE_TERM_LINKING' ) && WL_ENABLE_TERM_LINKING ) {
133
+		if (defined('WL_ENABLE_TERM_LINKING') && WL_ENABLE_TERM_LINKING) {
134 134
 			// Try to find one term matching the entity.
135 135
 			$terms = get_terms(
136 136
 				array(
@@ -147,9 +147,9 @@  discard block
 block discarded – undo
147 147
 		$type = self::TYPE_ENTITY_LINK;
148 148
 		$term = null;
149 149
 		// If found use the term link, otherwise the permalink.
150
-		if ( 1 === count( $terms ) ) {
151
-			$term      = current( $terms );
152
-			$permalink = get_term_link( $term );
150
+		if (1 === count($terms)) {
151
+			$term      = current($terms);
152
+			$permalink = get_term_link($term);
153 153
 			$type      = self::TYPE_TERM_LINK;
154 154
 		}
155 155
 
@@ -163,7 +163,7 @@  discard block
 block discarded – undo
163 163
 		 *
164 164
 		 * @since 3.23.0 add the permalink type and term parameters.
165 165
 		 */
166
-		return apply_filters( 'wl_production_permalink', $permalink, $post_id, $type, $term );
166
+		return apply_filters('wl_production_permalink', $permalink, $post_id, $type, $term);
167 167
 	}
168 168
 
169 169
 	/**
@@ -174,16 +174,16 @@  discard block
 block discarded – undo
174 174
 	 * @since 3.27.2
175 175
 	 */
176 176
 	public function keywords() {
177
-		$tags = get_the_tags( $this->post_id );
177
+		$tags = get_the_tags($this->post_id);
178 178
 
179
-		if ( empty( $tags ) ) {
179
+		if (empty($tags)) {
180 180
 			return;
181 181
 		}
182 182
 
183 183
 		return implode(
184 184
 			',',
185 185
 			array_map(
186
-				function ( $tag ) {
186
+				function($tag) {
187 187
 					return $tag->name;
188 188
 				},
189 189
 				$tags
@@ -199,9 +199,9 @@  discard block
 block discarded – undo
199 199
 	 * @since 3.27.2
200 200
 	 */
201 201
 	public function article_section() {
202
-		$categories = get_the_category( $this->post_id );
202
+		$categories = get_the_category($this->post_id);
203 203
 
204
-		return wp_list_pluck( $categories, 'cat_name' );
204
+		return wp_list_pluck($categories, 'cat_name');
205 205
 	}
206 206
 
207 207
 	/**
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 	 * @since 3.27.2
213 213
 	 */
214 214
 	public function comment_count() {
215
-		return get_comments_number( $this->post_id );
215
+		return get_comments_number($this->post_id);
216 216
 	}
217 217
 
218 218
 	/**
@@ -226,22 +226,22 @@  discard block
 block discarded – undo
226 226
 	public function locale() {
227 227
 		$language = 'en-US';
228 228
 
229
-		if ( function_exists( 'wpml_get_language_information' ) ) {
229
+		if (function_exists('wpml_get_language_information')) {
230 230
 			// WPML handling
231 231
 			// WPML: Updated function signature.
232 232
 			// function wpml_get_language_information( $empty_value = null, $post_id = null )
233
-			$post_language = wpml_get_language_information( null, $this->post_id );
234
-			if ( ! $post_language instanceof WP_Error ) {
233
+			$post_language = wpml_get_language_information(null, $this->post_id);
234
+			if ( ! $post_language instanceof WP_Error) {
235 235
 				$language = $post_language['locale'];
236 236
 			}
237
-		} elseif ( function_exists( 'pll_get_post_language' ) ) {
237
+		} elseif (function_exists('pll_get_post_language')) {
238 238
 			// Polylang handling
239
-			$language = pll_get_post_language( $this->post_id, 'locale' );
239
+			$language = pll_get_post_language($this->post_id, 'locale');
240 240
 		} else {
241 241
 			$language = get_locale();
242 242
 		}
243 243
 
244
-		return str_replace( '_', '-', $language );
244
+		return str_replace('_', '-', $language);
245 245
 	}
246 246
 
247 247
 }
Please login to merge, or discard this patch.
src/wordlift/vocabulary-terms/jsonld/class-jsonld-generator.php 1 patch
Indentation   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -11,167 +11,167 @@
 block discarded – undo
11 11
 
12 12
 class Jsonld_Generator {
13 13
 
14
-	/**
15
-	 * @var \Wordlift_Entity_Type_Service
16
-	 */
17
-	private $entity_type_service;
18
-	/**
19
-	 * @var \Wordlift_Property_Getter
20
-	 */
21
-	private $property_getter;
22
-	/**
23
-	 * @var Type_Service
24
-	 */
25
-	private $term_entity_type_service;
26
-	/**
27
-	 * @var \Wordlift_Entity_Service
28
-	 */
29
-	private $entity_service;
30
-
31
-	public function __construct( $entity_type_service, $property_getter ) {
32
-		$this->entity_type_service      = $entity_type_service;
33
-		$this->property_getter          = $property_getter;
34
-		$this->term_entity_type_service = Type_Service::get_instance();
35
-		$this->entity_service           = \Wordlift_Entity_Service::get_instance();
36
-	}
37
-
38
-	public function init() {
39
-		add_filter( 'wl_term_jsonld_array', array( $this, 'wl_term_jsonld_array' ), 10, 2 );
40
-	}
41
-
42
-	public function wl_term_jsonld_array( $data, $term_id ) {
43
-		$jsonld     = $data['jsonld'];
44
-		$references = $data['references'];
45
-
46
-		$term_jsonld_data = $this->get_jsonld_data_for_term( $term_id );
47
-
48
-		// Return early if we dont have the entity data
49
-		// for the term.
50
-		if ( ! $term_jsonld_data ) {
51
-			return $data;
52
-		}
53
-
54
-		$term_jsonld = $term_jsonld_data['jsonld'];
55
-
56
-		$references = array_merge( $references, $term_jsonld_data['references'] );
57
-
58
-		array_unshift( $jsonld, $term_jsonld );
59
-
60
-		return array(
61
-			'jsonld'     => $jsonld,
62
-			'references' => $references,
63
-		);
64
-	}
65
-
66
-	private function get_jsonld_data_for_term( $term_id ) {
67
-
68
-		$id = $this->entity_service->get_uri( $term_id, Object_Type_Enum::TERM );
69
-
70
-		// If we don't have a dataset  URI, then don't publish the term data
71
-		// on this page.
72
-		if ( ! $id ) {
73
-			return false;
74
-		}
75
-
76
-		$references = array();
77
-		$term       = get_term( $term_id );
78
-		$permalink  = get_term_link( $term );
79
-
80
-		$custom_fields = $this->entity_type_service->get_custom_fields_for_term( $term_id );
81
-		$term          = get_term( $term_id );
82
-		$jsonld        = array(
83
-			'@context'    => 'http://schema.org',
84
-			'name'        => $term->name,
85
-			'@type'       => $this->term_entity_type_service->get_entity_types_labels( $term_id ),
86
-			'@id'         => $id,
87
-			'description' => wp_strip_all_tags( self::strip_all_shortcodes( $term->description ) ),
88
-		);
89
-
90
-		if ( ! $custom_fields || ! is_array( $custom_fields ) ) {
91
-			return $jsonld;
92
-		}
93
-
94
-		foreach ( $custom_fields as $key => $value ) {
95
-			$name  = $this->relative_to_schema_context( $value['predicate'] );
96
-			$value = $this->property_getter->get( $term_id, $key, Object_Type_Enum::TERM );
97
-			$value = $this->process_value( $value, $references );
98
-			if ( ! isset( $value ) ||
99
-				 is_array( $value ) && empty( $value ) ||
100
-				 is_string( $value ) && empty( $value ) ) {
101
-				continue;
102
-			}
103
-			$jsonld[ $name ] = $value;
104
-
105
-		}
106
-
107
-		$jsonld = \Wordlift_Entity_Post_To_Jsonld_Converter::post_process( $jsonld );
108
-
109
-		if ( $permalink ) {
110
-			$jsonld['mainEntityOfPage'] = $permalink;
111
-		}
112
-
113
-		return apply_filters(
114
-			'wl_no_vocabulary_term_jsonld_array',
115
-			array(
116
-				'jsonld'     => $jsonld,
117
-				'references' => $references,
118
-			),
119
-			$term_id
120
-		);
121
-
122
-	}
123
-
124
-	private function relative_to_schema_context( $predicate ) {
125
-		return str_replace( 'http://schema.org/', '', $predicate );
126
-	}
127
-
128
-	private function process_value( $value, &$references ) {
129
-
130
-		if ( is_array( $value )
131
-			 && count( $value ) > 0
132
-			 && $value[0] instanceof \Wordlift_Property_Entity_Reference ) {
133
-
134
-			// All of the references from the custom fields are post references.
135
-			$references = array_merge(
136
-				$references,
137
-				array_map(
138
-					function ( $property_entity_reference ) {
139
-						/**
140
-						 * @var $property_entity_reference \Wordlift_Property_Entity_Reference
141
-						 */
142
-						return $property_entity_reference->get_id();
143
-					},
144
-					$value
145
-				)
146
-			);
147
-
148
-			return array_map(
149
-				function ( $reference ) {
150
-					/**
151
-					 * @var $reference \Wordlift_Property_Entity_Reference
152
-					 */
153
-					return array( '@id' => $reference->get_url() );
154
-				},
155
-				$value
156
-			);
157
-
158
-		}
159
-
160
-		return $value;
161
-	}
162
-
163
-	/**
164
-	 * Remove all the shortcodes from the content. We're using our own function
165
-	 * because WordPress' own `strip_shortcodes` only takes into consideration
166
-	 * shortcodes for installed plugins/themes.
167
-	 *
168
-	 * @since 3.12.0
169
-	 *
170
-	 * @param string $content The content with shortcodes.
171
-	 *
172
-	 * @return string The content without shortcodes.
173
-	 */
174
-	private static function strip_all_shortcodes( $content ) {
175
-		return preg_replace( '/\[[^]]+\]/', '', $content );
176
-	}
14
+    /**
15
+     * @var \Wordlift_Entity_Type_Service
16
+     */
17
+    private $entity_type_service;
18
+    /**
19
+     * @var \Wordlift_Property_Getter
20
+     */
21
+    private $property_getter;
22
+    /**
23
+     * @var Type_Service
24
+     */
25
+    private $term_entity_type_service;
26
+    /**
27
+     * @var \Wordlift_Entity_Service
28
+     */
29
+    private $entity_service;
30
+
31
+    public function __construct( $entity_type_service, $property_getter ) {
32
+        $this->entity_type_service      = $entity_type_service;
33
+        $this->property_getter          = $property_getter;
34
+        $this->term_entity_type_service = Type_Service::get_instance();
35
+        $this->entity_service           = \Wordlift_Entity_Service::get_instance();
36
+    }
37
+
38
+    public function init() {
39
+        add_filter( 'wl_term_jsonld_array', array( $this, 'wl_term_jsonld_array' ), 10, 2 );
40
+    }
41
+
42
+    public function wl_term_jsonld_array( $data, $term_id ) {
43
+        $jsonld     = $data['jsonld'];
44
+        $references = $data['references'];
45
+
46
+        $term_jsonld_data = $this->get_jsonld_data_for_term( $term_id );
47
+
48
+        // Return early if we dont have the entity data
49
+        // for the term.
50
+        if ( ! $term_jsonld_data ) {
51
+            return $data;
52
+        }
53
+
54
+        $term_jsonld = $term_jsonld_data['jsonld'];
55
+
56
+        $references = array_merge( $references, $term_jsonld_data['references'] );
57
+
58
+        array_unshift( $jsonld, $term_jsonld );
59
+
60
+        return array(
61
+            'jsonld'     => $jsonld,
62
+            'references' => $references,
63
+        );
64
+    }
65
+
66
+    private function get_jsonld_data_for_term( $term_id ) {
67
+
68
+        $id = $this->entity_service->get_uri( $term_id, Object_Type_Enum::TERM );
69
+
70
+        // If we don't have a dataset  URI, then don't publish the term data
71
+        // on this page.
72
+        if ( ! $id ) {
73
+            return false;
74
+        }
75
+
76
+        $references = array();
77
+        $term       = get_term( $term_id );
78
+        $permalink  = get_term_link( $term );
79
+
80
+        $custom_fields = $this->entity_type_service->get_custom_fields_for_term( $term_id );
81
+        $term          = get_term( $term_id );
82
+        $jsonld        = array(
83
+            '@context'    => 'http://schema.org',
84
+            'name'        => $term->name,
85
+            '@type'       => $this->term_entity_type_service->get_entity_types_labels( $term_id ),
86
+            '@id'         => $id,
87
+            'description' => wp_strip_all_tags( self::strip_all_shortcodes( $term->description ) ),
88
+        );
89
+
90
+        if ( ! $custom_fields || ! is_array( $custom_fields ) ) {
91
+            return $jsonld;
92
+        }
93
+
94
+        foreach ( $custom_fields as $key => $value ) {
95
+            $name  = $this->relative_to_schema_context( $value['predicate'] );
96
+            $value = $this->property_getter->get( $term_id, $key, Object_Type_Enum::TERM );
97
+            $value = $this->process_value( $value, $references );
98
+            if ( ! isset( $value ) ||
99
+                 is_array( $value ) && empty( $value ) ||
100
+                 is_string( $value ) && empty( $value ) ) {
101
+                continue;
102
+            }
103
+            $jsonld[ $name ] = $value;
104
+
105
+        }
106
+
107
+        $jsonld = \Wordlift_Entity_Post_To_Jsonld_Converter::post_process( $jsonld );
108
+
109
+        if ( $permalink ) {
110
+            $jsonld['mainEntityOfPage'] = $permalink;
111
+        }
112
+
113
+        return apply_filters(
114
+            'wl_no_vocabulary_term_jsonld_array',
115
+            array(
116
+                'jsonld'     => $jsonld,
117
+                'references' => $references,
118
+            ),
119
+            $term_id
120
+        );
121
+
122
+    }
123
+
124
+    private function relative_to_schema_context( $predicate ) {
125
+        return str_replace( 'http://schema.org/', '', $predicate );
126
+    }
127
+
128
+    private function process_value( $value, &$references ) {
129
+
130
+        if ( is_array( $value )
131
+             && count( $value ) > 0
132
+             && $value[0] instanceof \Wordlift_Property_Entity_Reference ) {
133
+
134
+            // All of the references from the custom fields are post references.
135
+            $references = array_merge(
136
+                $references,
137
+                array_map(
138
+                    function ( $property_entity_reference ) {
139
+                        /**
140
+                         * @var $property_entity_reference \Wordlift_Property_Entity_Reference
141
+                         */
142
+                        return $property_entity_reference->get_id();
143
+                    },
144
+                    $value
145
+                )
146
+            );
147
+
148
+            return array_map(
149
+                function ( $reference ) {
150
+                    /**
151
+                     * @var $reference \Wordlift_Property_Entity_Reference
152
+                     */
153
+                    return array( '@id' => $reference->get_url() );
154
+                },
155
+                $value
156
+            );
157
+
158
+        }
159
+
160
+        return $value;
161
+    }
162
+
163
+    /**
164
+     * Remove all the shortcodes from the content. We're using our own function
165
+     * because WordPress' own `strip_shortcodes` only takes into consideration
166
+     * shortcodes for installed plugins/themes.
167
+     *
168
+     * @since 3.12.0
169
+     *
170
+     * @param string $content The content with shortcodes.
171
+     *
172
+     * @return string The content without shortcodes.
173
+     */
174
+    private static function strip_all_shortcodes( $content ) {
175
+        return preg_replace( '/\[[^]]+\]/', '', $content );
176
+    }
177 177
 }
Please login to merge, or discard this patch.
src/wordlift/class-assertions.php 2 patches
Indentation   +100 added lines, -100 removed lines patch added patch discarded remove patch
@@ -15,105 +15,105 @@
 block discarded – undo
15 15
 
16 16
 class Assertions {
17 17
 
18
-	/**
19
-	 * Asserts that the provided value is of the specified type.
20
-	 *
21
-	 * @param mixed  $value The value to test.
22
-	 * @param string $type The expected type.
23
-	 *
24
-	 * @throws Exception when an error occurs.
25
-	 */
26
-	public static function assert_of_type( $value, $type ) {
27
-
28
-		// Check for nulls.
29
-		if ( null === $value ) {
30
-			throw new Exception( 'Value can`t be null.' );
31
-		}
32
-
33
-		// Check for type.
34
-		if ( get_class( $value ) !== $type ) {
35
-			throw new Exception( "Value must be a $type." );
36
-		}
37
-
38
-	}
39
-
40
-	/**
41
-	 * @throws Exception when the argument is not a string.
42
-	 */
43
-	public static function is_string( $arg, $message = 'Value must be a string' ) {
44
-		if ( ! is_string( $arg ) ) {
45
-			throw new Exception( $message );
46
-		}
47
-	}
48
-
49
-	/**
50
-	 * @throws Exception when actual doesn't match expected.
51
-	 */
52
-	public static function equals( $actual, $expected, $message = 'Values do not match' ) {
53
-		if ( $actual !== $expected ) {
54
-			throw new Exception( $message );
55
-		}
56
-	}
57
-
58
-	/**
59
-	 * @throws Exception when actual doesn't match expected.
60
-	 */
61
-	public static function array_key_exists( $arr, $key ) {
62
-		if ( ! array_key_exists( $key, $arr ) ) {
63
-			throw new Exception( "The key {$key} doesn't exist in array" );
64
-		}
65
-	}
66
-
67
-	/**
68
-	 * @throws Exception when the value doesn't match the pattern.
69
-	 */
70
-	public static function matches( $value, $pattern, $message = "Value doesn't match" ) {
71
-		if ( 1 !== preg_match( $pattern, $value ) ) {
72
-			throw new Exception( $message );
73
-		}
74
-
75
-	}
76
-
77
-	/**
78
-	 * @throws Exception when the value doesn't start with the provided scope.
79
-	 */
80
-	public static function starts_with( $value, $scope, $message = "Value doesn't start with provided scope" ) {
81
-		if ( 0 !== strpos( $value, $scope ) ) {
82
-			throw new Exception( $message );
83
-		}
84
-	}
85
-
86
-	/**
87
-	 * @throws Exception when the value is not of the specified type.
88
-	 */
89
-	public static function is_a( $value, $type, $message = 'Value is not of the required type' ) {
90
-		if ( ! is_a( $value, $type ) ) {
91
-			throw new Exception( $message );
92
-		}
93
-	}
94
-
95
-	public static function is_set( $value, $message = 'Value is not set' ) {
96
-		if ( ! isset( $value ) ) {
97
-			throw new Exception( $message );
98
-		}
99
-	}
100
-
101
-	public static function not_empty( $value, $message = "Value can't be empty" ) {
102
-		if ( empty( $value ) ) {
103
-			throw new Exception( $message );
104
-		}
105
-	}
106
-
107
-	public static function is_array( $value, $message = 'Value should be array' ) {
108
-		if ( ! is_array( $value ) ) {
109
-			throw new Exception( $message );
110
-		}
111
-	}
112
-
113
-	public static function is_numeric( $value, $message = 'Value should be numeric' ) {
114
-		if ( ! is_numeric( $value ) ) {
115
-			throw new Exception( $message );
116
-		}
117
-	}
18
+    /**
19
+     * Asserts that the provided value is of the specified type.
20
+     *
21
+     * @param mixed  $value The value to test.
22
+     * @param string $type The expected type.
23
+     *
24
+     * @throws Exception when an error occurs.
25
+     */
26
+    public static function assert_of_type( $value, $type ) {
27
+
28
+        // Check for nulls.
29
+        if ( null === $value ) {
30
+            throw new Exception( 'Value can`t be null.' );
31
+        }
32
+
33
+        // Check for type.
34
+        if ( get_class( $value ) !== $type ) {
35
+            throw new Exception( "Value must be a $type." );
36
+        }
37
+
38
+    }
39
+
40
+    /**
41
+     * @throws Exception when the argument is not a string.
42
+     */
43
+    public static function is_string( $arg, $message = 'Value must be a string' ) {
44
+        if ( ! is_string( $arg ) ) {
45
+            throw new Exception( $message );
46
+        }
47
+    }
48
+
49
+    /**
50
+     * @throws Exception when actual doesn't match expected.
51
+     */
52
+    public static function equals( $actual, $expected, $message = 'Values do not match' ) {
53
+        if ( $actual !== $expected ) {
54
+            throw new Exception( $message );
55
+        }
56
+    }
57
+
58
+    /**
59
+     * @throws Exception when actual doesn't match expected.
60
+     */
61
+    public static function array_key_exists( $arr, $key ) {
62
+        if ( ! array_key_exists( $key, $arr ) ) {
63
+            throw new Exception( "The key {$key} doesn't exist in array" );
64
+        }
65
+    }
66
+
67
+    /**
68
+     * @throws Exception when the value doesn't match the pattern.
69
+     */
70
+    public static function matches( $value, $pattern, $message = "Value doesn't match" ) {
71
+        if ( 1 !== preg_match( $pattern, $value ) ) {
72
+            throw new Exception( $message );
73
+        }
74
+
75
+    }
76
+
77
+    /**
78
+     * @throws Exception when the value doesn't start with the provided scope.
79
+     */
80
+    public static function starts_with( $value, $scope, $message = "Value doesn't start with provided scope" ) {
81
+        if ( 0 !== strpos( $value, $scope ) ) {
82
+            throw new Exception( $message );
83
+        }
84
+    }
85
+
86
+    /**
87
+     * @throws Exception when the value is not of the specified type.
88
+     */
89
+    public static function is_a( $value, $type, $message = 'Value is not of the required type' ) {
90
+        if ( ! is_a( $value, $type ) ) {
91
+            throw new Exception( $message );
92
+        }
93
+    }
94
+
95
+    public static function is_set( $value, $message = 'Value is not set' ) {
96
+        if ( ! isset( $value ) ) {
97
+            throw new Exception( $message );
98
+        }
99
+    }
100
+
101
+    public static function not_empty( $value, $message = "Value can't be empty" ) {
102
+        if ( empty( $value ) ) {
103
+            throw new Exception( $message );
104
+        }
105
+    }
106
+
107
+    public static function is_array( $value, $message = 'Value should be array' ) {
108
+        if ( ! is_array( $value ) ) {
109
+            throw new Exception( $message );
110
+        }
111
+    }
112
+
113
+    public static function is_numeric( $value, $message = 'Value should be numeric' ) {
114
+        if ( ! is_numeric( $value ) ) {
115
+            throw new Exception( $message );
116
+        }
117
+    }
118 118
 
119 119
 }
Please login to merge, or discard this patch.
Spacing   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -23,16 +23,16 @@  discard block
 block discarded – undo
23 23
 	 *
24 24
 	 * @throws Exception when an error occurs.
25 25
 	 */
26
-	public static function assert_of_type( $value, $type ) {
26
+	public static function assert_of_type($value, $type) {
27 27
 
28 28
 		// Check for nulls.
29
-		if ( null === $value ) {
30
-			throw new Exception( 'Value can`t be null.' );
29
+		if (null === $value) {
30
+			throw new Exception('Value can`t be null.');
31 31
 		}
32 32
 
33 33
 		// Check for type.
34
-		if ( get_class( $value ) !== $type ) {
35
-			throw new Exception( "Value must be a $type." );
34
+		if (get_class($value) !== $type) {
35
+			throw new Exception("Value must be a $type.");
36 36
 		}
37 37
 
38 38
 	}
@@ -40,36 +40,36 @@  discard block
 block discarded – undo
40 40
 	/**
41 41
 	 * @throws Exception when the argument is not a string.
42 42
 	 */
43
-	public static function is_string( $arg, $message = 'Value must be a string' ) {
44
-		if ( ! is_string( $arg ) ) {
45
-			throw new Exception( $message );
43
+	public static function is_string($arg, $message = 'Value must be a string') {
44
+		if ( ! is_string($arg)) {
45
+			throw new Exception($message);
46 46
 		}
47 47
 	}
48 48
 
49 49
 	/**
50 50
 	 * @throws Exception when actual doesn't match expected.
51 51
 	 */
52
-	public static function equals( $actual, $expected, $message = 'Values do not match' ) {
53
-		if ( $actual !== $expected ) {
54
-			throw new Exception( $message );
52
+	public static function equals($actual, $expected, $message = 'Values do not match') {
53
+		if ($actual !== $expected) {
54
+			throw new Exception($message);
55 55
 		}
56 56
 	}
57 57
 
58 58
 	/**
59 59
 	 * @throws Exception when actual doesn't match expected.
60 60
 	 */
61
-	public static function array_key_exists( $arr, $key ) {
62
-		if ( ! array_key_exists( $key, $arr ) ) {
63
-			throw new Exception( "The key {$key} doesn't exist in array" );
61
+	public static function array_key_exists($arr, $key) {
62
+		if ( ! array_key_exists($key, $arr)) {
63
+			throw new Exception("The key {$key} doesn't exist in array");
64 64
 		}
65 65
 	}
66 66
 
67 67
 	/**
68 68
 	 * @throws Exception when the value doesn't match the pattern.
69 69
 	 */
70
-	public static function matches( $value, $pattern, $message = "Value doesn't match" ) {
71
-		if ( 1 !== preg_match( $pattern, $value ) ) {
72
-			throw new Exception( $message );
70
+	public static function matches($value, $pattern, $message = "Value doesn't match") {
71
+		if (1 !== preg_match($pattern, $value)) {
72
+			throw new Exception($message);
73 73
 		}
74 74
 
75 75
 	}
@@ -77,42 +77,42 @@  discard block
 block discarded – undo
77 77
 	/**
78 78
 	 * @throws Exception when the value doesn't start with the provided scope.
79 79
 	 */
80
-	public static function starts_with( $value, $scope, $message = "Value doesn't start with provided scope" ) {
81
-		if ( 0 !== strpos( $value, $scope ) ) {
82
-			throw new Exception( $message );
80
+	public static function starts_with($value, $scope, $message = "Value doesn't start with provided scope") {
81
+		if (0 !== strpos($value, $scope)) {
82
+			throw new Exception($message);
83 83
 		}
84 84
 	}
85 85
 
86 86
 	/**
87 87
 	 * @throws Exception when the value is not of the specified type.
88 88
 	 */
89
-	public static function is_a( $value, $type, $message = 'Value is not of the required type' ) {
90
-		if ( ! is_a( $value, $type ) ) {
91
-			throw new Exception( $message );
89
+	public static function is_a($value, $type, $message = 'Value is not of the required type') {
90
+		if ( ! is_a($value, $type)) {
91
+			throw new Exception($message);
92 92
 		}
93 93
 	}
94 94
 
95
-	public static function is_set( $value, $message = 'Value is not set' ) {
96
-		if ( ! isset( $value ) ) {
97
-			throw new Exception( $message );
95
+	public static function is_set($value, $message = 'Value is not set') {
96
+		if ( ! isset($value)) {
97
+			throw new Exception($message);
98 98
 		}
99 99
 	}
100 100
 
101
-	public static function not_empty( $value, $message = "Value can't be empty" ) {
102
-		if ( empty( $value ) ) {
103
-			throw new Exception( $message );
101
+	public static function not_empty($value, $message = "Value can't be empty") {
102
+		if (empty($value)) {
103
+			throw new Exception($message);
104 104
 		}
105 105
 	}
106 106
 
107
-	public static function is_array( $value, $message = 'Value should be array' ) {
108
-		if ( ! is_array( $value ) ) {
109
-			throw new Exception( $message );
107
+	public static function is_array($value, $message = 'Value should be array') {
108
+		if ( ! is_array($value)) {
109
+			throw new Exception($message);
110 110
 		}
111 111
 	}
112 112
 
113
-	public static function is_numeric( $value, $message = 'Value should be numeric' ) {
114
-		if ( ! is_numeric( $value ) ) {
115
-			throw new Exception( $message );
113
+	public static function is_numeric($value, $message = 'Value should be numeric') {
114
+		if ( ! is_numeric($value)) {
115
+			throw new Exception($message);
116 116
 		}
117 117
 	}
118 118
 
Please login to merge, or discard this patch.
src/wordlift/jsonld/class-graph.php 2 patches
Indentation   +147 added lines, -147 removed lines patch added patch discarded remove patch
@@ -14,152 +14,152 @@
 block discarded – undo
14 14
  */
15 15
 class Graph {
16 16
 
17
-	/**
18
-	 * A single item in jsonld ( associative array )
19
-	 *
20
-	 * @var array
21
-	 */
22
-	private $main_jsonld;
23
-
24
-	/**
25
-	 * @var array<Content_Id>
26
-	 */
27
-	private $referenced_content_ids = array();
28
-	/**
29
-	 * @var \Wordlift_Post_Converter
30
-	 */
31
-	private $post_converter;
32
-	/**
33
-	 * @var \Wordlift_Term_JsonLd_Adapter
34
-	 */
35
-	private $term_converter;
36
-
37
-	public function __construct( $main_jsonld, $post_converter, $term_converter ) {
38
-		$this->main_jsonld    = $main_jsonld;
39
-		$this->post_converter = $post_converter;
40
-		$this->term_converter = $term_converter;
41
-	}
42
-
43
-	public function set_main_jsonld( $main_jsonld ) {
44
-		$this->main_jsonld = $main_jsonld;
45
-	}
46
-
47
-	public function get_main_jsonld() {
48
-		return $this->main_jsonld;
49
-	}
50
-
51
-	/**
52
-	 * @param $references array<int>
53
-	 *
54
-	 * @return Graph
55
-	 */
56
-	public function add_references( $refs ) {
57
-		Assertions::is_array( $refs );
58
-
59
-		foreach ( $refs as $ref ) {
60
-			$this->referenced_content_ids[] = Wordpress_Content_Id::create_post( $ref );
61
-		}
62
-		return $this;
63
-	}
64
-
65
-	/**
66
-	 * @param $reference_infos array
67
-	 *     Structure: [
68
-	 *         [
69
-	 *             'reference' => \Wordlift_Property_Entity_Reference,
70
-	 *         ],
71
-	 *         // more array items ...
72
-	 *     ]
73
-	 *
74
-	 * @return Graph
75
-	 */
76
-	public function add_required_reference_infos( $references_infos ) {
77
-
78
-		/**
79
-		 * @var $required_references array<\Wordlift_Property_Entity_Reference>
80
-		 */
81
-		$required_references = array_filter(
82
-			$references_infos,
83
-			function ( $item ) {
84
-				return isset( $item['reference'] ) &&
85
-					   // Check that the reference is required
86
-					   $item['reference']->get_required();
87
-			}
88
-		);
89
-
90
-		foreach ( $required_references as $required_reference ) {
91
-			$this->referenced_content_ids[] = new Wordpress_Content_Id(
92
-				$required_reference->get_id(),
93
-				$required_reference->get_type()
94
-			);
95
-		}
96
-		return $this;
97
-
98
-	}
99
-
100
-	/**
101
-	 * @param $relations Relations
102
-	 *
103
-	 * @return Graph
104
-	 */
105
-	public function add_relations( $relations ) {
106
-
107
-		foreach ( $relations->toArray() as $relation ) {
108
-
109
-			$this->referenced_content_ids[] = $relation->get_object();
110
-
111
-		}
112
-
113
-		return $this;
114
-	}
115
-
116
-	/**
117
-	 * @param $content_id Wordpress_Content_Id
118
-	 * @param $context int
119
-	 * @return array|bool
120
-	 */
121
-	private function expand( $content_id, $context ) {
122
-		$object_id   = $content_id->get_id();
123
-		$object_type = $content_id->get_type();
124
-
125
-		if ( $object_type === Object_Type_Enum::POST ) {
126
-			$references     = array();
127
-			$reference_info = array();
128
-			$relations      = new Relations();
129
-			return $this->post_converter->convert( $object_id, $references, $reference_info, $relations );
130
-		} elseif ( $object_type === Object_Type_Enum::TERM ) {
131
-			// Skip the Uncategorized term.
132
-			if ( 1 === $object_id ) {
133
-				return false;
134
-			}
135
-			return $this->term_converter->get( $object_id, $context );
136
-		} else {
137
-			return false;
138
-		}
139
-	}
140
-
141
-	/**
142
-	 * @param $context int Instance of Jsonld_Context_Enum
143
-	 *
144
-	 * @return array
145
-	 */
146
-	public function render( $context ) {
147
-
148
-		/**
149
-		 * This is possible because the toString() method of
150
-		 * Wordpress_Content_Id is used to get the unique value.
151
-		 */
152
-		$unique_content_ids = array_unique( $this->referenced_content_ids, SORT_STRING );
153
-
154
-		$result = array( $this->main_jsonld );
155
-
156
-		foreach ( $unique_content_ids as $unique_content_id ) {
157
-			$result[] = $this->expand( $unique_content_id, $context );
158
-		}
159
-
160
-		// Filter out the false and empty results.
161
-		return array_filter( $result );
162
-
163
-	}
17
+    /**
18
+     * A single item in jsonld ( associative array )
19
+     *
20
+     * @var array
21
+     */
22
+    private $main_jsonld;
23
+
24
+    /**
25
+     * @var array<Content_Id>
26
+     */
27
+    private $referenced_content_ids = array();
28
+    /**
29
+     * @var \Wordlift_Post_Converter
30
+     */
31
+    private $post_converter;
32
+    /**
33
+     * @var \Wordlift_Term_JsonLd_Adapter
34
+     */
35
+    private $term_converter;
36
+
37
+    public function __construct( $main_jsonld, $post_converter, $term_converter ) {
38
+        $this->main_jsonld    = $main_jsonld;
39
+        $this->post_converter = $post_converter;
40
+        $this->term_converter = $term_converter;
41
+    }
42
+
43
+    public function set_main_jsonld( $main_jsonld ) {
44
+        $this->main_jsonld = $main_jsonld;
45
+    }
46
+
47
+    public function get_main_jsonld() {
48
+        return $this->main_jsonld;
49
+    }
50
+
51
+    /**
52
+     * @param $references array<int>
53
+     *
54
+     * @return Graph
55
+     */
56
+    public function add_references( $refs ) {
57
+        Assertions::is_array( $refs );
58
+
59
+        foreach ( $refs as $ref ) {
60
+            $this->referenced_content_ids[] = Wordpress_Content_Id::create_post( $ref );
61
+        }
62
+        return $this;
63
+    }
64
+
65
+    /**
66
+     * @param $reference_infos array
67
+     *     Structure: [
68
+     *         [
69
+     *             'reference' => \Wordlift_Property_Entity_Reference,
70
+     *         ],
71
+     *         // more array items ...
72
+     *     ]
73
+     *
74
+     * @return Graph
75
+     */
76
+    public function add_required_reference_infos( $references_infos ) {
77
+
78
+        /**
79
+         * @var $required_references array<\Wordlift_Property_Entity_Reference>
80
+         */
81
+        $required_references = array_filter(
82
+            $references_infos,
83
+            function ( $item ) {
84
+                return isset( $item['reference'] ) &&
85
+                       // Check that the reference is required
86
+                       $item['reference']->get_required();
87
+            }
88
+        );
89
+
90
+        foreach ( $required_references as $required_reference ) {
91
+            $this->referenced_content_ids[] = new Wordpress_Content_Id(
92
+                $required_reference->get_id(),
93
+                $required_reference->get_type()
94
+            );
95
+        }
96
+        return $this;
97
+
98
+    }
99
+
100
+    /**
101
+     * @param $relations Relations
102
+     *
103
+     * @return Graph
104
+     */
105
+    public function add_relations( $relations ) {
106
+
107
+        foreach ( $relations->toArray() as $relation ) {
108
+
109
+            $this->referenced_content_ids[] = $relation->get_object();
110
+
111
+        }
112
+
113
+        return $this;
114
+    }
115
+
116
+    /**
117
+     * @param $content_id Wordpress_Content_Id
118
+     * @param $context int
119
+     * @return array|bool
120
+     */
121
+    private function expand( $content_id, $context ) {
122
+        $object_id   = $content_id->get_id();
123
+        $object_type = $content_id->get_type();
124
+
125
+        if ( $object_type === Object_Type_Enum::POST ) {
126
+            $references     = array();
127
+            $reference_info = array();
128
+            $relations      = new Relations();
129
+            return $this->post_converter->convert( $object_id, $references, $reference_info, $relations );
130
+        } elseif ( $object_type === Object_Type_Enum::TERM ) {
131
+            // Skip the Uncategorized term.
132
+            if ( 1 === $object_id ) {
133
+                return false;
134
+            }
135
+            return $this->term_converter->get( $object_id, $context );
136
+        } else {
137
+            return false;
138
+        }
139
+    }
140
+
141
+    /**
142
+     * @param $context int Instance of Jsonld_Context_Enum
143
+     *
144
+     * @return array
145
+     */
146
+    public function render( $context ) {
147
+
148
+        /**
149
+         * This is possible because the toString() method of
150
+         * Wordpress_Content_Id is used to get the unique value.
151
+         */
152
+        $unique_content_ids = array_unique( $this->referenced_content_ids, SORT_STRING );
153
+
154
+        $result = array( $this->main_jsonld );
155
+
156
+        foreach ( $unique_content_ids as $unique_content_id ) {
157
+            $result[] = $this->expand( $unique_content_id, $context );
158
+        }
159
+
160
+        // Filter out the false and empty results.
161
+        return array_filter( $result );
162
+
163
+    }
164 164
 
165 165
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -34,13 +34,13 @@  discard block
 block discarded – undo
34 34
 	 */
35 35
 	private $term_converter;
36 36
 
37
-	public function __construct( $main_jsonld, $post_converter, $term_converter ) {
37
+	public function __construct($main_jsonld, $post_converter, $term_converter) {
38 38
 		$this->main_jsonld    = $main_jsonld;
39 39
 		$this->post_converter = $post_converter;
40 40
 		$this->term_converter = $term_converter;
41 41
 	}
42 42
 
43
-	public function set_main_jsonld( $main_jsonld ) {
43
+	public function set_main_jsonld($main_jsonld) {
44 44
 		$this->main_jsonld = $main_jsonld;
45 45
 	}
46 46
 
@@ -53,11 +53,11 @@  discard block
 block discarded – undo
53 53
 	 *
54 54
 	 * @return Graph
55 55
 	 */
56
-	public function add_references( $refs ) {
57
-		Assertions::is_array( $refs );
56
+	public function add_references($refs) {
57
+		Assertions::is_array($refs);
58 58
 
59
-		foreach ( $refs as $ref ) {
60
-			$this->referenced_content_ids[] = Wordpress_Content_Id::create_post( $ref );
59
+		foreach ($refs as $ref) {
60
+			$this->referenced_content_ids[] = Wordpress_Content_Id::create_post($ref);
61 61
 		}
62 62
 		return $this;
63 63
 	}
@@ -73,21 +73,21 @@  discard block
 block discarded – undo
73 73
 	 *
74 74
 	 * @return Graph
75 75
 	 */
76
-	public function add_required_reference_infos( $references_infos ) {
76
+	public function add_required_reference_infos($references_infos) {
77 77
 
78 78
 		/**
79 79
 		 * @var $required_references array<\Wordlift_Property_Entity_Reference>
80 80
 		 */
81 81
 		$required_references = array_filter(
82 82
 			$references_infos,
83
-			function ( $item ) {
84
-				return isset( $item['reference'] ) &&
83
+			function($item) {
84
+				return isset($item['reference']) &&
85 85
 					   // Check that the reference is required
86 86
 					   $item['reference']->get_required();
87 87
 			}
88 88
 		);
89 89
 
90
-		foreach ( $required_references as $required_reference ) {
90
+		foreach ($required_references as $required_reference) {
91 91
 			$this->referenced_content_ids[] = new Wordpress_Content_Id(
92 92
 				$required_reference->get_id(),
93 93
 				$required_reference->get_type()
@@ -102,9 +102,9 @@  discard block
 block discarded – undo
102 102
 	 *
103 103
 	 * @return Graph
104 104
 	 */
105
-	public function add_relations( $relations ) {
105
+	public function add_relations($relations) {
106 106
 
107
-		foreach ( $relations->toArray() as $relation ) {
107
+		foreach ($relations->toArray() as $relation) {
108 108
 
109 109
 			$this->referenced_content_ids[] = $relation->get_object();
110 110
 
@@ -118,21 +118,21 @@  discard block
 block discarded – undo
118 118
 	 * @param $context int
119 119
 	 * @return array|bool
120 120
 	 */
121
-	private function expand( $content_id, $context ) {
121
+	private function expand($content_id, $context) {
122 122
 		$object_id   = $content_id->get_id();
123 123
 		$object_type = $content_id->get_type();
124 124
 
125
-		if ( $object_type === Object_Type_Enum::POST ) {
125
+		if ($object_type === Object_Type_Enum::POST) {
126 126
 			$references     = array();
127 127
 			$reference_info = array();
128 128
 			$relations      = new Relations();
129
-			return $this->post_converter->convert( $object_id, $references, $reference_info, $relations );
130
-		} elseif ( $object_type === Object_Type_Enum::TERM ) {
129
+			return $this->post_converter->convert($object_id, $references, $reference_info, $relations);
130
+		} elseif ($object_type === Object_Type_Enum::TERM) {
131 131
 			// Skip the Uncategorized term.
132
-			if ( 1 === $object_id ) {
132
+			if (1 === $object_id) {
133 133
 				return false;
134 134
 			}
135
-			return $this->term_converter->get( $object_id, $context );
135
+			return $this->term_converter->get($object_id, $context);
136 136
 		} else {
137 137
 			return false;
138 138
 		}
@@ -143,22 +143,22 @@  discard block
 block discarded – undo
143 143
 	 *
144 144
 	 * @return array
145 145
 	 */
146
-	public function render( $context ) {
146
+	public function render($context) {
147 147
 
148 148
 		/**
149 149
 		 * This is possible because the toString() method of
150 150
 		 * Wordpress_Content_Id is used to get the unique value.
151 151
 		 */
152
-		$unique_content_ids = array_unique( $this->referenced_content_ids, SORT_STRING );
152
+		$unique_content_ids = array_unique($this->referenced_content_ids, SORT_STRING);
153 153
 
154
-		$result = array( $this->main_jsonld );
154
+		$result = array($this->main_jsonld);
155 155
 
156
-		foreach ( $unique_content_ids as $unique_content_id ) {
157
-			$result[] = $this->expand( $unique_content_id, $context );
156
+		foreach ($unique_content_ids as $unique_content_id) {
157
+			$result[] = $this->expand($unique_content_id, $context);
158 158
 		}
159 159
 
160 160
 		// Filter out the false and empty results.
161
-		return array_filter( $result );
161
+		return array_filter($result);
162 162
 
163 163
 	}
164 164
 
Please login to merge, or discard this patch.
src/wordlift/jsonld/class-jsonld-article-wrapper.php 2 patches
Indentation   +152 added lines, -152 removed lines patch added patch discarded remove patch
@@ -7,167 +7,167 @@
 block discarded – undo
7 7
 
8 8
 class Jsonld_Article_Wrapper {
9 9
 
10
-	public static $article_types = array(
11
-		'Article',
12
-		'AdvertiserContentArticle',
13
-		'NewsArticle',
14
-		'AnalysisNewsArticle',
15
-		'AskPublicNewsArticle',
16
-		'BackgroundNewsArticle',
17
-		'OpinionNewsArticle',
18
-		'ReportageNewsArticle',
19
-		'ReviewNewsArticle',
20
-		'Report',
21
-		'SatiricalArticle',
22
-		'ScholarlyArticle',
23
-		'MedicalScholarlyArticle',
24
-		'SocialMediaPosting',
25
-		'BlogPosting',
26
-		'LiveBlogPosting',
27
-		'DiscussionForumPosting',
28
-		'TechArticle',
29
-		'APIReference',
30
-	);
31
-
32
-	/**
33
-	 * @var Wordlift_Post_To_Jsonld_Converter
34
-	 */
35
-	private $post_to_jsonld_converter;
36
-	/**
37
-	 * @var \Wordlift_Cached_Post_Converter
38
-	 */
39
-	private $cached_postid_to_jsonld_converter;
40
-	/**
41
-	 * @var \Wordlift_Entity_Uri_Service
42
-	 */
43
-	private $entity_uri_service;
44
-
45
-	/**
46
-	 * Jsonld_Article_Wrapper constructor.
47
-	 *
48
-	 * @param Wordlift_Post_To_Jsonld_Converter $post_to_jsonld_converter
49
-	 * @param $cached_postid_to_jsonld_converter
50
-	 */
51
-	public function __construct( $post_to_jsonld_converter, $cached_postid_to_jsonld_converter ) {
52
-
53
-		$this->post_to_jsonld_converter = $post_to_jsonld_converter->new_instance_with_filters_disabled();
54
-
55
-		add_filter(
56
-			'wl_after_get_jsonld',
57
-			array(
58
-				$this,
59
-				'after_get_jsonld',
60
-			),
61
-			PHP_INT_MAX - 100,
62
-			3
63
-		);
64
-
65
-		$this->cached_postid_to_jsonld_converter = $cached_postid_to_jsonld_converter;
66
-
67
-		$this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
68
-	}
69
-
70
-	public function after_get_jsonld( $jsonld, $post_id, $context ) {
71
-
72
-		// Invalid data structure
73
-		if ( ! is_array( $jsonld ) || ! isset( $jsonld[0] ) || ! is_array( $jsonld[0] ) ) {
74
-			return $jsonld;
75
-		}
76
-
77
-		if ( Jsonld_Context_Enum::PAGE !== $context
78
-			 // Returns true for "1", "true", "on" and "yes". Returns false otherwise.
79
-			 && ! filter_input( INPUT_GET, 'article_wrapper', FILTER_VALIDATE_BOOLEAN ) ) {
80
-			return $jsonld;
81
-		}
82
-
83
-		// Copy the 1st array element
84
-		$post_jsonld = $jsonld[0];
85
-
86
-		// Don't wrap in article if the json-ld is already about an Article (or its descendants). `@type` must be
87
-		// in the schema.org context, i.e. `Article`, not `http://schema.org/Article`.
88
-		if ( ! isset( $post_jsonld['@id'] ) || ! isset( $post_jsonld['@type'] ) || $this->is_article( $post_jsonld['@type'] ) ) {
89
-			return $jsonld;
90
-		}
91
-
92
-		$references      = array();
93
-		$reference_infos = array();
94
-
95
-		// Convert the post as Article.
96
-		$article_jsonld = $this->post_to_jsonld_converter->convert( $post_id, $references, $reference_infos, new Relations() );
97
-
98
-		$article_jsonld['@id'] = $post_jsonld['@id'] . '#article';
99
-		// Reset the type, since by default the type assigned via the Entity Type taxonomy is used.
100
-		$article_jsonld['@type'] = 'Article';
101
-		$article_jsonld['about'] = array( '@id' => $post_jsonld['@id'] );
102
-
103
-		// Copy over the URLs.
104
-		if ( isset( $post_jsonld['url'] ) ) {
105
-			$article_jsonld['url'] = $post_jsonld['url'];
106
-		}
107
-
108
-		array_unshift( $jsonld, $article_jsonld );
109
-
110
-		$author_jsonld = $this->get_author_linked_entity( $article_jsonld );
111
-
112
-		/**
113
-		 * The author entities can be present in graph for some entity types
114
-		 * for Person and Organization, so check before we add it to graph.
115
-		 * reference : https://schema.org/author
116
-		 */
117
-		if ( $author_jsonld && ! $this->is_author_entity_present_in_graph( $jsonld, $article_jsonld['author']['@id'] ) ) {
118
-			$jsonld[] = $author_jsonld;
119
-		}
120
-
121
-		return $jsonld;
122
-	}
123
-
124
-	private function is_article( $schema_types ) {
125
-
126
-		$array_intersect = array_intersect( self::$article_types, (array) $schema_types );
127
-
128
-		return ! empty( $array_intersect );
129
-	}
130
-
131
-	private function get_author_linked_entity( $article_jsonld ) {
132
-		if ( ! array_key_exists( 'author', $article_jsonld ) ) {
133
-			return false;
134
-		}
135
-
136
-		$author = $article_jsonld['author'];
10
+    public static $article_types = array(
11
+        'Article',
12
+        'AdvertiserContentArticle',
13
+        'NewsArticle',
14
+        'AnalysisNewsArticle',
15
+        'AskPublicNewsArticle',
16
+        'BackgroundNewsArticle',
17
+        'OpinionNewsArticle',
18
+        'ReportageNewsArticle',
19
+        'ReviewNewsArticle',
20
+        'Report',
21
+        'SatiricalArticle',
22
+        'ScholarlyArticle',
23
+        'MedicalScholarlyArticle',
24
+        'SocialMediaPosting',
25
+        'BlogPosting',
26
+        'LiveBlogPosting',
27
+        'DiscussionForumPosting',
28
+        'TechArticle',
29
+        'APIReference',
30
+    );
31
+
32
+    /**
33
+     * @var Wordlift_Post_To_Jsonld_Converter
34
+     */
35
+    private $post_to_jsonld_converter;
36
+    /**
37
+     * @var \Wordlift_Cached_Post_Converter
38
+     */
39
+    private $cached_postid_to_jsonld_converter;
40
+    /**
41
+     * @var \Wordlift_Entity_Uri_Service
42
+     */
43
+    private $entity_uri_service;
44
+
45
+    /**
46
+     * Jsonld_Article_Wrapper constructor.
47
+     *
48
+     * @param Wordlift_Post_To_Jsonld_Converter $post_to_jsonld_converter
49
+     * @param $cached_postid_to_jsonld_converter
50
+     */
51
+    public function __construct( $post_to_jsonld_converter, $cached_postid_to_jsonld_converter ) {
52
+
53
+        $this->post_to_jsonld_converter = $post_to_jsonld_converter->new_instance_with_filters_disabled();
54
+
55
+        add_filter(
56
+            'wl_after_get_jsonld',
57
+            array(
58
+                $this,
59
+                'after_get_jsonld',
60
+            ),
61
+            PHP_INT_MAX - 100,
62
+            3
63
+        );
64
+
65
+        $this->cached_postid_to_jsonld_converter = $cached_postid_to_jsonld_converter;
66
+
67
+        $this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
68
+    }
69
+
70
+    public function after_get_jsonld( $jsonld, $post_id, $context ) {
71
+
72
+        // Invalid data structure
73
+        if ( ! is_array( $jsonld ) || ! isset( $jsonld[0] ) || ! is_array( $jsonld[0] ) ) {
74
+            return $jsonld;
75
+        }
76
+
77
+        if ( Jsonld_Context_Enum::PAGE !== $context
78
+                // Returns true for "1", "true", "on" and "yes". Returns false otherwise.
79
+             && ! filter_input( INPUT_GET, 'article_wrapper', FILTER_VALIDATE_BOOLEAN ) ) {
80
+            return $jsonld;
81
+        }
82
+
83
+        // Copy the 1st array element
84
+        $post_jsonld = $jsonld[0];
85
+
86
+        // Don't wrap in article if the json-ld is already about an Article (or its descendants). `@type` must be
87
+        // in the schema.org context, i.e. `Article`, not `http://schema.org/Article`.
88
+        if ( ! isset( $post_jsonld['@id'] ) || ! isset( $post_jsonld['@type'] ) || $this->is_article( $post_jsonld['@type'] ) ) {
89
+            return $jsonld;
90
+        }
91
+
92
+        $references      = array();
93
+        $reference_infos = array();
94
+
95
+        // Convert the post as Article.
96
+        $article_jsonld = $this->post_to_jsonld_converter->convert( $post_id, $references, $reference_infos, new Relations() );
97
+
98
+        $article_jsonld['@id'] = $post_jsonld['@id'] . '#article';
99
+        // Reset the type, since by default the type assigned via the Entity Type taxonomy is used.
100
+        $article_jsonld['@type'] = 'Article';
101
+        $article_jsonld['about'] = array( '@id' => $post_jsonld['@id'] );
102
+
103
+        // Copy over the URLs.
104
+        if ( isset( $post_jsonld['url'] ) ) {
105
+            $article_jsonld['url'] = $post_jsonld['url'];
106
+        }
107
+
108
+        array_unshift( $jsonld, $article_jsonld );
109
+
110
+        $author_jsonld = $this->get_author_linked_entity( $article_jsonld );
111
+
112
+        /**
113
+         * The author entities can be present in graph for some entity types
114
+         * for Person and Organization, so check before we add it to graph.
115
+         * reference : https://schema.org/author
116
+         */
117
+        if ( $author_jsonld && ! $this->is_author_entity_present_in_graph( $jsonld, $article_jsonld['author']['@id'] ) ) {
118
+            $jsonld[] = $author_jsonld;
119
+        }
120
+
121
+        return $jsonld;
122
+    }
123
+
124
+    private function is_article( $schema_types ) {
125
+
126
+        $array_intersect = array_intersect( self::$article_types, (array) $schema_types );
127
+
128
+        return ! empty( $array_intersect );
129
+    }
130
+
131
+    private function get_author_linked_entity( $article_jsonld ) {
132
+        if ( ! array_key_exists( 'author', $article_jsonld ) ) {
133
+            return false;
134
+        }
135
+
136
+        $author = $article_jsonld['author'];
137 137
 
138
-		if ( count( array_keys( $author ) ) !== 1 || ! array_key_exists( '@id', $author ) ) {
139
-			return false;
140
-		}
138
+        if ( count( array_keys( $author ) ) !== 1 || ! array_key_exists( '@id', $author ) ) {
139
+            return false;
140
+        }
141 141
 
142
-		$author_linked_entity_id = $author['@id'];
142
+        $author_linked_entity_id = $author['@id'];
143 143
 
144
-		$author_entity_post = $this->entity_uri_service->get_entity( $author_linked_entity_id );
144
+        $author_entity_post = $this->entity_uri_service->get_entity( $author_linked_entity_id );
145 145
 
146
-		if ( ! $author_entity_post instanceof \WP_Post ) {
147
-			return false;
148
-		}
146
+        if ( ! $author_entity_post instanceof \WP_Post ) {
147
+            return false;
148
+        }
149 149
 
150
-		$references      = array();
151
-		$reference_infos = array();
150
+        $references      = array();
151
+        $reference_infos = array();
152 152
 
153
-		return $this->cached_postid_to_jsonld_converter->convert(
154
-			$author_entity_post->ID,
155
-			$references,
156
-			$reference_infos,
157
-			new Relations()
158
-		);
153
+        return $this->cached_postid_to_jsonld_converter->convert(
154
+            $author_entity_post->ID,
155
+            $references,
156
+            $reference_infos,
157
+            new Relations()
158
+        );
159 159
 
160
-	}
160
+    }
161 161
 
162
-	private function is_author_entity_present_in_graph( $jsonld, $author_entity_id ) {
162
+    private function is_author_entity_present_in_graph( $jsonld, $author_entity_id ) {
163 163
 
164
-		foreach ( $jsonld as $item ) {
165
-			if ( $item && array_key_exists( '@id', $item ) && $item['@id'] === $author_entity_id ) {
166
-				return true;
167
-			}
168
-		}
164
+        foreach ( $jsonld as $item ) {
165
+            if ( $item && array_key_exists( '@id', $item ) && $item['@id'] === $author_entity_id ) {
166
+                return true;
167
+            }
168
+        }
169 169
 
170
-		return false;
171
-	}
170
+        return false;
171
+    }
172 172
 
173 173
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -48,7 +48,7 @@  discard block
 block discarded – undo
48 48
 	 * @param Wordlift_Post_To_Jsonld_Converter $post_to_jsonld_converter
49 49
 	 * @param $cached_postid_to_jsonld_converter
50 50
 	 */
51
-	public function __construct( $post_to_jsonld_converter, $cached_postid_to_jsonld_converter ) {
51
+	public function __construct($post_to_jsonld_converter, $cached_postid_to_jsonld_converter) {
52 52
 
53 53
 		$this->post_to_jsonld_converter = $post_to_jsonld_converter->new_instance_with_filters_disabled();
54 54
 
@@ -67,16 +67,16 @@  discard block
 block discarded – undo
67 67
 		$this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
68 68
 	}
69 69
 
70
-	public function after_get_jsonld( $jsonld, $post_id, $context ) {
70
+	public function after_get_jsonld($jsonld, $post_id, $context) {
71 71
 
72 72
 		// Invalid data structure
73
-		if ( ! is_array( $jsonld ) || ! isset( $jsonld[0] ) || ! is_array( $jsonld[0] ) ) {
73
+		if ( ! is_array($jsonld) || ! isset($jsonld[0]) || ! is_array($jsonld[0])) {
74 74
 			return $jsonld;
75 75
 		}
76 76
 
77
-		if ( Jsonld_Context_Enum::PAGE !== $context
77
+		if (Jsonld_Context_Enum::PAGE !== $context
78 78
 			 // Returns true for "1", "true", "on" and "yes". Returns false otherwise.
79
-			 && ! filter_input( INPUT_GET, 'article_wrapper', FILTER_VALIDATE_BOOLEAN ) ) {
79
+			 && ! filter_input(INPUT_GET, 'article_wrapper', FILTER_VALIDATE_BOOLEAN)) {
80 80
 			return $jsonld;
81 81
 		}
82 82
 
@@ -85,7 +85,7 @@  discard block
 block discarded – undo
85 85
 
86 86
 		// Don't wrap in article if the json-ld is already about an Article (or its descendants). `@type` must be
87 87
 		// in the schema.org context, i.e. `Article`, not `http://schema.org/Article`.
88
-		if ( ! isset( $post_jsonld['@id'] ) || ! isset( $post_jsonld['@type'] ) || $this->is_article( $post_jsonld['@type'] ) ) {
88
+		if ( ! isset($post_jsonld['@id']) || ! isset($post_jsonld['@type']) || $this->is_article($post_jsonld['@type'])) {
89 89
 			return $jsonld;
90 90
 		}
91 91
 
@@ -93,57 +93,57 @@  discard block
 block discarded – undo
93 93
 		$reference_infos = array();
94 94
 
95 95
 		// Convert the post as Article.
96
-		$article_jsonld = $this->post_to_jsonld_converter->convert( $post_id, $references, $reference_infos, new Relations() );
96
+		$article_jsonld = $this->post_to_jsonld_converter->convert($post_id, $references, $reference_infos, new Relations());
97 97
 
98
-		$article_jsonld['@id'] = $post_jsonld['@id'] . '#article';
98
+		$article_jsonld['@id'] = $post_jsonld['@id'].'#article';
99 99
 		// Reset the type, since by default the type assigned via the Entity Type taxonomy is used.
100 100
 		$article_jsonld['@type'] = 'Article';
101
-		$article_jsonld['about'] = array( '@id' => $post_jsonld['@id'] );
101
+		$article_jsonld['about'] = array('@id' => $post_jsonld['@id']);
102 102
 
103 103
 		// Copy over the URLs.
104
-		if ( isset( $post_jsonld['url'] ) ) {
104
+		if (isset($post_jsonld['url'])) {
105 105
 			$article_jsonld['url'] = $post_jsonld['url'];
106 106
 		}
107 107
 
108
-		array_unshift( $jsonld, $article_jsonld );
108
+		array_unshift($jsonld, $article_jsonld);
109 109
 
110
-		$author_jsonld = $this->get_author_linked_entity( $article_jsonld );
110
+		$author_jsonld = $this->get_author_linked_entity($article_jsonld);
111 111
 
112 112
 		/**
113 113
 		 * The author entities can be present in graph for some entity types
114 114
 		 * for Person and Organization, so check before we add it to graph.
115 115
 		 * reference : https://schema.org/author
116 116
 		 */
117
-		if ( $author_jsonld && ! $this->is_author_entity_present_in_graph( $jsonld, $article_jsonld['author']['@id'] ) ) {
117
+		if ($author_jsonld && ! $this->is_author_entity_present_in_graph($jsonld, $article_jsonld['author']['@id'])) {
118 118
 			$jsonld[] = $author_jsonld;
119 119
 		}
120 120
 
121 121
 		return $jsonld;
122 122
 	}
123 123
 
124
-	private function is_article( $schema_types ) {
124
+	private function is_article($schema_types) {
125 125
 
126
-		$array_intersect = array_intersect( self::$article_types, (array) $schema_types );
126
+		$array_intersect = array_intersect(self::$article_types, (array) $schema_types);
127 127
 
128
-		return ! empty( $array_intersect );
128
+		return ! empty($array_intersect);
129 129
 	}
130 130
 
131
-	private function get_author_linked_entity( $article_jsonld ) {
132
-		if ( ! array_key_exists( 'author', $article_jsonld ) ) {
131
+	private function get_author_linked_entity($article_jsonld) {
132
+		if ( ! array_key_exists('author', $article_jsonld)) {
133 133
 			return false;
134 134
 		}
135 135
 
136 136
 		$author = $article_jsonld['author'];
137 137
 
138
-		if ( count( array_keys( $author ) ) !== 1 || ! array_key_exists( '@id', $author ) ) {
138
+		if (count(array_keys($author)) !== 1 || ! array_key_exists('@id', $author)) {
139 139
 			return false;
140 140
 		}
141 141
 
142 142
 		$author_linked_entity_id = $author['@id'];
143 143
 
144
-		$author_entity_post = $this->entity_uri_service->get_entity( $author_linked_entity_id );
144
+		$author_entity_post = $this->entity_uri_service->get_entity($author_linked_entity_id);
145 145
 
146
-		if ( ! $author_entity_post instanceof \WP_Post ) {
146
+		if ( ! $author_entity_post instanceof \WP_Post) {
147 147
 			return false;
148 148
 		}
149 149
 
@@ -159,10 +159,10 @@  discard block
 block discarded – undo
159 159
 
160 160
 	}
161 161
 
162
-	private function is_author_entity_present_in_graph( $jsonld, $author_entity_id ) {
162
+	private function is_author_entity_present_in_graph($jsonld, $author_entity_id) {
163 163
 
164
-		foreach ( $jsonld as $item ) {
165
-			if ( $item && array_key_exists( '@id', $item ) && $item['@id'] === $author_entity_id ) {
164
+		foreach ($jsonld as $item) {
165
+			if ($item && array_key_exists('@id', $item) && $item['@id'] === $author_entity_id) {
166 166
 				return true;
167 167
 			}
168 168
 		}
Please login to merge, or discard this patch.
src/wordlift/analysis/occurrences/class-occurrences.php 2 patches
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -10,9 +10,9 @@
 block discarded – undo
10 10
 
11 11
 interface Occurrences {
12 12
 
13
-	/**
14
-	 * @return array Return json data structure.
15
-	 */
16
-	public function add_occurrences_to_entities( $occurrences, $json, $post_id );
13
+    /**
14
+     * @return array Return json data structure.
15
+     */
16
+    public function add_occurrences_to_entities( $occurrences, $json, $post_id );
17 17
 
18 18
 }
Please login to merge, or discard this patch.
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -13,6 +13,6 @@
 block discarded – undo
13 13
 	/**
14 14
 	 * @return array Return json data structure.
15 15
 	 */
16
-	public function add_occurrences_to_entities( $occurrences, $json, $post_id );
16
+	public function add_occurrences_to_entities($occurrences, $json, $post_id);
17 17
 
18 18
 }
Please login to merge, or discard this patch.
src/wordlift/analysis/occurrences/class-default-strategy.php 2 patches
Indentation   +12 added lines, -12 removed lines patch added patch discarded remove patch
@@ -11,20 +11,20 @@
 block discarded – undo
11 11
 
12 12
 class Default_Strategy extends Singleton implements Occurrences {
13 13
 
14
-	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
15
-	public function add_occurrences_to_entities( $occurrences, $json, $post_id ) {
14
+    // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
15
+    public function add_occurrences_to_entities( $occurrences, $json, $post_id ) {
16 16
 
17
-		foreach ( $json->entities as $id => $entity ) {
17
+        foreach ( $json->entities as $id => $entity ) {
18 18
 
19
-			$json->entities->{$id}->occurrences = isset( $occurrences[ $id ] ) ? $occurrences[ $id ] : array();
19
+            $json->entities->{$id}->occurrences = isset( $occurrences[ $id ] ) ? $occurrences[ $id ] : array();
20 20
 
21
-			foreach ( $json->entities->{$id}->occurrences as $annotation_id ) {
22
-				$json->entities->{$id}->annotations[ $annotation_id ] = array(
23
-					'id' => $annotation_id,
24
-				);
25
-			}
26
-		}
21
+            foreach ( $json->entities->{$id}->occurrences as $annotation_id ) {
22
+                $json->entities->{$id}->annotations[ $annotation_id ] = array(
23
+                    'id' => $annotation_id,
24
+                );
25
+            }
26
+        }
27 27
 
28
-		return $json;
29
-	}
28
+        return $json;
29
+    }
30 30
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -12,14 +12,14 @@
 block discarded – undo
12 12
 class Default_Strategy extends Singleton implements Occurrences {
13 13
 
14 14
 	// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
15
-	public function add_occurrences_to_entities( $occurrences, $json, $post_id ) {
15
+	public function add_occurrences_to_entities($occurrences, $json, $post_id) {
16 16
 
17
-		foreach ( $json->entities as $id => $entity ) {
17
+		foreach ($json->entities as $id => $entity) {
18 18
 
19
-			$json->entities->{$id}->occurrences = isset( $occurrences[ $id ] ) ? $occurrences[ $id ] : array();
19
+			$json->entities->{$id}->occurrences = isset($occurrences[$id]) ? $occurrences[$id] : array();
20 20
 
21
-			foreach ( $json->entities->{$id}->occurrences as $annotation_id ) {
22
-				$json->entities->{$id}->annotations[ $annotation_id ] = array(
21
+			foreach ($json->entities->{$id}->occurrences as $annotation_id) {
22
+				$json->entities->{$id}->annotations[$annotation_id] = array(
23 23
 					'id' => $annotation_id,
24 24
 				);
25 25
 			}
Please login to merge, or discard this patch.
src/wordlift/analysis/response/class-analysis-response-ops.php 2 patches
Indentation   +377 added lines, -377 removed lines patch added patch discarded remove patch
@@ -16,382 +16,382 @@
 block discarded – undo
16 16
 
17 17
 class Analysis_Response_Ops {
18 18
 
19
-	/**
20
-	 * The analysis response json.
21
-	 *
22
-	 * @since 3.21.5
23
-	 * @access private
24
-	 * @var mixed $json Holds the analysis response json.
25
-	 */
26
-	private $json;
27
-
28
-	/**
29
-	 * Holds the {@link Wordlift_Entity_Uri_Service}.
30
-	 *
31
-	 * @since 3.21.5
32
-	 * @access private
33
-	 * @var \Wordlift_Entity_Uri_Service $entity_uri_service The {@link Wordlift_Entity_Uri_Service} instance.
34
-	 */
35
-	private $entity_uri_service;
36
-
37
-	/**
38
-	 * @var Entity_Helper
39
-	 */
40
-	private $entity_helper;
41
-
42
-	/**
43
-	 * @var int $post_id
44
-	 */
45
-	private $post_id;
46
-
47
-	/**
48
-	 * Analysis_Response_Ops constructor.
49
-	 *
50
-	 * @param \Wordlift_Entity_Uri_Service $entity_uri_service The {@link Wordlift_Entity_Uri_Service}.
51
-	 * @param Entity_Helper                $entity_helper The {@link Entity_Helper}.
52
-	 * @param mixed                        $json The analysis response json.
53
-	 *
54
-	 * @since 3.21.5
55
-	 */
56
-	public function __construct( $entity_uri_service, $entity_helper, $json, $post_id ) {
57
-		$this->json               = $json;
58
-		$this->entity_uri_service = $entity_uri_service;
59
-		$this->entity_helper      = $entity_helper;
60
-		$this->post_id            = $post_id;
61
-	}
62
-
63
-	/**
64
-	 * Switches remote entities, i.e. entities with id outside the local dataset, to local entities.
65
-	 *
66
-	 * The function takes all the entities that have an id which is not local. For each remote entity, a list of URIs
67
-	 * is built comprising the entity id and the sameAs. Then a query is issued in the local database to find potential
68
-	 * matches from the local vocabulary.
69
-	 *
70
-	 * If found, the entity id is swapped with the local id and the remote id is added to the sameAs.
71
-	 *
72
-	 * @return Analysis_Response_Ops The current Analysis_Response_Ops instance.
73
-	 */
74
-	public function make_entities_local() {
75
-
76
-		if ( ! isset( $this->json->entities ) ) {
77
-			return $this;
78
-		}
79
-
80
-		// Get the URIs.
81
-		$uris     = array_keys( get_object_vars( $this->json->entities ) );
82
-		$mappings = $this->entity_helper->map_many_to_local( $uris );
83
-
84
-		foreach ( $mappings as $external_uri => $internal_uri ) {
85
-
86
-			// Move the data from the external URI to the internal URI.
87
-			if ( ! isset( $this->json->entities->{$internal_uri} ) ) {
88
-				$this->json->entities->{$internal_uri} = $this->json->entities->{$external_uri};
89
-			}
90
-
91
-			// Ensure sameAs is an array.
92
-			if ( ! isset( $this->json->entities->{$internal_uri}->sameAs )
93
-				 || ! is_array( $this->json->entities->{$internal_uri}->sameAs ) ) {
94
-				$this->json->entities->{$internal_uri}->sameAs = array();
95
-			}
96
-
97
-			// Add the external URI as sameAs.
98
-			$this->json->entities->{$internal_uri}->sameAs[] = $external_uri;
99
-
100
-			// Finally remove the external URI.
101
-			unset( $this->json->entities->{$external_uri} );
102
-		}
103
-
104
-		// Set the internal uri in the annotation for the entityMatch in annotations.
105
-		if ( isset( $this->json->annotations ) ) {
106
-			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
107
-			foreach ( $this->json->annotations as $key => $annotation ) {
108
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
109
-				if ( isset( $annotation->entityMatches ) ) {
110
-					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
111
-					foreach ( $annotation->entityMatches as $match ) {
112
-						// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
113
-						if ( isset( $match->entityId ) && isset( $mappings[ $match->entityId ] ) ) {
114
-							// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
115
-							$match->entityId = $mappings[ $match->entityId ];
116
-						}
117
-					}
118
-				}
119
-			}
120
-		}
121
-
122
-		return $this;
123
-	}
124
-
125
-	/**
126
-	 * Add occurrences by parsing the provided html content.
127
-	 *
128
-	 * @param string $content The html content with annotations.
129
-	 *
130
-	 * @return Analysis_Response_Ops The {@link Analysis_Response_Ops} instance.
131
-	 *
132
-	 * @since 3.23.7 refactor the regex pattern to take into account that there might be css classes between textannotation
133
-	 *  and disambiguated.
134
-	 *
135
-	 * @link https://github.com/insideout10/wordlift-plugin/issues/1001
136
-	 */
137
-	public function add_occurrences( $content ) {
138
-
139
-		// Try to get all the disambiguated annotations and bail out if an error occurs.
140
-		if ( false === preg_match_all(
141
-			'|<span\s+id="([^"]+)"\s+class="textannotation\s+(?:\S+\s+)?disambiguated(?=[\s"])[^"]*"\s+itemid="([^"]*)">(.*?)</span>|',
142
-			$content,
143
-			$matches,
144
-			PREG_OFFSET_CAPTURE
145
-		) ) {
146
-			return $this;
147
-		}
148
-
149
-		if ( empty( $matches ) ) {
150
-			return $this;
151
-		}
152
-
153
-		$parse_data = array_reduce(
154
-			range( 0, count( $matches[1] ) - 1 ),
155
-			function ( $carry, $i ) use ( $matches ) {
156
-				if ( empty( $matches[0] ) ) {
157
-					return $carry;
158
-				}
159
-
160
-				$start         = $matches[0][ $i ][1];
161
-				$end           = $start + strlen( $matches[0][ $i ][0] );
162
-				$annotation_id = $matches[1][ $i ][0];
163
-				$item_id       = $matches[2][ $i ][0];
164
-				$text          = $matches[3][ $i ][0];
165
-
166
-				$annotation = new StdClass();
167
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
168
-				$annotation->annotationId = $annotation_id;
169
-				$annotation->start        = $start;
170
-				$annotation->end          = $end;
171
-				$annotation->text         = $text;
172
-
173
-				$entity_match             = new StdClass();
174
-				$entity_match->confidence = 100;
175
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
176
-				$entity_match->entityId = $item_id;
177
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
178
-				$annotation->entityMatches[] = $entity_match;
179
-
180
-				$carry['annotations'][ $annotation_id ] = $annotation;
181
-				$carry['occurrences'][ $item_id ][]     = $annotation_id;
182
-
183
-				return $carry;
184
-			},
185
-			array(
186
-				'annotations' => array(),
187
-				'occurrences' => array(),
188
-			)
189
-		);
190
-
191
-		$annotations = $parse_data['annotations'];
192
-		$occurrences = $parse_data['occurrences'];
193
-
194
-		$entity_provider_registry = Entity_Provider_Registry::get_instance();
195
-
196
-		foreach ( array_keys( $occurrences ) as $item_id ) {
197
-
198
-			// If the entity isn't there, add it.
199
-			if ( ! is_bool( $this->json ) && ! isset( $this->json->entities->{$item_id} ) ) {
200
-				$entity = $entity_provider_registry->get_local_entity( $item_id );
201
-
202
-				// Entity not found in the local vocabulary, continue to the next one.
203
-				if ( false === $entity ) {
204
-					continue;
205
-				}
206
-
207
-				$this->json->entities->{$item_id} = $entity;
208
-			}
209
-		}
210
-
211
-		// Here we're adding back some data structures required by the client-side code.
212
-		//
213
-		// We're adding:
214
-		// 1. the .entities[entity_id].occurrences array with the annotations' ids.
215
-		// 2. the .entities[entity_id].annotations[annotation_id] = { id: annotation_id } map.
216
-		//
217
-		// Before 3.23.0 this was done by the client-side code located in src/coffee/editpost-widget/app.services.AnalysisService.coffee
218
-		// function `preselect`, which was called by src/coffee/editpost-widget/app.services.EditorService.coffee in
219
-		// `embedAnalysis`.
220
-
221
-		if ( ! is_bool( $this->json ) && isset( $this->json->entities ) ) {
222
-			$occurrences_processor = Occurrences_Factory::get_instance( $this->post_id );
223
-			$this->json            = $occurrences_processor->add_occurrences_to_entities( $occurrences, $this->json, $this->post_id );
224
-		}
225
-
226
-		// Add the missing annotations. This allows the analysis response to work also if we didn't receive results
227
-		// from the analysis API.
228
-		foreach ( $annotations as $annotation_id => $annotation ) {
229
-
230
-			if ( ! is_bool( $this->json ) && ! isset( $this->json->annotations->{$annotation_id} ) ) {
231
-				$this->json->annotations->{$annotation_id} = $annotation;
232
-			}
233
-		}
234
-
235
-		return $this;
236
-	}
237
-
238
-	/**
239
-	 * Add local entities
240
-	 *
241
-	 * @return Analysis_Response_Ops The {@link Analysis_Response_Ops} instance.
242
-	 *
243
-	 * @since 3.27.6
244
-	 *
245
-	 * @link https://github.com/insideout10/wordlift-plugin/issues/1178
246
-	 */
247
-	public function add_local_entities() {
248
-
249
-		// Populating the local entities object
250
-		$entities = array();
251
-		foreach ( $this->json->annotations as $annotation ) {
252
-			// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
253
-			foreach ( $annotation->entityMatches as $entity_matches ) {
254
-
255
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
256
-				$entity_id         = $this->entity_uri_service->get_post_id_from_url( $entity_matches->entityId );
257
-				$serialized_entity = wl_serialize_entity( $entity_id );
258
-
259
-				if ( $serialized_entity ) {
260
-					$serialized_entity['entityId'] = $serialized_entity['id'];
261
-					unset( $serialized_entity['id'] );
262
-
263
-					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
264
-					$entities[ $entity_matches->entityId ] = $serialized_entity;
265
-				}
266
-			}
267
-		}
268
-
269
-		// Adding occurrences and annotations data structures required by the client-side code.
270
-		foreach ( $entities as $entity_id => $entity ) {
271
-			foreach ( $this->json->annotations as $annotation ) {
272
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
273
-				if ( $annotation->entityMatches[0]->entityId === $entity_id ) {
274
-					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
275
-					$entities[ $entity_id ]['occurrences'][] = $annotation->annotationId;
276
-					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
277
-					$entities[ $entity_id ]['annotations'][ $annotation->annotationId ]['id'] = $annotation->annotationId;
278
-				}
279
-			}
280
-		}
281
-
282
-		$this->json->entities = $entities;
283
-
284
-		return $this;
285
-
286
-	}
287
-
288
-	/**
289
-	 * Return the JSON response.
290
-	 *
291
-	 * @return mixed The JSON response.
292
-	 * @since 3.24.2
293
-	 */
294
-	public function get_json() {
295
-
296
-		return $this->json;
297
-	}
298
-
299
-	/**
300
-	 * This function should be invoked after `make_entities_local` after this
301
-	 * method.
302
-	 *
303
-	 * @param $excluded_uris array An array of entity URIs to be excluded.
304
-	 *
305
-	 * @return $this
306
-	 * @since 3.32.3.1
307
-	 */
308
-	public function remove_excluded_entities( $excluded_uris ) {
309
-
310
-		// If we didnt receive array, return early.
311
-		if ( ! is_array( $excluded_uris ) ) {
312
-			return $this;
313
-		}
314
-
315
-		// We may also receive an array of null, make sure to filter uris when receiving.
316
-		$excluded_uris = array_filter( $excluded_uris, 'is_string' );
317
-
318
-		$this->remove_entities_with_excluded_uris( $excluded_uris );
319
-
320
-		$this->remove_annotations_with_excluded_uris( $excluded_uris );
321
-
322
-		return $this;
323
-	}
324
-
325
-	/**
326
-	 * Get the string representation of the JSON.
327
-	 *
328
-	 * @return false|string The string representation or false in case of error.
329
-	 */
330
-	public function to_string() {
331
-
332
-		// Add the `JSON_UNESCAPED_UNICODE` only for PHP 5.4+.
333
-		$options = ( version_compare( PHP_VERSION, '5.4', '>=' )
334
-			? 256 : 0 );
335
-
336
-		return wp_json_encode( $this->json, $options );
337
-	}
338
-
339
-	/**
340
-	 * Remove all the entities with the excluded URIs.
341
-	 *
342
-	 * @param array $excluded_uris The array of URIs to be excluded.
343
-	 */
344
-	private function remove_entities_with_excluded_uris( array $excluded_uris ) {
345
-		// Remove the excluded entity uris.
346
-		if ( isset( $this->json->entities ) ) {
347
-			foreach ( $excluded_uris as $excluded_uri ) {
348
-
349
-				if ( isset( $this->json->entities->{$excluded_uri} ) ) {
350
-					// Remove this entity.
351
-					unset( $this->json->entities->{$excluded_uri} );
352
-					// Also remove the annotations.
353
-				}
354
-			}
355
-		}
356
-	}
357
-
358
-	/**
359
-	 * Remove all the annotations with the excluded entity URIs.
360
-	 *
361
-	 * @param array $excluded_uris The array of URIs to be excluded.
362
-	 *
363
-	 * @return void
364
-	 */
365
-	private function remove_annotations_with_excluded_uris( array $excluded_uris ) {
366
-		if ( isset( $this->json->annotations ) ) {
367
-			foreach ( $this->json->annotations as $annotation_key => &$annotation_data ) {
368
-
369
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
370
-				if ( ! isset( $annotation_data->entityMatches ) ) {
371
-					continue;
372
-				}
373
-
374
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
375
-				foreach ( $annotation_data->entityMatches as $entity_match_key => $entity_match_data ) {
376
-
377
-					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
378
-					$entity_uri = $entity_match_data->entityId;
379
-
380
-					if ( ! in_array( $entity_uri, $excluded_uris, true ) ) {
381
-						continue;
382
-					}
383
-					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
384
-					unset( $annotation_data->entityMatches[ $entity_match_key ] );
385
-				}
386
-
387
-				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
388
-				if ( count( $annotation_data->entityMatches ) === 0 ) {
389
-					// Remove the annotation if we have zero empty annotation matches.
390
-					unset( $this->json->annotations->{$annotation_key} );
391
-				}
392
-			}
393
-		}
394
-
395
-	}
19
+    /**
20
+     * The analysis response json.
21
+     *
22
+     * @since 3.21.5
23
+     * @access private
24
+     * @var mixed $json Holds the analysis response json.
25
+     */
26
+    private $json;
27
+
28
+    /**
29
+     * Holds the {@link Wordlift_Entity_Uri_Service}.
30
+     *
31
+     * @since 3.21.5
32
+     * @access private
33
+     * @var \Wordlift_Entity_Uri_Service $entity_uri_service The {@link Wordlift_Entity_Uri_Service} instance.
34
+     */
35
+    private $entity_uri_service;
36
+
37
+    /**
38
+     * @var Entity_Helper
39
+     */
40
+    private $entity_helper;
41
+
42
+    /**
43
+     * @var int $post_id
44
+     */
45
+    private $post_id;
46
+
47
+    /**
48
+     * Analysis_Response_Ops constructor.
49
+     *
50
+     * @param \Wordlift_Entity_Uri_Service $entity_uri_service The {@link Wordlift_Entity_Uri_Service}.
51
+     * @param Entity_Helper                $entity_helper The {@link Entity_Helper}.
52
+     * @param mixed                        $json The analysis response json.
53
+     *
54
+     * @since 3.21.5
55
+     */
56
+    public function __construct( $entity_uri_service, $entity_helper, $json, $post_id ) {
57
+        $this->json               = $json;
58
+        $this->entity_uri_service = $entity_uri_service;
59
+        $this->entity_helper      = $entity_helper;
60
+        $this->post_id            = $post_id;
61
+    }
62
+
63
+    /**
64
+     * Switches remote entities, i.e. entities with id outside the local dataset, to local entities.
65
+     *
66
+     * The function takes all the entities that have an id which is not local. For each remote entity, a list of URIs
67
+     * is built comprising the entity id and the sameAs. Then a query is issued in the local database to find potential
68
+     * matches from the local vocabulary.
69
+     *
70
+     * If found, the entity id is swapped with the local id and the remote id is added to the sameAs.
71
+     *
72
+     * @return Analysis_Response_Ops The current Analysis_Response_Ops instance.
73
+     */
74
+    public function make_entities_local() {
75
+
76
+        if ( ! isset( $this->json->entities ) ) {
77
+            return $this;
78
+        }
79
+
80
+        // Get the URIs.
81
+        $uris     = array_keys( get_object_vars( $this->json->entities ) );
82
+        $mappings = $this->entity_helper->map_many_to_local( $uris );
83
+
84
+        foreach ( $mappings as $external_uri => $internal_uri ) {
85
+
86
+            // Move the data from the external URI to the internal URI.
87
+            if ( ! isset( $this->json->entities->{$internal_uri} ) ) {
88
+                $this->json->entities->{$internal_uri} = $this->json->entities->{$external_uri};
89
+            }
90
+
91
+            // Ensure sameAs is an array.
92
+            if ( ! isset( $this->json->entities->{$internal_uri}->sameAs )
93
+                 || ! is_array( $this->json->entities->{$internal_uri}->sameAs ) ) {
94
+                $this->json->entities->{$internal_uri}->sameAs = array();
95
+            }
96
+
97
+            // Add the external URI as sameAs.
98
+            $this->json->entities->{$internal_uri}->sameAs[] = $external_uri;
99
+
100
+            // Finally remove the external URI.
101
+            unset( $this->json->entities->{$external_uri} );
102
+        }
103
+
104
+        // Set the internal uri in the annotation for the entityMatch in annotations.
105
+        if ( isset( $this->json->annotations ) ) {
106
+            // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
107
+            foreach ( $this->json->annotations as $key => $annotation ) {
108
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
109
+                if ( isset( $annotation->entityMatches ) ) {
110
+                    // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
111
+                    foreach ( $annotation->entityMatches as $match ) {
112
+                        // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
113
+                        if ( isset( $match->entityId ) && isset( $mappings[ $match->entityId ] ) ) {
114
+                            // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
115
+                            $match->entityId = $mappings[ $match->entityId ];
116
+                        }
117
+                    }
118
+                }
119
+            }
120
+        }
121
+
122
+        return $this;
123
+    }
124
+
125
+    /**
126
+     * Add occurrences by parsing the provided html content.
127
+     *
128
+     * @param string $content The html content with annotations.
129
+     *
130
+     * @return Analysis_Response_Ops The {@link Analysis_Response_Ops} instance.
131
+     *
132
+     * @since 3.23.7 refactor the regex pattern to take into account that there might be css classes between textannotation
133
+     *  and disambiguated.
134
+     *
135
+     * @link https://github.com/insideout10/wordlift-plugin/issues/1001
136
+     */
137
+    public function add_occurrences( $content ) {
138
+
139
+        // Try to get all the disambiguated annotations and bail out if an error occurs.
140
+        if ( false === preg_match_all(
141
+            '|<span\s+id="([^"]+)"\s+class="textannotation\s+(?:\S+\s+)?disambiguated(?=[\s"])[^"]*"\s+itemid="([^"]*)">(.*?)</span>|',
142
+            $content,
143
+            $matches,
144
+            PREG_OFFSET_CAPTURE
145
+        ) ) {
146
+            return $this;
147
+        }
148
+
149
+        if ( empty( $matches ) ) {
150
+            return $this;
151
+        }
152
+
153
+        $parse_data = array_reduce(
154
+            range( 0, count( $matches[1] ) - 1 ),
155
+            function ( $carry, $i ) use ( $matches ) {
156
+                if ( empty( $matches[0] ) ) {
157
+                    return $carry;
158
+                }
159
+
160
+                $start         = $matches[0][ $i ][1];
161
+                $end           = $start + strlen( $matches[0][ $i ][0] );
162
+                $annotation_id = $matches[1][ $i ][0];
163
+                $item_id       = $matches[2][ $i ][0];
164
+                $text          = $matches[3][ $i ][0];
165
+
166
+                $annotation = new StdClass();
167
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
168
+                $annotation->annotationId = $annotation_id;
169
+                $annotation->start        = $start;
170
+                $annotation->end          = $end;
171
+                $annotation->text         = $text;
172
+
173
+                $entity_match             = new StdClass();
174
+                $entity_match->confidence = 100;
175
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
176
+                $entity_match->entityId = $item_id;
177
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
178
+                $annotation->entityMatches[] = $entity_match;
179
+
180
+                $carry['annotations'][ $annotation_id ] = $annotation;
181
+                $carry['occurrences'][ $item_id ][]     = $annotation_id;
182
+
183
+                return $carry;
184
+            },
185
+            array(
186
+                'annotations' => array(),
187
+                'occurrences' => array(),
188
+            )
189
+        );
190
+
191
+        $annotations = $parse_data['annotations'];
192
+        $occurrences = $parse_data['occurrences'];
193
+
194
+        $entity_provider_registry = Entity_Provider_Registry::get_instance();
195
+
196
+        foreach ( array_keys( $occurrences ) as $item_id ) {
197
+
198
+            // If the entity isn't there, add it.
199
+            if ( ! is_bool( $this->json ) && ! isset( $this->json->entities->{$item_id} ) ) {
200
+                $entity = $entity_provider_registry->get_local_entity( $item_id );
201
+
202
+                // Entity not found in the local vocabulary, continue to the next one.
203
+                if ( false === $entity ) {
204
+                    continue;
205
+                }
206
+
207
+                $this->json->entities->{$item_id} = $entity;
208
+            }
209
+        }
210
+
211
+        // Here we're adding back some data structures required by the client-side code.
212
+        //
213
+        // We're adding:
214
+        // 1. the .entities[entity_id].occurrences array with the annotations' ids.
215
+        // 2. the .entities[entity_id].annotations[annotation_id] = { id: annotation_id } map.
216
+        //
217
+        // Before 3.23.0 this was done by the client-side code located in src/coffee/editpost-widget/app.services.AnalysisService.coffee
218
+        // function `preselect`, which was called by src/coffee/editpost-widget/app.services.EditorService.coffee in
219
+        // `embedAnalysis`.
220
+
221
+        if ( ! is_bool( $this->json ) && isset( $this->json->entities ) ) {
222
+            $occurrences_processor = Occurrences_Factory::get_instance( $this->post_id );
223
+            $this->json            = $occurrences_processor->add_occurrences_to_entities( $occurrences, $this->json, $this->post_id );
224
+        }
225
+
226
+        // Add the missing annotations. This allows the analysis response to work also if we didn't receive results
227
+        // from the analysis API.
228
+        foreach ( $annotations as $annotation_id => $annotation ) {
229
+
230
+            if ( ! is_bool( $this->json ) && ! isset( $this->json->annotations->{$annotation_id} ) ) {
231
+                $this->json->annotations->{$annotation_id} = $annotation;
232
+            }
233
+        }
234
+
235
+        return $this;
236
+    }
237
+
238
+    /**
239
+     * Add local entities
240
+     *
241
+     * @return Analysis_Response_Ops The {@link Analysis_Response_Ops} instance.
242
+     *
243
+     * @since 3.27.6
244
+     *
245
+     * @link https://github.com/insideout10/wordlift-plugin/issues/1178
246
+     */
247
+    public function add_local_entities() {
248
+
249
+        // Populating the local entities object
250
+        $entities = array();
251
+        foreach ( $this->json->annotations as $annotation ) {
252
+            // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
253
+            foreach ( $annotation->entityMatches as $entity_matches ) {
254
+
255
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
256
+                $entity_id         = $this->entity_uri_service->get_post_id_from_url( $entity_matches->entityId );
257
+                $serialized_entity = wl_serialize_entity( $entity_id );
258
+
259
+                if ( $serialized_entity ) {
260
+                    $serialized_entity['entityId'] = $serialized_entity['id'];
261
+                    unset( $serialized_entity['id'] );
262
+
263
+                    // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
264
+                    $entities[ $entity_matches->entityId ] = $serialized_entity;
265
+                }
266
+            }
267
+        }
268
+
269
+        // Adding occurrences and annotations data structures required by the client-side code.
270
+        foreach ( $entities as $entity_id => $entity ) {
271
+            foreach ( $this->json->annotations as $annotation ) {
272
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
273
+                if ( $annotation->entityMatches[0]->entityId === $entity_id ) {
274
+                    // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
275
+                    $entities[ $entity_id ]['occurrences'][] = $annotation->annotationId;
276
+                    // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
277
+                    $entities[ $entity_id ]['annotations'][ $annotation->annotationId ]['id'] = $annotation->annotationId;
278
+                }
279
+            }
280
+        }
281
+
282
+        $this->json->entities = $entities;
283
+
284
+        return $this;
285
+
286
+    }
287
+
288
+    /**
289
+     * Return the JSON response.
290
+     *
291
+     * @return mixed The JSON response.
292
+     * @since 3.24.2
293
+     */
294
+    public function get_json() {
295
+
296
+        return $this->json;
297
+    }
298
+
299
+    /**
300
+     * This function should be invoked after `make_entities_local` after this
301
+     * method.
302
+     *
303
+     * @param $excluded_uris array An array of entity URIs to be excluded.
304
+     *
305
+     * @return $this
306
+     * @since 3.32.3.1
307
+     */
308
+    public function remove_excluded_entities( $excluded_uris ) {
309
+
310
+        // If we didnt receive array, return early.
311
+        if ( ! is_array( $excluded_uris ) ) {
312
+            return $this;
313
+        }
314
+
315
+        // We may also receive an array of null, make sure to filter uris when receiving.
316
+        $excluded_uris = array_filter( $excluded_uris, 'is_string' );
317
+
318
+        $this->remove_entities_with_excluded_uris( $excluded_uris );
319
+
320
+        $this->remove_annotations_with_excluded_uris( $excluded_uris );
321
+
322
+        return $this;
323
+    }
324
+
325
+    /**
326
+     * Get the string representation of the JSON.
327
+     *
328
+     * @return false|string The string representation or false in case of error.
329
+     */
330
+    public function to_string() {
331
+
332
+        // Add the `JSON_UNESCAPED_UNICODE` only for PHP 5.4+.
333
+        $options = ( version_compare( PHP_VERSION, '5.4', '>=' )
334
+            ? 256 : 0 );
335
+
336
+        return wp_json_encode( $this->json, $options );
337
+    }
338
+
339
+    /**
340
+     * Remove all the entities with the excluded URIs.
341
+     *
342
+     * @param array $excluded_uris The array of URIs to be excluded.
343
+     */
344
+    private function remove_entities_with_excluded_uris( array $excluded_uris ) {
345
+        // Remove the excluded entity uris.
346
+        if ( isset( $this->json->entities ) ) {
347
+            foreach ( $excluded_uris as $excluded_uri ) {
348
+
349
+                if ( isset( $this->json->entities->{$excluded_uri} ) ) {
350
+                    // Remove this entity.
351
+                    unset( $this->json->entities->{$excluded_uri} );
352
+                    // Also remove the annotations.
353
+                }
354
+            }
355
+        }
356
+    }
357
+
358
+    /**
359
+     * Remove all the annotations with the excluded entity URIs.
360
+     *
361
+     * @param array $excluded_uris The array of URIs to be excluded.
362
+     *
363
+     * @return void
364
+     */
365
+    private function remove_annotations_with_excluded_uris( array $excluded_uris ) {
366
+        if ( isset( $this->json->annotations ) ) {
367
+            foreach ( $this->json->annotations as $annotation_key => &$annotation_data ) {
368
+
369
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
370
+                if ( ! isset( $annotation_data->entityMatches ) ) {
371
+                    continue;
372
+                }
373
+
374
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
375
+                foreach ( $annotation_data->entityMatches as $entity_match_key => $entity_match_data ) {
376
+
377
+                    // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
378
+                    $entity_uri = $entity_match_data->entityId;
379
+
380
+                    if ( ! in_array( $entity_uri, $excluded_uris, true ) ) {
381
+                        continue;
382
+                    }
383
+                    // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
384
+                    unset( $annotation_data->entityMatches[ $entity_match_key ] );
385
+                }
386
+
387
+                // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
388
+                if ( count( $annotation_data->entityMatches ) === 0 ) {
389
+                    // Remove the annotation if we have zero empty annotation matches.
390
+                    unset( $this->json->annotations->{$annotation_key} );
391
+                }
392
+            }
393
+        }
394
+
395
+    }
396 396
 
397 397
 }
Please login to merge, or discard this patch.
Spacing   +72 added lines, -72 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	 *
54 54
 	 * @since 3.21.5
55 55
 	 */
56
-	public function __construct( $entity_uri_service, $entity_helper, $json, $post_id ) {
56
+	public function __construct($entity_uri_service, $entity_helper, $json, $post_id) {
57 57
 		$this->json               = $json;
58 58
 		$this->entity_uri_service = $entity_uri_service;
59 59
 		$this->entity_helper      = $entity_helper;
@@ -73,24 +73,24 @@  discard block
 block discarded – undo
73 73
 	 */
74 74
 	public function make_entities_local() {
75 75
 
76
-		if ( ! isset( $this->json->entities ) ) {
76
+		if ( ! isset($this->json->entities)) {
77 77
 			return $this;
78 78
 		}
79 79
 
80 80
 		// Get the URIs.
81
-		$uris     = array_keys( get_object_vars( $this->json->entities ) );
82
-		$mappings = $this->entity_helper->map_many_to_local( $uris );
81
+		$uris     = array_keys(get_object_vars($this->json->entities));
82
+		$mappings = $this->entity_helper->map_many_to_local($uris);
83 83
 
84
-		foreach ( $mappings as $external_uri => $internal_uri ) {
84
+		foreach ($mappings as $external_uri => $internal_uri) {
85 85
 
86 86
 			// Move the data from the external URI to the internal URI.
87
-			if ( ! isset( $this->json->entities->{$internal_uri} ) ) {
87
+			if ( ! isset($this->json->entities->{$internal_uri} )) {
88 88
 				$this->json->entities->{$internal_uri} = $this->json->entities->{$external_uri};
89 89
 			}
90 90
 
91 91
 			// Ensure sameAs is an array.
92
-			if ( ! isset( $this->json->entities->{$internal_uri}->sameAs )
93
-				 || ! is_array( $this->json->entities->{$internal_uri}->sameAs ) ) {
92
+			if ( ! isset($this->json->entities->{$internal_uri}->sameAs)
93
+				 || ! is_array($this->json->entities->{$internal_uri}->sameAs)) {
94 94
 				$this->json->entities->{$internal_uri}->sameAs = array();
95 95
 			}
96 96
 
@@ -98,21 +98,21 @@  discard block
 block discarded – undo
98 98
 			$this->json->entities->{$internal_uri}->sameAs[] = $external_uri;
99 99
 
100 100
 			// Finally remove the external URI.
101
-			unset( $this->json->entities->{$external_uri} );
101
+			unset($this->json->entities->{$external_uri} );
102 102
 		}
103 103
 
104 104
 		// Set the internal uri in the annotation for the entityMatch in annotations.
105
-		if ( isset( $this->json->annotations ) ) {
105
+		if (isset($this->json->annotations)) {
106 106
 			// phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
107
-			foreach ( $this->json->annotations as $key => $annotation ) {
107
+			foreach ($this->json->annotations as $key => $annotation) {
108 108
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
109
-				if ( isset( $annotation->entityMatches ) ) {
109
+				if (isset($annotation->entityMatches)) {
110 110
 					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
111
-					foreach ( $annotation->entityMatches as $match ) {
111
+					foreach ($annotation->entityMatches as $match) {
112 112
 						// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
113
-						if ( isset( $match->entityId ) && isset( $mappings[ $match->entityId ] ) ) {
113
+						if (isset($match->entityId) && isset($mappings[$match->entityId])) {
114 114
 							// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
115
-							$match->entityId = $mappings[ $match->entityId ];
115
+							$match->entityId = $mappings[$match->entityId];
116 116
 						}
117 117
 					}
118 118
 				}
@@ -134,34 +134,34 @@  discard block
 block discarded – undo
134 134
 	 *
135 135
 	 * @link https://github.com/insideout10/wordlift-plugin/issues/1001
136 136
 	 */
137
-	public function add_occurrences( $content ) {
137
+	public function add_occurrences($content) {
138 138
 
139 139
 		// Try to get all the disambiguated annotations and bail out if an error occurs.
140
-		if ( false === preg_match_all(
140
+		if (false === preg_match_all(
141 141
 			'|<span\s+id="([^"]+)"\s+class="textannotation\s+(?:\S+\s+)?disambiguated(?=[\s"])[^"]*"\s+itemid="([^"]*)">(.*?)</span>|',
142 142
 			$content,
143 143
 			$matches,
144 144
 			PREG_OFFSET_CAPTURE
145
-		) ) {
145
+		)) {
146 146
 			return $this;
147 147
 		}
148 148
 
149
-		if ( empty( $matches ) ) {
149
+		if (empty($matches)) {
150 150
 			return $this;
151 151
 		}
152 152
 
153 153
 		$parse_data = array_reduce(
154
-			range( 0, count( $matches[1] ) - 1 ),
155
-			function ( $carry, $i ) use ( $matches ) {
156
-				if ( empty( $matches[0] ) ) {
154
+			range(0, count($matches[1]) - 1),
155
+			function($carry, $i) use ($matches) {
156
+				if (empty($matches[0])) {
157 157
 					return $carry;
158 158
 				}
159 159
 
160
-				$start         = $matches[0][ $i ][1];
161
-				$end           = $start + strlen( $matches[0][ $i ][0] );
162
-				$annotation_id = $matches[1][ $i ][0];
163
-				$item_id       = $matches[2][ $i ][0];
164
-				$text          = $matches[3][ $i ][0];
160
+				$start         = $matches[0][$i][1];
161
+				$end           = $start + strlen($matches[0][$i][0]);
162
+				$annotation_id = $matches[1][$i][0];
163
+				$item_id       = $matches[2][$i][0];
164
+				$text          = $matches[3][$i][0];
165 165
 
166 166
 				$annotation = new StdClass();
167 167
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
@@ -177,8 +177,8 @@  discard block
 block discarded – undo
177 177
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
178 178
 				$annotation->entityMatches[] = $entity_match;
179 179
 
180
-				$carry['annotations'][ $annotation_id ] = $annotation;
181
-				$carry['occurrences'][ $item_id ][]     = $annotation_id;
180
+				$carry['annotations'][$annotation_id] = $annotation;
181
+				$carry['occurrences'][$item_id][]     = $annotation_id;
182 182
 
183 183
 				return $carry;
184 184
 			},
@@ -193,14 +193,14 @@  discard block
 block discarded – undo
193 193
 
194 194
 		$entity_provider_registry = Entity_Provider_Registry::get_instance();
195 195
 
196
-		foreach ( array_keys( $occurrences ) as $item_id ) {
196
+		foreach (array_keys($occurrences) as $item_id) {
197 197
 
198 198
 			// If the entity isn't there, add it.
199
-			if ( ! is_bool( $this->json ) && ! isset( $this->json->entities->{$item_id} ) ) {
200
-				$entity = $entity_provider_registry->get_local_entity( $item_id );
199
+			if ( ! is_bool($this->json) && ! isset($this->json->entities->{$item_id} )) {
200
+				$entity = $entity_provider_registry->get_local_entity($item_id);
201 201
 
202 202
 				// Entity not found in the local vocabulary, continue to the next one.
203
-				if ( false === $entity ) {
203
+				if (false === $entity) {
204 204
 					continue;
205 205
 				}
206 206
 
@@ -218,16 +218,16 @@  discard block
 block discarded – undo
218 218
 		// function `preselect`, which was called by src/coffee/editpost-widget/app.services.EditorService.coffee in
219 219
 		// `embedAnalysis`.
220 220
 
221
-		if ( ! is_bool( $this->json ) && isset( $this->json->entities ) ) {
222
-			$occurrences_processor = Occurrences_Factory::get_instance( $this->post_id );
223
-			$this->json            = $occurrences_processor->add_occurrences_to_entities( $occurrences, $this->json, $this->post_id );
221
+		if ( ! is_bool($this->json) && isset($this->json->entities)) {
222
+			$occurrences_processor = Occurrences_Factory::get_instance($this->post_id);
223
+			$this->json            = $occurrences_processor->add_occurrences_to_entities($occurrences, $this->json, $this->post_id);
224 224
 		}
225 225
 
226 226
 		// Add the missing annotations. This allows the analysis response to work also if we didn't receive results
227 227
 		// from the analysis API.
228
-		foreach ( $annotations as $annotation_id => $annotation ) {
228
+		foreach ($annotations as $annotation_id => $annotation) {
229 229
 
230
-			if ( ! is_bool( $this->json ) && ! isset( $this->json->annotations->{$annotation_id} ) ) {
230
+			if ( ! is_bool($this->json) && ! isset($this->json->annotations->{$annotation_id} )) {
231 231
 				$this->json->annotations->{$annotation_id} = $annotation;
232 232
 			}
233 233
 		}
@@ -248,33 +248,33 @@  discard block
 block discarded – undo
248 248
 
249 249
 		// Populating the local entities object
250 250
 		$entities = array();
251
-		foreach ( $this->json->annotations as $annotation ) {
251
+		foreach ($this->json->annotations as $annotation) {
252 252
 			// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
253
-			foreach ( $annotation->entityMatches as $entity_matches ) {
253
+			foreach ($annotation->entityMatches as $entity_matches) {
254 254
 
255 255
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
256
-				$entity_id         = $this->entity_uri_service->get_post_id_from_url( $entity_matches->entityId );
257
-				$serialized_entity = wl_serialize_entity( $entity_id );
256
+				$entity_id         = $this->entity_uri_service->get_post_id_from_url($entity_matches->entityId);
257
+				$serialized_entity = wl_serialize_entity($entity_id);
258 258
 
259
-				if ( $serialized_entity ) {
259
+				if ($serialized_entity) {
260 260
 					$serialized_entity['entityId'] = $serialized_entity['id'];
261
-					unset( $serialized_entity['id'] );
261
+					unset($serialized_entity['id']);
262 262
 
263 263
 					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
264
-					$entities[ $entity_matches->entityId ] = $serialized_entity;
264
+					$entities[$entity_matches->entityId] = $serialized_entity;
265 265
 				}
266 266
 			}
267 267
 		}
268 268
 
269 269
 		// Adding occurrences and annotations data structures required by the client-side code.
270
-		foreach ( $entities as $entity_id => $entity ) {
271
-			foreach ( $this->json->annotations as $annotation ) {
270
+		foreach ($entities as $entity_id => $entity) {
271
+			foreach ($this->json->annotations as $annotation) {
272 272
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
273
-				if ( $annotation->entityMatches[0]->entityId === $entity_id ) {
273
+				if ($annotation->entityMatches[0]->entityId === $entity_id) {
274 274
 					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
275
-					$entities[ $entity_id ]['occurrences'][] = $annotation->annotationId;
275
+					$entities[$entity_id]['occurrences'][] = $annotation->annotationId;
276 276
 					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
277
-					$entities[ $entity_id ]['annotations'][ $annotation->annotationId ]['id'] = $annotation->annotationId;
277
+					$entities[$entity_id]['annotations'][$annotation->annotationId]['id'] = $annotation->annotationId;
278 278
 				}
279 279
 			}
280 280
 		}
@@ -305,19 +305,19 @@  discard block
 block discarded – undo
305 305
 	 * @return $this
306 306
 	 * @since 3.32.3.1
307 307
 	 */
308
-	public function remove_excluded_entities( $excluded_uris ) {
308
+	public function remove_excluded_entities($excluded_uris) {
309 309
 
310 310
 		// If we didnt receive array, return early.
311
-		if ( ! is_array( $excluded_uris ) ) {
311
+		if ( ! is_array($excluded_uris)) {
312 312
 			return $this;
313 313
 		}
314 314
 
315 315
 		// We may also receive an array of null, make sure to filter uris when receiving.
316
-		$excluded_uris = array_filter( $excluded_uris, 'is_string' );
316
+		$excluded_uris = array_filter($excluded_uris, 'is_string');
317 317
 
318
-		$this->remove_entities_with_excluded_uris( $excluded_uris );
318
+		$this->remove_entities_with_excluded_uris($excluded_uris);
319 319
 
320
-		$this->remove_annotations_with_excluded_uris( $excluded_uris );
320
+		$this->remove_annotations_with_excluded_uris($excluded_uris);
321 321
 
322 322
 		return $this;
323 323
 	}
@@ -330,10 +330,10 @@  discard block
 block discarded – undo
330 330
 	public function to_string() {
331 331
 
332 332
 		// Add the `JSON_UNESCAPED_UNICODE` only for PHP 5.4+.
333
-		$options = ( version_compare( PHP_VERSION, '5.4', '>=' )
334
-			? 256 : 0 );
333
+		$options = (version_compare(PHP_VERSION, '5.4', '>=')
334
+			? 256 : 0);
335 335
 
336
-		return wp_json_encode( $this->json, $options );
336
+		return wp_json_encode($this->json, $options);
337 337
 	}
338 338
 
339 339
 	/**
@@ -341,14 +341,14 @@  discard block
 block discarded – undo
341 341
 	 *
342 342
 	 * @param array $excluded_uris The array of URIs to be excluded.
343 343
 	 */
344
-	private function remove_entities_with_excluded_uris( array $excluded_uris ) {
344
+	private function remove_entities_with_excluded_uris(array $excluded_uris) {
345 345
 		// Remove the excluded entity uris.
346
-		if ( isset( $this->json->entities ) ) {
347
-			foreach ( $excluded_uris as $excluded_uri ) {
346
+		if (isset($this->json->entities)) {
347
+			foreach ($excluded_uris as $excluded_uri) {
348 348
 
349
-				if ( isset( $this->json->entities->{$excluded_uri} ) ) {
349
+				if (isset($this->json->entities->{$excluded_uri} )) {
350 350
 					// Remove this entity.
351
-					unset( $this->json->entities->{$excluded_uri} );
351
+					unset($this->json->entities->{$excluded_uri} );
352 352
 					// Also remove the annotations.
353 353
 				}
354 354
 			}
@@ -362,32 +362,32 @@  discard block
 block discarded – undo
362 362
 	 *
363 363
 	 * @return void
364 364
 	 */
365
-	private function remove_annotations_with_excluded_uris( array $excluded_uris ) {
366
-		if ( isset( $this->json->annotations ) ) {
367
-			foreach ( $this->json->annotations as $annotation_key => &$annotation_data ) {
365
+	private function remove_annotations_with_excluded_uris(array $excluded_uris) {
366
+		if (isset($this->json->annotations)) {
367
+			foreach ($this->json->annotations as $annotation_key => &$annotation_data) {
368 368
 
369 369
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
370
-				if ( ! isset( $annotation_data->entityMatches ) ) {
370
+				if ( ! isset($annotation_data->entityMatches)) {
371 371
 					continue;
372 372
 				}
373 373
 
374 374
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
375
-				foreach ( $annotation_data->entityMatches as $entity_match_key => $entity_match_data ) {
375
+				foreach ($annotation_data->entityMatches as $entity_match_key => $entity_match_data) {
376 376
 
377 377
 					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
378 378
 					$entity_uri = $entity_match_data->entityId;
379 379
 
380
-					if ( ! in_array( $entity_uri, $excluded_uris, true ) ) {
380
+					if ( ! in_array($entity_uri, $excluded_uris, true)) {
381 381
 						continue;
382 382
 					}
383 383
 					// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
384
-					unset( $annotation_data->entityMatches[ $entity_match_key ] );
384
+					unset($annotation_data->entityMatches[$entity_match_key]);
385 385
 				}
386 386
 
387 387
 				// phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
388
-				if ( count( $annotation_data->entityMatches ) === 0 ) {
388
+				if (count($annotation_data->entityMatches) === 0) {
389 389
 					// Remove the annotation if we have zero empty annotation matches.
390
-					unset( $this->json->annotations->{$annotation_key} );
390
+					unset($this->json->annotations->{$annotation_key} );
391 391
 				}
392 392
 			}
393 393
 		}
Please login to merge, or discard this patch.