Completed
Pull Request — master (#1537)
by Naveen
56s
created
src/wordlift/post/class-post-adapter.php 1 patch
Indentation   +363 added lines, -363 removed lines patch added patch discarded remove patch
@@ -20,368 +20,368 @@
 block discarded – undo
20 20
 
21 21
 class Post_Adapter {
22 22
 
23
-	/**
24
-	 * A {@link Wordlift_Log_Service} logging instance.
25
-	 *
26
-	 * @access private
27
-	 * @var \Wordlift_Log_Service A {@link Wordlift_Log_Service} logging instance.
28
-	 */
29
-	private $log;
30
-
31
-	public function __construct() {
32
-
33
-		// Bail out if block editor's functions aren't available.
34
-		if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
35
-			return;
36
-		}
37
-
38
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
39
-
40
-		add_action( 'init', array( $this, 'init' ) );
41
-		add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
42
-
43
-	}
44
-
45
-	/**
46
-	 * Initialize by registering our block type `wordlift/classification`, required for {@link parse_blocks) to work
47
-	 * correctly.
48
-	 */
49
-	public function init() {
50
-
51
-		register_block_type( 'wordlift/classification', array(
52
-			'editor_script' => 'wl-block-editor',
53
-			'attributes'    => array(
54
-				'entities' => array( 'type' => 'array' ),
55
-			),
56
-		) );
57
-
58
-	}
59
-
60
-	/**
61
-	 * A sample structure:
62
-	 *
63
-	 * {
64
-	 *   "entities": [
65
-	 *     {
66
-	 *       "annotations": {
67
-	 *         "urn:enhancement-7e8e66fc": {
68
-	 *           "start": 3480,
69
-	 *           "end": 3486,
70
-	 *           "text": "libero"
71
-	 *         }
72
-	 *       },
73
-	 *       "description": "Le libero ou libéro est un poste défensif du volley-ball. Des règles particulières le concernant ont été introduites à la fin des années 1990. De par sa spécificité, le libéro a un statut à part au sein d’une équipe de volley-ball. Pour être identifié, il doit porter un uniforme qui contraste avec ceux des autres membres de son équipe, titulaires ou remplaçants.",
74
-	 *       "id": "http://fr.dbpedia.org/resource/Libero_(volley-ball)",
75
-	 *       "label": "Libero (volley-ball)",
76
-	 *       "mainType": "other",
77
-	 *       "occurrences": ["urn:enhancement-7e8e66fc"],
78
-	 *       "sameAs": null,
79
-	 *       "synonyms": [],
80
-	 *       "types": ["other"]
81
-	 *     }
82
-	 *   ]
83
-	 * }
84
-	 *
85
-	 * @param array $data An array of slashed post data.
86
-	 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
87
-	 *
88
-	 * @return array The data array.
89
-	 */
90
-	public function wp_insert_post_data( $data, $postarr ) {
91
-		$post_status = $data['post_status'];
92
-		if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
93
-			return $data;
94
-		}
95
-
96
-		$this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
97
-		                   . var_export( $data, true ) );
98
-
99
-
100
-		try {
101
-			$entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
102
-
103
-			foreach ( $entities as $entity ) {
104
-
105
-				$entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
106
-
107
-				if ( ! $this->entity_id_valid( $entity_id ) ) {
108
-					continue;
109
-				}
110
-
111
-				$entity_uris = $this->get_entity_uris( $entity );
112
-
113
-				if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
114
-				     Post_Entities_Validator::is_local_entity_uri_exist( Wordlift_Entity_Uri_Service::get_instance(), $entity_uris ) ) {
115
-					// Skip the entity
116
-					continue;
117
-				}
118
-
119
-				// If 'entity auto publish' is false, we set the status to `draft` by default.
120
-				$post_status = apply_filters( 'wl_feature__enable__entity-auto-publish', true )
121
-					? $data['post_status'] : 'draft';
122
-				$this->create_or_update_entity( $entity, $post_status );
123
-
124
-			}
125
-
126
-		} catch ( \Exception $e ) {
127
-			$this->log->error( $e->getMessage() );
128
-		}
129
-
130
-
131
-		return $data;
132
-	}
133
-
134
-	/**
135
-	 * Parse the post content to find the `wordlift/classification` block and return the entities' data.
136
-	 *
137
-	 * @param string $post_content The post content.
138
-	 *
139
-	 * @return array An array of entities' structures.
140
-	 * @throws \Exception
141
-	 */
142
-	private function parse_content( $post_content ) {
143
-
144
-		$all_blocks = parse_blocks( $post_content );
145
-		$this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
146
-		                   . var_export( $all_blocks, true ) );
147
-
148
-		$blocks = array_filter( $all_blocks, function ( $item ) {
149
-			return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
150
-		} );
151
-
152
-		// Bail out if the blocks' array is empty.
153
-		if ( empty( $blocks ) ) {
154
-			return array();
155
-		}
156
-
157
-		$block = current( $blocks );
158
-		$this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
159
-		                   . var_export( $block, true ) );
160
-
161
-		// Bail out if the entities array is empty.
162
-		if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
163
-			return array();
164
-		}
165
-
166
-		return $block['attrs']['entities'];
167
-	}
168
-
169
-	/**
170
-	 * Collect entity labels from the entity array.
171
-	 *
172
-	 * This function expects an array with the following keys:
173
-	 *
174
-	 * array(
175
-	 *   'label'       => ...,
176
-	 *   'synonyms'    => array( ... ),
177
-	 *   'annotations' => array(
178
-	 *     ...id...      => array( text => ... ),
179
-	 *   ),
180
-	 *   'occurrences' => array( ... ),
181
-	 * )
182
-	 *
183
-	 * and it is going to output an array with all the labels, keeping the `label` at first position:
184
-	 *
185
-	 * array(
186
-	 *   ...label...,
187
-	 *   ...synonyms...,
188
-	 *   ...texts...,
189
-	 * )
190
-	 *
191
-	 * This function is going to collect the label from the `label` property, from the `synonyms` property and from
192
-	 * `annotations` property. Since the `annotations` property contains all the annotations including those that
193
-	 * haven't been selected, this function is going to only get the `text` for the annotations property listed in
194
-	 * `occurrences`.
195
-	 *
196
-	 * @param array $entity {
197
-	 *  The entity data.
198
-	 *
199
-	 * @type string $label The entity label.
200
-	 * @type array $synonyms The entity synonyms.
201
-	 * @type array $occurrences The selected occurrences.
202
-	 * @type array $annotations The annotations.
203
-	 * }
204
-	 *
205
-	 * @return array An array of labels.
206
-	 */
207
-	public function get_labels( $entity ) {
208
-
209
-		$args = wp_parse_args( $entity, array(
210
-			'label'       => array(),
211
-			'synonyms'    => array(),
212
-			'annotations' => array(),
213
-			'occurrences' => array(),
214
-		) );
215
-
216
-		// We gather all the labels, occurrences texts and synonyms into one array.
217
-		$initial = array_merge(
218
-			(array) $args['label'],
219
-			(array) $args['synonyms']
220
-		);
221
-
222
-		$annotations = $args['annotations'];
223
-
224
-		return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
225
-
226
-			// Bail out if occurrences->$item->text isn't set or its contents are already
227
-			// in `$carry`.
228
-			if ( ! isset( $annotations[ $item ]['text'] )
229
-			     || in_array( $annotations[ $item ]['text'], $carry ) ) {
230
-				return $carry;
231
-			}
232
-
233
-			// Push the label.
234
-			$carry[] = $annotations[ $item ]['text'];
235
-
236
-			return $carry;
237
-		}, $initial );
238
-	}
239
-
240
-	/**
241
-	 * Create or update the entity.
242
-	 *
243
-	 * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
244
-	 * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
245
-	 *
246
-	 * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
247
-	 *
248
-	 * @param array $entity {
249
-	 * The entity parameters.
250
-	 *
251
-	 * @type string The entity item id URI.
252
-	 * @type string|array The entity sameAs URI(s).
253
-	 * @type string $description The entity description.
254
-	 * }
255
-	 *
256
-	 * @param       $string $post_status The post status, default 'draft'.
257
-	 *
258
-	 * @return int|\WP_Error
259
-	 * @throws \Exception
260
-	 */
261
-	private function create_or_update_entity( $entity, $post_status = 'draft' ) {
262
-
263
-		// Get only valid IDs.
264
-		$uris = $this->get_entity_uris( $entity );
265
-
266
-		$post = $this->get_first_matching_entity_by_uri( $uris );
267
-
268
-		$this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
269
-		                   . var_export( $uris, true ) );
270
-
271
-		// Get the labels.
272
-		$labels = $this->get_labels( $entity );
273
-
274
-		if ( empty( $post ) ) {
275
-			$entity_description = array_key_exists( 'description', $entity ) ? $entity['description'] : '';
276
-			// Create the entity if it doesn't exist.
277
-			$post_id = Entity_Store::get_instance()->create( array(
278
-				'labels'      => $labels,
279
-				'description' => $entity_description,
280
-				'same_as'     => $uris,
281
-			), $post_status );
282
-
283
-			// Return the WP_Error if we got one.
284
-			if ( is_wp_error( $post_id ) ) {
285
-				return $post_id;
286
-			}
287
-
288
-			// Add the entity type.
289
-			if ( isset( $entity['mainType'] ) ) {
290
-				wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
291
-			}
292
-
293
-			if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
294
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
295
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
296
-			}
297
-		} else {
298
-			// Update the entity otherwise.
299
-			$post_id = Entity_Store::get_instance()->update( array(
300
-				'ID'      => $post->ID,
301
-				'labels'  => $labels,
302
-				'same_as' => $uris,
303
-			) );
304
-
305
-			// Add the entity type.
306
-			if ( isset( $entity['mainType'] ) ) {
307
-				wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
308
-			}
309
-
310
-			// see https://github.com/insideout10/wordlift-plugin/issues/1304
311
-			// Set the post status, we need to set that in order to support entities
312
-			// created using rest endpoint on block editor, so that they get published
313
-			// when the post is published.
314
-			// Once the entity is published dont update the post status.
315
-			if ( $post->post_status !== 'publish' ) {
316
-				wp_update_post( array(
317
-					'ID'          => $post->ID,
318
-					'post_status' => $post_status
319
-				) );
320
-			}
321
-		}
322
-
323
-		return $post_id;
324
-	}
325
-
326
-	/**
327
-	 * Get the first matching entity for the provided URI array.
328
-	 *
329
-	 * Entities IDs and sameAs are searched.
330
-	 *
331
-	 * @param array $uris An array of URIs.
332
-	 *
333
-	 * @return \WP_Post|null The entity WP_Post if found or null if not found.
334
-	 */
335
-	private function get_first_matching_entity_by_uri( $uris ) {
336
-
337
-		foreach ( $uris as $uri ) {
338
-
339
-			$content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
340
-
341
-			if ( ! $content ) {
342
-				continue;
343
-			}
344
-
345
-			$existing_entity = $content->get_bag();
346
-
347
-			if ( is_a( $existing_entity, 'WP_Post' ) ) {
348
-				return $existing_entity;
349
-			}
350
-		}
351
-
352
-		return null;
353
-	}
354
-
355
-	/**
356
-	 * @param $entity
357
-	 *
358
-	 * @return array
359
-	 */
360
-	private function filter_valid_entity_ids( $entity ) {
361
-		$id = $entity['id'];
362
-
363
-		return array_filter( (array) $id, function ( $id ) {
364
-			return preg_match( '|^https?://|', $id );
365
-		} );
366
-	}
367
-
368
-	/**
369
-	 * @param array $entity
370
-	 *
371
-	 * @return array
372
-	 */
373
-	private function get_entity_uris( $entity ) {
374
-		$ids     = $this->filter_valid_entity_ids( $entity );
375
-		$same_as = array_key_exists( 'sameAs', $entity ) ? $entity['sameAs'] : array();
376
-
377
-		return array_merge(
378
-			(array) $ids,
379
-			(array) $same_as
380
-		);
381
-	}
382
-
383
-	private function entity_id_valid( $entity_id ) {
384
-		return preg_match( '#^https?://#i', $entity_id ) === 1;
385
-	}
23
+    /**
24
+     * A {@link Wordlift_Log_Service} logging instance.
25
+     *
26
+     * @access private
27
+     * @var \Wordlift_Log_Service A {@link Wordlift_Log_Service} logging instance.
28
+     */
29
+    private $log;
30
+
31
+    public function __construct() {
32
+
33
+        // Bail out if block editor's functions aren't available.
34
+        if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
35
+            return;
36
+        }
37
+
38
+        $this->log = \Wordlift_Log_Service::get_logger( get_class() );
39
+
40
+        add_action( 'init', array( $this, 'init' ) );
41
+        add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
42
+
43
+    }
44
+
45
+    /**
46
+     * Initialize by registering our block type `wordlift/classification`, required for {@link parse_blocks) to work
47
+     * correctly.
48
+     */
49
+    public function init() {
50
+
51
+        register_block_type( 'wordlift/classification', array(
52
+            'editor_script' => 'wl-block-editor',
53
+            'attributes'    => array(
54
+                'entities' => array( 'type' => 'array' ),
55
+            ),
56
+        ) );
57
+
58
+    }
59
+
60
+    /**
61
+     * A sample structure:
62
+     *
63
+     * {
64
+     *   "entities": [
65
+     *     {
66
+     *       "annotations": {
67
+     *         "urn:enhancement-7e8e66fc": {
68
+     *           "start": 3480,
69
+     *           "end": 3486,
70
+     *           "text": "libero"
71
+     *         }
72
+     *       },
73
+     *       "description": "Le libero ou libéro est un poste défensif du volley-ball. Des règles particulières le concernant ont été introduites à la fin des années 1990. De par sa spécificité, le libéro a un statut à part au sein d’une équipe de volley-ball. Pour être identifié, il doit porter un uniforme qui contraste avec ceux des autres membres de son équipe, titulaires ou remplaçants.",
74
+     *       "id": "http://fr.dbpedia.org/resource/Libero_(volley-ball)",
75
+     *       "label": "Libero (volley-ball)",
76
+     *       "mainType": "other",
77
+     *       "occurrences": ["urn:enhancement-7e8e66fc"],
78
+     *       "sameAs": null,
79
+     *       "synonyms": [],
80
+     *       "types": ["other"]
81
+     *     }
82
+     *   ]
83
+     * }
84
+     *
85
+     * @param array $data An array of slashed post data.
86
+     * @param array $postarr An array of sanitized, but otherwise unmodified post data.
87
+     *
88
+     * @return array The data array.
89
+     */
90
+    public function wp_insert_post_data( $data, $postarr ) {
91
+        $post_status = $data['post_status'];
92
+        if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
93
+            return $data;
94
+        }
95
+
96
+        $this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
97
+                            . var_export( $data, true ) );
98
+
99
+
100
+        try {
101
+            $entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
102
+
103
+            foreach ( $entities as $entity ) {
104
+
105
+                $entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
106
+
107
+                if ( ! $this->entity_id_valid( $entity_id ) ) {
108
+                    continue;
109
+                }
110
+
111
+                $entity_uris = $this->get_entity_uris( $entity );
112
+
113
+                if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
114
+                     Post_Entities_Validator::is_local_entity_uri_exist( Wordlift_Entity_Uri_Service::get_instance(), $entity_uris ) ) {
115
+                    // Skip the entity
116
+                    continue;
117
+                }
118
+
119
+                // If 'entity auto publish' is false, we set the status to `draft` by default.
120
+                $post_status = apply_filters( 'wl_feature__enable__entity-auto-publish', true )
121
+                    ? $data['post_status'] : 'draft';
122
+                $this->create_or_update_entity( $entity, $post_status );
123
+
124
+            }
125
+
126
+        } catch ( \Exception $e ) {
127
+            $this->log->error( $e->getMessage() );
128
+        }
129
+
130
+
131
+        return $data;
132
+    }
133
+
134
+    /**
135
+     * Parse the post content to find the `wordlift/classification` block and return the entities' data.
136
+     *
137
+     * @param string $post_content The post content.
138
+     *
139
+     * @return array An array of entities' structures.
140
+     * @throws \Exception
141
+     */
142
+    private function parse_content( $post_content ) {
143
+
144
+        $all_blocks = parse_blocks( $post_content );
145
+        $this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
146
+                            . var_export( $all_blocks, true ) );
147
+
148
+        $blocks = array_filter( $all_blocks, function ( $item ) {
149
+            return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
150
+        } );
151
+
152
+        // Bail out if the blocks' array is empty.
153
+        if ( empty( $blocks ) ) {
154
+            return array();
155
+        }
156
+
157
+        $block = current( $blocks );
158
+        $this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
159
+                            . var_export( $block, true ) );
160
+
161
+        // Bail out if the entities array is empty.
162
+        if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
163
+            return array();
164
+        }
165
+
166
+        return $block['attrs']['entities'];
167
+    }
168
+
169
+    /**
170
+     * Collect entity labels from the entity array.
171
+     *
172
+     * This function expects an array with the following keys:
173
+     *
174
+     * array(
175
+     *   'label'       => ...,
176
+     *   'synonyms'    => array( ... ),
177
+     *   'annotations' => array(
178
+     *     ...id...      => array( text => ... ),
179
+     *   ),
180
+     *   'occurrences' => array( ... ),
181
+     * )
182
+     *
183
+     * and it is going to output an array with all the labels, keeping the `label` at first position:
184
+     *
185
+     * array(
186
+     *   ...label...,
187
+     *   ...synonyms...,
188
+     *   ...texts...,
189
+     * )
190
+     *
191
+     * This function is going to collect the label from the `label` property, from the `synonyms` property and from
192
+     * `annotations` property. Since the `annotations` property contains all the annotations including those that
193
+     * haven't been selected, this function is going to only get the `text` for the annotations property listed in
194
+     * `occurrences`.
195
+     *
196
+     * @param array $entity {
197
+     *  The entity data.
198
+     *
199
+     * @type string $label The entity label.
200
+     * @type array $synonyms The entity synonyms.
201
+     * @type array $occurrences The selected occurrences.
202
+     * @type array $annotations The annotations.
203
+     * }
204
+     *
205
+     * @return array An array of labels.
206
+     */
207
+    public function get_labels( $entity ) {
208
+
209
+        $args = wp_parse_args( $entity, array(
210
+            'label'       => array(),
211
+            'synonyms'    => array(),
212
+            'annotations' => array(),
213
+            'occurrences' => array(),
214
+        ) );
215
+
216
+        // We gather all the labels, occurrences texts and synonyms into one array.
217
+        $initial = array_merge(
218
+            (array) $args['label'],
219
+            (array) $args['synonyms']
220
+        );
221
+
222
+        $annotations = $args['annotations'];
223
+
224
+        return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
225
+
226
+            // Bail out if occurrences->$item->text isn't set or its contents are already
227
+            // in `$carry`.
228
+            if ( ! isset( $annotations[ $item ]['text'] )
229
+                 || in_array( $annotations[ $item ]['text'], $carry ) ) {
230
+                return $carry;
231
+            }
232
+
233
+            // Push the label.
234
+            $carry[] = $annotations[ $item ]['text'];
235
+
236
+            return $carry;
237
+        }, $initial );
238
+    }
239
+
240
+    /**
241
+     * Create or update the entity.
242
+     *
243
+     * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
244
+     * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
245
+     *
246
+     * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
247
+     *
248
+     * @param array $entity {
249
+     * The entity parameters.
250
+     *
251
+     * @type string The entity item id URI.
252
+     * @type string|array The entity sameAs URI(s).
253
+     * @type string $description The entity description.
254
+     * }
255
+     *
256
+     * @param       $string $post_status The post status, default 'draft'.
257
+     *
258
+     * @return int|\WP_Error
259
+     * @throws \Exception
260
+     */
261
+    private function create_or_update_entity( $entity, $post_status = 'draft' ) {
262
+
263
+        // Get only valid IDs.
264
+        $uris = $this->get_entity_uris( $entity );
265
+
266
+        $post = $this->get_first_matching_entity_by_uri( $uris );
267
+
268
+        $this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
269
+                            . var_export( $uris, true ) );
270
+
271
+        // Get the labels.
272
+        $labels = $this->get_labels( $entity );
273
+
274
+        if ( empty( $post ) ) {
275
+            $entity_description = array_key_exists( 'description', $entity ) ? $entity['description'] : '';
276
+            // Create the entity if it doesn't exist.
277
+            $post_id = Entity_Store::get_instance()->create( array(
278
+                'labels'      => $labels,
279
+                'description' => $entity_description,
280
+                'same_as'     => $uris,
281
+            ), $post_status );
282
+
283
+            // Return the WP_Error if we got one.
284
+            if ( is_wp_error( $post_id ) ) {
285
+                return $post_id;
286
+            }
287
+
288
+            // Add the entity type.
289
+            if ( isset( $entity['mainType'] ) ) {
290
+                wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
291
+            }
292
+
293
+            if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
294
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
295
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
296
+            }
297
+        } else {
298
+            // Update the entity otherwise.
299
+            $post_id = Entity_Store::get_instance()->update( array(
300
+                'ID'      => $post->ID,
301
+                'labels'  => $labels,
302
+                'same_as' => $uris,
303
+            ) );
304
+
305
+            // Add the entity type.
306
+            if ( isset( $entity['mainType'] ) ) {
307
+                wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
308
+            }
309
+
310
+            // see https://github.com/insideout10/wordlift-plugin/issues/1304
311
+            // Set the post status, we need to set that in order to support entities
312
+            // created using rest endpoint on block editor, so that they get published
313
+            // when the post is published.
314
+            // Once the entity is published dont update the post status.
315
+            if ( $post->post_status !== 'publish' ) {
316
+                wp_update_post( array(
317
+                    'ID'          => $post->ID,
318
+                    'post_status' => $post_status
319
+                ) );
320
+            }
321
+        }
322
+
323
+        return $post_id;
324
+    }
325
+
326
+    /**
327
+     * Get the first matching entity for the provided URI array.
328
+     *
329
+     * Entities IDs and sameAs are searched.
330
+     *
331
+     * @param array $uris An array of URIs.
332
+     *
333
+     * @return \WP_Post|null The entity WP_Post if found or null if not found.
334
+     */
335
+    private function get_first_matching_entity_by_uri( $uris ) {
336
+
337
+        foreach ( $uris as $uri ) {
338
+
339
+            $content = Wordpress_Content_Service::get_instance()->get_by_entity_id_or_same_as( $uri );
340
+
341
+            if ( ! $content ) {
342
+                continue;
343
+            }
344
+
345
+            $existing_entity = $content->get_bag();
346
+
347
+            if ( is_a( $existing_entity, 'WP_Post' ) ) {
348
+                return $existing_entity;
349
+            }
350
+        }
351
+
352
+        return null;
353
+    }
354
+
355
+    /**
356
+     * @param $entity
357
+     *
358
+     * @return array
359
+     */
360
+    private function filter_valid_entity_ids( $entity ) {
361
+        $id = $entity['id'];
362
+
363
+        return array_filter( (array) $id, function ( $id ) {
364
+            return preg_match( '|^https?://|', $id );
365
+        } );
366
+    }
367
+
368
+    /**
369
+     * @param array $entity
370
+     *
371
+     * @return array
372
+     */
373
+    private function get_entity_uris( $entity ) {
374
+        $ids     = $this->filter_valid_entity_ids( $entity );
375
+        $same_as = array_key_exists( 'sameAs', $entity ) ? $entity['sameAs'] : array();
376
+
377
+        return array_merge(
378
+            (array) $ids,
379
+            (array) $same_as
380
+        );
381
+    }
382
+
383
+    private function entity_id_valid( $entity_id ) {
384
+        return preg_match( '#^https?://#i', $entity_id ) === 1;
385
+    }
386 386
 
387 387
 }
Please login to merge, or discard this patch.
src/wordlift/entity/class-entity-store.php 2 patches
Indentation   +120 added lines, -120 removed lines patch added patch discarded remove patch
@@ -32,125 +32,125 @@
 block discarded – undo
32 32
  */
33 33
 class Entity_Store {
34 34
 
35
-	protected function __construct() {
36
-	}
37
-
38
-	private static $instance = null;
39
-
40
-	/**
41
-	 * Get the Entity_Store singleton, lazily initialized.
42
-	 *
43
-	 * @return Entity_Store The singleton.
44
-	 */
45
-	public static function get_instance() {
46
-		if ( ! isset( self::$instance ) ) {
47
-			self::$instance = new Entity_Store();
48
-		}
49
-
50
-		return self::$instance;
51
-	}
52
-
53
-	/**
54
-	 * Create and persist an entity.
55
-	 *
56
-	 * @param array $params {
57
-	 *      The entity parameters.
58
-	 *
59
-	 * @type string|array $labels A label, or an array of labels. The first label is set as post title.
60
-	 * @type string $description The entity description, stored in the post content.
61
-	 * @type string|array $same_as One or more entity URIs, stored in the sameAs post meta.
62
-	 * }
63
-	 *
64
-	 * @param string $post_status The post status, by default `draft`.
65
-	 *
66
-	 * @return int|\WP_Error
67
-	 * @throws \Exception
68
-	 */
69
-	public function create( $params, $post_status = 'draft' ) {
70
-
71
-		$args = wp_parse_args( $params, array(
72
-			'labels'      => array(),
73
-			'description' => '',
74
-			'same_as'     => array(),
75
-		) );
76
-
77
-		// Use the first label as `post_title`.
78
-		$labels = (array) $args['labels'];
79
-		$label  = array_shift( $labels );
80
-
81
-		$post_id = wp_insert_post( array(
82
-			'post_type'    => Wordlift_Entity_Service::TYPE_NAME,
83
-			'post_status'  => $post_status,
84
-			'post_title'   => $label,
85
-			'post_name'    => sanitize_title( $label ),
86
-			'post_content' => $args['description'],
87
-		) );
88
-
89
-		// Bail out if we've got an error.
90
-		if ( empty( $post_id ) || is_wp_error( $post_id ) ) {
91
-			throw new \Exception( "An error occurred while creating an entity." );
92
-		}
93
-
94
-		Wordlift_Entity_Service::get_instance()
95
-		                       ->set_alternative_labels( $post_id, array_diff( $labels, array( $label ) ) );
96
-		$this->merge_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
97
-			(array) Wordpress_Content_Service::get_instance()->get_entity_id( Wordpress_Content_Id::create_post( $post_id ) ) );
98
-
99
-		return $post_id;
100
-	}
101
-
102
-	/**
103
-	 * Update an entity.
104
-	 *
105
-	 * @param array $params {
106
-	 *
107
-	 * @type int $ID The post ID.
108
-	 * @type string|array One or more labels to add to the synonyms.
109
-	 * @type string|array One or more URIs to add to the sameAs.
110
-	 * }
111
-	 *
112
-	 * @return int The post id.
113
-	 */
114
-	public function update( $params ) {
115
-
116
-		$args = wp_parse_args( $params, array(
117
-			'ID'      => 0,
118
-			'labels'  => array(),
119
-			'same_as' => array(),
120
-		) );
121
-
122
-		$post_id = $args['ID'];
123
-
124
-		// Save synonyms except title.
125
-		Wordlift_Entity_Service::get_instance()
126
-		                       ->append_alternative_labels( $post_id, array_diff( (array) $args['labels'], array( get_the_title( $post_id ) ) ) );
127
-
128
-		$this->merge_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
129
-			(array) Wordpress_Content_Service::get_instance()->get_entity_id( Wordpress_Content_Id::create_post( $post_id ) ) );
130
-
131
-		return $post_id;
132
-	}
133
-
134
-	/**
135
-	 * Merge the post meta.
136
-	 *
137
-	 * @param int $post_id The post ID.
138
-	 * @param string $meta_key The post meta key.
139
-	 * @param string|array $values One or more values to add.
140
-	 * @param string|array $exclusions An additional list of values to exclude.
141
-	 */
142
-	private function merge_post_meta( $post_id, $meta_key, $values, $exclusions = array() ) {
143
-
144
-		$existing = array_merge(
145
-			(array) $exclusions,
146
-			get_post_meta( $post_id, $meta_key )
147
-		);
148
-
149
-		foreach ( (array) $values as $value ) {
150
-			if ( ! in_array( $value, $existing ) ) {
151
-				add_post_meta( $post_id, $meta_key, $value );
152
-			}
153
-		}
154
-	}
35
+    protected function __construct() {
36
+    }
37
+
38
+    private static $instance = null;
39
+
40
+    /**
41
+     * Get the Entity_Store singleton, lazily initialized.
42
+     *
43
+     * @return Entity_Store The singleton.
44
+     */
45
+    public static function get_instance() {
46
+        if ( ! isset( self::$instance ) ) {
47
+            self::$instance = new Entity_Store();
48
+        }
49
+
50
+        return self::$instance;
51
+    }
52
+
53
+    /**
54
+     * Create and persist an entity.
55
+     *
56
+     * @param array $params {
57
+     *      The entity parameters.
58
+     *
59
+     * @type string|array $labels A label, or an array of labels. The first label is set as post title.
60
+     * @type string $description The entity description, stored in the post content.
61
+     * @type string|array $same_as One or more entity URIs, stored in the sameAs post meta.
62
+     * }
63
+     *
64
+     * @param string $post_status The post status, by default `draft`.
65
+     *
66
+     * @return int|\WP_Error
67
+     * @throws \Exception
68
+     */
69
+    public function create( $params, $post_status = 'draft' ) {
70
+
71
+        $args = wp_parse_args( $params, array(
72
+            'labels'      => array(),
73
+            'description' => '',
74
+            'same_as'     => array(),
75
+        ) );
76
+
77
+        // Use the first label as `post_title`.
78
+        $labels = (array) $args['labels'];
79
+        $label  = array_shift( $labels );
80
+
81
+        $post_id = wp_insert_post( array(
82
+            'post_type'    => Wordlift_Entity_Service::TYPE_NAME,
83
+            'post_status'  => $post_status,
84
+            'post_title'   => $label,
85
+            'post_name'    => sanitize_title( $label ),
86
+            'post_content' => $args['description'],
87
+        ) );
88
+
89
+        // Bail out if we've got an error.
90
+        if ( empty( $post_id ) || is_wp_error( $post_id ) ) {
91
+            throw new \Exception( "An error occurred while creating an entity." );
92
+        }
93
+
94
+        Wordlift_Entity_Service::get_instance()
95
+                                ->set_alternative_labels( $post_id, array_diff( $labels, array( $label ) ) );
96
+        $this->merge_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
97
+            (array) Wordpress_Content_Service::get_instance()->get_entity_id( Wordpress_Content_Id::create_post( $post_id ) ) );
98
+
99
+        return $post_id;
100
+    }
101
+
102
+    /**
103
+     * Update an entity.
104
+     *
105
+     * @param array $params {
106
+     *
107
+     * @type int $ID The post ID.
108
+     * @type string|array One or more labels to add to the synonyms.
109
+     * @type string|array One or more URIs to add to the sameAs.
110
+     * }
111
+     *
112
+     * @return int The post id.
113
+     */
114
+    public function update( $params ) {
115
+
116
+        $args = wp_parse_args( $params, array(
117
+            'ID'      => 0,
118
+            'labels'  => array(),
119
+            'same_as' => array(),
120
+        ) );
121
+
122
+        $post_id = $args['ID'];
123
+
124
+        // Save synonyms except title.
125
+        Wordlift_Entity_Service::get_instance()
126
+                                ->append_alternative_labels( $post_id, array_diff( (array) $args['labels'], array( get_the_title( $post_id ) ) ) );
127
+
128
+        $this->merge_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
129
+            (array) Wordpress_Content_Service::get_instance()->get_entity_id( Wordpress_Content_Id::create_post( $post_id ) ) );
130
+
131
+        return $post_id;
132
+    }
133
+
134
+    /**
135
+     * Merge the post meta.
136
+     *
137
+     * @param int $post_id The post ID.
138
+     * @param string $meta_key The post meta key.
139
+     * @param string|array $values One or more values to add.
140
+     * @param string|array $exclusions An additional list of values to exclude.
141
+     */
142
+    private function merge_post_meta( $post_id, $meta_key, $values, $exclusions = array() ) {
143
+
144
+        $existing = array_merge(
145
+            (array) $exclusions,
146
+            get_post_meta( $post_id, $meta_key )
147
+        );
148
+
149
+        foreach ( (array) $values as $value ) {
150
+            if ( ! in_array( $value, $existing ) ) {
151
+                add_post_meta( $post_id, $meta_key, $value );
152
+            }
153
+        }
154
+    }
155 155
 
156 156
 }
Please login to merge, or discard this patch.
Spacing   +24 added lines, -24 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 	 * @return Entity_Store The singleton.
44 44
 	 */
45 45
 	public static function get_instance() {
46
-		if ( ! isset( self::$instance ) ) {
46
+		if ( ! isset(self::$instance)) {
47 47
 			self::$instance = new Entity_Store();
48 48
 		}
49 49
 
@@ -66,35 +66,35 @@  discard block
 block discarded – undo
66 66
 	 * @return int|\WP_Error
67 67
 	 * @throws \Exception
68 68
 	 */
69
-	public function create( $params, $post_status = 'draft' ) {
69
+	public function create($params, $post_status = 'draft') {
70 70
 
71
-		$args = wp_parse_args( $params, array(
71
+		$args = wp_parse_args($params, array(
72 72
 			'labels'      => array(),
73 73
 			'description' => '',
74 74
 			'same_as'     => array(),
75
-		) );
75
+		));
76 76
 
77 77
 		// Use the first label as `post_title`.
78 78
 		$labels = (array) $args['labels'];
79
-		$label  = array_shift( $labels );
79
+		$label  = array_shift($labels);
80 80
 
81
-		$post_id = wp_insert_post( array(
81
+		$post_id = wp_insert_post(array(
82 82
 			'post_type'    => Wordlift_Entity_Service::TYPE_NAME,
83 83
 			'post_status'  => $post_status,
84 84
 			'post_title'   => $label,
85
-			'post_name'    => sanitize_title( $label ),
85
+			'post_name'    => sanitize_title($label),
86 86
 			'post_content' => $args['description'],
87
-		) );
87
+		));
88 88
 
89 89
 		// Bail out if we've got an error.
90
-		if ( empty( $post_id ) || is_wp_error( $post_id ) ) {
91
-			throw new \Exception( "An error occurred while creating an entity." );
90
+		if (empty($post_id) || is_wp_error($post_id)) {
91
+			throw new \Exception("An error occurred while creating an entity.");
92 92
 		}
93 93
 
94 94
 		Wordlift_Entity_Service::get_instance()
95
-		                       ->set_alternative_labels( $post_id, array_diff( $labels, array( $label ) ) );
96
-		$this->merge_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
97
-			(array) Wordpress_Content_Service::get_instance()->get_entity_id( Wordpress_Content_Id::create_post( $post_id ) ) );
95
+		                       ->set_alternative_labels($post_id, array_diff($labels, array($label)));
96
+		$this->merge_post_meta($post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
97
+			(array) Wordpress_Content_Service::get_instance()->get_entity_id(Wordpress_Content_Id::create_post($post_id)));
98 98
 
99 99
 		return $post_id;
100 100
 	}
@@ -111,22 +111,22 @@  discard block
 block discarded – undo
111 111
 	 *
112 112
 	 * @return int The post id.
113 113
 	 */
114
-	public function update( $params ) {
114
+	public function update($params) {
115 115
 
116
-		$args = wp_parse_args( $params, array(
116
+		$args = wp_parse_args($params, array(
117 117
 			'ID'      => 0,
118 118
 			'labels'  => array(),
119 119
 			'same_as' => array(),
120
-		) );
120
+		));
121 121
 
122 122
 		$post_id = $args['ID'];
123 123
 
124 124
 		// Save synonyms except title.
125 125
 		Wordlift_Entity_Service::get_instance()
126
-		                       ->append_alternative_labels( $post_id, array_diff( (array) $args['labels'], array( get_the_title( $post_id ) ) ) );
126
+		                       ->append_alternative_labels($post_id, array_diff((array) $args['labels'], array(get_the_title($post_id))));
127 127
 
128
-		$this->merge_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
129
-			(array) Wordpress_Content_Service::get_instance()->get_entity_id( Wordpress_Content_Id::create_post( $post_id ) ) );
128
+		$this->merge_post_meta($post_id, \Wordlift_Schema_Service::FIELD_SAME_AS, (array) $args['same_as'],
129
+			(array) Wordpress_Content_Service::get_instance()->get_entity_id(Wordpress_Content_Id::create_post($post_id)));
130 130
 
131 131
 		return $post_id;
132 132
 	}
@@ -139,16 +139,16 @@  discard block
 block discarded – undo
139 139
 	 * @param string|array $values One or more values to add.
140 140
 	 * @param string|array $exclusions An additional list of values to exclude.
141 141
 	 */
142
-	private function merge_post_meta( $post_id, $meta_key, $values, $exclusions = array() ) {
142
+	private function merge_post_meta($post_id, $meta_key, $values, $exclusions = array()) {
143 143
 
144 144
 		$existing = array_merge(
145 145
 			(array) $exclusions,
146
-			get_post_meta( $post_id, $meta_key )
146
+			get_post_meta($post_id, $meta_key)
147 147
 		);
148 148
 
149
-		foreach ( (array) $values as $value ) {
150
-			if ( ! in_array( $value, $existing ) ) {
151
-				add_post_meta( $post_id, $meta_key, $value );
149
+		foreach ((array) $values as $value) {
150
+			if ( ! in_array($value, $existing)) {
151
+				add_post_meta($post_id, $meta_key, $value);
152 152
 			}
153 153
 		}
154 154
 	}
Please login to merge, or discard this patch.
src/includes/class-wordlift-entity-service.php 2 patches
Indentation   +578 added lines, -578 removed lines patch added patch discarded remove patch
@@ -21,499 +21,499 @@  discard block
 block discarded – undo
21 21
  */
22 22
 class Wordlift_Entity_Service {
23 23
 
24
-	/**
25
-	 * The Log service.
26
-	 *
27
-	 * @since  3.2.0
28
-	 * @access private
29
-	 * @var \Wordlift_Log_Service $log The Log service.
30
-	 */
31
-	private $log;
32
-
33
-	/**
34
-	 * The {@link Wordlift_Relation_Service} instance.
35
-	 *
36
-	 * @since  3.15.0
37
-	 * @access private
38
-	 * @var \Wordlift_Relation_Service $relation_service The {@link Wordlift_Relation_Service} instance.
39
-	 */
40
-	private $relation_service;
41
-
42
-	/**
43
-	 * The {@link Wordlift_Entity_Uri_Service} instance.
44
-	 *
45
-	 * @since  3.16.3
46
-	 * @access private
47
-	 * @var \Wordlift_Entity_Uri_Service $entity_uri_service The {@link Wordlift_Entity_Uri_Service} instance.
48
-	 */
49
-	private $entity_uri_service;
50
-
51
-	/**
52
-	 * The entity post type name.
53
-	 *
54
-	 * @since 3.1.0
55
-	 */
56
-	const TYPE_NAME = 'entity';
57
-
58
-	/**
59
-	 * The alternative label meta key.
60
-	 *
61
-	 * @since 3.2.0
62
-	 */
63
-	const ALTERNATIVE_LABEL_META_KEY = '_wl_alt_label';
64
-
65
-	/**
66
-	 * The alternative label input template.
67
-	 *
68
-	 * @since 3.2.0
69
-	 */
70
-	// TODO: this should be moved to a class that deals with HTML code.
71
-	const ALTERNATIVE_LABEL_INPUT_TEMPLATE = '<div class="wl-alternative-label">
24
+    /**
25
+     * The Log service.
26
+     *
27
+     * @since  3.2.0
28
+     * @access private
29
+     * @var \Wordlift_Log_Service $log The Log service.
30
+     */
31
+    private $log;
32
+
33
+    /**
34
+     * The {@link Wordlift_Relation_Service} instance.
35
+     *
36
+     * @since  3.15.0
37
+     * @access private
38
+     * @var \Wordlift_Relation_Service $relation_service The {@link Wordlift_Relation_Service} instance.
39
+     */
40
+    private $relation_service;
41
+
42
+    /**
43
+     * The {@link Wordlift_Entity_Uri_Service} instance.
44
+     *
45
+     * @since  3.16.3
46
+     * @access private
47
+     * @var \Wordlift_Entity_Uri_Service $entity_uri_service The {@link Wordlift_Entity_Uri_Service} instance.
48
+     */
49
+    private $entity_uri_service;
50
+
51
+    /**
52
+     * The entity post type name.
53
+     *
54
+     * @since 3.1.0
55
+     */
56
+    const TYPE_NAME = 'entity';
57
+
58
+    /**
59
+     * The alternative label meta key.
60
+     *
61
+     * @since 3.2.0
62
+     */
63
+    const ALTERNATIVE_LABEL_META_KEY = '_wl_alt_label';
64
+
65
+    /**
66
+     * The alternative label input template.
67
+     *
68
+     * @since 3.2.0
69
+     */
70
+    // TODO: this should be moved to a class that deals with HTML code.
71
+    const ALTERNATIVE_LABEL_INPUT_TEMPLATE = '<div class="wl-alternative-label">
72 72
                 <label class="screen-reader-text" id="wl-alternative-label-prompt-text" for="wl-alternative-label">Enter alternative label here</label>
73 73
                 <input name="wl_alternative_label[]" size="30" value="%s" id="wl-alternative-label" type="text">
74 74
                 <button class="button wl-delete-button">%s</button>
75 75
                 </div>';
76 76
 
77
-	/**
78
-	 * Create a Wordlift_Entity_Service instance.
79
-	 *
80
-	 * @throws Exception if the `$content_service` is not of the `Content_Service` type.
81
-	 * @since 3.2.0
82
-	 */
83
-	protected function __construct() {
84
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Entity_Service' );
85
-
86
-		$this->entity_uri_service = Wordlift_Entity_Uri_Service::get_instance();
87
-		$this->relation_service   = Wordlift_Relation_Service::get_instance();
88
-
89
-	}
90
-
91
-	/**
92
-	 * A singleton instance of the Entity service.
93
-	 *
94
-	 * @since  3.2.0
95
-	 * @access private
96
-	 * @var Wordlift_Entity_Service $instance A singleton instance of the Entity service.
97
-	 */
98
-	private static $instance = null;
99
-
100
-	/**
101
-	 * Get the singleton instance of the Entity service.
102
-	 *
103
-	 * @return Wordlift_Entity_Service The singleton instance of the Entity service.
104
-	 * @since 3.2.0
105
-	 */
106
-	public static function get_instance() {
107
-
108
-		if ( ! isset( self::$instance ) ) {
109
-			self::$instance = new self();
110
-		}
111
-
112
-		return self::$instance;
113
-	}
114
-
115
-	/**
116
-	 * Determines whether a post is an entity or not. Entity is in this context
117
-	 * something which is not an article.
118
-	 *
119
-	 * @param int $post_id A post id.
120
-	 *
121
-	 * @return bool Return true if the post is an entity otherwise false.
122
-	 * @since 3.1.0
123
-	 *
124
-	 */
125
-	public function is_entity( $post_id ) {
126
-
127
-		// Improve performance by giving for granted that a product is an entity.
128
-		if ( 'product' === get_post_type( $post_id ) ) {
129
-			return true;
130
-		}
131
-
132
-		$terms = wp_get_object_terms( $post_id, Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
133
-
134
-		if ( is_wp_error( $terms ) ) {
135
-			$this->log->error( "Cannot get the terms for post $post_id: " . $terms->get_error_message() );
136
-
137
-			return false;
138
-		}
139
-
140
-		if ( empty( $terms ) ) {
141
-			return false;
142
-		}
143
-
144
-		/*
77
+    /**
78
+     * Create a Wordlift_Entity_Service instance.
79
+     *
80
+     * @throws Exception if the `$content_service` is not of the `Content_Service` type.
81
+     * @since 3.2.0
82
+     */
83
+    protected function __construct() {
84
+        $this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Entity_Service' );
85
+
86
+        $this->entity_uri_service = Wordlift_Entity_Uri_Service::get_instance();
87
+        $this->relation_service   = Wordlift_Relation_Service::get_instance();
88
+
89
+    }
90
+
91
+    /**
92
+     * A singleton instance of the Entity service.
93
+     *
94
+     * @since  3.2.0
95
+     * @access private
96
+     * @var Wordlift_Entity_Service $instance A singleton instance of the Entity service.
97
+     */
98
+    private static $instance = null;
99
+
100
+    /**
101
+     * Get the singleton instance of the Entity service.
102
+     *
103
+     * @return Wordlift_Entity_Service The singleton instance of the Entity service.
104
+     * @since 3.2.0
105
+     */
106
+    public static function get_instance() {
107
+
108
+        if ( ! isset( self::$instance ) ) {
109
+            self::$instance = new self();
110
+        }
111
+
112
+        return self::$instance;
113
+    }
114
+
115
+    /**
116
+     * Determines whether a post is an entity or not. Entity is in this context
117
+     * something which is not an article.
118
+     *
119
+     * @param int $post_id A post id.
120
+     *
121
+     * @return bool Return true if the post is an entity otherwise false.
122
+     * @since 3.1.0
123
+     *
124
+     */
125
+    public function is_entity( $post_id ) {
126
+
127
+        // Improve performance by giving for granted that a product is an entity.
128
+        if ( 'product' === get_post_type( $post_id ) ) {
129
+            return true;
130
+        }
131
+
132
+        $terms = wp_get_object_terms( $post_id, Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
133
+
134
+        if ( is_wp_error( $terms ) ) {
135
+            $this->log->error( "Cannot get the terms for post $post_id: " . $terms->get_error_message() );
136
+
137
+            return false;
138
+        }
139
+
140
+        if ( empty( $terms ) ) {
141
+            return false;
142
+        }
143
+
144
+        /*
145 145
 		 * We don't consider an `article` to be an entity.
146 146
 		 *
147 147
 		 * @since 3.20.0 At least one associated mustn't be an `article`.
148 148
 		 *
149 149
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/835
150 150
 		 */
151
-		foreach ( $terms as $term ) {
152
-			if ( 1 !== preg_match( '~(^|-)article$~', $term->slug ) ) {
153
-				return true;
154
-			}
155
-		}
156
-
157
-		return false;
158
-	}
159
-
160
-	/**
161
-	 * Get the proper classification scope for a given entity post
162
-	 *
163
-	 * @param integer $post_id An entity post id.
164
-	 *
165
-	 * @param string $default The default classification scope, `what` if not
166
-	 *                         provided.
167
-	 *
168
-	 * @return string Returns a classification scope (e.g. 'what').
169
-	 * @since 3.5.0
170
-	 *
171
-	 */
172
-	public function get_classification_scope_for( $post_id, $default = WL_WHAT_RELATION ) {
173
-
174
-		if ( false === $this->is_entity( $post_id ) ) {
175
-			return $default;
176
-		}
177
-
178
-		// Retrieve the entity type
179
-		$entity_type_arr = Wordlift_Entity_Type_Service::get_instance()->get( $post_id );
180
-		$entity_type     = str_replace( 'wl-', '', $entity_type_arr['css_class'] );
181
-		// Retrieve classification boxes configuration
182
-		$classification_boxes = unserialize( WL_CORE_POST_CLASSIFICATION_BOXES );
183
-		foreach ( $classification_boxes as $cb ) {
184
-			if ( in_array( $entity_type, $cb['registeredTypes'] ) ) {
185
-				return $cb['id'];
186
-			}
187
-		}
188
-
189
-		return $default;
190
-	}
191
-
192
-	/**
193
-	 * Check whether a {@link WP_Post} is used.
194
-	 *
195
-	 * @param int $post_id The {@link WP_Post}'s id.
196
-	 *
197
-	 * @return bool|null Null if it's not an entity, otherwise true if it's used.
198
-	 */
199
-	public function is_used( $post_id ) {
200
-
201
-		if ( false === $this->is_entity( $post_id ) ) {
202
-			return null;
203
-		}
204
-		// Retrieve the post
205
-		$entity = get_post( $post_id );
206
-
207
-		global $wpdb;
208
-		// Retrieve Wordlift relation instances table name
209
-		$table_name = wl_core_get_relation_instances_table_name();
210
-
211
-		// Check is it's referenced / related to another post / entity
212
-		$stmt = $wpdb->prepare(
213
-			"SELECT COUNT(*) FROM $table_name WHERE  object_id = %d",
214
-			$entity->ID
215
-		);
216
-
217
-		// Perform the query
218
-		$relation_instances = (int) $wpdb->get_var( $stmt );
219
-		// If there is at least one relation instance for the current entity, then it's used
220
-		if ( 0 < $relation_instances ) {
221
-			return true;
222
-		}
223
-
224
-		// Check if the entity uri is used as meta_value
225
-		$stmt = $wpdb->prepare(
226
-			"SELECT COUNT(*) FROM $wpdb->postmeta WHERE post_id != %d AND meta_value = %s",
227
-			$entity->ID,
228
-			wl_get_entity_uri( $entity->ID )
229
-		);
230
-		// Perform the query
231
-		$meta_instances = (int) $wpdb->get_var( $stmt );
232
-
233
-		// If there is at least one meta that refers the current entity uri, then current entity is used
234
-		if ( 0 < $meta_instances ) {
235
-			return true;
236
-		}
237
-
238
-		// If we are here, it means the current entity is not used at the moment
239
-		return false;
240
-	}
241
-
242
-	/**
243
-	 * Find entity posts by the entity URI. Entity as searched by their entity URI or same as.
244
-	 *
245
-	 * @param string $uri The entity URI.
246
-	 *
247
-	 * @return WP_Post|null A WP_Post instance or null if not found.
248
-	 * @deprecated in favor of Wordlift_Entity_Uri_Service->get_entity( $uri );
249
-	 *
250
-	 * @since      3.16.3 deprecated in favor of Wordlift_Entity_Uri_Service->get_entity( $uri );
251
-	 * @since      3.2.0
252
-	 *
253
-	 */
254
-	public function get_entity_post_by_uri( $uri ) {
255
-
256
-		return $this->entity_uri_service->get_entity( $uri );
257
-	}
258
-
259
-	/**
260
-	 * Fires once a post has been saved. This function uses the $_REQUEST, therefore
261
-	 * we check that the post we're saving is the current post.
262
-	 *
263
-	 * @see   https://github.com/insideout10/wordlift-plugin/issues/363
264
-	 *
265
-	 * @since 3.2.0
266
-	 *
267
-	 * @param int $post_id Post ID.
268
-	 * @param WP_Post $post Post object.
269
-	 * @param bool $update Whether this is an existing post being updated or not.
270
-	 */
271
-	public function save_post( $post_id, $post, $update ) {
272
-
273
-		// Avoid doing anything if post is autosave or a revision.
274
-		if ( wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
275
-			return;
276
-		}
277
-
278
-		// We're setting the alternative label that have been provided via the UI
279
-		// (in fact we're using $_REQUEST), while save_post may be also called
280
-		// programmatically by some other function: we need to check therefore if
281
-		// the $post_id in the save_post call matches the post id set in the request.
282
-		//
283
-		// If this is not the current post being saved or if it's not an entity, return.
284
-		if ( ! isset( $_REQUEST['post_ID'] ) || $_REQUEST['post_ID'] != $post_id || ! $this->is_entity( $post_id ) ) {
285
-			return;
286
-		}
287
-
288
-		// Get the alt labels from the request (or empty array).
289
-		$alt_labels = isset( $_REQUEST['wl_alternative_label'] ) ? (array) $_REQUEST['wl_alternative_label'] : array();
290
-
291
-		if ( ( ! empty( $_POST['content'] ) && ! empty( $_POST['post_content'] ) ) || isset( $_REQUEST['wl_alternative_label'] ) ) {
292
-			// This is via classic editor, so set the alternative labels.
293
-			$this->set_alternative_labels( $post_id, $alt_labels );
294
-		}
295
-
296
-
297
-	}
298
-
299
-	/**
300
-	 * Set the alternative labels.
301
-	 *
302
-	 * @param int $post_id The post id.
303
-	 * @param array $alt_labels An array of labels.
304
-	 *
305
-	 * @since 3.2.0
306
-	 *
307
-	 */
308
-	public function set_alternative_labels( $post_id, $alt_labels ) {
309
-
310
-		// Bail out if post id is not numeric. We add this check as we found a WP install that was sending a WP_Error
311
-		// instead of post id.
312
-		if ( ! is_numeric( $post_id ) ) {
313
-			return;
314
-		}
315
-
316
-		// Force $alt_labels to be an array
317
-		if ( ! is_array( $alt_labels ) ) {
318
-			$alt_labels = array( $alt_labels );
319
-		}
320
-
321
-		$this->log->debug( "Setting alternative labels [ post id :: $post_id ][ alt labels :: " . implode( ',', $alt_labels ) . " ]" );
322
-
323
-		// Delete all the existing alternate labels.
324
-		delete_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
325
-
326
-		// Save only unique synonymns.
327
-		$alt_labels = array_unique( $alt_labels );
328
-
329
-		// Set the alternative labels.
330
-		foreach ( $alt_labels as $alt_label ) {
331
-
332
-			// Strip html code from synonym.
333
-			$alt_label = wp_strip_all_tags( $alt_label );
334
-
335
-			if ( ! empty( $alt_label ) ) {
336
-				add_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY, (string) $alt_label );
337
-			}
338
-		}
339
-
340
-	}
341
-
342
-	public function append_alternative_labels( $post_id, $labels_to_append ) {
343
-
344
-
345
-		$merged_labels = $this->get_alternative_labels( $post_id );
151
+        foreach ( $terms as $term ) {
152
+            if ( 1 !== preg_match( '~(^|-)article$~', $term->slug ) ) {
153
+                return true;
154
+            }
155
+        }
156
+
157
+        return false;
158
+    }
159
+
160
+    /**
161
+     * Get the proper classification scope for a given entity post
162
+     *
163
+     * @param integer $post_id An entity post id.
164
+     *
165
+     * @param string $default The default classification scope, `what` if not
166
+     *                         provided.
167
+     *
168
+     * @return string Returns a classification scope (e.g. 'what').
169
+     * @since 3.5.0
170
+     *
171
+     */
172
+    public function get_classification_scope_for( $post_id, $default = WL_WHAT_RELATION ) {
173
+
174
+        if ( false === $this->is_entity( $post_id ) ) {
175
+            return $default;
176
+        }
177
+
178
+        // Retrieve the entity type
179
+        $entity_type_arr = Wordlift_Entity_Type_Service::get_instance()->get( $post_id );
180
+        $entity_type     = str_replace( 'wl-', '', $entity_type_arr['css_class'] );
181
+        // Retrieve classification boxes configuration
182
+        $classification_boxes = unserialize( WL_CORE_POST_CLASSIFICATION_BOXES );
183
+        foreach ( $classification_boxes as $cb ) {
184
+            if ( in_array( $entity_type, $cb['registeredTypes'] ) ) {
185
+                return $cb['id'];
186
+            }
187
+        }
188
+
189
+        return $default;
190
+    }
191
+
192
+    /**
193
+     * Check whether a {@link WP_Post} is used.
194
+     *
195
+     * @param int $post_id The {@link WP_Post}'s id.
196
+     *
197
+     * @return bool|null Null if it's not an entity, otherwise true if it's used.
198
+     */
199
+    public function is_used( $post_id ) {
200
+
201
+        if ( false === $this->is_entity( $post_id ) ) {
202
+            return null;
203
+        }
204
+        // Retrieve the post
205
+        $entity = get_post( $post_id );
206
+
207
+        global $wpdb;
208
+        // Retrieve Wordlift relation instances table name
209
+        $table_name = wl_core_get_relation_instances_table_name();
210
+
211
+        // Check is it's referenced / related to another post / entity
212
+        $stmt = $wpdb->prepare(
213
+            "SELECT COUNT(*) FROM $table_name WHERE  object_id = %d",
214
+            $entity->ID
215
+        );
216
+
217
+        // Perform the query
218
+        $relation_instances = (int) $wpdb->get_var( $stmt );
219
+        // If there is at least one relation instance for the current entity, then it's used
220
+        if ( 0 < $relation_instances ) {
221
+            return true;
222
+        }
223
+
224
+        // Check if the entity uri is used as meta_value
225
+        $stmt = $wpdb->prepare(
226
+            "SELECT COUNT(*) FROM $wpdb->postmeta WHERE post_id != %d AND meta_value = %s",
227
+            $entity->ID,
228
+            wl_get_entity_uri( $entity->ID )
229
+        );
230
+        // Perform the query
231
+        $meta_instances = (int) $wpdb->get_var( $stmt );
232
+
233
+        // If there is at least one meta that refers the current entity uri, then current entity is used
234
+        if ( 0 < $meta_instances ) {
235
+            return true;
236
+        }
237
+
238
+        // If we are here, it means the current entity is not used at the moment
239
+        return false;
240
+    }
241
+
242
+    /**
243
+     * Find entity posts by the entity URI. Entity as searched by their entity URI or same as.
244
+     *
245
+     * @param string $uri The entity URI.
246
+     *
247
+     * @return WP_Post|null A WP_Post instance or null if not found.
248
+     * @deprecated in favor of Wordlift_Entity_Uri_Service->get_entity( $uri );
249
+     *
250
+     * @since      3.16.3 deprecated in favor of Wordlift_Entity_Uri_Service->get_entity( $uri );
251
+     * @since      3.2.0
252
+     *
253
+     */
254
+    public function get_entity_post_by_uri( $uri ) {
255
+
256
+        return $this->entity_uri_service->get_entity( $uri );
257
+    }
258
+
259
+    /**
260
+     * Fires once a post has been saved. This function uses the $_REQUEST, therefore
261
+     * we check that the post we're saving is the current post.
262
+     *
263
+     * @see   https://github.com/insideout10/wordlift-plugin/issues/363
264
+     *
265
+     * @since 3.2.0
266
+     *
267
+     * @param int $post_id Post ID.
268
+     * @param WP_Post $post Post object.
269
+     * @param bool $update Whether this is an existing post being updated or not.
270
+     */
271
+    public function save_post( $post_id, $post, $update ) {
272
+
273
+        // Avoid doing anything if post is autosave or a revision.
274
+        if ( wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
275
+            return;
276
+        }
277
+
278
+        // We're setting the alternative label that have been provided via the UI
279
+        // (in fact we're using $_REQUEST), while save_post may be also called
280
+        // programmatically by some other function: we need to check therefore if
281
+        // the $post_id in the save_post call matches the post id set in the request.
282
+        //
283
+        // If this is not the current post being saved or if it's not an entity, return.
284
+        if ( ! isset( $_REQUEST['post_ID'] ) || $_REQUEST['post_ID'] != $post_id || ! $this->is_entity( $post_id ) ) {
285
+            return;
286
+        }
287
+
288
+        // Get the alt labels from the request (or empty array).
289
+        $alt_labels = isset( $_REQUEST['wl_alternative_label'] ) ? (array) $_REQUEST['wl_alternative_label'] : array();
290
+
291
+        if ( ( ! empty( $_POST['content'] ) && ! empty( $_POST['post_content'] ) ) || isset( $_REQUEST['wl_alternative_label'] ) ) {
292
+            // This is via classic editor, so set the alternative labels.
293
+            $this->set_alternative_labels( $post_id, $alt_labels );
294
+        }
295
+
296
+
297
+    }
298
+
299
+    /**
300
+     * Set the alternative labels.
301
+     *
302
+     * @param int $post_id The post id.
303
+     * @param array $alt_labels An array of labels.
304
+     *
305
+     * @since 3.2.0
306
+     *
307
+     */
308
+    public function set_alternative_labels( $post_id, $alt_labels ) {
309
+
310
+        // Bail out if post id is not numeric. We add this check as we found a WP install that was sending a WP_Error
311
+        // instead of post id.
312
+        if ( ! is_numeric( $post_id ) ) {
313
+            return;
314
+        }
315
+
316
+        // Force $alt_labels to be an array
317
+        if ( ! is_array( $alt_labels ) ) {
318
+            $alt_labels = array( $alt_labels );
319
+        }
320
+
321
+        $this->log->debug( "Setting alternative labels [ post id :: $post_id ][ alt labels :: " . implode( ',', $alt_labels ) . " ]" );
322
+
323
+        // Delete all the existing alternate labels.
324
+        delete_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
325
+
326
+        // Save only unique synonymns.
327
+        $alt_labels = array_unique( $alt_labels );
328
+
329
+        // Set the alternative labels.
330
+        foreach ( $alt_labels as $alt_label ) {
331
+
332
+            // Strip html code from synonym.
333
+            $alt_label = wp_strip_all_tags( $alt_label );
334
+
335
+            if ( ! empty( $alt_label ) ) {
336
+                add_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY, (string) $alt_label );
337
+            }
338
+        }
339
+
340
+    }
341
+
342
+    public function append_alternative_labels( $post_id, $labels_to_append ) {
343
+
344
+
345
+        $merged_labels = $this->get_alternative_labels( $post_id );
346 346
 		
347
-		// Append new synonyms to the end.
348
-		$merged_labels = array_merge( $merged_labels, $labels_to_append );
349
-
350
-		$this->set_alternative_labels( $post_id, $merged_labels );
351
-
352
-	}
353
-
354
-	/**
355
-	 * Retrieve the alternate labels.
356
-	 *
357
-	 * @param int $post_id Post id.
358
-	 *
359
-	 * @return mixed An array  of alternative labels.
360
-	 * @since 3.2.0
361
-	 *
362
-	 */
363
-	public function get_alternative_labels( $post_id ) {
364
-
365
-		return get_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
366
-	}
367
-
368
-	/**
369
-	 * Retrieve the labels for an entity, i.e. the title + the synonyms.
370
-	 *
371
-	 * @param int $post_id The entity {@link WP_Post} id.
372
-	 * @param int $object_type The object type {@link Object_Type_Enum}
373
-	 *
374
-	 * @return array An array with the entity title and labels.
375
-	 * @since 3.12.0
376
-	 */
377
-	public function get_labels( $post_id, $object_type = Object_Type_Enum::POST ) {
378
-		if ( $object_type === Object_Type_Enum::POST ) {
379
-			return array_merge( (array) get_the_title( $post_id ), $this->get_alternative_labels( $post_id ) );
380
-		}
381
-
382
-		// Term Reference dont have synonyms yet.
383
-		return array();
384
-	}
385
-
386
-	/**
387
-	 * Fires before the permalink field in the edit form (this event is available in WP from 4.1.0).
388
-	 *
389
-	 * @param WP_Post $post Post object.
390
-	 *
391
-	 * @since 3.2.0
392
-	 *
393
-	 */
394
-	public function edit_form_before_permalink( $post ) {
395
-
396
-		// If it's not an entity, return.
397
-		if ( ! $this->is_entity( $post->ID ) ) {
398
-			return;
399
-		}
400
-
401
-		// If disabled by filter, return.
402
-		if ( ! apply_filters( 'wl_feature__enable__add-synonyms', true ) ) {
403
-			return;
404
-		}
405
-
406
-		// Print the input template.
407
-		Wordlift_UI_Service::print_template( 'wl-tmpl-alternative-label-input', $this->get_alternative_label_input() );
408
-
409
-		// Print all the currently set alternative labels.
410
-		foreach ( $this->get_alternative_labels( $post->ID ) as $alt_label ) {
411
-
412
-			echo $this->get_alternative_label_input( $alt_label );
413
-
414
-		};
415
-
416
-		// Print the button.
417
-		Wordlift_UI_Service::print_button( 'wl-add-alternative-labels-button', __( 'Add more titles', 'wordlift' ) );
418
-
419
-	}
420
-
421
-	public function get_uri( $object_id, $type = Object_Type_Enum::POST ) {
422
-		$content_service = Wordpress_Content_Service::get_instance();
423
-		$entity_id       = $content_service->get_entity_id( new Wordpress_Content_Id( $object_id, $type ) );
424
-		$dataset_uri     = Wordlift_Configuration_Service::get_instance()->get_dataset_uri();
425
-
426
-		if ( ! isset( $entity_id ) || ( $dataset_uri && 0 !== strpos( $entity_id, $dataset_uri ) ) ) {
427
-			$rel_uri = Entity_Uri_Generator::create_uri( $type, $object_id );
428
-			try {
429
-				$content_service->set_entity_id( new Wordpress_Content_Id( $object_id, $type ), $rel_uri );
430
-				$entity_id = $content_service->get_entity_id( new Wordpress_Content_Id( $object_id, $type ) );
431
-			} catch ( Exception $e ) {
432
-				return null;
433
-			}
434
-		}
435
-
436
-		return $entity_id;
437
-	}
438
-
439
-	/**
440
-	 * Get the alternative label input HTML code.
441
-	 *
442
-	 * @param string $value The input value.
443
-	 *
444
-	 * @return string The input HTML code.
445
-	 * @since 3.2.0
446
-	 *
447
-	 */
448
-	private function get_alternative_label_input( $value = '' ) {
449
-
450
-		return sprintf( self::ALTERNATIVE_LABEL_INPUT_TEMPLATE, esc_attr( $value ), __( 'Delete', 'wordlift' ) );
451
-	}
452
-
453
-	/**
454
-	 * Get the number of entity posts published in this blog.
455
-	 *
456
-	 * @return int The number of published entity posts.
457
-	 * @since 3.6.0
458
-	 *
459
-	 */
460
-	public function count() {
461
-		global $wpdb;
462
-
463
-		// Try to get the count from the transient.
464
-		$count = get_transient( '_wl_entity_service__count' );
465
-		if ( false !== $count ) {
466
-			return $count;
467
-		}
468
-
469
-		// Query the count.
470
-		$count = $wpdb->get_var( $wpdb->prepare(
471
-			"SELECT COUNT( DISTINCT( tr.object_id ) )"
472
-			. " FROM {$wpdb->term_relationships} tr"
473
-			. " INNER JOIN {$wpdb->term_taxonomy} tt"
474
-			. "  ON tt.taxonomy = %s AND tt.term_taxonomy_id = tr.term_taxonomy_id"
475
-			. " INNER JOIN {$wpdb->terms} t"
476
-			. "  ON t.term_id = tt.term_id AND t.name != %s",
477
-			Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
478
-			'article'
479
-		) );
480
-
481
-		// Store the count in cache.
482
-		set_transient( '_wl_entity_service__count', $count, 900 );
483
-
484
-		return $count;
485
-	}
486
-
487
-	/**
488
-	 * Add the entity filtering criterias to the arguments for a `get_posts`
489
-	 * call.
490
-	 *
491
-	 * @param array $args The arguments for a `get_posts` call.
492
-	 *
493
-	 * @return array The arguments for a `get_posts` call.
494
-	 * @since 3.15.0
495
-	 *
496
-	 */
497
-	public static function add_criterias( $args ) {
498
-
499
-		// Build an optimal tax-query.
500
-		$tax_query = array(
501
-			'relation' => 'AND',
502
-			array(
503
-				'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
504
-				'operator' => 'EXISTS',
505
-			),
506
-			array(
507
-				'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
508
-				'field'    => 'slug',
509
-				'terms'    => 'article',
510
-				'operator' => 'NOT IN',
511
-			),
512
-		);
513
-
514
-		return $args + array(
515
-				'post_type' => Wordlift_Entity_Service::valid_entity_post_types(),
516
-				/*
347
+        // Append new synonyms to the end.
348
+        $merged_labels = array_merge( $merged_labels, $labels_to_append );
349
+
350
+        $this->set_alternative_labels( $post_id, $merged_labels );
351
+
352
+    }
353
+
354
+    /**
355
+     * Retrieve the alternate labels.
356
+     *
357
+     * @param int $post_id Post id.
358
+     *
359
+     * @return mixed An array  of alternative labels.
360
+     * @since 3.2.0
361
+     *
362
+     */
363
+    public function get_alternative_labels( $post_id ) {
364
+
365
+        return get_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
366
+    }
367
+
368
+    /**
369
+     * Retrieve the labels for an entity, i.e. the title + the synonyms.
370
+     *
371
+     * @param int $post_id The entity {@link WP_Post} id.
372
+     * @param int $object_type The object type {@link Object_Type_Enum}
373
+     *
374
+     * @return array An array with the entity title and labels.
375
+     * @since 3.12.0
376
+     */
377
+    public function get_labels( $post_id, $object_type = Object_Type_Enum::POST ) {
378
+        if ( $object_type === Object_Type_Enum::POST ) {
379
+            return array_merge( (array) get_the_title( $post_id ), $this->get_alternative_labels( $post_id ) );
380
+        }
381
+
382
+        // Term Reference dont have synonyms yet.
383
+        return array();
384
+    }
385
+
386
+    /**
387
+     * Fires before the permalink field in the edit form (this event is available in WP from 4.1.0).
388
+     *
389
+     * @param WP_Post $post Post object.
390
+     *
391
+     * @since 3.2.0
392
+     *
393
+     */
394
+    public function edit_form_before_permalink( $post ) {
395
+
396
+        // If it's not an entity, return.
397
+        if ( ! $this->is_entity( $post->ID ) ) {
398
+            return;
399
+        }
400
+
401
+        // If disabled by filter, return.
402
+        if ( ! apply_filters( 'wl_feature__enable__add-synonyms', true ) ) {
403
+            return;
404
+        }
405
+
406
+        // Print the input template.
407
+        Wordlift_UI_Service::print_template( 'wl-tmpl-alternative-label-input', $this->get_alternative_label_input() );
408
+
409
+        // Print all the currently set alternative labels.
410
+        foreach ( $this->get_alternative_labels( $post->ID ) as $alt_label ) {
411
+
412
+            echo $this->get_alternative_label_input( $alt_label );
413
+
414
+        };
415
+
416
+        // Print the button.
417
+        Wordlift_UI_Service::print_button( 'wl-add-alternative-labels-button', __( 'Add more titles', 'wordlift' ) );
418
+
419
+    }
420
+
421
+    public function get_uri( $object_id, $type = Object_Type_Enum::POST ) {
422
+        $content_service = Wordpress_Content_Service::get_instance();
423
+        $entity_id       = $content_service->get_entity_id( new Wordpress_Content_Id( $object_id, $type ) );
424
+        $dataset_uri     = Wordlift_Configuration_Service::get_instance()->get_dataset_uri();
425
+
426
+        if ( ! isset( $entity_id ) || ( $dataset_uri && 0 !== strpos( $entity_id, $dataset_uri ) ) ) {
427
+            $rel_uri = Entity_Uri_Generator::create_uri( $type, $object_id );
428
+            try {
429
+                $content_service->set_entity_id( new Wordpress_Content_Id( $object_id, $type ), $rel_uri );
430
+                $entity_id = $content_service->get_entity_id( new Wordpress_Content_Id( $object_id, $type ) );
431
+            } catch ( Exception $e ) {
432
+                return null;
433
+            }
434
+        }
435
+
436
+        return $entity_id;
437
+    }
438
+
439
+    /**
440
+     * Get the alternative label input HTML code.
441
+     *
442
+     * @param string $value The input value.
443
+     *
444
+     * @return string The input HTML code.
445
+     * @since 3.2.0
446
+     *
447
+     */
448
+    private function get_alternative_label_input( $value = '' ) {
449
+
450
+        return sprintf( self::ALTERNATIVE_LABEL_INPUT_TEMPLATE, esc_attr( $value ), __( 'Delete', 'wordlift' ) );
451
+    }
452
+
453
+    /**
454
+     * Get the number of entity posts published in this blog.
455
+     *
456
+     * @return int The number of published entity posts.
457
+     * @since 3.6.0
458
+     *
459
+     */
460
+    public function count() {
461
+        global $wpdb;
462
+
463
+        // Try to get the count from the transient.
464
+        $count = get_transient( '_wl_entity_service__count' );
465
+        if ( false !== $count ) {
466
+            return $count;
467
+        }
468
+
469
+        // Query the count.
470
+        $count = $wpdb->get_var( $wpdb->prepare(
471
+            "SELECT COUNT( DISTINCT( tr.object_id ) )"
472
+            . " FROM {$wpdb->term_relationships} tr"
473
+            . " INNER JOIN {$wpdb->term_taxonomy} tt"
474
+            . "  ON tt.taxonomy = %s AND tt.term_taxonomy_id = tr.term_taxonomy_id"
475
+            . " INNER JOIN {$wpdb->terms} t"
476
+            . "  ON t.term_id = tt.term_id AND t.name != %s",
477
+            Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
478
+            'article'
479
+        ) );
480
+
481
+        // Store the count in cache.
482
+        set_transient( '_wl_entity_service__count', $count, 900 );
483
+
484
+        return $count;
485
+    }
486
+
487
+    /**
488
+     * Add the entity filtering criterias to the arguments for a `get_posts`
489
+     * call.
490
+     *
491
+     * @param array $args The arguments for a `get_posts` call.
492
+     *
493
+     * @return array The arguments for a `get_posts` call.
494
+     * @since 3.15.0
495
+     *
496
+     */
497
+    public static function add_criterias( $args ) {
498
+
499
+        // Build an optimal tax-query.
500
+        $tax_query = array(
501
+            'relation' => 'AND',
502
+            array(
503
+                'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
504
+                'operator' => 'EXISTS',
505
+            ),
506
+            array(
507
+                'taxonomy' => Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
508
+                'field'    => 'slug',
509
+                'terms'    => 'article',
510
+                'operator' => 'NOT IN',
511
+            ),
512
+        );
513
+
514
+        return $args + array(
515
+                'post_type' => Wordlift_Entity_Service::valid_entity_post_types(),
516
+                /*
517 517
 				 * Ensure compatibility with Polylang.
518 518
 				 *
519 519
 				 * @see https://github.com/insideout10/wordlift-plugin/issues/855.
@@ -521,102 +521,102 @@  discard block
 block discarded – undo
521 521
 				 *
522 522
 				 * @since 3.19.5
523 523
 				 */
524
-				'lang'      => '',
525
-				'tax_query' => $tax_query,
526
-			);
527
-	}
528
-
529
-	/**
530
-	 * Create a new entity.
531
-	 *
532
-	 * @param string $name The entity name.
533
-	 * @param string $type_uri The entity's type URI.
534
-	 * @param null $logo The entity logo id (or NULL if none).
535
-	 * @param string $status The post status, by default 'publish'.
536
-	 *
537
-	 * @return int|WP_Error The entity post id or a {@link WP_Error} in case the `wp_insert_post` call fails.
538
-	 * @since 3.9.0
539
-	 *
540
-	 */
541
-	public function create( $name, $type_uri, $logo = null, $status = 'publish' ) {
542
-
543
-		// Create an entity for the publisher.
544
-		$post_id = @wp_insert_post( array(
545
-			'post_type'    => self::TYPE_NAME,
546
-			'post_title'   => $name,
547
-			'post_status'  => $status,
548
-			'post_content' => '',
549
-		) );
550
-
551
-		// Return the error if any.
552
-		if ( is_wp_error( $post_id ) ) {
553
-			return $post_id;
554
-		}
555
-
556
-		// Set the entity logo.
557
-		if ( $logo && is_numeric( $logo ) ) {
558
-			set_post_thumbnail( $post_id, $logo );
559
-		}
560
-
561
-		// Set the entity type.
562
-		Wordlift_Entity_Type_Service::get_instance()->set( $post_id, $type_uri );
563
-
564
-		return $post_id;
565
-	}
566
-
567
-	/**
568
-	 * Get the entities related to the one with the specified id. By default only
569
-	 * published entities will be returned.
570
-	 *
571
-	 * @param int $id The post id.
572
-	 * @param string $post_status The target post status (default = publish).
573
-	 *
574
-	 * @return array An array of post ids.
575
-	 * @since 3.10.0
576
-	 *
577
-	 */
578
-	public function get_related_entities( $id, $post_status = 'publish' ) {
579
-
580
-		return $this->relation_service->get_objects( $id, 'ids', null, $post_status );
581
-	}
582
-
583
-	/**
584
-	 * Get the list of entities.
585
-	 *
586
-	 * @param array $params Custom parameters for WordPress' own {@link get_posts} function.
587
-	 *
588
-	 * @return array An array of entity posts.
589
-	 * @since 3.12.2
590
-	 *
591
-	 */
592
-	public function get( $params = array() ) {
593
-
594
-		// Set the defaults.
595
-		$defaults = array( 'post_type' => 'entity' );
596
-
597
-		// Merge the defaults with the provided parameters.
598
-		$args = wp_parse_args( $params, $defaults );
599
-
600
-		// Call the `get_posts` function.
601
-		return get_posts( $args );
602
-	}
603
-
604
-	/**
605
-	 * The list of post type names which can be used for entities
606
-	 *
607
-	 * Criteria is that the post type is public. The list of valid post types
608
-	 * can be overridden with a filter.
609
-	 *
610
-	 * @return array Array containing the names of the valid post types.
611
-	 * @since 3.15.0
612
-	 *
613
-	 */
614
-	static function valid_entity_post_types() {
615
-
616
-		// Ignore builtins in the call to avoid getting attachments.
617
-		$post_types = array( 'post', 'page', self::TYPE_NAME, 'product' );
618
-
619
-		return apply_filters( 'wl_valid_entity_post_types', $post_types );
620
-	}
524
+                'lang'      => '',
525
+                'tax_query' => $tax_query,
526
+            );
527
+    }
528
+
529
+    /**
530
+     * Create a new entity.
531
+     *
532
+     * @param string $name The entity name.
533
+     * @param string $type_uri The entity's type URI.
534
+     * @param null $logo The entity logo id (or NULL if none).
535
+     * @param string $status The post status, by default 'publish'.
536
+     *
537
+     * @return int|WP_Error The entity post id or a {@link WP_Error} in case the `wp_insert_post` call fails.
538
+     * @since 3.9.0
539
+     *
540
+     */
541
+    public function create( $name, $type_uri, $logo = null, $status = 'publish' ) {
542
+
543
+        // Create an entity for the publisher.
544
+        $post_id = @wp_insert_post( array(
545
+            'post_type'    => self::TYPE_NAME,
546
+            'post_title'   => $name,
547
+            'post_status'  => $status,
548
+            'post_content' => '',
549
+        ) );
550
+
551
+        // Return the error if any.
552
+        if ( is_wp_error( $post_id ) ) {
553
+            return $post_id;
554
+        }
555
+
556
+        // Set the entity logo.
557
+        if ( $logo && is_numeric( $logo ) ) {
558
+            set_post_thumbnail( $post_id, $logo );
559
+        }
560
+
561
+        // Set the entity type.
562
+        Wordlift_Entity_Type_Service::get_instance()->set( $post_id, $type_uri );
563
+
564
+        return $post_id;
565
+    }
566
+
567
+    /**
568
+     * Get the entities related to the one with the specified id. By default only
569
+     * published entities will be returned.
570
+     *
571
+     * @param int $id The post id.
572
+     * @param string $post_status The target post status (default = publish).
573
+     *
574
+     * @return array An array of post ids.
575
+     * @since 3.10.0
576
+     *
577
+     */
578
+    public function get_related_entities( $id, $post_status = 'publish' ) {
579
+
580
+        return $this->relation_service->get_objects( $id, 'ids', null, $post_status );
581
+    }
582
+
583
+    /**
584
+     * Get the list of entities.
585
+     *
586
+     * @param array $params Custom parameters for WordPress' own {@link get_posts} function.
587
+     *
588
+     * @return array An array of entity posts.
589
+     * @since 3.12.2
590
+     *
591
+     */
592
+    public function get( $params = array() ) {
593
+
594
+        // Set the defaults.
595
+        $defaults = array( 'post_type' => 'entity' );
596
+
597
+        // Merge the defaults with the provided parameters.
598
+        $args = wp_parse_args( $params, $defaults );
599
+
600
+        // Call the `get_posts` function.
601
+        return get_posts( $args );
602
+    }
603
+
604
+    /**
605
+     * The list of post type names which can be used for entities
606
+     *
607
+     * Criteria is that the post type is public. The list of valid post types
608
+     * can be overridden with a filter.
609
+     *
610
+     * @return array Array containing the names of the valid post types.
611
+     * @since 3.15.0
612
+     *
613
+     */
614
+    static function valid_entity_post_types() {
615
+
616
+        // Ignore builtins in the call to avoid getting attachments.
617
+        $post_types = array( 'post', 'page', self::TYPE_NAME, 'product' );
618
+
619
+        return apply_filters( 'wl_valid_entity_post_types', $post_types );
620
+    }
621 621
 
622 622
 }
Please login to merge, or discard this patch.
Spacing   +90 added lines, -90 removed lines patch added patch discarded remove patch
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 	 * @since 3.2.0
82 82
 	 */
83 83
 	protected function __construct() {
84
-		$this->log = Wordlift_Log_Service::get_logger( 'Wordlift_Entity_Service' );
84
+		$this->log = Wordlift_Log_Service::get_logger('Wordlift_Entity_Service');
85 85
 
86 86
 		$this->entity_uri_service = Wordlift_Entity_Uri_Service::get_instance();
87 87
 		$this->relation_service   = Wordlift_Relation_Service::get_instance();
@@ -105,7 +105,7 @@  discard block
 block discarded – undo
105 105
 	 */
106 106
 	public static function get_instance() {
107 107
 
108
-		if ( ! isset( self::$instance ) ) {
108
+		if ( ! isset(self::$instance)) {
109 109
 			self::$instance = new self();
110 110
 		}
111 111
 
@@ -122,22 +122,22 @@  discard block
 block discarded – undo
122 122
 	 * @since 3.1.0
123 123
 	 *
124 124
 	 */
125
-	public function is_entity( $post_id ) {
125
+	public function is_entity($post_id) {
126 126
 
127 127
 		// Improve performance by giving for granted that a product is an entity.
128
-		if ( 'product' === get_post_type( $post_id ) ) {
128
+		if ('product' === get_post_type($post_id)) {
129 129
 			return true;
130 130
 		}
131 131
 
132
-		$terms = wp_get_object_terms( $post_id, Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
132
+		$terms = wp_get_object_terms($post_id, Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
133 133
 
134
-		if ( is_wp_error( $terms ) ) {
135
-			$this->log->error( "Cannot get the terms for post $post_id: " . $terms->get_error_message() );
134
+		if (is_wp_error($terms)) {
135
+			$this->log->error("Cannot get the terms for post $post_id: ".$terms->get_error_message());
136 136
 
137 137
 			return false;
138 138
 		}
139 139
 
140
-		if ( empty( $terms ) ) {
140
+		if (empty($terms)) {
141 141
 			return false;
142 142
 		}
143 143
 
@@ -148,8 +148,8 @@  discard block
 block discarded – undo
148 148
 		 *
149 149
 		 * @see https://github.com/insideout10/wordlift-plugin/issues/835
150 150
 		 */
151
-		foreach ( $terms as $term ) {
152
-			if ( 1 !== preg_match( '~(^|-)article$~', $term->slug ) ) {
151
+		foreach ($terms as $term) {
152
+			if (1 !== preg_match('~(^|-)article$~', $term->slug)) {
153 153
 				return true;
154 154
 			}
155 155
 		}
@@ -169,19 +169,19 @@  discard block
 block discarded – undo
169 169
 	 * @since 3.5.0
170 170
 	 *
171 171
 	 */
172
-	public function get_classification_scope_for( $post_id, $default = WL_WHAT_RELATION ) {
172
+	public function get_classification_scope_for($post_id, $default = WL_WHAT_RELATION) {
173 173
 
174
-		if ( false === $this->is_entity( $post_id ) ) {
174
+		if (false === $this->is_entity($post_id)) {
175 175
 			return $default;
176 176
 		}
177 177
 
178 178
 		// Retrieve the entity type
179
-		$entity_type_arr = Wordlift_Entity_Type_Service::get_instance()->get( $post_id );
180
-		$entity_type     = str_replace( 'wl-', '', $entity_type_arr['css_class'] );
179
+		$entity_type_arr = Wordlift_Entity_Type_Service::get_instance()->get($post_id);
180
+		$entity_type     = str_replace('wl-', '', $entity_type_arr['css_class']);
181 181
 		// Retrieve classification boxes configuration
182
-		$classification_boxes = unserialize( WL_CORE_POST_CLASSIFICATION_BOXES );
183
-		foreach ( $classification_boxes as $cb ) {
184
-			if ( in_array( $entity_type, $cb['registeredTypes'] ) ) {
182
+		$classification_boxes = unserialize(WL_CORE_POST_CLASSIFICATION_BOXES);
183
+		foreach ($classification_boxes as $cb) {
184
+			if (in_array($entity_type, $cb['registeredTypes'])) {
185 185
 				return $cb['id'];
186 186
 			}
187 187
 		}
@@ -196,13 +196,13 @@  discard block
 block discarded – undo
196 196
 	 *
197 197
 	 * @return bool|null Null if it's not an entity, otherwise true if it's used.
198 198
 	 */
199
-	public function is_used( $post_id ) {
199
+	public function is_used($post_id) {
200 200
 
201
-		if ( false === $this->is_entity( $post_id ) ) {
201
+		if (false === $this->is_entity($post_id)) {
202 202
 			return null;
203 203
 		}
204 204
 		// Retrieve the post
205
-		$entity = get_post( $post_id );
205
+		$entity = get_post($post_id);
206 206
 
207 207
 		global $wpdb;
208 208
 		// Retrieve Wordlift relation instances table name
@@ -215,9 +215,9 @@  discard block
 block discarded – undo
215 215
 		);
216 216
 
217 217
 		// Perform the query
218
-		$relation_instances = (int) $wpdb->get_var( $stmt );
218
+		$relation_instances = (int) $wpdb->get_var($stmt);
219 219
 		// If there is at least one relation instance for the current entity, then it's used
220
-		if ( 0 < $relation_instances ) {
220
+		if (0 < $relation_instances) {
221 221
 			return true;
222 222
 		}
223 223
 
@@ -225,13 +225,13 @@  discard block
 block discarded – undo
225 225
 		$stmt = $wpdb->prepare(
226 226
 			"SELECT COUNT(*) FROM $wpdb->postmeta WHERE post_id != %d AND meta_value = %s",
227 227
 			$entity->ID,
228
-			wl_get_entity_uri( $entity->ID )
228
+			wl_get_entity_uri($entity->ID)
229 229
 		);
230 230
 		// Perform the query
231
-		$meta_instances = (int) $wpdb->get_var( $stmt );
231
+		$meta_instances = (int) $wpdb->get_var($stmt);
232 232
 
233 233
 		// If there is at least one meta that refers the current entity uri, then current entity is used
234
-		if ( 0 < $meta_instances ) {
234
+		if (0 < $meta_instances) {
235 235
 			return true;
236 236
 		}
237 237
 
@@ -251,9 +251,9 @@  discard block
 block discarded – undo
251 251
 	 * @since      3.2.0
252 252
 	 *
253 253
 	 */
254
-	public function get_entity_post_by_uri( $uri ) {
254
+	public function get_entity_post_by_uri($uri) {
255 255
 
256
-		return $this->entity_uri_service->get_entity( $uri );
256
+		return $this->entity_uri_service->get_entity($uri);
257 257
 	}
258 258
 
259 259
 	/**
@@ -268,10 +268,10 @@  discard block
 block discarded – undo
268 268
 	 * @param WP_Post $post Post object.
269 269
 	 * @param bool $update Whether this is an existing post being updated or not.
270 270
 	 */
271
-	public function save_post( $post_id, $post, $update ) {
271
+	public function save_post($post_id, $post, $update) {
272 272
 
273 273
 		// Avoid doing anything if post is autosave or a revision.
274
-		if ( wp_is_post_autosave( $post ) || wp_is_post_revision( $post ) ) {
274
+		if (wp_is_post_autosave($post) || wp_is_post_revision($post)) {
275 275
 			return;
276 276
 		}
277 277
 
@@ -281,16 +281,16 @@  discard block
 block discarded – undo
281 281
 		// the $post_id in the save_post call matches the post id set in the request.
282 282
 		//
283 283
 		// If this is not the current post being saved or if it's not an entity, return.
284
-		if ( ! isset( $_REQUEST['post_ID'] ) || $_REQUEST['post_ID'] != $post_id || ! $this->is_entity( $post_id ) ) {
284
+		if ( ! isset($_REQUEST['post_ID']) || $_REQUEST['post_ID'] != $post_id || ! $this->is_entity($post_id)) {
285 285
 			return;
286 286
 		}
287 287
 
288 288
 		// Get the alt labels from the request (or empty array).
289
-		$alt_labels = isset( $_REQUEST['wl_alternative_label'] ) ? (array) $_REQUEST['wl_alternative_label'] : array();
289
+		$alt_labels = isset($_REQUEST['wl_alternative_label']) ? (array) $_REQUEST['wl_alternative_label'] : array();
290 290
 
291
-		if ( ( ! empty( $_POST['content'] ) && ! empty( $_POST['post_content'] ) ) || isset( $_REQUEST['wl_alternative_label'] ) ) {
291
+		if (( ! empty($_POST['content']) && ! empty($_POST['post_content'])) || isset($_REQUEST['wl_alternative_label'])) {
292 292
 			// This is via classic editor, so set the alternative labels.
293
-			$this->set_alternative_labels( $post_id, $alt_labels );
293
+			$this->set_alternative_labels($post_id, $alt_labels);
294 294
 		}
295 295
 
296 296
 
@@ -305,49 +305,49 @@  discard block
 block discarded – undo
305 305
 	 * @since 3.2.0
306 306
 	 *
307 307
 	 */
308
-	public function set_alternative_labels( $post_id, $alt_labels ) {
308
+	public function set_alternative_labels($post_id, $alt_labels) {
309 309
 
310 310
 		// Bail out if post id is not numeric. We add this check as we found a WP install that was sending a WP_Error
311 311
 		// instead of post id.
312
-		if ( ! is_numeric( $post_id ) ) {
312
+		if ( ! is_numeric($post_id)) {
313 313
 			return;
314 314
 		}
315 315
 
316 316
 		// Force $alt_labels to be an array
317
-		if ( ! is_array( $alt_labels ) ) {
318
-			$alt_labels = array( $alt_labels );
317
+		if ( ! is_array($alt_labels)) {
318
+			$alt_labels = array($alt_labels);
319 319
 		}
320 320
 
321
-		$this->log->debug( "Setting alternative labels [ post id :: $post_id ][ alt labels :: " . implode( ',', $alt_labels ) . " ]" );
321
+		$this->log->debug("Setting alternative labels [ post id :: $post_id ][ alt labels :: ".implode(',', $alt_labels)." ]");
322 322
 
323 323
 		// Delete all the existing alternate labels.
324
-		delete_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
324
+		delete_post_meta($post_id, self::ALTERNATIVE_LABEL_META_KEY);
325 325
 
326 326
 		// Save only unique synonymns.
327
-		$alt_labels = array_unique( $alt_labels );
327
+		$alt_labels = array_unique($alt_labels);
328 328
 
329 329
 		// Set the alternative labels.
330
-		foreach ( $alt_labels as $alt_label ) {
330
+		foreach ($alt_labels as $alt_label) {
331 331
 
332 332
 			// Strip html code from synonym.
333
-			$alt_label = wp_strip_all_tags( $alt_label );
333
+			$alt_label = wp_strip_all_tags($alt_label);
334 334
 
335
-			if ( ! empty( $alt_label ) ) {
336
-				add_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY, (string) $alt_label );
335
+			if ( ! empty($alt_label)) {
336
+				add_post_meta($post_id, self::ALTERNATIVE_LABEL_META_KEY, (string) $alt_label);
337 337
 			}
338 338
 		}
339 339
 
340 340
 	}
341 341
 
342
-	public function append_alternative_labels( $post_id, $labels_to_append ) {
342
+	public function append_alternative_labels($post_id, $labels_to_append) {
343 343
 
344 344
 
345
-		$merged_labels = $this->get_alternative_labels( $post_id );
345
+		$merged_labels = $this->get_alternative_labels($post_id);
346 346
 		
347 347
 		// Append new synonyms to the end.
348
-		$merged_labels = array_merge( $merged_labels, $labels_to_append );
348
+		$merged_labels = array_merge($merged_labels, $labels_to_append);
349 349
 
350
-		$this->set_alternative_labels( $post_id, $merged_labels );
350
+		$this->set_alternative_labels($post_id, $merged_labels);
351 351
 
352 352
 	}
353 353
 
@@ -360,9 +360,9 @@  discard block
 block discarded – undo
360 360
 	 * @since 3.2.0
361 361
 	 *
362 362
 	 */
363
-	public function get_alternative_labels( $post_id ) {
363
+	public function get_alternative_labels($post_id) {
364 364
 
365
-		return get_post_meta( $post_id, self::ALTERNATIVE_LABEL_META_KEY );
365
+		return get_post_meta($post_id, self::ALTERNATIVE_LABEL_META_KEY);
366 366
 	}
367 367
 
368 368
 	/**
@@ -374,9 +374,9 @@  discard block
 block discarded – undo
374 374
 	 * @return array An array with the entity title and labels.
375 375
 	 * @since 3.12.0
376 376
 	 */
377
-	public function get_labels( $post_id, $object_type = Object_Type_Enum::POST ) {
378
-		if ( $object_type === Object_Type_Enum::POST ) {
379
-			return array_merge( (array) get_the_title( $post_id ), $this->get_alternative_labels( $post_id ) );
377
+	public function get_labels($post_id, $object_type = Object_Type_Enum::POST) {
378
+		if ($object_type === Object_Type_Enum::POST) {
379
+			return array_merge((array) get_the_title($post_id), $this->get_alternative_labels($post_id));
380 380
 		}
381 381
 
382 382
 		// Term Reference dont have synonyms yet.
@@ -391,44 +391,44 @@  discard block
 block discarded – undo
391 391
 	 * @since 3.2.0
392 392
 	 *
393 393
 	 */
394
-	public function edit_form_before_permalink( $post ) {
394
+	public function edit_form_before_permalink($post) {
395 395
 
396 396
 		// If it's not an entity, return.
397
-		if ( ! $this->is_entity( $post->ID ) ) {
397
+		if ( ! $this->is_entity($post->ID)) {
398 398
 			return;
399 399
 		}
400 400
 
401 401
 		// If disabled by filter, return.
402
-		if ( ! apply_filters( 'wl_feature__enable__add-synonyms', true ) ) {
402
+		if ( ! apply_filters('wl_feature__enable__add-synonyms', true)) {
403 403
 			return;
404 404
 		}
405 405
 
406 406
 		// Print the input template.
407
-		Wordlift_UI_Service::print_template( 'wl-tmpl-alternative-label-input', $this->get_alternative_label_input() );
407
+		Wordlift_UI_Service::print_template('wl-tmpl-alternative-label-input', $this->get_alternative_label_input());
408 408
 
409 409
 		// Print all the currently set alternative labels.
410
-		foreach ( $this->get_alternative_labels( $post->ID ) as $alt_label ) {
410
+		foreach ($this->get_alternative_labels($post->ID) as $alt_label) {
411 411
 
412
-			echo $this->get_alternative_label_input( $alt_label );
412
+			echo $this->get_alternative_label_input($alt_label);
413 413
 
414 414
 		};
415 415
 
416 416
 		// Print the button.
417
-		Wordlift_UI_Service::print_button( 'wl-add-alternative-labels-button', __( 'Add more titles', 'wordlift' ) );
417
+		Wordlift_UI_Service::print_button('wl-add-alternative-labels-button', __('Add more titles', 'wordlift'));
418 418
 
419 419
 	}
420 420
 
421
-	public function get_uri( $object_id, $type = Object_Type_Enum::POST ) {
421
+	public function get_uri($object_id, $type = Object_Type_Enum::POST) {
422 422
 		$content_service = Wordpress_Content_Service::get_instance();
423
-		$entity_id       = $content_service->get_entity_id( new Wordpress_Content_Id( $object_id, $type ) );
423
+		$entity_id       = $content_service->get_entity_id(new Wordpress_Content_Id($object_id, $type));
424 424
 		$dataset_uri     = Wordlift_Configuration_Service::get_instance()->get_dataset_uri();
425 425
 
426
-		if ( ! isset( $entity_id ) || ( $dataset_uri && 0 !== strpos( $entity_id, $dataset_uri ) ) ) {
427
-			$rel_uri = Entity_Uri_Generator::create_uri( $type, $object_id );
426
+		if ( ! isset($entity_id) || ($dataset_uri && 0 !== strpos($entity_id, $dataset_uri))) {
427
+			$rel_uri = Entity_Uri_Generator::create_uri($type, $object_id);
428 428
 			try {
429
-				$content_service->set_entity_id( new Wordpress_Content_Id( $object_id, $type ), $rel_uri );
430
-				$entity_id = $content_service->get_entity_id( new Wordpress_Content_Id( $object_id, $type ) );
431
-			} catch ( Exception $e ) {
429
+				$content_service->set_entity_id(new Wordpress_Content_Id($object_id, $type), $rel_uri);
430
+				$entity_id = $content_service->get_entity_id(new Wordpress_Content_Id($object_id, $type));
431
+			} catch (Exception $e) {
432 432
 				return null;
433 433
 			}
434 434
 		}
@@ -445,9 +445,9 @@  discard block
 block discarded – undo
445 445
 	 * @since 3.2.0
446 446
 	 *
447 447
 	 */
448
-	private function get_alternative_label_input( $value = '' ) {
448
+	private function get_alternative_label_input($value = '') {
449 449
 
450
-		return sprintf( self::ALTERNATIVE_LABEL_INPUT_TEMPLATE, esc_attr( $value ), __( 'Delete', 'wordlift' ) );
450
+		return sprintf(self::ALTERNATIVE_LABEL_INPUT_TEMPLATE, esc_attr($value), __('Delete', 'wordlift'));
451 451
 	}
452 452
 
453 453
 	/**
@@ -461,13 +461,13 @@  discard block
 block discarded – undo
461 461
 		global $wpdb;
462 462
 
463 463
 		// Try to get the count from the transient.
464
-		$count = get_transient( '_wl_entity_service__count' );
465
-		if ( false !== $count ) {
464
+		$count = get_transient('_wl_entity_service__count');
465
+		if (false !== $count) {
466 466
 			return $count;
467 467
 		}
468 468
 
469 469
 		// Query the count.
470
-		$count = $wpdb->get_var( $wpdb->prepare(
470
+		$count = $wpdb->get_var($wpdb->prepare(
471 471
 			"SELECT COUNT( DISTINCT( tr.object_id ) )"
472 472
 			. " FROM {$wpdb->term_relationships} tr"
473 473
 			. " INNER JOIN {$wpdb->term_taxonomy} tt"
@@ -476,10 +476,10 @@  discard block
 block discarded – undo
476 476
 			. "  ON t.term_id = tt.term_id AND t.name != %s",
477 477
 			Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME,
478 478
 			'article'
479
-		) );
479
+		));
480 480
 
481 481
 		// Store the count in cache.
482
-		set_transient( '_wl_entity_service__count', $count, 900 );
482
+		set_transient('_wl_entity_service__count', $count, 900);
483 483
 
484 484
 		return $count;
485 485
 	}
@@ -494,7 +494,7 @@  discard block
 block discarded – undo
494 494
 	 * @since 3.15.0
495 495
 	 *
496 496
 	 */
497
-	public static function add_criterias( $args ) {
497
+	public static function add_criterias($args) {
498 498
 
499 499
 		// Build an optimal tax-query.
500 500
 		$tax_query = array(
@@ -538,28 +538,28 @@  discard block
 block discarded – undo
538 538
 	 * @since 3.9.0
539 539
 	 *
540 540
 	 */
541
-	public function create( $name, $type_uri, $logo = null, $status = 'publish' ) {
541
+	public function create($name, $type_uri, $logo = null, $status = 'publish') {
542 542
 
543 543
 		// Create an entity for the publisher.
544
-		$post_id = @wp_insert_post( array(
544
+		$post_id = @wp_insert_post(array(
545 545
 			'post_type'    => self::TYPE_NAME,
546 546
 			'post_title'   => $name,
547 547
 			'post_status'  => $status,
548 548
 			'post_content' => '',
549
-		) );
549
+		));
550 550
 
551 551
 		// Return the error if any.
552
-		if ( is_wp_error( $post_id ) ) {
552
+		if (is_wp_error($post_id)) {
553 553
 			return $post_id;
554 554
 		}
555 555
 
556 556
 		// Set the entity logo.
557
-		if ( $logo && is_numeric( $logo ) ) {
558
-			set_post_thumbnail( $post_id, $logo );
557
+		if ($logo && is_numeric($logo)) {
558
+			set_post_thumbnail($post_id, $logo);
559 559
 		}
560 560
 
561 561
 		// Set the entity type.
562
-		Wordlift_Entity_Type_Service::get_instance()->set( $post_id, $type_uri );
562
+		Wordlift_Entity_Type_Service::get_instance()->set($post_id, $type_uri);
563 563
 
564 564
 		return $post_id;
565 565
 	}
@@ -575,9 +575,9 @@  discard block
 block discarded – undo
575 575
 	 * @since 3.10.0
576 576
 	 *
577 577
 	 */
578
-	public function get_related_entities( $id, $post_status = 'publish' ) {
578
+	public function get_related_entities($id, $post_status = 'publish') {
579 579
 
580
-		return $this->relation_service->get_objects( $id, 'ids', null, $post_status );
580
+		return $this->relation_service->get_objects($id, 'ids', null, $post_status);
581 581
 	}
582 582
 
583 583
 	/**
@@ -589,16 +589,16 @@  discard block
 block discarded – undo
589 589
 	 * @since 3.12.2
590 590
 	 *
591 591
 	 */
592
-	public function get( $params = array() ) {
592
+	public function get($params = array()) {
593 593
 
594 594
 		// Set the defaults.
595
-		$defaults = array( 'post_type' => 'entity' );
595
+		$defaults = array('post_type' => 'entity');
596 596
 
597 597
 		// Merge the defaults with the provided parameters.
598
-		$args = wp_parse_args( $params, $defaults );
598
+		$args = wp_parse_args($params, $defaults);
599 599
 
600 600
 		// Call the `get_posts` function.
601
-		return get_posts( $args );
601
+		return get_posts($args);
602 602
 	}
603 603
 
604 604
 	/**
@@ -614,9 +614,9 @@  discard block
 block discarded – undo
614 614
 	static function valid_entity_post_types() {
615 615
 
616 616
 		// Ignore builtins in the call to avoid getting attachments.
617
-		$post_types = array( 'post', 'page', self::TYPE_NAME, 'product' );
617
+		$post_types = array('post', 'page', self::TYPE_NAME, 'product');
618 618
 
619
-		return apply_filters( 'wl_valid_entity_post_types', $post_types );
619
+		return apply_filters('wl_valid_entity_post_types', $post_types);
620 620
 	}
621 621
 
622 622
 }
Please login to merge, or discard this patch.