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