Completed
Pull Request — master (#1489)
by Naveen
57s
created
src/wordlift/post/class-post-adapter.php 2 patches
Indentation   +374 added lines, -374 removed lines patch added patch discarded remove patch
@@ -18,379 +18,379 @@
 block discarded – undo
18 18
 
19 19
 class Post_Adapter {
20 20
 
21
-	/**
22
-	 * A {@link Wordlift_Log_Service} logging instance.
23
-	 *
24
-	 * @access private
25
-	 * @var \Wordlift_Log_Service A {@link Wordlift_Log_Service} logging instance.
26
-	 */
27
-	private $log;
28
-
29
-	/**
30
-	 * A {@link Wordlift_Entity_Service} instance.
31
-	 *
32
-	 * @access private
33
-	 * @var \Wordlift_Entity_Service A {@link Wordlift_Entity_Service} instance.
34
-	 */
35
-	private $entity_service;
36
-
37
-	/**
38
-	 * A {@link Entity_Store} instance.
39
-	 *
40
-	 * @access private
41
-	 * @var Entity_Store $entity_store A {@link Entity_Store} instance.
42
-	 */
43
-	private $entity_store;
44
-	/**
45
-	 * @var \Wordlift_Entity_Uri_Service
46
-	 */
47
-	private $entity_uri_service;
48
-
49
-	public function __construct() {
50
-
51
-		// Bail out if block editor's functions aren't available.
52
-		if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
53
-			return;
54
-		}
55
-
56
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
57
-
58
-		$this->entity_service     = \Wordlift_Entity_Service::get_instance();
59
-		$this->entity_store       = Entity_Store::get_instance();
60
-		$this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
61
-		add_action( 'init', array( $this, 'init' ) );
62
-		add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
63
-
64
-	}
65
-
66
-	/**
67
-	 * Initialize by registering our block type `wordlift/classification`, required for {@link parse_blocks) to work
68
-	 * correctly.
69
-	 */
70
-	public function init() {
71
-
72
-		register_block_type( 'wordlift/classification', array(
73
-			'editor_script' => 'wl-block-editor',
74
-			'attributes'    => array(
75
-				'entities' => array( 'type' => 'array' ),
76
-			),
77
-		) );
78
-
79
-	}
80
-
81
-	/**
82
-	 * A sample structure:
83
-	 *
84
-	 * {
85
-	 *   "entities": [
86
-	 *     {
87
-	 *       "annotations": {
88
-	 *         "urn:enhancement-7e8e66fc": {
89
-	 *           "start": 3480,
90
-	 *           "end": 3486,
91
-	 *           "text": "libero"
92
-	 *         }
93
-	 *       },
94
-	 *       "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.",
95
-	 *       "id": "http://fr.dbpedia.org/resource/Libero_(volley-ball)",
96
-	 *       "label": "Libero (volley-ball)",
97
-	 *       "mainType": "other",
98
-	 *       "occurrences": ["urn:enhancement-7e8e66fc"],
99
-	 *       "sameAs": null,
100
-	 *       "synonyms": [],
101
-	 *       "types": ["other"]
102
-	 *     }
103
-	 *   ]
104
-	 * }
105
-	 *
106
-	 * @param array $data An array of slashed post data.
107
-	 * @param array $postarr An array of sanitized, but otherwise unmodified post data.
108
-	 *
109
-	 * @return array The data array.
110
-	 * @throws \Exception
111
-	 */
112
-	public function wp_insert_post_data( $data, $postarr ) {
113
-
114
-		$post_status = $data['post_status'];
115
-		if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
116
-			return $data;
117
-		}
118
-
119
-		$this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
120
-		                   . var_export( $data, true ) );
121
-
122
-
123
-		try {
124
-			$entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
125
-
126
-			foreach ( $entities as $entity ) {
127
-
128
-				$entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
129
-
130
-				if ( ! $this->entity_id_valid( $entity_id ) ) {
131
-					continue;
132
-				}
133
-
134
-				$entity_uris = $this->get_entity_uris( $entity );
135
-
136
-				if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
137
-				     Post_Entities_Validator::is_local_entity_uri_exist( $this->entity_uri_service, $entity_uris ) ) {
138
-					// Skip the entity
139
-					continue;
140
-				}
141
-				$this->create_or_update_entity( $entity, $data['post_status'] );
142
-
143
-			}
144
-
145
-		} catch ( \Exception $e ) {
146
-			$this->log->error( $e->getMessage() );
147
-		}
148
-
149
-
150
-		return $data;
151
-	}
152
-
153
-	/**
154
-	 * Parse the post content to find the `wordlift/classification` block and return the entities' data.
155
-	 *
156
-	 * @param string $post_content The post content.
157
-	 *
158
-	 * @return array An array of entities' structures.
159
-	 * @throws \Exception
160
-	 */
161
-	private function parse_content( $post_content ) {
162
-
163
-		$all_blocks = parse_blocks( $post_content );
164
-		$this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
165
-		                   . var_export( $all_blocks, true ) );
166
-
167
-		$blocks = array_filter( $all_blocks, function ( $item ) {
168
-			return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
169
-		} );
170
-
171
-		// Bail out if the blocks' array is empty.
172
-		if ( empty( $blocks ) ) {
173
-			return array();
174
-		}
175
-
176
-		$block = current( $blocks );
177
-		$this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
178
-		                   . var_export( $block, true ) );
179
-
180
-		// Bail out if the entities array is empty.
181
-		if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
182
-			return array();
183
-		}
184
-
185
-		return $block['attrs']['entities'];
186
-	}
187
-
188
-	/**
189
-	 * Collect entity labels from the entity array.
190
-	 *
191
-	 * This function expects an array with the following keys:
192
-	 *
193
-	 * array(
194
-	 *   'label'       => ...,
195
-	 *   'synonyms'    => array( ... ),
196
-	 *   'annotations' => array(
197
-	 *     ...id...      => array( text => ... ),
198
-	 *   ),
199
-	 *   'occurrences' => array( ... ),
200
-	 * )
201
-	 *
202
-	 * and it is going to output an array with all the labels, keeping the `label` at first position:
203
-	 *
204
-	 * array(
205
-	 *   ...label...,
206
-	 *   ...synonyms...,
207
-	 *   ...texts...,
208
-	 * )
209
-	 *
210
-	 * This function is going to collect the label from the `label` property, from the `synonyms` property and from
211
-	 * `annotations` property. Since the `annotations` property contains all the annotations including those that
212
-	 * haven't been selected, this function is going to only get the `text` for the annotations property listed in
213
-	 * `occurrences`.
214
-	 *
215
-	 * @param array $entity {
216
-	 *  The entity data.
217
-	 *
218
-	 * @type string $label The entity label.
219
-	 * @type array $synonyms The entity synonyms.
220
-	 * @type array $occurrences The selected occurrences.
221
-	 * @type array $annotations The annotations.
222
-	 * }
223
-	 *
224
-	 * @return array An array of labels.
225
-	 */
226
-	public function get_labels( $entity ) {
227
-
228
-		$args = wp_parse_args( $entity, array(
229
-			'label'       => array(),
230
-			'synonyms'    => array(),
231
-			'annotations' => array(),
232
-			'occurrences' => array(),
233
-		) );
234
-
235
-		// We gather all the labels, occurrences texts and synonyms into one array.
236
-		$initial = array_merge(
237
-			(array) $args['label'],
238
-			(array) $args['synonyms']
239
-		);
240
-
241
-		$annotations = $args['annotations'];
242
-
243
-		return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
244
-
245
-			// Bail out if occurrences->$item->text isn't set or its contents are already
246
-			// in `$carry`.
247
-			if ( ! isset( $annotations[ $item ]['text'] )
248
-			     || in_array( $annotations[ $item ]['text'], $carry ) ) {
249
-				return $carry;
250
-			}
251
-
252
-			// Push the label.
253
-			$carry[] = $annotations[ $item ]['text'];
254
-
255
-			return $carry;
256
-		}, $initial );
257
-	}
258
-
259
-	/**
260
-	 * Create or update the entity.
261
-	 *
262
-	 * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
263
-	 * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
264
-	 *
265
-	 * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
266
-	 *
267
-	 * @param array $entity {
268
-	 * The entity parameters.
269
-	 *
270
-	 * @type string The entity item id URI.
271
-	 * @type string|array The entity sameAs URI(s).
272
-	 * @type string $description The entity description.
273
-	 * }
274
-	 *
275
-	 * @param       $string $post_status The post status, default 'draft'.
276
-	 *
277
-	 * @return int|\WP_Error
278
-	 * @throws \Exception
279
-	 */
280
-	private function create_or_update_entity( $entity, $post_status = 'draft' ) {
281
-
282
-		// Get only valid IDs.
283
-		$uris = $this->get_entity_uris( $entity );
284
-
285
-		$post = $this->get_first_matching_entity_by_uri( $uris );
286
-
287
-		$this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
288
-		                   . var_export( $uris, true ) );
289
-
290
-		// Get the labels.
291
-		$labels = $this->get_labels( $entity );
292
-
293
-		if ( empty( $post ) ) {
294
-			// Create the entity if it doesn't exist.
295
-			$post_id = $this->entity_store->create( array(
296
-				'labels'      => $labels,
297
-				'description' => $entity['description'],
298
-				'same_as'     => $uris,
299
-			), $post_status );
300
-
301
-			// Return the WP_Error if we got one.
302
-			if ( is_wp_error( $post_id ) ) {
303
-				return $post_id;
304
-			}
305
-
306
-			// Add the entity type.
307
-			if ( isset( $entity['mainType'] ) ) {
308
-				wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
309
-			}
310
-
311
-			if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
312
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
313
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
314
-			}
315
-		} else {
316
-			// Update the entity otherwise.
317
-			$post_id = $this->entity_store->update( array(
318
-				'ID'      => $post->ID,
319
-				'labels'  => $labels,
320
-				'same_as' => $uris,
321
-			) );
322
-
323
-			// Add the entity type.
324
-			if ( isset( $entity['mainType'] ) ) {
325
-				wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
326
-			}
327
-
328
-			// see https://github.com/insideout10/wordlift-plugin/issues/1304
329
-			// Set the post status, we need to set that in order to support entities
330
-			// created using rest endpoint on block editor, so that they get published
331
-			// when the post is published.
332
-			// Once the entity is published dont update the post status.
333
-			if ( $post->post_status !== 'publish' ) {
334
-				wp_update_post( array(
335
-					'ID'          => $post->ID,
336
-					'post_status' => $post_status
337
-				) );
338
-			}
339
-		}
340
-
341
-		return $post_id;
342
-	}
343
-
344
-	/**
345
-	 * Get the first matching entity for the provided URI array.
346
-	 *
347
-	 * Entities IDs and sameAs are searched.
348
-	 *
349
-	 * @param array $uris An array of URIs.
350
-	 *
351
-	 * @return \WP_Post|null The entity WP_Post if found or null if not found.
352
-	 */
353
-	private function get_first_matching_entity_by_uri( $uris ) {
354
-
355
-		foreach ( $uris as $uri ) {
356
-			$existing_entity = $this->entity_service->get_entity_post_by_uri( $uri );
357
-			if ( isset( $existing_entity ) ) {
358
-				return $existing_entity;
359
-			}
360
-		}
361
-
362
-		return null;
363
-	}
364
-
365
-	/**
366
-	 * @param $entity
367
-	 *
368
-	 * @return array
369
-	 */
370
-	private function filter_valid_entity_ids( $entity ) {
371
-		$id = $entity['id'];
372
-
373
-		return array_filter( (array) $id, function ( $id ) {
374
-			return preg_match( '|^https?://|', $id );
375
-		} );
376
-	}
377
-
378
-	/**
379
-	 * @param array $entity
380
-	 *
381
-	 * @return array
382
-	 */
383
-	private function get_entity_uris( $entity ) {
384
-		$ids = $this->filter_valid_entity_ids( $entity );
385
-
386
-		return array_merge(
387
-			(array) $ids,
388
-			(array) $entity['sameAs']
389
-		);
390
-	}
391
-
392
-	private function entity_id_valid( $entity_id ) {
393
-		return preg_match( '#^https?://#i', $entity_id ) === 1;
394
-	}
21
+    /**
22
+     * A {@link Wordlift_Log_Service} logging instance.
23
+     *
24
+     * @access private
25
+     * @var \Wordlift_Log_Service A {@link Wordlift_Log_Service} logging instance.
26
+     */
27
+    private $log;
28
+
29
+    /**
30
+     * A {@link Wordlift_Entity_Service} instance.
31
+     *
32
+     * @access private
33
+     * @var \Wordlift_Entity_Service A {@link Wordlift_Entity_Service} instance.
34
+     */
35
+    private $entity_service;
36
+
37
+    /**
38
+     * A {@link Entity_Store} instance.
39
+     *
40
+     * @access private
41
+     * @var Entity_Store $entity_store A {@link Entity_Store} instance.
42
+     */
43
+    private $entity_store;
44
+    /**
45
+     * @var \Wordlift_Entity_Uri_Service
46
+     */
47
+    private $entity_uri_service;
48
+
49
+    public function __construct() {
50
+
51
+        // Bail out if block editor's functions aren't available.
52
+        if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
53
+            return;
54
+        }
55
+
56
+        $this->log = \Wordlift_Log_Service::get_logger( get_class() );
57
+
58
+        $this->entity_service     = \Wordlift_Entity_Service::get_instance();
59
+        $this->entity_store       = Entity_Store::get_instance();
60
+        $this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
61
+        add_action( 'init', array( $this, 'init' ) );
62
+        add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
63
+
64
+    }
65
+
66
+    /**
67
+     * Initialize by registering our block type `wordlift/classification`, required for {@link parse_blocks) to work
68
+     * correctly.
69
+     */
70
+    public function init() {
71
+
72
+        register_block_type( 'wordlift/classification', array(
73
+            'editor_script' => 'wl-block-editor',
74
+            'attributes'    => array(
75
+                'entities' => array( 'type' => 'array' ),
76
+            ),
77
+        ) );
78
+
79
+    }
80
+
81
+    /**
82
+     * A sample structure:
83
+     *
84
+     * {
85
+     *   "entities": [
86
+     *     {
87
+     *       "annotations": {
88
+     *         "urn:enhancement-7e8e66fc": {
89
+     *           "start": 3480,
90
+     *           "end": 3486,
91
+     *           "text": "libero"
92
+     *         }
93
+     *       },
94
+     *       "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.",
95
+     *       "id": "http://fr.dbpedia.org/resource/Libero_(volley-ball)",
96
+     *       "label": "Libero (volley-ball)",
97
+     *       "mainType": "other",
98
+     *       "occurrences": ["urn:enhancement-7e8e66fc"],
99
+     *       "sameAs": null,
100
+     *       "synonyms": [],
101
+     *       "types": ["other"]
102
+     *     }
103
+     *   ]
104
+     * }
105
+     *
106
+     * @param array $data An array of slashed post data.
107
+     * @param array $postarr An array of sanitized, but otherwise unmodified post data.
108
+     *
109
+     * @return array The data array.
110
+     * @throws \Exception
111
+     */
112
+    public function wp_insert_post_data( $data, $postarr ) {
113
+
114
+        $post_status = $data['post_status'];
115
+        if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
116
+            return $data;
117
+        }
118
+
119
+        $this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
120
+                            . var_export( $data, true ) );
121
+
122
+
123
+        try {
124
+            $entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
125
+
126
+            foreach ( $entities as $entity ) {
127
+
128
+                $entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
129
+
130
+                if ( ! $this->entity_id_valid( $entity_id ) ) {
131
+                    continue;
132
+                }
133
+
134
+                $entity_uris = $this->get_entity_uris( $entity );
135
+
136
+                if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
137
+                     Post_Entities_Validator::is_local_entity_uri_exist( $this->entity_uri_service, $entity_uris ) ) {
138
+                    // Skip the entity
139
+                    continue;
140
+                }
141
+                $this->create_or_update_entity( $entity, $data['post_status'] );
142
+
143
+            }
144
+
145
+        } catch ( \Exception $e ) {
146
+            $this->log->error( $e->getMessage() );
147
+        }
148
+
149
+
150
+        return $data;
151
+    }
152
+
153
+    /**
154
+     * Parse the post content to find the `wordlift/classification` block and return the entities' data.
155
+     *
156
+     * @param string $post_content The post content.
157
+     *
158
+     * @return array An array of entities' structures.
159
+     * @throws \Exception
160
+     */
161
+    private function parse_content( $post_content ) {
162
+
163
+        $all_blocks = parse_blocks( $post_content );
164
+        $this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
165
+                            . var_export( $all_blocks, true ) );
166
+
167
+        $blocks = array_filter( $all_blocks, function ( $item ) {
168
+            return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
169
+        } );
170
+
171
+        // Bail out if the blocks' array is empty.
172
+        if ( empty( $blocks ) ) {
173
+            return array();
174
+        }
175
+
176
+        $block = current( $blocks );
177
+        $this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
178
+                            . var_export( $block, true ) );
179
+
180
+        // Bail out if the entities array is empty.
181
+        if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
182
+            return array();
183
+        }
184
+
185
+        return $block['attrs']['entities'];
186
+    }
187
+
188
+    /**
189
+     * Collect entity labels from the entity array.
190
+     *
191
+     * This function expects an array with the following keys:
192
+     *
193
+     * array(
194
+     *   'label'       => ...,
195
+     *   'synonyms'    => array( ... ),
196
+     *   'annotations' => array(
197
+     *     ...id...      => array( text => ... ),
198
+     *   ),
199
+     *   'occurrences' => array( ... ),
200
+     * )
201
+     *
202
+     * and it is going to output an array with all the labels, keeping the `label` at first position:
203
+     *
204
+     * array(
205
+     *   ...label...,
206
+     *   ...synonyms...,
207
+     *   ...texts...,
208
+     * )
209
+     *
210
+     * This function is going to collect the label from the `label` property, from the `synonyms` property and from
211
+     * `annotations` property. Since the `annotations` property contains all the annotations including those that
212
+     * haven't been selected, this function is going to only get the `text` for the annotations property listed in
213
+     * `occurrences`.
214
+     *
215
+     * @param array $entity {
216
+     *  The entity data.
217
+     *
218
+     * @type string $label The entity label.
219
+     * @type array $synonyms The entity synonyms.
220
+     * @type array $occurrences The selected occurrences.
221
+     * @type array $annotations The annotations.
222
+     * }
223
+     *
224
+     * @return array An array of labels.
225
+     */
226
+    public function get_labels( $entity ) {
227
+
228
+        $args = wp_parse_args( $entity, array(
229
+            'label'       => array(),
230
+            'synonyms'    => array(),
231
+            'annotations' => array(),
232
+            'occurrences' => array(),
233
+        ) );
234
+
235
+        // We gather all the labels, occurrences texts and synonyms into one array.
236
+        $initial = array_merge(
237
+            (array) $args['label'],
238
+            (array) $args['synonyms']
239
+        );
240
+
241
+        $annotations = $args['annotations'];
242
+
243
+        return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
244
+
245
+            // Bail out if occurrences->$item->text isn't set or its contents are already
246
+            // in `$carry`.
247
+            if ( ! isset( $annotations[ $item ]['text'] )
248
+                 || in_array( $annotations[ $item ]['text'], $carry ) ) {
249
+                return $carry;
250
+            }
251
+
252
+            // Push the label.
253
+            $carry[] = $annotations[ $item ]['text'];
254
+
255
+            return $carry;
256
+        }, $initial );
257
+    }
258
+
259
+    /**
260
+     * Create or update the entity.
261
+     *
262
+     * An entity lookup is performed on the local vocabulary using the `id` and `sameAs` URIs. If an entity is found
263
+     * the {@link Entity_Store} update function is called to update the `labels` and the `sameAs` values.
264
+     *
265
+     * If an entity is not found the {@link Entity_Store} create function is called to create a new entity.
266
+     *
267
+     * @param array $entity {
268
+     * The entity parameters.
269
+     *
270
+     * @type string The entity item id URI.
271
+     * @type string|array The entity sameAs URI(s).
272
+     * @type string $description The entity description.
273
+     * }
274
+     *
275
+     * @param       $string $post_status The post status, default 'draft'.
276
+     *
277
+     * @return int|\WP_Error
278
+     * @throws \Exception
279
+     */
280
+    private function create_or_update_entity( $entity, $post_status = 'draft' ) {
281
+
282
+        // Get only valid IDs.
283
+        $uris = $this->get_entity_uris( $entity );
284
+
285
+        $post = $this->get_first_matching_entity_by_uri( $uris );
286
+
287
+        $this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
288
+                            . var_export( $uris, true ) );
289
+
290
+        // Get the labels.
291
+        $labels = $this->get_labels( $entity );
292
+
293
+        if ( empty( $post ) ) {
294
+            // Create the entity if it doesn't exist.
295
+            $post_id = $this->entity_store->create( array(
296
+                'labels'      => $labels,
297
+                'description' => $entity['description'],
298
+                'same_as'     => $uris,
299
+            ), $post_status );
300
+
301
+            // Return the WP_Error if we got one.
302
+            if ( is_wp_error( $post_id ) ) {
303
+                return $post_id;
304
+            }
305
+
306
+            // Add the entity type.
307
+            if ( isset( $entity['mainType'] ) ) {
308
+                wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
309
+            }
310
+
311
+            if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
312
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
313
+                add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
314
+            }
315
+        } else {
316
+            // Update the entity otherwise.
317
+            $post_id = $this->entity_store->update( array(
318
+                'ID'      => $post->ID,
319
+                'labels'  => $labels,
320
+                'same_as' => $uris,
321
+            ) );
322
+
323
+            // Add the entity type.
324
+            if ( isset( $entity['mainType'] ) ) {
325
+                wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
326
+            }
327
+
328
+            // see https://github.com/insideout10/wordlift-plugin/issues/1304
329
+            // Set the post status, we need to set that in order to support entities
330
+            // created using rest endpoint on block editor, so that they get published
331
+            // when the post is published.
332
+            // Once the entity is published dont update the post status.
333
+            if ( $post->post_status !== 'publish' ) {
334
+                wp_update_post( array(
335
+                    'ID'          => $post->ID,
336
+                    'post_status' => $post_status
337
+                ) );
338
+            }
339
+        }
340
+
341
+        return $post_id;
342
+    }
343
+
344
+    /**
345
+     * Get the first matching entity for the provided URI array.
346
+     *
347
+     * Entities IDs and sameAs are searched.
348
+     *
349
+     * @param array $uris An array of URIs.
350
+     *
351
+     * @return \WP_Post|null The entity WP_Post if found or null if not found.
352
+     */
353
+    private function get_first_matching_entity_by_uri( $uris ) {
354
+
355
+        foreach ( $uris as $uri ) {
356
+            $existing_entity = $this->entity_service->get_entity_post_by_uri( $uri );
357
+            if ( isset( $existing_entity ) ) {
358
+                return $existing_entity;
359
+            }
360
+        }
361
+
362
+        return null;
363
+    }
364
+
365
+    /**
366
+     * @param $entity
367
+     *
368
+     * @return array
369
+     */
370
+    private function filter_valid_entity_ids( $entity ) {
371
+        $id = $entity['id'];
372
+
373
+        return array_filter( (array) $id, function ( $id ) {
374
+            return preg_match( '|^https?://|', $id );
375
+        } );
376
+    }
377
+
378
+    /**
379
+     * @param array $entity
380
+     *
381
+     * @return array
382
+     */
383
+    private function get_entity_uris( $entity ) {
384
+        $ids = $this->filter_valid_entity_ids( $entity );
385
+
386
+        return array_merge(
387
+            (array) $ids,
388
+            (array) $entity['sameAs']
389
+        );
390
+    }
391
+
392
+    private function entity_id_valid( $entity_id ) {
393
+        return preg_match( '#^https?://#i', $entity_id ) === 1;
394
+    }
395 395
 
396 396
 }
Please login to merge, or discard this patch.
Spacing   +73 added lines, -73 removed lines patch added patch discarded remove patch
@@ -49,17 +49,17 @@  discard block
 block discarded – undo
49 49
 	public function __construct() {
50 50
 
51 51
 		// Bail out if block editor's functions aren't available.
52
-		if ( ! function_exists( 'register_block_type' ) || ! function_exists( 'parse_blocks' ) ) {
52
+		if ( ! function_exists('register_block_type') || ! function_exists('parse_blocks')) {
53 53
 			return;
54 54
 		}
55 55
 
56
-		$this->log = \Wordlift_Log_Service::get_logger( get_class() );
56
+		$this->log = \Wordlift_Log_Service::get_logger(get_class());
57 57
 
58 58
 		$this->entity_service     = \Wordlift_Entity_Service::get_instance();
59 59
 		$this->entity_store       = Entity_Store::get_instance();
60 60
 		$this->entity_uri_service = \Wordlift_Entity_Uri_Service::get_instance();
61
-		add_action( 'init', array( $this, 'init' ) );
62
-		add_filter( 'wp_insert_post_data', array( $this, 'wp_insert_post_data' ), 10, 2 );
61
+		add_action('init', array($this, 'init'));
62
+		add_filter('wp_insert_post_data', array($this, 'wp_insert_post_data'), 10, 2);
63 63
 
64 64
 	}
65 65
 
@@ -69,12 +69,12 @@  discard block
 block discarded – undo
69 69
 	 */
70 70
 	public function init() {
71 71
 
72
-		register_block_type( 'wordlift/classification', array(
72
+		register_block_type('wordlift/classification', array(
73 73
 			'editor_script' => 'wl-block-editor',
74 74
 			'attributes'    => array(
75
-				'entities' => array( 'type' => 'array' ),
75
+				'entities' => array('type' => 'array'),
76 76
 			),
77
-		) );
77
+		));
78 78
 
79 79
 	}
80 80
 
@@ -109,41 +109,41 @@  discard block
 block discarded – undo
109 109
 	 * @return array The data array.
110 110
 	 * @throws \Exception
111 111
 	 */
112
-	public function wp_insert_post_data( $data, $postarr ) {
112
+	public function wp_insert_post_data($data, $postarr) {
113 113
 
114 114
 		$post_status = $data['post_status'];
115
-		if ( 'auto-draft' === $post_status || 'inherit' === $post_status ) {
115
+		if ('auto-draft' === $post_status || 'inherit' === $post_status) {
116 116
 			return $data;
117 117
 		}
118 118
 
119
-		$this->log->trace( "The following data has been received by `wp_insert_post_data`:\n"
120
-		                   . var_export( $data, true ) );
119
+		$this->log->trace("The following data has been received by `wp_insert_post_data`:\n"
120
+		                   . var_export($data, true));
121 121
 
122 122
 
123 123
 		try {
124
-			$entities = $this->parse_content( wp_unslash( $data['post_content'] ) );
124
+			$entities = $this->parse_content(wp_unslash($data['post_content']));
125 125
 
126
-			foreach ( $entities as $entity ) {
126
+			foreach ($entities as $entity) {
127 127
 
128
-				$entity_id = array_key_exists( 'id', $entity ) ? $entity['id'] : '';
128
+				$entity_id = array_key_exists('id', $entity) ? $entity['id'] : '';
129 129
 
130
-				if ( ! $this->entity_id_valid( $entity_id ) ) {
130
+				if ( ! $this->entity_id_valid($entity_id)) {
131 131
 					continue;
132 132
 				}
133 133
 
134
-				$entity_uris = $this->get_entity_uris( $entity );
134
+				$entity_uris = $this->get_entity_uris($entity);
135 135
 
136
-				if ( $this->get_first_matching_entity_by_uri( $entity_uris ) === null &&
137
-				     Post_Entities_Validator::is_local_entity_uri_exist( $this->entity_uri_service, $entity_uris ) ) {
136
+				if ($this->get_first_matching_entity_by_uri($entity_uris) === null &&
137
+				     Post_Entities_Validator::is_local_entity_uri_exist($this->entity_uri_service, $entity_uris)) {
138 138
 					// Skip the entity
139 139
 					continue;
140 140
 				}
141
-				$this->create_or_update_entity( $entity, $data['post_status'] );
141
+				$this->create_or_update_entity($entity, $data['post_status']);
142 142
 
143 143
 			}
144 144
 
145
-		} catch ( \Exception $e ) {
146
-			$this->log->error( $e->getMessage() );
145
+		} catch (\Exception $e) {
146
+			$this->log->error($e->getMessage());
147 147
 		}
148 148
 
149 149
 
@@ -158,27 +158,27 @@  discard block
 block discarded – undo
158 158
 	 * @return array An array of entities' structures.
159 159
 	 * @throws \Exception
160 160
 	 */
161
-	private function parse_content( $post_content ) {
161
+	private function parse_content($post_content) {
162 162
 
163
-		$all_blocks = parse_blocks( $post_content );
164
-		$this->log->trace( "The following blocks have been parsed while in `wp_insert_post`:\n"
165
-		                   . var_export( $all_blocks, true ) );
163
+		$all_blocks = parse_blocks($post_content);
164
+		$this->log->trace("The following blocks have been parsed while in `wp_insert_post`:\n"
165
+		                   . var_export($all_blocks, true));
166 166
 
167
-		$blocks = array_filter( $all_blocks, function ( $item ) {
168
-			return ! empty( $item['blockName'] ) && 'wordlift/classification' === $item['blockName'];
167
+		$blocks = array_filter($all_blocks, function($item) {
168
+			return ! empty($item['blockName']) && 'wordlift/classification' === $item['blockName'];
169 169
 		} );
170 170
 
171 171
 		// Bail out if the blocks' array is empty.
172
-		if ( empty( $blocks ) ) {
172
+		if (empty($blocks)) {
173 173
 			return array();
174 174
 		}
175 175
 
176
-		$block = current( $blocks );
177
-		$this->log->trace( "The following block has been found while in `wp_insert_post`:\n"
178
-		                   . var_export( $block, true ) );
176
+		$block = current($blocks);
177
+		$this->log->trace("The following block has been found while in `wp_insert_post`:\n"
178
+		                   . var_export($block, true));
179 179
 
180 180
 		// Bail out if the entities array is empty.
181
-		if ( empty( $block['attrs'] ) && empty( $block['attrs']['entities'] ) ) {
181
+		if (empty($block['attrs']) && empty($block['attrs']['entities'])) {
182 182
 			return array();
183 183
 		}
184 184
 
@@ -223,14 +223,14 @@  discard block
 block discarded – undo
223 223
 	 *
224 224
 	 * @return array An array of labels.
225 225
 	 */
226
-	public function get_labels( $entity ) {
226
+	public function get_labels($entity) {
227 227
 
228
-		$args = wp_parse_args( $entity, array(
228
+		$args = wp_parse_args($entity, array(
229 229
 			'label'       => array(),
230 230
 			'synonyms'    => array(),
231 231
 			'annotations' => array(),
232 232
 			'occurrences' => array(),
233
-		) );
233
+		));
234 234
 
235 235
 		// We gather all the labels, occurrences texts and synonyms into one array.
236 236
 		$initial = array_merge(
@@ -240,20 +240,20 @@  discard block
 block discarded – undo
240 240
 
241 241
 		$annotations = $args['annotations'];
242 242
 
243
-		return array_reduce( $args['occurrences'], function ( $carry, $item ) use ( $annotations ) {
243
+		return array_reduce($args['occurrences'], function($carry, $item) use ($annotations) {
244 244
 
245 245
 			// Bail out if occurrences->$item->text isn't set or its contents are already
246 246
 			// in `$carry`.
247
-			if ( ! isset( $annotations[ $item ]['text'] )
248
-			     || in_array( $annotations[ $item ]['text'], $carry ) ) {
247
+			if ( ! isset($annotations[$item]['text'])
248
+			     || in_array($annotations[$item]['text'], $carry)) {
249 249
 				return $carry;
250 250
 			}
251 251
 
252 252
 			// Push the label.
253
-			$carry[] = $annotations[ $item ]['text'];
253
+			$carry[] = $annotations[$item]['text'];
254 254
 
255 255
 			return $carry;
256
-		}, $initial );
256
+		}, $initial);
257 257
 	}
258 258
 
259 259
 	/**
@@ -277,52 +277,52 @@  discard block
 block discarded – undo
277 277
 	 * @return int|\WP_Error
278 278
 	 * @throws \Exception
279 279
 	 */
280
-	private function create_or_update_entity( $entity, $post_status = 'draft' ) {
280
+	private function create_or_update_entity($entity, $post_status = 'draft') {
281 281
 
282 282
 		// Get only valid IDs.
283
-		$uris = $this->get_entity_uris( $entity );
283
+		$uris = $this->get_entity_uris($entity);
284 284
 
285
-		$post = $this->get_first_matching_entity_by_uri( $uris );
285
+		$post = $this->get_first_matching_entity_by_uri($uris);
286 286
 
287
-		$this->log->trace( 'Entity' . ( empty( $post ) ? ' not' : '' ) . " found with the following URIs:\n"
288
-		                   . var_export( $uris, true ) );
287
+		$this->log->trace('Entity'.(empty($post) ? ' not' : '')." found with the following URIs:\n"
288
+		                   . var_export($uris, true));
289 289
 
290 290
 		// Get the labels.
291
-		$labels = $this->get_labels( $entity );
291
+		$labels = $this->get_labels($entity);
292 292
 
293
-		if ( empty( $post ) ) {
293
+		if (empty($post)) {
294 294
 			// Create the entity if it doesn't exist.
295
-			$post_id = $this->entity_store->create( array(
295
+			$post_id = $this->entity_store->create(array(
296 296
 				'labels'      => $labels,
297 297
 				'description' => $entity['description'],
298 298
 				'same_as'     => $uris,
299
-			), $post_status );
299
+			), $post_status);
300 300
 
301 301
 			// Return the WP_Error if we got one.
302
-			if ( is_wp_error( $post_id ) ) {
302
+			if (is_wp_error($post_id)) {
303 303
 				return $post_id;
304 304
 			}
305 305
 
306 306
 			// Add the entity type.
307
-			if ( isset( $entity['mainType'] ) ) {
308
-				wp_set_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
307
+			if (isset($entity['mainType'])) {
308
+				wp_set_object_terms($post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
309 309
 			}
310 310
 
311
-			if ( isset( $entity['properties'] ) && isset( $entity['properties']['latitude'] ) && isset( $entity['properties']['longitude'] ) ) {
312
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude'] );
313
-				add_post_meta( $post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude'] );
311
+			if (isset($entity['properties']) && isset($entity['properties']['latitude']) && isset($entity['properties']['longitude'])) {
312
+				add_post_meta($post_id, \Wordlift_Schema_Service::FIELD_GEO_LATITUDE, $entity['properties']['latitude']);
313
+				add_post_meta($post_id, \Wordlift_Schema_Service::FIELD_GEO_LONGITUDE, $entity['properties']['longitude']);
314 314
 			}
315 315
 		} else {
316 316
 			// Update the entity otherwise.
317
-			$post_id = $this->entity_store->update( array(
317
+			$post_id = $this->entity_store->update(array(
318 318
 				'ID'      => $post->ID,
319 319
 				'labels'  => $labels,
320 320
 				'same_as' => $uris,
321
-			) );
321
+			));
322 322
 
323 323
 			// Add the entity type.
324
-			if ( isset( $entity['mainType'] ) ) {
325
-				wp_add_object_terms( $post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME );
324
+			if (isset($entity['mainType'])) {
325
+				wp_add_object_terms($post_id, $entity['mainType'], \Wordlift_Entity_Type_Taxonomy_Service::TAXONOMY_NAME);
326 326
 			}
327 327
 
328 328
 			// see https://github.com/insideout10/wordlift-plugin/issues/1304
@@ -330,11 +330,11 @@  discard block
 block discarded – undo
330 330
 			// created using rest endpoint on block editor, so that they get published
331 331
 			// when the post is published.
332 332
 			// Once the entity is published dont update the post status.
333
-			if ( $post->post_status !== 'publish' ) {
334
-				wp_update_post( array(
333
+			if ($post->post_status !== 'publish') {
334
+				wp_update_post(array(
335 335
 					'ID'          => $post->ID,
336 336
 					'post_status' => $post_status
337
-				) );
337
+				));
338 338
 			}
339 339
 		}
340 340
 
@@ -350,11 +350,11 @@  discard block
 block discarded – undo
350 350
 	 *
351 351
 	 * @return \WP_Post|null The entity WP_Post if found or null if not found.
352 352
 	 */
353
-	private function get_first_matching_entity_by_uri( $uris ) {
353
+	private function get_first_matching_entity_by_uri($uris) {
354 354
 
355
-		foreach ( $uris as $uri ) {
356
-			$existing_entity = $this->entity_service->get_entity_post_by_uri( $uri );
357
-			if ( isset( $existing_entity ) ) {
355
+		foreach ($uris as $uri) {
356
+			$existing_entity = $this->entity_service->get_entity_post_by_uri($uri);
357
+			if (isset($existing_entity)) {
358 358
 				return $existing_entity;
359 359
 			}
360 360
 		}
@@ -367,11 +367,11 @@  discard block
 block discarded – undo
367 367
 	 *
368 368
 	 * @return array
369 369
 	 */
370
-	private function filter_valid_entity_ids( $entity ) {
370
+	private function filter_valid_entity_ids($entity) {
371 371
 		$id = $entity['id'];
372 372
 
373
-		return array_filter( (array) $id, function ( $id ) {
374
-			return preg_match( '|^https?://|', $id );
373
+		return array_filter((array) $id, function($id) {
374
+			return preg_match('|^https?://|', $id);
375 375
 		} );
376 376
 	}
377 377
 
@@ -380,8 +380,8 @@  discard block
 block discarded – undo
380 380
 	 *
381 381
 	 * @return array
382 382
 	 */
383
-	private function get_entity_uris( $entity ) {
384
-		$ids = $this->filter_valid_entity_ids( $entity );
383
+	private function get_entity_uris($entity) {
384
+		$ids = $this->filter_valid_entity_ids($entity);
385 385
 
386 386
 		return array_merge(
387 387
 			(array) $ids,
@@ -389,8 +389,8 @@  discard block
 block discarded – undo
389 389
 		);
390 390
 	}
391 391
 
392
-	private function entity_id_valid( $entity_id ) {
393
-		return preg_match( '#^https?://#i', $entity_id ) === 1;
392
+	private function entity_id_valid($entity_id) {
393
+		return preg_match('#^https?://#i', $entity_id) === 1;
394 394
 	}
395 395
 
396 396
 }
Please login to merge, or discard this patch.